blob: 6c510557e24a6e55339a7bb3197000b6d975a3c6 [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
Christopher Faulet0f226952018-10-22 09:29:56 +020019#include <types/capture.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020020
21#include <proto/acl.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020022#include <proto/action.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020023#include <proto/channel.h>
24#include <proto/checks.h>
25#include <proto/connection.h>
26#include <proto/filters.h>
27#include <proto/hdr_idx.h>
Christopher Faulet0f226952018-10-22 09:29:56 +020028#include <proto/http_htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020029#include <proto/log.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020030#include <proto/pattern.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020031#include <proto/proto_http.h>
32#include <proto/proxy.h>
Christopher Fauletfefc73d2018-10-24 21:18:04 +020033#include <proto/server.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020034#include <proto/stream.h>
35#include <proto/stream_interface.h>
36#include <proto/stats.h>
37
Christopher Faulet377c5a52018-10-24 21:21:30 +020038extern const char *stat_status_codes[];
Christopher Fauletf2824e62018-10-01 12:12:37 +020039
40static void htx_end_request(struct stream *s);
41static void htx_end_response(struct stream *s);
42
Christopher Faulet0f226952018-10-22 09:29:56 +020043static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr);
Christopher Faulet0b6bdc52018-10-24 11:05:36 +020044static int htx_del_hdr_value(char *start, char *end, char **from, char *next);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010045static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len);
46static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len);
47static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl);
Christopher Faulet0f226952018-10-22 09:29:56 +020048static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v);
49
Christopher Faulet3e964192018-10-24 11:39:23 +020050static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s, int *deny_status);
51static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s);
52
Christopher Faulet33640082018-10-24 11:53:01 +020053static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px);
54static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px);
55
Christopher Fauletfcda7c62018-10-24 11:56:22 +020056static void htx_manage_client_side_cookies(struct stream *s, struct channel *req);
57static void htx_manage_server_side_cookies(struct stream *s, struct channel *res);
58
Christopher Faulet377c5a52018-10-24 21:21:30 +020059static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend);
60static int htx_handle_stats(struct stream *s, struct channel *req);
61
Christopher Faulet4a28a532019-03-01 11:19:40 +010062static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg);
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 Faulet29f17582019-05-23 11:03:26 +0200135 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet0ef372a2019-04-08 10:57:20 +0200136 if (htx->flags & HTX_FL_UPGRADE)
137 goto failed_keep_alive;
138
Christopher Faulet9768c262018-10-22 09:34:31 +0200139 /* 1: have we encountered a read error ? */
140 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200141 if (!(s->flags & SF_ERR_MASK))
142 s->flags |= SF_ERR_CLICL;
143
144 if (txn->flags & TX_WAIT_NEXT_RQ)
145 goto failed_keep_alive;
146
147 if (sess->fe->options & PR_O_IGNORE_PRB)
148 goto failed_keep_alive;
149
Christopher Faulet9768c262018-10-22 09:34:31 +0200150 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200151 stream_inc_http_req_ctr(s);
152 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100153 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200154 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100155 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200156
Christopher Faulet9768c262018-10-22 09:34:31 +0200157 txn->status = 400;
158 msg->err_state = msg->msg_state;
159 msg->msg_state = HTTP_MSG_ERROR;
160 htx_reply_and_close(s, txn->status, NULL);
161 req->analysers &= AN_REQ_FLT_END;
162
Christopher Faulete0768eb2018-10-03 16:38:02 +0200163 if (!(s->flags & SF_FINST_MASK))
164 s->flags |= SF_FINST_R;
165 return 0;
166 }
167
Christopher Faulet9768c262018-10-22 09:34:31 +0200168 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200169 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
170 if (!(s->flags & SF_ERR_MASK))
171 s->flags |= SF_ERR_CLITO;
172
173 if (txn->flags & TX_WAIT_NEXT_RQ)
174 goto failed_keep_alive;
175
176 if (sess->fe->options & PR_O_IGNORE_PRB)
177 goto failed_keep_alive;
178
Christopher Faulet9768c262018-10-22 09:34:31 +0200179 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200180 stream_inc_http_req_ctr(s);
181 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100182 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200183 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100184 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200185
Christopher Faulet9768c262018-10-22 09:34:31 +0200186 txn->status = 408;
187 msg->err_state = msg->msg_state;
188 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100189 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200190 req->analysers &= AN_REQ_FLT_END;
191
Christopher Faulete0768eb2018-10-03 16:38:02 +0200192 if (!(s->flags & SF_FINST_MASK))
193 s->flags |= SF_FINST_R;
194 return 0;
195 }
196
Christopher Faulet9768c262018-10-22 09:34:31 +0200197 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200198 else if (req->flags & CF_SHUTR) {
199 if (!(s->flags & SF_ERR_MASK))
200 s->flags |= SF_ERR_CLICL;
201
202 if (txn->flags & TX_WAIT_NEXT_RQ)
203 goto failed_keep_alive;
204
205 if (sess->fe->options & PR_O_IGNORE_PRB)
206 goto failed_keep_alive;
207
Christopher Faulete0768eb2018-10-03 16:38:02 +0200208 stream_inc_http_err_ctr(s);
209 stream_inc_http_req_ctr(s);
210 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100211 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200212 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100213 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200214
Christopher Faulet9768c262018-10-22 09:34:31 +0200215 txn->status = 400;
216 msg->err_state = msg->msg_state;
217 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100218 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200219 req->analysers &= AN_REQ_FLT_END;
220
Christopher Faulete0768eb2018-10-03 16:38:02 +0200221 if (!(s->flags & SF_FINST_MASK))
222 s->flags |= SF_FINST_R;
223 return 0;
224 }
225
226 channel_dont_connect(req);
227 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
228 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100229
Christopher Faulet9768c262018-10-22 09:34:31 +0200230 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200231 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
232 /* We need more data, we have to re-enable quick-ack in case we
233 * previously disabled it, otherwise we might cause the client
234 * to delay next data.
235 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100236 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200237 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100238
Christopher Faulet47365272018-10-31 17:40:50 +0100239 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200240 /* If the client starts to talk, let's fall back to
241 * request timeout processing.
242 */
243 txn->flags &= ~TX_WAIT_NEXT_RQ;
244 req->analyse_exp = TICK_ETERNITY;
245 }
246
247 /* just set the request timeout once at the beginning of the request */
248 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100249 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200250 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
251 else
252 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
253 }
254
255 /* we're not ready yet */
256 return 0;
257
258 failed_keep_alive:
259 /* Here we process low-level errors for keep-alive requests. In
260 * short, if the request is not the first one and it experiences
261 * a timeout, read error or shutdown, we just silently close so
262 * that the client can try again.
263 */
264 txn->status = 0;
265 msg->msg_state = HTTP_MSG_RQBEFORE;
266 req->analysers &= AN_REQ_FLT_END;
267 s->logs.logwait = 0;
268 s->logs.level = 0;
269 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200270 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200271 return 0;
272 }
273
Christopher Faulet9768c262018-10-22 09:34:31 +0200274 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200275 stream_inc_http_req_ctr(s);
276 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
277
Christopher Faulet9768c262018-10-22 09:34:31 +0200278 /* kill the pending keep-alive timeout */
279 txn->flags &= ~TX_WAIT_NEXT_RQ;
280 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200281
Christopher Faulet29f17582019-05-23 11:03:26 +0200282 BUG_ON(htx_get_first_type(htx) != HTX_BLK_REQ_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +0200283 sl = http_get_stline(htx);
Christopher Faulet03599112018-11-27 11:21:21 +0100284
Christopher Faulet9768c262018-10-22 09:34:31 +0200285 /* 0: we might have to print this header in debug mode */
286 if (unlikely((global.mode & MODE_DEBUG) &&
287 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
288 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200289
Christopher Faulet03599112018-11-27 11:21:21 +0100290 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200291
Christopher Fauleta3f15502019-05-13 15:27:23 +0200292 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200293 struct htx_blk *blk = htx_get_blk(htx, pos);
294 enum htx_blk_type type = htx_get_blk_type(blk);
295
296 if (type == HTX_BLK_EOH)
297 break;
298 if (type != HTX_BLK_HDR)
299 continue;
300
301 htx_debug_hdr("clihdr", s,
302 htx_get_blk_name(htx, blk),
303 htx_get_blk_value(htx, blk));
304 }
305 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200306
307 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100308 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200309 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100310 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100311 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200312 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100313 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100314 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100315 if (sl->flags & HTX_SL_F_BODYLESS)
316 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200317
318 /* we can make use of server redirect on GET and HEAD */
319 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
320 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100321 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200322 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200323 goto return_bad_req;
324 }
325
326 /*
327 * 2: check if the URI matches the monitor_uri.
328 * We have to do this for every request which gets in, because
329 * the monitor-uri is defined by the frontend.
330 */
331 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100332 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200333 /*
334 * We have found the monitor URI
335 */
336 struct acl_cond *cond;
337
338 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100339 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200340
341 /* Check if we want to fail this monitor request or not */
342 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
343 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
344
345 ret = acl_pass(ret);
346 if (cond->pol == ACL_COND_UNLESS)
347 ret = !ret;
348
349 if (ret) {
350 /* we fail this request, let's return 503 service unavail */
351 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100352 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200353 if (!(s->flags & SF_ERR_MASK))
354 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
355 goto return_prx_cond;
356 }
357 }
358
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800359 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200360 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100361 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200362 if (!(s->flags & SF_ERR_MASK))
363 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
364 goto return_prx_cond;
365 }
366
367 /*
368 * 3: Maybe we have to copy the original REQURI for the logs ?
369 * Note: we cannot log anymore if the request has been
370 * classified as invalid.
371 */
372 if (unlikely(s->logs.logwait & LW_REQ)) {
373 /* we have a complete HTTP request that we must log */
374 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200375 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200376
Christopher Faulet9768c262018-10-22 09:34:31 +0200377 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
378 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200379
380 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
381 s->do_log(s);
382 } else {
383 ha_alert("HTTP logging : out of memory.\n");
384 }
385 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200386
Christopher Faulete0768eb2018-10-03 16:38:02 +0200387 /* if the frontend has "option http-use-proxy-header", we'll check if
388 * we have what looks like a proxied connection instead of a connection,
389 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
390 * Note that this is *not* RFC-compliant, however browsers and proxies
391 * happen to do that despite being non-standard :-(
392 * We consider that a request not beginning with either '/' or '*' is
393 * a proxied connection, which covers both "scheme://location" and
394 * CONNECT ip:port.
395 */
396 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100397 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200398 txn->flags |= TX_USE_PX_CONN;
399
Christopher Faulete0768eb2018-10-03 16:38:02 +0200400 /* 5: we may need to capture headers */
401 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200402 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200403
Christopher Faulet03b9d8b2019-03-26 22:02:00 +0100404 /* by default, close the stream at the end of the transaction. */
405 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200406
407 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200408 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200409 req->analysers |= AN_REQ_HTTP_BODY;
410
411 /*
412 * RFC7234#4:
413 * A cache MUST write through requests with methods
414 * that are unsafe (Section 4.2.1 of [RFC7231]) to
415 * the origin server; i.e., a cache is not allowed
416 * to generate a reply to such a request before
417 * having forwarded the request and having received
418 * a corresponding response.
419 *
420 * RFC7231#4.2.1:
421 * Of the request methods defined by this
422 * specification, the GET, HEAD, OPTIONS, and TRACE
423 * methods are defined to be safe.
424 */
425 if (likely(txn->meth == HTTP_METH_GET ||
426 txn->meth == HTTP_METH_HEAD ||
427 txn->meth == HTTP_METH_OPTIONS ||
428 txn->meth == HTTP_METH_TRACE))
429 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
430
431 /* end of job, return OK */
432 req->analysers &= ~an_bit;
433 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200434
Christopher Faulete0768eb2018-10-03 16:38:02 +0200435 return 1;
436
437 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200438 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200439 txn->req.err_state = txn->req.msg_state;
440 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100441 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100442 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200443 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100444 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200445
446 return_prx_cond:
447 if (!(s->flags & SF_ERR_MASK))
448 s->flags |= SF_ERR_PRXCOND;
449 if (!(s->flags & SF_FINST_MASK))
450 s->flags |= SF_FINST_R;
451
452 req->analysers &= AN_REQ_FLT_END;
453 req->analyse_exp = TICK_ETERNITY;
454 return 0;
455}
456
457
458/* This stream analyser runs all HTTP request processing which is common to
459 * frontends and backends, which means blocking ACLs, filters, connection-close,
460 * reqadd, stats and redirects. This is performed for the designated proxy.
461 * It returns 1 if the processing can continue on next analysers, or zero if it
462 * either needs more data or wants to immediately abort the request (eg: deny,
463 * error, ...).
464 */
465int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
466{
467 struct session *sess = s->sess;
468 struct http_txn *txn = s->txn;
469 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200470 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200471 struct redirect_rule *rule;
472 struct cond_wordlist *wl;
473 enum rule_result verdict;
474 int deny_status = HTTP_ERR_403;
475 struct connection *conn = objt_conn(sess->origin);
476
477 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
478 /* we need more data */
479 goto return_prx_yield;
480 }
481
482 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
483 now_ms, __FUNCTION__,
484 s,
485 req,
486 req->rex, req->wex,
487 req->flags,
488 ci_data(req),
489 req->analysers);
490
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100491 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200492
Christopher Faulet1907ccc2019-04-29 13:12:02 +0200493 /* just in case we have some per-backend tracking. Only called the first
494 * execution of the analyser. */
495 if (!s->current_rule || s->current_rule_list != &px->http_req_rules)
496 stream_inc_be_http_req_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200497
498 /* evaluate http-request rules */
499 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200500 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200501
502 switch (verdict) {
503 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
504 goto return_prx_yield;
505
506 case HTTP_RULE_RES_CONT:
507 case HTTP_RULE_RES_STOP: /* nothing to do */
508 break;
509
510 case HTTP_RULE_RES_DENY: /* deny or tarpit */
511 if (txn->flags & TX_CLTARPIT)
512 goto tarpit;
513 goto deny;
514
515 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
516 goto return_prx_cond;
517
518 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
519 goto done;
520
521 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
522 goto return_bad_req;
523 }
524 }
525
526 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
527 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200528 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200529
Christopher Fauletff2759f2018-10-24 11:13:16 +0200530 ctx.blk = NULL;
531 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
532 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200533 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200534 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200535 }
536
537 /* OK at this stage, we know that the request was accepted according to
538 * the http-request rules, we can check for the stats. Note that the
539 * URI is detected *before* the req* rules in order not to be affected
540 * by a possible reqrep, while they are processed *after* so that a
541 * reqdeny can still block them. This clearly needs to change in 1.6!
542 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200543 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200544 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100545 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200546 txn->status = 500;
547 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100548 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200549
550 if (!(s->flags & SF_ERR_MASK))
551 s->flags |= SF_ERR_RESOURCE;
552 goto return_prx_cond;
553 }
554
555 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200556 htx_handle_stats(s, req);
557 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200558 /* not all actions implemented: deny, allow, auth */
559
560 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
561 goto deny;
562
563 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
564 goto return_prx_cond;
565 }
566
567 /* evaluate the req* rules except reqadd */
568 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200569 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200570 goto return_bad_req;
571
572 if (txn->flags & TX_CLDENY)
573 goto deny;
574
575 if (txn->flags & TX_CLTARPIT) {
576 deny_status = HTTP_ERR_500;
577 goto tarpit;
578 }
579 }
580
581 /* add request headers from the rule sets in the same order */
582 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200583 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200584 if (wl->cond) {
585 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
586 ret = acl_pass(ret);
587 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
588 ret = !ret;
589 if (!ret)
590 continue;
591 }
592
Christopher Fauletff2759f2018-10-24 11:13:16 +0200593 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
594 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200595 goto return_bad_req;
596 }
597
Christopher Faulet2571bc62019-03-01 11:44:26 +0100598 /* Proceed with the applets now. */
599 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200600 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100601 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200602
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100603 if (htx_handle_expect_hdr(s, htx, msg) == -1)
604 goto return_bad_req;
605
Christopher Faulete0768eb2018-10-03 16:38:02 +0200606 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
607 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
608 if (!(s->flags & SF_FINST_MASK))
609 s->flags |= SF_FINST_R;
610
611 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
612 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
613 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
614 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100615
616 req->flags |= CF_SEND_DONTWAIT;
617 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200618 goto done;
619 }
620
621 /* check whether we have some ACLs set to redirect this request */
622 list_for_each_entry(rule, &px->redirect_rules, list) {
623 if (rule->cond) {
624 int ret;
625
626 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
627 ret = acl_pass(ret);
628 if (rule->cond->pol == ACL_COND_UNLESS)
629 ret = !ret;
630 if (!ret)
631 continue;
632 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200633 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200634 goto return_bad_req;
635 goto done;
636 }
637
638 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
639 * If this happens, then the data will not come immediately, so we must
640 * send all what we have without waiting. Note that due to the small gain
641 * in waiting for the body of the request, it's easier to simply put the
642 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
643 * itself once used.
644 */
645 req->flags |= CF_SEND_DONTWAIT;
646
647 done: /* done with this analyser, continue with next ones that the calling
648 * points will have set, if any.
649 */
650 req->analyse_exp = TICK_ETERNITY;
651 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
652 req->analysers &= ~an_bit;
653 return 1;
654
655 tarpit:
656 /* Allow cookie logging
657 */
658 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200659 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200660
661 /* When a connection is tarpitted, we use the tarpit timeout,
662 * which may be the same as the connect timeout if unspecified.
663 * If unset, then set it to zero because we really want it to
664 * eventually expire. We build the tarpit as an analyser.
665 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100666 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200667
668 /* wipe the request out so that we can drop the connection early
669 * if the client closes first.
670 */
671 channel_dont_connect(req);
672
673 txn->status = http_err_codes[deny_status];
674
675 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
676 req->analysers |= AN_REQ_HTTP_TARPIT;
677 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
678 if (!req->analyse_exp)
679 req->analyse_exp = tick_add(now_ms, 0);
680 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100681 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200682 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100683 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200684 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100685 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200686 goto done_without_exp;
687
688 deny: /* this request was blocked (denied) */
689
690 /* Allow cookie logging
691 */
692 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200693 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200694
695 txn->flags |= TX_CLDENY;
696 txn->status = http_err_codes[deny_status];
697 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100698 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200699 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100700 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200701 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100702 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200703 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100704 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200705 goto return_prx_cond;
706
707 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200708 txn->req.err_state = txn->req.msg_state;
709 txn->req.msg_state = HTTP_MSG_ERROR;
710 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100711 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200712
Olivier Houcharda798bf52019-03-08 18:52:00 +0100713 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200714 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100715 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200716
717 return_prx_cond:
718 if (!(s->flags & SF_ERR_MASK))
719 s->flags |= SF_ERR_PRXCOND;
720 if (!(s->flags & SF_FINST_MASK))
721 s->flags |= SF_FINST_R;
722
723 req->analysers &= AN_REQ_FLT_END;
724 req->analyse_exp = TICK_ETERNITY;
725 return 0;
726
727 return_prx_yield:
728 channel_dont_connect(req);
729 return 0;
730}
731
732/* This function performs all the processing enabled for the current request.
733 * It returns 1 if the processing can continue on next analysers, or zero if it
734 * needs more data, encounters an error, or wants to immediately abort the
735 * request. It relies on buffers flags, and updates s->req.analysers.
736 */
737int htx_process_request(struct stream *s, struct channel *req, int an_bit)
738{
739 struct session *sess = s->sess;
740 struct http_txn *txn = s->txn;
741 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200742 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200743 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
744
745 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
746 /* we need more data */
747 channel_dont_connect(req);
748 return 0;
749 }
750
751 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
752 now_ms, __FUNCTION__,
753 s,
754 req,
755 req->rex, req->wex,
756 req->flags,
757 ci_data(req),
758 req->analysers);
759
760 /*
761 * Right now, we know that we have processed the entire headers
762 * and that unwanted requests have been filtered out. We can do
763 * whatever we want with the remaining request. Also, now we
764 * may have separate values for ->fe, ->be.
765 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100766 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200767
768 /*
769 * If HTTP PROXY is set we simply get remote server address parsing
770 * incoming request. Note that this requires that a connection is
771 * allocated on the server side.
772 */
773 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
774 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100775 struct htx_sl *sl;
776 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200777
778 /* Note that for now we don't reuse existing proxy connections */
779 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
780 txn->req.err_state = txn->req.msg_state;
781 txn->req.msg_state = HTTP_MSG_ERROR;
782 txn->status = 500;
783 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100784 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200785
786 if (!(s->flags & SF_ERR_MASK))
787 s->flags |= SF_ERR_RESOURCE;
788 if (!(s->flags & SF_FINST_MASK))
789 s->flags |= SF_FINST_R;
790
791 return 0;
792 }
Christopher Faulet297fbb42019-05-13 14:41:27 +0200793 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100794 uri = htx_sl_req_uri(sl);
795 path = http_get_path(uri);
796 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200797 goto return_bad_req;
798
799 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200800 * uri.ptr and path.ptr (excluded). If it was not found, we need
801 * to replace from all the uri by a single "/".
802 *
803 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100804 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200805 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200806 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100807 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200808 }
809
810 /*
811 * 7: Now we can work with the cookies.
812 * Note that doing so might move headers in the request, but
813 * the fields will stay coherent and the URI will not move.
814 * This should only be performed in the backend.
815 */
816 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100817 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200818
819 /* add unique-id if "header-unique-id" is specified */
820
821 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
822 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
823 goto return_bad_req;
824 s->unique_id[0] = '\0';
825 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
826 }
827
828 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200829 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
830 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
831
832 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200833 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200834 }
835
836 /*
837 * 9: add X-Forwarded-For if either the frontend or the backend
838 * asks for it.
839 */
840 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200841 struct http_hdr_ctx ctx = { .blk = NULL };
842 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
843 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
844
Christopher Faulete0768eb2018-10-03 16:38:02 +0200845 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200846 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200847 /* The header is set to be added only if none is present
848 * and we found it, so don't do anything.
849 */
850 }
851 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
852 /* Add an X-Forwarded-For header unless the source IP is
853 * in the 'except' network range.
854 */
855 if ((!sess->fe->except_mask.s_addr ||
856 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
857 != sess->fe->except_net.s_addr) &&
858 (!s->be->except_mask.s_addr ||
859 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
860 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200861 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200862
863 /* Note: we rely on the backend to get the header name to be used for
864 * x-forwarded-for, because the header is really meant for the backends.
865 * However, if the backend did not specify any option, we have to rely
866 * on the frontend's header name.
867 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200868 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
869 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200870 goto return_bad_req;
871 }
872 }
873 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
874 /* FIXME: for the sake of completeness, we should also support
875 * 'except' here, although it is mostly useless in this case.
876 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200877 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200878
Christopher Faulete0768eb2018-10-03 16:38:02 +0200879 inet_ntop(AF_INET6,
880 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
881 pn, sizeof(pn));
882
883 /* Note: we rely on the backend to get the header name to be used for
884 * x-forwarded-for, because the header is really meant for the backends.
885 * However, if the backend did not specify any option, we have to rely
886 * on the frontend's header name.
887 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200888 chunk_printf(&trash, "%s", pn);
889 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200890 goto return_bad_req;
891 }
892 }
893
894 /*
895 * 10: add X-Original-To if either the frontend or the backend
896 * asks for it.
897 */
898 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
899
900 /* FIXME: don't know if IPv6 can handle that case too. */
901 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
902 /* Add an X-Original-To header unless the destination IP is
903 * in the 'except' network range.
904 */
905 conn_get_to_addr(cli_conn);
906
907 if (cli_conn->addr.to.ss_family == AF_INET &&
908 ((!sess->fe->except_mask_to.s_addr ||
909 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
910 != sess->fe->except_to.s_addr) &&
911 (!s->be->except_mask_to.s_addr ||
912 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
913 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200914 struct ist hdr;
915 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200916
917 /* Note: we rely on the backend to get the header name to be used for
918 * x-original-to, because the header is really meant for the backends.
919 * However, if the backend did not specify any option, we have to rely
920 * on the frontend's header name.
921 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200922 if (s->be->orgto_hdr_len)
923 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
924 else
925 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200926
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200927 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
928 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200929 goto return_bad_req;
930 }
931 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200932 }
933
Christopher Faulete0768eb2018-10-03 16:38:02 +0200934 /* If we have no server assigned yet and we're balancing on url_param
935 * with a POST request, we may be interested in checking the body for
936 * that parameter. This will be done in another analyser.
937 */
938 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100939 s->txn->meth == HTTP_METH_POST &&
940 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200941 channel_dont_connect(req);
942 req->analysers |= AN_REQ_HTTP_BODY;
943 }
944
945 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
946 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100947
Christopher Faulete0768eb2018-10-03 16:38:02 +0200948 /* We expect some data from the client. Unless we know for sure
949 * we already have a full request, we have to re-enable quick-ack
950 * in case we previously disabled it, otherwise we might cause
951 * the client to delay further data.
952 */
953 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200954 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100955 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200956
957 /*************************************************************
958 * OK, that's finished for the headers. We have done what we *
959 * could. Let's switch to the DATA state. *
960 ************************************************************/
961 req->analyse_exp = TICK_ETERNITY;
962 req->analysers &= ~an_bit;
963
964 s->logs.tv_request = now;
965 /* OK let's go on with the BODY now */
966 return 1;
967
968 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200969 txn->req.err_state = txn->req.msg_state;
970 txn->req.msg_state = HTTP_MSG_ERROR;
971 txn->status = 400;
972 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100973 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200974
Olivier Houcharda798bf52019-03-08 18:52:00 +0100975 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200976 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100977 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200978
979 if (!(s->flags & SF_ERR_MASK))
980 s->flags |= SF_ERR_PRXCOND;
981 if (!(s->flags & SF_FINST_MASK))
982 s->flags |= SF_FINST_R;
983 return 0;
984}
985
986/* This function is an analyser which processes the HTTP tarpit. It always
987 * returns zero, at the beginning because it prevents any other processing
988 * from occurring, and at the end because it terminates the request.
989 */
990int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
991{
992 struct http_txn *txn = s->txn;
993
994 /* This connection is being tarpitted. The CLIENT side has
995 * already set the connect expiration date to the right
996 * timeout. We just have to check that the client is still
997 * there and that the timeout has not expired.
998 */
999 channel_dont_connect(req);
1000 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1001 !tick_is_expired(req->analyse_exp, now_ms))
1002 return 0;
1003
1004 /* We will set the queue timer to the time spent, just for
1005 * logging purposes. We fake a 500 server error, so that the
1006 * attacker will not suspect his connection has been tarpitted.
1007 * It will not cause trouble to the logs because we can exclude
1008 * the tarpitted connections by filtering on the 'PT' status flags.
1009 */
1010 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1011
1012 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001013 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001014
1015 req->analysers &= AN_REQ_FLT_END;
1016 req->analyse_exp = TICK_ETERNITY;
1017
1018 if (!(s->flags & SF_ERR_MASK))
1019 s->flags |= SF_ERR_PRXCOND;
1020 if (!(s->flags & SF_FINST_MASK))
1021 s->flags |= SF_FINST_T;
1022 return 0;
1023}
1024
1025/* This function is an analyser which waits for the HTTP request body. It waits
1026 * for either the buffer to be full, or the full advertised contents to have
1027 * reached the buffer. It must only be called after the standard HTTP request
1028 * processing has occurred, because it expects the request to be parsed and will
1029 * look for the Expect header. It may send a 100-Continue interim response. It
1030 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1031 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1032 * needs to read more data, or 1 once it has completed its analysis.
1033 */
1034int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1035{
1036 struct session *sess = s->sess;
1037 struct http_txn *txn = s->txn;
1038 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001039 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001040
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001041
1042 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1043 now_ms, __FUNCTION__,
1044 s,
1045 req,
1046 req->rex, req->wex,
1047 req->flags,
1048 ci_data(req),
1049 req->analysers);
1050
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001051 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001052
Willy Tarreau4236f032019-03-05 10:43:32 +01001053 if (htx->flags & HTX_FL_PARSING_ERROR)
1054 goto return_bad_req;
1055
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001056 if (msg->msg_state < HTTP_MSG_BODY)
1057 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001058
Christopher Faulete0768eb2018-10-03 16:38:02 +02001059 /* We have to parse the HTTP request body to find any required data.
1060 * "balance url_param check_post" should have been the only way to get
1061 * into this. We were brought here after HTTP header analysis, so all
1062 * related structures are ready.
1063 */
1064
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001065 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001066 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1067 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001068 }
1069
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001070 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001071
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001072 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1073 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001074 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001075 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001076 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001077 goto http_end;
1078
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001079 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001080 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1081 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001082 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001083
1084 if (!(s->flags & SF_ERR_MASK))
1085 s->flags |= SF_ERR_CLITO;
1086 if (!(s->flags & SF_FINST_MASK))
1087 s->flags |= SF_FINST_D;
1088 goto return_err_msg;
1089 }
1090
1091 /* we get here if we need to wait for more data */
1092 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1093 /* Not enough data. We'll re-use the http-request
1094 * timeout here. Ideally, we should set the timeout
1095 * relative to the accept() date. We just set the
1096 * request timeout once at the beginning of the
1097 * request.
1098 */
1099 channel_dont_connect(req);
1100 if (!tick_isset(req->analyse_exp))
1101 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1102 return 0;
1103 }
1104
1105 http_end:
1106 /* The situation will not evolve, so let's give up on the analysis. */
1107 s->logs.tv_request = now; /* update the request timer to reflect full request */
1108 req->analysers &= ~an_bit;
1109 req->analyse_exp = TICK_ETERNITY;
1110 return 1;
1111
1112 return_bad_req: /* let's centralize all bad requests */
1113 txn->req.err_state = txn->req.msg_state;
1114 txn->req.msg_state = HTTP_MSG_ERROR;
1115 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001116 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001117
1118 if (!(s->flags & SF_ERR_MASK))
1119 s->flags |= SF_ERR_PRXCOND;
1120 if (!(s->flags & SF_FINST_MASK))
1121 s->flags |= SF_FINST_R;
1122
1123 return_err_msg:
1124 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001125 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001126 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001127 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001128 return 0;
1129}
1130
1131/* This function is an analyser which forwards request body (including chunk
1132 * sizes if any). It is called as soon as we must forward, even if we forward
1133 * zero byte. The only situation where it must not be called is when we're in
1134 * tunnel mode and we want to forward till the close. It's used both to forward
1135 * remaining data and to resync after end of body. It expects the msg_state to
1136 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1137 * read more data, or 1 once we can go on with next request or end the stream.
1138 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1139 * bytes of pending data + the headers if not already done.
1140 */
1141int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1142{
1143 struct session *sess = s->sess;
1144 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001145 struct http_msg *msg = &txn->req;
1146 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001147 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001148 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001149
1150 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1151 now_ms, __FUNCTION__,
1152 s,
1153 req,
1154 req->rex, req->wex,
1155 req->flags,
1156 ci_data(req),
1157 req->analysers);
1158
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001159 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001160
1161 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1162 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1163 /* Output closed while we were sending data. We must abort and
1164 * wake the other side up.
1165 */
1166 msg->err_state = msg->msg_state;
1167 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001168 htx_end_request(s);
1169 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001170 return 1;
1171 }
1172
1173 /* Note that we don't have to send 100-continue back because we don't
1174 * need the data to complete our job, and it's up to the server to
1175 * decide whether to return 100, 417 or anything else in return of
1176 * an "Expect: 100-continue" header.
1177 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001178 if (msg->msg_state == HTTP_MSG_BODY)
1179 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001180
1181 /* Some post-connect processing might want us to refrain from starting to
1182 * forward data. Currently, the only reason for this is "balance url_param"
1183 * whichs need to parse/process the request after we've enabled forwarding.
1184 */
1185 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1186 if (!(s->res.flags & CF_READ_ATTACHED)) {
1187 channel_auto_connect(req);
1188 req->flags |= CF_WAKE_CONNECT;
1189 channel_dont_close(req); /* don't fail on early shutr */
1190 goto waiting;
1191 }
1192 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1193 }
1194
1195 /* in most states, we should abort in case of early close */
1196 channel_auto_close(req);
1197
1198 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001199 if (req->to_forward == CHN_INFINITE_FORWARD) {
1200 if (req->flags & (CF_SHUTR|CF_EOI)) {
1201 msg->msg_state = HTTP_MSG_DONE;
1202 req->to_forward = 0;
1203 goto done;
1204 }
1205 }
1206 else {
1207 /* We can't process the buffer's contents yet */
1208 req->flags |= CF_WAKE_WRITE;
1209 goto missing_data_or_waiting;
1210 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001211 }
1212
Christopher Faulet9768c262018-10-22 09:34:31 +02001213 if (msg->msg_state >= HTTP_MSG_DONE)
1214 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001215 /* Forward input data. We get it by removing all outgoing data not
1216 * forwarded yet from HTX data size. If there are some data filters, we
1217 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001218 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001219 if (HAS_REQ_DATA_FILTERS(s)) {
1220 ret = flt_http_payload(s, msg, htx->data);
1221 if (ret < 0)
1222 goto return_bad_req;
Christopher Fauletee847d42019-05-23 11:55:33 +02001223 channel_htx_fwd_payload(req, htx, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001224 if (htx->data != co_data(req) || htx->extra)
1225 goto missing_data_or_waiting;
1226 }
1227 else {
Christopher Faulet16af60e2019-05-23 11:53:17 +02001228 channel_htx_fwd_all(req, htx);
Christopher Faulet66af0b22019-03-22 14:54:52 +01001229 if (msg->flags & HTTP_MSGF_XFER_LEN)
1230 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001231 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001232
Christopher Fauletc62c2b92019-03-28 11:41:39 +01001233 if (txn->meth == HTTP_METH_CONNECT) {
1234 msg->msg_state = HTTP_MSG_TUNNEL;
1235 goto done;
1236 }
1237
Christopher Faulet9768c262018-10-22 09:34:31 +02001238 /* Check if the end-of-message is reached and if so, switch the message
1239 * in HTTP_MSG_DONE state.
1240 */
1241 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1242 goto missing_data_or_waiting;
1243
1244 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01001245 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001246
1247 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001248 /* other states, DONE...TUNNEL */
1249 /* we don't want to forward closes on DONE except in tunnel mode. */
1250 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1251 channel_dont_close(req);
1252
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001253 if (HAS_REQ_DATA_FILTERS(s)) {
1254 ret = flt_http_end(s, msg);
1255 if (ret <= 0) {
1256 if (!ret)
1257 goto missing_data_or_waiting;
1258 goto return_bad_req;
1259 }
1260 }
1261
Christopher Fauletf2824e62018-10-01 12:12:37 +02001262 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001263 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001264 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001265 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1266 if (req->flags & CF_SHUTW) {
1267 /* request errors are most likely due to the
1268 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001269 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001270 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001271 goto return_bad_req;
1272 }
1273 return 1;
1274 }
1275
1276 /* If "option abortonclose" is set on the backend, we want to monitor
1277 * the client's connection and forward any shutdown notification to the
1278 * server, which will decide whether to close or to go on processing the
1279 * request. We only do that in tunnel mode, and not in other modes since
1280 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001281 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001282 channel_auto_read(req);
1283 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1284 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1285 s->si[1].flags |= SI_FL_NOLINGER;
1286 channel_auto_close(req);
1287 }
1288 else if (s->txn->meth == HTTP_METH_POST) {
1289 /* POST requests may require to read extra CRLF sent by broken
1290 * browsers and which could cause an RST to be sent upon close
1291 * on some systems (eg: Linux). */
1292 channel_auto_read(req);
1293 }
1294 return 0;
1295
1296 missing_data_or_waiting:
1297 /* stop waiting for data if the input is closed before the end */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001298 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR)
1299 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001300
1301 waiting:
1302 /* waiting for the last bits to leave the buffer */
1303 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001304 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001305
Christopher Faulet47365272018-10-31 17:40:50 +01001306 if (htx->flags & HTX_FL_PARSING_ERROR)
1307 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001308
Christopher Faulete0768eb2018-10-03 16:38:02 +02001309 /* When TE: chunked is used, we need to get there again to parse remaining
1310 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1311 * And when content-length is used, we never want to let the possible
1312 * shutdown be forwarded to the other side, as the state machine will
1313 * take care of it once the client responds. It's also important to
1314 * prevent TIME_WAITs from accumulating on the backend side, and for
1315 * HTTP/2 where the last frame comes with a shutdown.
1316 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001317 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001318 channel_dont_close(req);
1319
1320 /* We know that more data are expected, but we couldn't send more that
1321 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1322 * system knows it must not set a PUSH on this first part. Interactive
1323 * modes are already handled by the stream sock layer. We must not do
1324 * this in content-length mode because it could present the MSG_MORE
1325 * flag with the last block of forwarded data, which would cause an
1326 * additional delay to be observed by the receiver.
1327 */
1328 if (msg->flags & HTTP_MSGF_TE_CHNK)
1329 req->flags |= CF_EXPECT_MORE;
1330
1331 return 0;
1332
Christopher Faulet93e02d82019-03-08 14:18:50 +01001333 return_cli_abort:
1334 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1335 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1336 if (objt_server(s->target))
1337 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1338 if (!(s->flags & SF_ERR_MASK))
1339 s->flags |= SF_ERR_CLICL;
1340 status = 400;
1341 goto return_error;
1342
1343 return_srv_abort:
1344 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1345 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1346 if (objt_server(s->target))
1347 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1348 if (!(s->flags & SF_ERR_MASK))
1349 s->flags |= SF_ERR_SRVCL;
1350 status = 502;
1351 goto return_error;
1352
1353 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001354 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001355 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001356 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001357 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001358 s->flags |= SF_ERR_CLICL;
1359 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001360
Christopher Faulet93e02d82019-03-08 14:18:50 +01001361 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001362 txn->req.err_state = txn->req.msg_state;
1363 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001364 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001365 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001366 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001367 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001368 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001369 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001370 }
1371 req->analysers &= AN_REQ_FLT_END;
1372 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 +01001373 if (!(s->flags & SF_FINST_MASK))
1374 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001375 return 0;
1376}
1377
Olivier Houcharda254a372019-04-05 15:30:12 +02001378/* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1379/* Returns 0 if we can attempt to retry, -1 otherwise */
1380static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1381{
1382 struct channel *req, *res;
1383 int co_data;
1384
1385 si->conn_retries--;
1386 if (si->conn_retries < 0)
1387 return -1;
1388
Willy Tarreau223995e2019-05-04 10:38:31 +02001389 if (objt_server(s->target))
1390 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
1391 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1392
Olivier Houcharda254a372019-04-05 15:30:12 +02001393 req = &s->req;
1394 res = &s->res;
1395 /* Remove any write error from the request, and read error from the response */
1396 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1397 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1398 res->analysers = 0;
1399 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
1400 si->state = SI_ST_REQ;
1401 si->exp = TICK_ETERNITY;
1402 res->rex = TICK_ETERNITY;
1403 res->to_forward = 0;
1404 res->analyse_exp = TICK_ETERNITY;
1405 res->total = 0;
1406 s->flags &= ~(SF_ASSIGNED | SF_ADDR_SET | SF_ERR_SRVTO | SF_ERR_SRVCL);
1407 si_release_endpoint(&s->si[1]);
1408 b_free(&req->buf);
1409 /* Swap the L7 buffer with the channel buffer */
1410 /* We know we stored the co_data as b_data, so get it there */
1411 co_data = b_data(&si->l7_buffer);
1412 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1413 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1414
1415 co_set_data(req, co_data);
1416 b_reset(&res->buf);
1417 co_set_data(res, 0);
1418 return 0;
1419}
1420
Christopher Faulete0768eb2018-10-03 16:38:02 +02001421/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1422 * processing can continue on next analysers, or zero if it either needs more
1423 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1424 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1425 * when it has nothing left to do, and may remove any analyser when it wants to
1426 * abort.
1427 */
1428int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1429{
Christopher Faulet9768c262018-10-22 09:34:31 +02001430 /*
1431 * We will analyze a complete HTTP response to check the its syntax.
1432 *
1433 * Once the start line and all headers are received, we may perform a
1434 * capture of the error (if any), and we will set a few fields. We also
1435 * logging and finally headers capture.
1436 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001437 struct session *sess = s->sess;
1438 struct http_txn *txn = s->txn;
1439 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001440 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001441 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001442 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001443 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001444 int n;
1445
1446 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1447 now_ms, __FUNCTION__,
1448 s,
1449 rep,
1450 rep->rex, rep->wex,
1451 rep->flags,
1452 ci_data(rep),
1453 rep->analysers);
1454
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001455 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001456
Willy Tarreau4236f032019-03-05 10:43:32 +01001457 /* Parsing errors are caught here */
1458 if (htx->flags & HTX_FL_PARSING_ERROR)
1459 goto return_bad_res;
1460
Christopher Faulete0768eb2018-10-03 16:38:02 +02001461 /*
1462 * Now we quickly check if we have found a full valid response.
1463 * If not so, we check the FD and buffer states before leaving.
1464 * A full response is indicated by the fact that we have seen
1465 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1466 * responses are checked first.
1467 *
1468 * Depending on whether the client is still there or not, we
1469 * may send an error response back or not. Note that normally
1470 * we should only check for HTTP status there, and check I/O
1471 * errors somewhere else.
1472 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001473 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001474 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001475 /* 1: have we encountered a read error ? */
1476 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001477 struct connection *conn = NULL;
1478
Olivier Houchard865d8392019-05-03 22:46:27 +02001479 if (objt_cs(s->si[1].end))
1480 conn = objt_cs(s->si[1].end)->conn;
1481
1482 if (si_b->flags & SI_FL_L7_RETRY &&
1483 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001484 /* If we arrive here, then CF_READ_ERROR was
1485 * set by si_cs_recv() because we matched a
1486 * status, overwise it would have removed
1487 * the SI_FL_L7_RETRY flag, so it's ok not
1488 * to check s->be->retry_type.
1489 */
1490 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1491 return 0;
1492 }
1493
Olivier Houchard6db16992019-05-17 15:40:49 +02001494 if (txn->flags & TX_NOT_FIRST)
1495 goto abort_keep_alive;
1496
Olivier Houcharda798bf52019-03-08 18:52:00 +01001497 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001498 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001499 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001500 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001501 }
1502
Christopher Faulete0768eb2018-10-03 16:38:02 +02001503 rep->analysers &= AN_RES_FLT_END;
1504 txn->status = 502;
1505
1506 /* Check to see if the server refused the early data.
1507 * If so, just send a 425
1508 */
Olivier Houchard865d8392019-05-03 22:46:27 +02001509 if (conn->err_code == CO_ER_SSL_EARLY_FAILED) {
1510 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001511 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001512 do_l7_retry(s, si_b) == 0)
1513 return 0;
1514 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001515 }
1516
1517 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001518 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001519
1520 if (!(s->flags & SF_ERR_MASK))
1521 s->flags |= SF_ERR_SRVCL;
1522 if (!(s->flags & SF_FINST_MASK))
1523 s->flags |= SF_FINST_H;
1524 return 0;
1525 }
1526
Christopher Faulet9768c262018-10-22 09:34:31 +02001527 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001528 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001529 if ((si_b->flags & SI_FL_L7_RETRY) &&
1530 (s->be->retry_type & PR_RE_TIMEOUT)) {
1531 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1532 return 0;
1533 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001534 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001535 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001536 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001537 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001538 }
1539
Christopher Faulete0768eb2018-10-03 16:38:02 +02001540 rep->analysers &= AN_RES_FLT_END;
1541 txn->status = 504;
1542 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001543 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001544
1545 if (!(s->flags & SF_ERR_MASK))
1546 s->flags |= SF_ERR_SRVTO;
1547 if (!(s->flags & SF_FINST_MASK))
1548 s->flags |= SF_FINST_H;
1549 return 0;
1550 }
1551
Christopher Faulet9768c262018-10-22 09:34:31 +02001552 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001553 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001554 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1555 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001556 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001557 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001558
1559 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001560 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001561 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001562
1563 if (!(s->flags & SF_ERR_MASK))
1564 s->flags |= SF_ERR_CLICL;
1565 if (!(s->flags & SF_FINST_MASK))
1566 s->flags |= SF_FINST_H;
1567
1568 /* process_stream() will take care of the error */
1569 return 0;
1570 }
1571
Christopher Faulet9768c262018-10-22 09:34:31 +02001572 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001573 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001574 if ((si_b->flags & SI_FL_L7_RETRY) &&
1575 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1576 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1577 return 0;
1578 }
1579
Olivier Houchard6db16992019-05-17 15:40:49 +02001580 if (txn->flags & TX_NOT_FIRST)
1581 goto abort_keep_alive;
1582
Olivier Houcharda798bf52019-03-08 18:52:00 +01001583 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001584 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001585 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001586 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001587 }
1588
Christopher Faulete0768eb2018-10-03 16:38:02 +02001589 rep->analysers &= AN_RES_FLT_END;
1590 txn->status = 502;
1591 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001592 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001593
1594 if (!(s->flags & SF_ERR_MASK))
1595 s->flags |= SF_ERR_SRVCL;
1596 if (!(s->flags & SF_FINST_MASK))
1597 s->flags |= SF_FINST_H;
1598 return 0;
1599 }
1600
Christopher Faulet9768c262018-10-22 09:34:31 +02001601 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001602 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001603 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001604 goto abort_keep_alive;
1605
Olivier Houcharda798bf52019-03-08 18:52:00 +01001606 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001607 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001608
1609 if (!(s->flags & SF_ERR_MASK))
1610 s->flags |= SF_ERR_CLICL;
1611 if (!(s->flags & SF_FINST_MASK))
1612 s->flags |= SF_FINST_H;
1613
1614 /* process_stream() will take care of the error */
1615 return 0;
1616 }
1617
1618 channel_dont_close(rep);
1619 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1620 return 0;
1621 }
1622
1623 /* More interesting part now : we know that we have a complete
1624 * response which at least looks like HTTP. We have an indicator
1625 * of each header's length, so we can parse them quickly.
1626 */
1627
Christopher Faulet9768c262018-10-22 09:34:31 +02001628 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001629 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001630 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001631
Christopher Faulet9768c262018-10-22 09:34:31 +02001632 /* 0: we might have to print this header in debug mode */
1633 if (unlikely((global.mode & MODE_DEBUG) &&
1634 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1635 int32_t pos;
1636
Christopher Faulet03599112018-11-27 11:21:21 +01001637 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001638
Christopher Fauleta3f15502019-05-13 15:27:23 +02001639 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001640 struct htx_blk *blk = htx_get_blk(htx, pos);
1641 enum htx_blk_type type = htx_get_blk_type(blk);
1642
1643 if (type == HTX_BLK_EOH)
1644 break;
1645 if (type != HTX_BLK_HDR)
1646 continue;
1647
1648 htx_debug_hdr("srvhdr", s,
1649 htx_get_blk_name(htx, blk),
1650 htx_get_blk_value(htx, blk));
1651 }
1652 }
1653
Christopher Faulet03599112018-11-27 11:21:21 +01001654 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001655 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001656 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001657 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001658 if (sl->flags & HTX_SL_F_XFER_LEN) {
1659 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001660 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001661 if (sl->flags & HTX_SL_F_BODYLESS)
1662 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001663 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001664
1665 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001666 if (n < 1 || n > 5)
1667 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001668
Christopher Faulete0768eb2018-10-03 16:38:02 +02001669 /* when the client triggers a 4xx from the server, it's most often due
1670 * to a missing object or permission. These events should be tracked
1671 * because if they happen often, it may indicate a brute force or a
1672 * vulnerability scan.
1673 */
1674 if (n == 4)
1675 stream_inc_http_err_ctr(s);
1676
1677 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001678 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001679
Christopher Faulete0768eb2018-10-03 16:38:02 +02001680 /* Adjust server's health based on status code. Note: status codes 501
1681 * and 505 are triggered on demand by client request, so we must not
1682 * count them as server failures.
1683 */
1684 if (objt_server(s->target)) {
1685 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001686 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001687 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001688 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001689 }
1690
1691 /*
1692 * We may be facing a 100-continue response, or any other informational
1693 * 1xx response which is non-final, in which case this is not the right
1694 * response, and we're waiting for the next one. Let's allow this response
1695 * to go to the client and wait for the next one. There's an exception for
1696 * 101 which is used later in the code to switch protocols.
1697 */
1698 if (txn->status < 200 &&
1699 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001700 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Fauletee1bd4b2019-05-23 10:33:12 +02001701 channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001702 msg->msg_state = HTTP_MSG_RPBEFORE;
1703 txn->status = 0;
1704 s->logs.t_data = -1; /* was not a response yet */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001705 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001706 }
1707
1708 /*
1709 * 2: check for cacheability.
1710 */
1711
1712 switch (txn->status) {
1713 case 200:
1714 case 203:
1715 case 204:
1716 case 206:
1717 case 300:
1718 case 301:
1719 case 404:
1720 case 405:
1721 case 410:
1722 case 414:
1723 case 501:
1724 break;
1725 default:
1726 /* RFC7231#6.1:
1727 * Responses with status codes that are defined as
1728 * cacheable by default (e.g., 200, 203, 204, 206,
1729 * 300, 301, 404, 405, 410, 414, and 501 in this
1730 * specification) can be reused by a cache with
1731 * heuristic expiration unless otherwise indicated
1732 * by the method definition or explicit cache
1733 * controls [RFC7234]; all other status codes are
1734 * not cacheable by default.
1735 */
1736 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1737 break;
1738 }
1739
1740 /*
1741 * 3: we may need to capture headers
1742 */
1743 s->logs.logwait &= ~LW_RESP;
1744 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001745 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001746
Christopher Faulet9768c262018-10-22 09:34:31 +02001747 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001748 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1749 txn->status == 101)) {
1750 /* Either we've established an explicit tunnel, or we're
1751 * switching the protocol. In both cases, we're very unlikely
1752 * to understand the next protocols. We have to switch to tunnel
1753 * mode, so that we transfer the request and responses then let
1754 * this protocol pass unmodified. When we later implement specific
1755 * parsers for such protocols, we'll want to check the Upgrade
1756 * header which contains information about that protocol for
1757 * responses with status 101 (eg: see RFC2817 about TLS).
1758 */
1759 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001760 }
1761
Christopher Faulet61608322018-11-23 16:23:45 +01001762 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1763 * 407 (Proxy-Authenticate) responses and set the connection to private
1764 */
1765 srv_conn = cs_conn(objt_cs(s->si[1].end));
1766 if (srv_conn) {
1767 struct ist hdr;
1768 struct http_hdr_ctx ctx;
1769
1770 if (txn->status == 401)
1771 hdr = ist("WWW-Authenticate");
1772 else if (txn->status == 407)
1773 hdr = ist("Proxy-Authenticate");
1774 else
1775 goto end;
1776
1777 ctx.blk = NULL;
1778 while (http_find_header(htx, hdr, &ctx, 0)) {
1779 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
Olivier Houchard250031e2019-05-29 15:01:50 +02001780 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4))) {
1781 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001782 srv_conn->flags |= CO_FL_PRIVATE;
Olivier Houchard250031e2019-05-29 15:01:50 +02001783 }
Christopher Faulet61608322018-11-23 16:23:45 +01001784 }
1785 }
1786
1787 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001788 /* we want to have the response time before we start processing it */
1789 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1790
1791 /* end of job, return OK */
1792 rep->analysers &= ~an_bit;
1793 rep->analyse_exp = TICK_ETERNITY;
1794 channel_auto_close(rep);
1795 return 1;
1796
Christopher Faulet47365272018-10-31 17:40:50 +01001797 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001798 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001799 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001800 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001801 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001802 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001803 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001804 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001805 do_l7_retry(s, si_b) == 0)
1806 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001807 txn->status = 502;
1808 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001809 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001810 rep->analysers &= AN_RES_FLT_END;
1811
1812 if (!(s->flags & SF_ERR_MASK))
1813 s->flags |= SF_ERR_PRXCOND;
1814 if (!(s->flags & SF_FINST_MASK))
1815 s->flags |= SF_FINST_H;
1816 return 0;
1817
Christopher Faulete0768eb2018-10-03 16:38:02 +02001818 abort_keep_alive:
1819 /* A keep-alive request to the server failed on a network error.
1820 * The client is required to retry. We need to close without returning
1821 * any other information so that the client retries.
1822 */
1823 txn->status = 0;
1824 rep->analysers &= AN_RES_FLT_END;
1825 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001826 s->logs.logwait = 0;
1827 s->logs.level = 0;
1828 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001829 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001830 return 0;
1831}
1832
1833/* This function performs all the processing enabled for the current response.
1834 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1835 * and updates s->res.analysers. It might make sense to explode it into several
1836 * other functions. It works like process_request (see indications above).
1837 */
1838int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1839{
1840 struct session *sess = s->sess;
1841 struct http_txn *txn = s->txn;
1842 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001843 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001844 struct proxy *cur_proxy;
1845 struct cond_wordlist *wl;
1846 enum rule_result ret = HTTP_RULE_RES_CONT;
1847
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001848 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1849 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001850
Christopher Faulete0768eb2018-10-03 16:38:02 +02001851 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1852 now_ms, __FUNCTION__,
1853 s,
1854 rep,
1855 rep->rex, rep->wex,
1856 rep->flags,
1857 ci_data(rep),
1858 rep->analysers);
1859
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001860 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001861
1862 /* The stats applet needs to adjust the Connection header but we don't
1863 * apply any filter there.
1864 */
1865 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1866 rep->analysers &= ~an_bit;
1867 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001868 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001869 }
1870
1871 /*
1872 * We will have to evaluate the filters.
1873 * As opposed to version 1.2, now they will be evaluated in the
1874 * filters order and not in the header order. This means that
1875 * each filter has to be validated among all headers.
1876 *
1877 * Filters are tried with ->be first, then with ->fe if it is
1878 * different from ->be.
1879 *
1880 * Maybe we are in resume condiion. In this case I choose the
1881 * "struct proxy" which contains the rule list matching the resume
1882 * pointer. If none of theses "struct proxy" match, I initialise
1883 * the process with the first one.
1884 *
1885 * In fact, I check only correspondance betwwen the current list
1886 * pointer and the ->fe rule list. If it doesn't match, I initialize
1887 * the loop with the ->be.
1888 */
1889 if (s->current_rule_list == &sess->fe->http_res_rules)
1890 cur_proxy = sess->fe;
1891 else
1892 cur_proxy = s->be;
1893 while (1) {
1894 struct proxy *rule_set = cur_proxy;
1895
1896 /* evaluate http-response rules */
1897 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001898 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001899
1900 if (ret == HTTP_RULE_RES_BADREQ)
1901 goto return_srv_prx_502;
1902
1903 if (ret == HTTP_RULE_RES_DONE) {
1904 rep->analysers &= ~an_bit;
1905 rep->analyse_exp = TICK_ETERNITY;
1906 return 1;
1907 }
1908 }
1909
1910 /* we need to be called again. */
1911 if (ret == HTTP_RULE_RES_YIELD) {
1912 channel_dont_close(rep);
1913 return 0;
1914 }
1915
1916 /* try headers filters */
1917 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001918 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1919 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001920 }
1921
1922 /* has the response been denied ? */
1923 if (txn->flags & TX_SVDENY) {
1924 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001925 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001926
Olivier Houcharda798bf52019-03-08 18:52:00 +01001927 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1928 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001929 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001930 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001931 goto return_srv_prx_502;
1932 }
1933
1934 /* add response headers from the rule sets in the same order */
1935 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001936 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001937 if (txn->status < 200 && txn->status != 101)
1938 break;
1939 if (wl->cond) {
1940 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1941 ret = acl_pass(ret);
1942 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1943 ret = !ret;
1944 if (!ret)
1945 continue;
1946 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001947
1948 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1949 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001950 goto return_bad_resp;
1951 }
1952
1953 /* check whether we're already working on the frontend */
1954 if (cur_proxy == sess->fe)
1955 break;
1956 cur_proxy = sess->fe;
1957 }
1958
1959 /* After this point, this anayzer can't return yield, so we can
1960 * remove the bit corresponding to this analyzer from the list.
1961 *
1962 * Note that the intermediate returns and goto found previously
1963 * reset the analyzers.
1964 */
1965 rep->analysers &= ~an_bit;
1966 rep->analyse_exp = TICK_ETERNITY;
1967
1968 /* OK that's all we can do for 1xx responses */
1969 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001970 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001971
1972 /*
1973 * Now check for a server cookie.
1974 */
1975 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001976 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001977
1978 /*
1979 * Check for cache-control or pragma headers if required.
1980 */
1981 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1982 check_response_for_cacheability(s, rep);
1983
1984 /*
1985 * Add server cookie in the response if needed
1986 */
1987 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1988 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1989 (!(s->flags & SF_DIRECT) ||
1990 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1991 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1992 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1993 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1994 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1995 !(s->flags & SF_IGNORE_PRST)) {
1996 /* the server is known, it's not the one the client requested, or the
1997 * cookie's last seen date needs to be refreshed. We have to
1998 * insert a set-cookie here, except if we want to insert only on POST
1999 * requests and this one isn't. Note that servers which don't have cookies
2000 * (eg: some backup servers) will return a full cookie removal request.
2001 */
2002 if (!objt_server(s->target)->cookie) {
2003 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002004 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002005 s->be->cookie_name);
2006 }
2007 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002008 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002009
2010 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2011 /* emit last_date, which is mandatory */
2012 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2013 s30tob64((date.tv_sec+3) >> 2,
2014 trash.area + trash.data);
2015 trash.data += 5;
2016
2017 if (s->be->cookie_maxlife) {
2018 /* emit first_date, which is either the original one or
2019 * the current date.
2020 */
2021 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2022 s30tob64(txn->cookie_first_date ?
2023 txn->cookie_first_date >> 2 :
2024 (date.tv_sec+3) >> 2,
2025 trash.area + trash.data);
2026 trash.data += 5;
2027 }
2028 }
2029 chunk_appendf(&trash, "; path=/");
2030 }
2031
2032 if (s->be->cookie_domain)
2033 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2034
2035 if (s->be->ck_opts & PR_CK_HTTPONLY)
2036 chunk_appendf(&trash, "; HttpOnly");
2037
2038 if (s->be->ck_opts & PR_CK_SECURE)
2039 chunk_appendf(&trash, "; Secure");
2040
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002041 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002042 goto return_bad_resp;
2043
2044 txn->flags &= ~TX_SCK_MASK;
2045 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2046 /* the server did not change, only the date was updated */
2047 txn->flags |= TX_SCK_UPDATED;
2048 else
2049 txn->flags |= TX_SCK_INSERTED;
2050
2051 /* Here, we will tell an eventual cache on the client side that we don't
2052 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2053 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2054 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2055 */
2056 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2057
2058 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2059
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002060 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002061 goto return_bad_resp;
2062 }
2063 }
2064
2065 /*
2066 * Check if result will be cacheable with a cookie.
2067 * We'll block the response if security checks have caught
2068 * nasty things such as a cacheable cookie.
2069 */
2070 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2071 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2072 (s->be->options & PR_O_CHK_CACHE)) {
2073 /* we're in presence of a cacheable response containing
2074 * a set-cookie header. We'll block it as requested by
2075 * the 'checkcache' option, and send an alert.
2076 */
2077 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002078 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002079
Olivier Houcharda798bf52019-03-08 18:52:00 +01002080 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2081 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002082 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002083 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002084
2085 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2086 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2087 send_log(s->be, LOG_ALERT,
2088 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2089 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2090 goto return_srv_prx_502;
2091 }
2092
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002093 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002094 /* Always enter in the body analyzer */
2095 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2096 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2097
2098 /* if the user wants to log as soon as possible, without counting
2099 * bytes from the server, then this is the right moment. We have
2100 * to temporarily assign bytes_out to log what we currently have.
2101 */
2102 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2103 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002104 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002105 s->do_log(s);
2106 s->logs.bytes_out = 0;
2107 }
2108 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002109
2110 return_bad_resp:
2111 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002112 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002113 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002114 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002115 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002116
2117 return_srv_prx_502:
2118 rep->analysers &= AN_RES_FLT_END;
2119 txn->status = 502;
2120 s->logs.t_data = -1; /* was not a valid response */
2121 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002122 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002123 if (!(s->flags & SF_ERR_MASK))
2124 s->flags |= SF_ERR_PRXCOND;
2125 if (!(s->flags & SF_FINST_MASK))
2126 s->flags |= SF_FINST_H;
2127 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002128}
2129
2130/* This function is an analyser which forwards response body (including chunk
2131 * sizes if any). It is called as soon as we must forward, even if we forward
2132 * zero byte. The only situation where it must not be called is when we're in
2133 * tunnel mode and we want to forward till the close. It's used both to forward
2134 * remaining data and to resync after end of body. It expects the msg_state to
2135 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2136 * read more data, or 1 once we can go on with next request or end the stream.
2137 *
2138 * It is capable of compressing response data both in content-length mode and
2139 * in chunked mode. The state machines follows different flows depending on
2140 * whether content-length and chunked modes are used, since there are no
2141 * trailers in content-length :
2142 *
2143 * chk-mode cl-mode
2144 * ,----- BODY -----.
2145 * / \
2146 * V size > 0 V chk-mode
2147 * .--> SIZE -------------> DATA -------------> CRLF
2148 * | | size == 0 | last byte |
2149 * | v final crlf v inspected |
2150 * | TRAILERS -----------> DONE |
2151 * | |
2152 * `----------------------------------------------'
2153 *
2154 * Compression only happens in the DATA state, and must be flushed in final
2155 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2156 * is performed at once on final states for all bytes parsed, or when leaving
2157 * on missing data.
2158 */
2159int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2160{
2161 struct session *sess = s->sess;
2162 struct http_txn *txn = s->txn;
2163 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002164 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002165 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002166
2167 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2168 now_ms, __FUNCTION__,
2169 s,
2170 res,
2171 res->rex, res->wex,
2172 res->flags,
2173 ci_data(res),
2174 res->analysers);
2175
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002176 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002177
2178 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002179 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002180 /* Output closed while we were sending data. We must abort and
2181 * wake the other side up.
2182 */
2183 msg->err_state = msg->msg_state;
2184 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002185 htx_end_response(s);
2186 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002187 return 1;
2188 }
2189
Christopher Faulet9768c262018-10-22 09:34:31 +02002190 if (msg->msg_state == HTTP_MSG_BODY)
2191 msg->msg_state = HTTP_MSG_DATA;
2192
Christopher Faulete0768eb2018-10-03 16:38:02 +02002193 /* in most states, we should abort in case of early close */
2194 channel_auto_close(res);
2195
Christopher Faulete0768eb2018-10-03 16:38:02 +02002196 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002197 if (res->to_forward == CHN_INFINITE_FORWARD) {
2198 if (res->flags & (CF_SHUTR|CF_EOI)) {
2199 msg->msg_state = HTTP_MSG_DONE;
2200 res->to_forward = 0;
2201 goto done;
2202 }
2203 }
2204 else {
2205 /* We can't process the buffer's contents yet */
2206 res->flags |= CF_WAKE_WRITE;
2207 goto missing_data_or_waiting;
2208 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002209 }
2210
Christopher Faulet9768c262018-10-22 09:34:31 +02002211 if (msg->msg_state >= HTTP_MSG_DONE)
2212 goto done;
2213
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002214 /* Forward input data. We get it by removing all outgoing data not
2215 * forwarded yet from HTX data size. If there are some data filters, we
2216 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002217 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002218 if (HAS_RSP_DATA_FILTERS(s)) {
2219 ret = flt_http_payload(s, msg, htx->data);
2220 if (ret < 0)
2221 goto return_bad_res;
Christopher Fauletee847d42019-05-23 11:55:33 +02002222 channel_htx_fwd_payload(res, htx, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002223 if (htx->data != co_data(res) || htx->extra)
2224 goto missing_data_or_waiting;
2225 }
2226 else {
Christopher Faulet16af60e2019-05-23 11:53:17 +02002227 channel_htx_fwd_all(res, htx);
Christopher Faulet66af0b22019-03-22 14:54:52 +01002228 if (msg->flags & HTTP_MSGF_XFER_LEN)
2229 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002230 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002231
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002232 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2233 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2234 msg->msg_state = HTTP_MSG_TUNNEL;
2235 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002236 }
2237
Christopher Faulet9768c262018-10-22 09:34:31 +02002238 /* Check if the end-of-message is reached and if so, switch the message
2239 * in HTTP_MSG_DONE state.
2240 */
2241 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2242 goto missing_data_or_waiting;
2243
2244 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002245 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002246
2247 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002248 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002249 channel_dont_close(res);
2250
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002251 if (HAS_RSP_DATA_FILTERS(s)) {
2252 ret = flt_http_end(s, msg);
2253 if (ret <= 0) {
2254 if (!ret)
2255 goto missing_data_or_waiting;
2256 goto return_bad_res;
2257 }
2258 }
2259
Christopher Fauletf2824e62018-10-01 12:12:37 +02002260 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002261 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002262 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002263 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2264 if (res->flags & CF_SHUTW) {
2265 /* response errors are most likely due to the
2266 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002267 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002268 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002269 goto return_bad_res;
2270 }
2271 return 1;
2272 }
2273 return 0;
2274
2275 missing_data_or_waiting:
2276 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002277 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002278
Christopher Faulet47365272018-10-31 17:40:50 +01002279 if (htx->flags & HTX_FL_PARSING_ERROR)
2280 goto return_bad_res;
2281
Christopher Faulete0768eb2018-10-03 16:38:02 +02002282 /* stop waiting for data if the input is closed before the end. If the
2283 * client side was already closed, it means that the client has aborted,
2284 * so we don't want to count this as a server abort. Otherwise it's a
2285 * server abort.
2286 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002287 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002288 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002289 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002290 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002291 if (htx_is_empty(htx))
2292 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002293 }
2294
Christopher Faulete0768eb2018-10-03 16:38:02 +02002295 /* When TE: chunked is used, we need to get there again to parse
2296 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002297 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2298 * are filters registered on the stream, we don't want to forward a
2299 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002300 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002301 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002302 channel_dont_close(res);
2303
2304 /* We know that more data are expected, but we couldn't send more that
2305 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2306 * system knows it must not set a PUSH on this first part. Interactive
2307 * modes are already handled by the stream sock layer. We must not do
2308 * this in content-length mode because it could present the MSG_MORE
2309 * flag with the last block of forwarded data, which would cause an
2310 * additional delay to be observed by the receiver.
2311 */
2312 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2313 res->flags |= CF_EXPECT_MORE;
2314
2315 /* the stream handler will take care of timeouts and errors */
2316 return 0;
2317
Christopher Faulet93e02d82019-03-08 14:18:50 +01002318 return_srv_abort:
2319 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2320 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002321 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002322 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2323 if (!(s->flags & SF_ERR_MASK))
2324 s->flags |= SF_ERR_SRVCL;
2325 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002326
Christopher Faulet93e02d82019-03-08 14:18:50 +01002327 return_cli_abort:
2328 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2329 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002330 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002331 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2332 if (!(s->flags & SF_ERR_MASK))
2333 s->flags |= SF_ERR_CLICL;
2334 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002335
Christopher Faulet93e02d82019-03-08 14:18:50 +01002336 return_bad_res:
2337 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2338 if (objt_server(s->target)) {
2339 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2340 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2341 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002342 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002343 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002344
Christopher Faulet93e02d82019-03-08 14:18:50 +01002345 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002346 txn->rsp.err_state = txn->rsp.msg_state;
2347 txn->rsp.msg_state = HTTP_MSG_ERROR;
2348 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002349 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002350 res->analysers &= AN_RES_FLT_END;
2351 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 +02002352 if (!(s->flags & SF_FINST_MASK))
2353 s->flags |= SF_FINST_D;
2354 return 0;
2355}
2356
Christopher Fauletf2824e62018-10-01 12:12:37 +02002357/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002358 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002359 * as too large a request to build a valid response.
2360 */
2361int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2362{
Christopher Faulet99daf282018-11-28 22:58:13 +01002363 struct channel *req = &s->req;
2364 struct channel *res = &s->res;
2365 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002366 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002367 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002368 struct ist status, reason, location;
2369 unsigned int flags;
2370 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002371 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002372
2373 chunk = alloc_trash_chunk();
2374 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002375 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002376
Christopher Faulet99daf282018-11-28 22:58:13 +01002377 /*
2378 * Create the location
2379 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002380 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002381 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002382 case REDIRECT_TYPE_SCHEME: {
2383 struct http_hdr_ctx ctx;
2384 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002385
Christopher Faulet99daf282018-11-28 22:58:13 +01002386 host = ist("");
2387 ctx.blk = NULL;
2388 if (http_find_header(htx, ist("Host"), &ctx, 0))
2389 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002390
Christopher Faulet297fbb42019-05-13 14:41:27 +02002391 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002392 path = http_get_path(htx_sl_req_uri(sl));
2393 /* build message using path */
2394 if (path.ptr) {
2395 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2396 int qs = 0;
2397 while (qs < path.len) {
2398 if (*(path.ptr + qs) == '?') {
2399 path.len = qs;
2400 break;
2401 }
2402 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002403 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002404 }
2405 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002406 else
2407 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002408
Christopher Faulet99daf282018-11-28 22:58:13 +01002409 if (rule->rdr_str) { /* this is an old "redirect" rule */
2410 /* add scheme */
2411 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2412 goto fail;
2413 }
2414 else {
2415 /* add scheme with executing log format */
2416 chunk->data += build_logline(s, chunk->area + chunk->data,
2417 chunk->size - chunk->data,
2418 &rule->rdr_fmt);
2419 }
2420 /* add "://" + host + path */
2421 if (!chunk_memcat(chunk, "://", 3) ||
2422 !chunk_memcat(chunk, host.ptr, host.len) ||
2423 !chunk_memcat(chunk, path.ptr, path.len))
2424 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002425
Christopher Faulet99daf282018-11-28 22:58:13 +01002426 /* append a slash at the end of the location if needed and missing */
2427 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2428 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2429 if (chunk->data + 1 >= chunk->size)
2430 goto fail;
2431 chunk->area[chunk->data++] = '/';
2432 }
2433 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002434 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002435
Christopher Faulet99daf282018-11-28 22:58:13 +01002436 case REDIRECT_TYPE_PREFIX: {
2437 struct ist path;
2438
Christopher Faulet297fbb42019-05-13 14:41:27 +02002439 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002440 path = http_get_path(htx_sl_req_uri(sl));
2441 /* build message using path */
2442 if (path.ptr) {
2443 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2444 int qs = 0;
2445 while (qs < path.len) {
2446 if (*(path.ptr + qs) == '?') {
2447 path.len = qs;
2448 break;
2449 }
2450 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002451 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002452 }
2453 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002454 else
2455 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002456
Christopher Faulet99daf282018-11-28 22:58:13 +01002457 if (rule->rdr_str) { /* this is an old "redirect" rule */
2458 /* add prefix. Note that if prefix == "/", we don't want to
2459 * add anything, otherwise it makes it hard for the user to
2460 * configure a self-redirection.
2461 */
2462 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2463 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2464 goto fail;
2465 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002466 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002467 else {
2468 /* add prefix with executing log format */
2469 chunk->data += build_logline(s, chunk->area + chunk->data,
2470 chunk->size - chunk->data,
2471 &rule->rdr_fmt);
2472 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002473
Christopher Faulet99daf282018-11-28 22:58:13 +01002474 /* add path */
2475 if (!chunk_memcat(chunk, path.ptr, path.len))
2476 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002477
Christopher Faulet99daf282018-11-28 22:58:13 +01002478 /* append a slash at the end of the location if needed and missing */
2479 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2480 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2481 if (chunk->data + 1 >= chunk->size)
2482 goto fail;
2483 chunk->area[chunk->data++] = '/';
2484 }
2485 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002486 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002487 case REDIRECT_TYPE_LOCATION:
2488 default:
2489 if (rule->rdr_str) { /* this is an old "redirect" rule */
2490 /* add location */
2491 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2492 goto fail;
2493 }
2494 else {
2495 /* add location with executing log format */
2496 chunk->data += build_logline(s, chunk->area + chunk->data,
2497 chunk->size - chunk->data,
2498 &rule->rdr_fmt);
2499 }
2500 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002501 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002502 location = ist2(chunk->area, chunk->data);
2503
2504 /*
2505 * Create the 30x response
2506 */
2507 switch (rule->code) {
2508 case 308:
2509 status = ist("308");
2510 reason = ist("Permanent Redirect");
2511 break;
2512 case 307:
2513 status = ist("307");
2514 reason = ist("Temporary Redirect");
2515 break;
2516 case 303:
2517 status = ist("303");
2518 reason = ist("See Other");
2519 break;
2520 case 301:
2521 status = ist("301");
2522 reason = ist("Moved Permanently");
2523 break;
2524 case 302:
2525 default:
2526 status = ist("302");
2527 reason = ist("Found");
2528 break;
2529 }
2530
Christopher Faulet08e66462019-05-23 16:44:59 +02002531 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2532 close = 1;
2533
Christopher Faulet99daf282018-11-28 22:58:13 +01002534 htx = htx_from_buf(&res->buf);
2535 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2536 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2537 if (!sl)
2538 goto fail;
2539 sl->info.res.status = rule->code;
2540 s->txn->status = rule->code;
2541
Christopher Faulet08e66462019-05-23 16:44:59 +02002542 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2543 goto fail;
2544
2545 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002546 !htx_add_header(htx, ist("Location"), location))
2547 goto fail;
2548
2549 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2550 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2551 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002552 }
2553
2554 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002555 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2556 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002557 }
2558
Christopher Faulet99daf282018-11-28 22:58:13 +01002559 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2560 goto fail;
2561
Christopher Fauletf2824e62018-10-01 12:12:37 +02002562 /* let's log the request time */
2563 s->logs.tv_request = now;
2564
Christopher Faulet99daf282018-11-28 22:58:13 +01002565 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002566 c_adv(res, data);
2567 res->total += data;
2568
2569 channel_auto_read(req);
2570 channel_abort(req);
2571 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002572 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002573
2574 res->wex = tick_add_ifset(now_ms, res->wto);
2575 channel_auto_read(res);
2576 channel_auto_close(res);
2577 channel_shutr_now(res);
2578
2579 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002580
2581 if (!(s->flags & SF_ERR_MASK))
2582 s->flags |= SF_ERR_LOCAL;
2583 if (!(s->flags & SF_FINST_MASK))
2584 s->flags |= SF_FINST_R;
2585
Christopher Faulet99daf282018-11-28 22:58:13 +01002586 free_trash_chunk(chunk);
2587 return 1;
2588
2589 fail:
2590 /* If an error occurred, remove the incomplete HTTP response from the
2591 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002592 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002593 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002594 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002595}
2596
Christopher Faulet72333522018-10-24 11:25:02 +02002597int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2598 struct ist name, const char *str, struct my_regex *re, int action)
2599{
2600 struct http_hdr_ctx ctx;
2601 struct buffer *output = get_trash_chunk();
2602
2603 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2604 ctx.blk = NULL;
2605 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2606 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2607 continue;
2608
2609 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2610 if (output->data == -1)
2611 return -1;
2612 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2613 return -1;
2614 }
2615 return 0;
2616}
2617
2618static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2619 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2620{
2621 struct buffer *replace;
2622 int ret = -1;
2623
2624 replace = alloc_trash_chunk();
2625 if (!replace)
2626 goto leave;
2627
2628 replace->data = build_logline(s, replace->area, replace->size, fmt);
2629 if (replace->data >= replace->size - 1)
2630 goto leave;
2631
2632 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2633
2634 leave:
2635 free_trash_chunk(replace);
2636 return ret;
2637}
2638
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002639
2640/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2641 * on success and -1 on error. The response channel is updated accordingly.
2642 */
2643static int htx_reply_103_early_hints(struct channel *res)
2644{
2645 struct htx *htx = htx_from_buf(&res->buf);
2646 size_t data;
2647
2648 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2649 /* If an error occurred during an Early-hint rule,
2650 * remove the incomplete HTTP 103 response from the
2651 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002652 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002653 return -1;
2654 }
2655
2656 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002657 c_adv(res, data);
2658 res->total += data;
2659 return 0;
2660}
2661
Christopher Faulet6eb92892018-11-15 16:39:29 +01002662/*
2663 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2664 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002665 * If <early_hints> is 0, it is starts a new response by adding the start
2666 * line. If an error occurred -1 is returned. On success 0 is returned. The
2667 * channel is not updated here. It must be done calling the function
2668 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002669 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002670static 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 +01002671{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002672 struct channel *res = &s->res;
2673 struct htx *htx = htx_from_buf(&res->buf);
2674 struct buffer *value = alloc_trash_chunk();
2675
Christopher Faulet6eb92892018-11-15 16:39:29 +01002676 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002677 struct htx_sl *sl;
2678 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2679 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2680
2681 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2682 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2683 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002684 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002685 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002686 }
2687
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002688 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2689 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002690 goto fail;
2691
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002692 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002693 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002694
2695 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002696 /* If an error occurred during an Early-hint rule, remove the incomplete
2697 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002698 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002699 free_trash_chunk(value);
2700 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002701}
2702
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002703/* This function executes one of the set-{method,path,query,uri} actions. It
2704 * takes the string from the variable 'replace' with length 'len', then modifies
2705 * the relevant part of the request line accordingly. Then it updates various
2706 * pointers to the next elements which were moved, and the total buffer length.
2707 * It finds the action to be performed in p[2], previously filled by function
2708 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2709 * error, though this can be revisited when this code is finally exploited.
2710 *
2711 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2712 * query string and 3 to replace uri.
2713 *
2714 * In query string case, the mark question '?' must be set at the start of the
2715 * string by the caller, event if the replacement query string is empty.
2716 */
2717int htx_req_replace_stline(int action, const char *replace, int len,
2718 struct proxy *px, struct stream *s)
2719{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002720 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002721
2722 switch (action) {
2723 case 0: // method
2724 if (!http_replace_req_meth(htx, ist2(replace, len)))
2725 return -1;
2726 break;
2727
2728 case 1: // path
2729 if (!http_replace_req_path(htx, ist2(replace, len)))
2730 return -1;
2731 break;
2732
2733 case 2: // query
2734 if (!http_replace_req_query(htx, ist2(replace, len)))
2735 return -1;
2736 break;
2737
2738 case 3: // uri
2739 if (!http_replace_req_uri(htx, ist2(replace, len)))
2740 return -1;
2741 break;
2742
2743 default:
2744 return -1;
2745 }
2746 return 0;
2747}
2748
2749/* This function replace the HTTP status code and the associated message. The
2750 * variable <status> contains the new status code. This function never fails.
2751 */
2752void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2753{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002754 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002755 char *res;
2756
2757 chunk_reset(&trash);
2758 res = ultoa_o(status, trash.area, trash.size);
2759 trash.data = res - trash.area;
2760
2761 /* Do we have a custom reason format string? */
2762 if (reason == NULL)
2763 reason = http_get_reason(status);
2764
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002765 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002766 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2767}
2768
Christopher Faulet3e964192018-10-24 11:39:23 +02002769/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2770 * transaction <txn>. Returns the verdict of the first rule that prevents
2771 * further processing of the request (auth, deny, ...), and defaults to
2772 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2773 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2774 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2775 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2776 * status.
2777 */
2778static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2779 struct stream *s, int *deny_status)
2780{
2781 struct session *sess = strm_sess(s);
2782 struct http_txn *txn = s->txn;
2783 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002784 struct act_rule *rule;
2785 struct http_hdr_ctx ctx;
2786 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002787 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2788 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002789 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002790
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002791 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002792
2793 /* If "the current_rule_list" match the executed rule list, we are in
2794 * resume condition. If a resume is needed it is always in the action
2795 * and never in the ACL or converters. In this case, we initialise the
2796 * current rule, and go to the action execution point.
2797 */
2798 if (s->current_rule) {
2799 rule = s->current_rule;
2800 s->current_rule = NULL;
2801 if (s->current_rule_list == rules)
2802 goto resume_execution;
2803 }
2804 s->current_rule_list = rules;
2805
2806 list_for_each_entry(rule, rules, list) {
2807 /* check optional condition */
2808 if (rule->cond) {
2809 int ret;
2810
2811 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2812 ret = acl_pass(ret);
2813
2814 if (rule->cond->pol == ACL_COND_UNLESS)
2815 ret = !ret;
2816
2817 if (!ret) /* condition not matched */
2818 continue;
2819 }
2820
2821 act_flags |= ACT_FLAG_FIRST;
2822 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002823 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2824 early_hints = 0;
2825 if (htx_reply_103_early_hints(&s->res) == -1) {
2826 rule_ret = HTTP_RULE_RES_BADREQ;
2827 goto end;
2828 }
2829 }
2830
Christopher Faulet3e964192018-10-24 11:39:23 +02002831 switch (rule->action) {
2832 case ACT_ACTION_ALLOW:
2833 rule_ret = HTTP_RULE_RES_STOP;
2834 goto end;
2835
2836 case ACT_ACTION_DENY:
2837 if (deny_status)
2838 *deny_status = rule->deny_status;
2839 rule_ret = HTTP_RULE_RES_DENY;
2840 goto end;
2841
2842 case ACT_HTTP_REQ_TARPIT:
2843 txn->flags |= TX_CLTARPIT;
2844 if (deny_status)
2845 *deny_status = rule->deny_status;
2846 rule_ret = HTTP_RULE_RES_DENY;
2847 goto end;
2848
2849 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002850 /* Auth might be performed on regular http-req rules as well as on stats */
2851 auth_realm = rule->arg.auth.realm;
2852 if (!auth_realm) {
2853 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2854 auth_realm = STATS_DEFAULT_REALM;
2855 else
2856 auth_realm = px->id;
2857 }
2858 /* send 401/407 depending on whether we use a proxy or not. We still
2859 * count one error, because normal browsing won't significantly
2860 * increase the counter but brute force attempts will.
2861 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002862 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002863 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2864 rule_ret = HTTP_RULE_RES_BADREQ;
2865 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002866 goto end;
2867
2868 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002869 rule_ret = HTTP_RULE_RES_DONE;
2870 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2871 rule_ret = HTTP_RULE_RES_BADREQ;
2872 goto end;
2873
2874 case ACT_HTTP_SET_NICE:
2875 s->task->nice = rule->arg.nice;
2876 break;
2877
2878 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002879 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002880 break;
2881
2882 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002883 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002884 break;
2885
2886 case ACT_HTTP_SET_LOGL:
2887 s->logs.level = rule->arg.loglevel;
2888 break;
2889
2890 case ACT_HTTP_REPLACE_HDR:
2891 case ACT_HTTP_REPLACE_VAL:
2892 if (htx_transform_header(s, &s->req, htx,
2893 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2894 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002895 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002896 rule_ret = HTTP_RULE_RES_BADREQ;
2897 goto end;
2898 }
2899 break;
2900
2901 case ACT_HTTP_DEL_HDR:
2902 /* remove all occurrences of the header */
2903 ctx.blk = NULL;
2904 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2905 http_remove_header(htx, &ctx);
2906 break;
2907
2908 case ACT_HTTP_SET_HDR:
2909 case ACT_HTTP_ADD_HDR: {
2910 /* The scope of the trash buffer must be limited to this function. The
2911 * build_logline() function can execute a lot of other function which
2912 * can use the trash buffer. So for limiting the scope of this global
2913 * buffer, we build first the header value using build_logline, and
2914 * after we store the header name.
2915 */
2916 struct buffer *replace;
2917 struct ist n, v;
2918
2919 replace = alloc_trash_chunk();
2920 if (!replace) {
2921 rule_ret = HTTP_RULE_RES_BADREQ;
2922 goto end;
2923 }
2924
2925 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2926 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2927 v = ist2(replace->area, replace->data);
2928
2929 if (rule->action == ACT_HTTP_SET_HDR) {
2930 /* remove all occurrences of the header */
2931 ctx.blk = NULL;
2932 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2933 http_remove_header(htx, &ctx);
2934 }
2935
2936 if (!http_add_header(htx, n, v)) {
2937 static unsigned char rate_limit = 0;
2938
2939 if ((rate_limit++ & 255) == 0) {
2940 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);
2941 }
2942
Olivier Houcharda798bf52019-03-08 18:52:00 +01002943 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002944 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002945 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002946 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002947 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002948 }
2949 free_trash_chunk(replace);
2950 break;
2951 }
2952
2953 case ACT_HTTP_DEL_ACL:
2954 case ACT_HTTP_DEL_MAP: {
2955 struct pat_ref *ref;
2956 struct buffer *key;
2957
2958 /* collect reference */
2959 ref = pat_ref_lookup(rule->arg.map.ref);
2960 if (!ref)
2961 continue;
2962
2963 /* allocate key */
2964 key = alloc_trash_chunk();
2965 if (!key) {
2966 rule_ret = HTTP_RULE_RES_BADREQ;
2967 goto end;
2968 }
2969
2970 /* collect key */
2971 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2972 key->area[key->data] = '\0';
2973
2974 /* perform update */
2975 /* returned code: 1=ok, 0=ko */
2976 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2977 pat_ref_delete(ref, key->area);
2978 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2979
2980 free_trash_chunk(key);
2981 break;
2982 }
2983
2984 case ACT_HTTP_ADD_ACL: {
2985 struct pat_ref *ref;
2986 struct buffer *key;
2987
2988 /* collect reference */
2989 ref = pat_ref_lookup(rule->arg.map.ref);
2990 if (!ref)
2991 continue;
2992
2993 /* allocate key */
2994 key = alloc_trash_chunk();
2995 if (!key) {
2996 rule_ret = HTTP_RULE_RES_BADREQ;
2997 goto end;
2998 }
2999
3000 /* collect key */
3001 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3002 key->area[key->data] = '\0';
3003
3004 /* perform update */
3005 /* add entry only if it does not already exist */
3006 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3007 if (pat_ref_find_elt(ref, key->area) == NULL)
3008 pat_ref_add(ref, key->area, NULL, NULL);
3009 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3010
3011 free_trash_chunk(key);
3012 break;
3013 }
3014
3015 case ACT_HTTP_SET_MAP: {
3016 struct pat_ref *ref;
3017 struct buffer *key, *value;
3018
3019 /* collect reference */
3020 ref = pat_ref_lookup(rule->arg.map.ref);
3021 if (!ref)
3022 continue;
3023
3024 /* allocate key */
3025 key = alloc_trash_chunk();
3026 if (!key) {
3027 rule_ret = HTTP_RULE_RES_BADREQ;
3028 goto end;
3029 }
3030
3031 /* allocate value */
3032 value = alloc_trash_chunk();
3033 if (!value) {
3034 free_trash_chunk(key);
3035 rule_ret = HTTP_RULE_RES_BADREQ;
3036 goto end;
3037 }
3038
3039 /* collect key */
3040 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3041 key->area[key->data] = '\0';
3042
3043 /* collect value */
3044 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3045 value->area[value->data] = '\0';
3046
3047 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003048 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003049 if (pat_ref_find_elt(ref, key->area) != NULL)
3050 /* update entry if it exists */
3051 pat_ref_set(ref, key->area, value->area, NULL);
3052 else
3053 /* insert a new entry */
3054 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003055 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003056 free_trash_chunk(key);
3057 free_trash_chunk(value);
3058 break;
3059 }
3060
3061 case ACT_HTTP_EARLY_HINT:
3062 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3063 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003064 early_hints = htx_add_early_hint_header(s, early_hints,
3065 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003066 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003067 if (early_hints == -1) {
3068 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003069 goto end;
3070 }
3071 break;
3072
3073 case ACT_CUSTOM:
3074 if ((s->req.flags & CF_READ_ERROR) ||
3075 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003076 (px->options & PR_O_ABRT_CLOSE)))
3077 act_flags |= ACT_FLAG_FINAL;
3078
3079 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3080 case ACT_RET_ERR:
3081 case ACT_RET_CONT:
3082 break;
3083 case ACT_RET_STOP:
3084 rule_ret = HTTP_RULE_RES_DONE;
3085 goto end;
3086 case ACT_RET_YIELD:
3087 s->current_rule = rule;
3088 rule_ret = HTTP_RULE_RES_YIELD;
3089 goto end;
3090 }
3091 break;
3092
3093 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3094 /* Note: only the first valid tracking parameter of each
3095 * applies.
3096 */
3097
3098 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3099 struct stktable *t;
3100 struct stksess *ts;
3101 struct stktable_key *key;
3102 void *ptr1, *ptr2;
3103
3104 t = rule->arg.trk_ctr.table.t;
3105 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3106 rule->arg.trk_ctr.expr, NULL);
3107
3108 if (key && (ts = stktable_get_entry(t, key))) {
3109 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3110
3111 /* let's count a new HTTP request as it's the first time we do it */
3112 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3113 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3114 if (ptr1 || ptr2) {
3115 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3116
3117 if (ptr1)
3118 stktable_data_cast(ptr1, http_req_cnt)++;
3119
3120 if (ptr2)
3121 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3122 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3123
3124 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3125
3126 /* If data was modified, we need to touch to re-schedule sync */
3127 stktable_touch_local(t, ts, 0);
3128 }
3129
3130 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3131 if (sess->fe != s->be)
3132 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3133 }
3134 }
3135 break;
3136
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003137 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003138 default:
3139 break;
3140 }
3141 }
3142
3143 end:
3144 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003145 if (htx_reply_103_early_hints(&s->res) == -1)
3146 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003147 }
3148
3149 /* we reached the end of the rules, nothing to report */
3150 return rule_ret;
3151}
3152
3153/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3154 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3155 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3156 * is returned, the process can continue the evaluation of next rule list. If
3157 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3158 * is returned, it means the operation could not be processed and a server error
3159 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3160 * deny rule. If *YIELD is returned, the caller must call again the function
3161 * with the same context.
3162 */
3163static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3164 struct stream *s)
3165{
3166 struct session *sess = strm_sess(s);
3167 struct http_txn *txn = s->txn;
3168 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003169 struct act_rule *rule;
3170 struct http_hdr_ctx ctx;
3171 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3172 int act_flags = 0;
3173
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003174 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003175
3176 /* If "the current_rule_list" match the executed rule list, we are in
3177 * resume condition. If a resume is needed it is always in the action
3178 * and never in the ACL or converters. In this case, we initialise the
3179 * current rule, and go to the action execution point.
3180 */
3181 if (s->current_rule) {
3182 rule = s->current_rule;
3183 s->current_rule = NULL;
3184 if (s->current_rule_list == rules)
3185 goto resume_execution;
3186 }
3187 s->current_rule_list = rules;
3188
3189 list_for_each_entry(rule, rules, list) {
3190 /* check optional condition */
3191 if (rule->cond) {
3192 int ret;
3193
3194 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3195 ret = acl_pass(ret);
3196
3197 if (rule->cond->pol == ACL_COND_UNLESS)
3198 ret = !ret;
3199
3200 if (!ret) /* condition not matched */
3201 continue;
3202 }
3203
3204 act_flags |= ACT_FLAG_FIRST;
3205resume_execution:
3206 switch (rule->action) {
3207 case ACT_ACTION_ALLOW:
3208 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3209 goto end;
3210
3211 case ACT_ACTION_DENY:
3212 txn->flags |= TX_SVDENY;
3213 rule_ret = HTTP_RULE_RES_STOP;
3214 goto end;
3215
3216 case ACT_HTTP_SET_NICE:
3217 s->task->nice = rule->arg.nice;
3218 break;
3219
3220 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003221 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003222 break;
3223
3224 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003225 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003226 break;
3227
3228 case ACT_HTTP_SET_LOGL:
3229 s->logs.level = rule->arg.loglevel;
3230 break;
3231
3232 case ACT_HTTP_REPLACE_HDR:
3233 case ACT_HTTP_REPLACE_VAL:
3234 if (htx_transform_header(s, &s->res, htx,
3235 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3236 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003237 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003238 rule_ret = HTTP_RULE_RES_BADREQ;
3239 goto end;
3240 }
3241 break;
3242
3243 case ACT_HTTP_DEL_HDR:
3244 /* remove all occurrences of the header */
3245 ctx.blk = NULL;
3246 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3247 http_remove_header(htx, &ctx);
3248 break;
3249
3250 case ACT_HTTP_SET_HDR:
3251 case ACT_HTTP_ADD_HDR: {
3252 struct buffer *replace;
3253 struct ist n, v;
3254
3255 replace = alloc_trash_chunk();
3256 if (!replace) {
3257 rule_ret = HTTP_RULE_RES_BADREQ;
3258 goto end;
3259 }
3260
3261 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3262 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3263 v = ist2(replace->area, replace->data);
3264
3265 if (rule->action == ACT_HTTP_SET_HDR) {
3266 /* remove all occurrences of the header */
3267 ctx.blk = NULL;
3268 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3269 http_remove_header(htx, &ctx);
3270 }
3271
3272 if (!http_add_header(htx, n, v)) {
3273 static unsigned char rate_limit = 0;
3274
3275 if ((rate_limit++ & 255) == 0) {
3276 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);
3277 }
3278
Olivier Houcharda798bf52019-03-08 18:52:00 +01003279 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003280 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003281 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003282 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003283 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003284 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003285 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003286 }
3287 free_trash_chunk(replace);
3288 break;
3289 }
3290
3291 case ACT_HTTP_DEL_ACL:
3292 case ACT_HTTP_DEL_MAP: {
3293 struct pat_ref *ref;
3294 struct buffer *key;
3295
3296 /* collect reference */
3297 ref = pat_ref_lookup(rule->arg.map.ref);
3298 if (!ref)
3299 continue;
3300
3301 /* allocate key */
3302 key = alloc_trash_chunk();
3303 if (!key) {
3304 rule_ret = HTTP_RULE_RES_BADREQ;
3305 goto end;
3306 }
3307
3308 /* collect key */
3309 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3310 key->area[key->data] = '\0';
3311
3312 /* perform update */
3313 /* returned code: 1=ok, 0=ko */
3314 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3315 pat_ref_delete(ref, key->area);
3316 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3317
3318 free_trash_chunk(key);
3319 break;
3320 }
3321
3322 case ACT_HTTP_ADD_ACL: {
3323 struct pat_ref *ref;
3324 struct buffer *key;
3325
3326 /* collect reference */
3327 ref = pat_ref_lookup(rule->arg.map.ref);
3328 if (!ref)
3329 continue;
3330
3331 /* allocate key */
3332 key = alloc_trash_chunk();
3333 if (!key) {
3334 rule_ret = HTTP_RULE_RES_BADREQ;
3335 goto end;
3336 }
3337
3338 /* collect key */
3339 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3340 key->area[key->data] = '\0';
3341
3342 /* perform update */
3343 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003344 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003345 if (pat_ref_find_elt(ref, key->area) == NULL)
3346 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003347 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003348 free_trash_chunk(key);
3349 break;
3350 }
3351
3352 case ACT_HTTP_SET_MAP: {
3353 struct pat_ref *ref;
3354 struct buffer *key, *value;
3355
3356 /* collect reference */
3357 ref = pat_ref_lookup(rule->arg.map.ref);
3358 if (!ref)
3359 continue;
3360
3361 /* allocate key */
3362 key = alloc_trash_chunk();
3363 if (!key) {
3364 rule_ret = HTTP_RULE_RES_BADREQ;
3365 goto end;
3366 }
3367
3368 /* allocate value */
3369 value = alloc_trash_chunk();
3370 if (!value) {
3371 free_trash_chunk(key);
3372 rule_ret = HTTP_RULE_RES_BADREQ;
3373 goto end;
3374 }
3375
3376 /* collect key */
3377 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3378 key->area[key->data] = '\0';
3379
3380 /* collect value */
3381 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3382 value->area[value->data] = '\0';
3383
3384 /* perform update */
3385 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3386 if (pat_ref_find_elt(ref, key->area) != NULL)
3387 /* update entry if it exists */
3388 pat_ref_set(ref, key->area, value->area, NULL);
3389 else
3390 /* insert a new entry */
3391 pat_ref_add(ref, key->area, value->area, NULL);
3392 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3393 free_trash_chunk(key);
3394 free_trash_chunk(value);
3395 break;
3396 }
3397
3398 case ACT_HTTP_REDIR:
3399 rule_ret = HTTP_RULE_RES_DONE;
3400 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3401 rule_ret = HTTP_RULE_RES_BADREQ;
3402 goto end;
3403
3404 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3405 /* Note: only the first valid tracking parameter of each
3406 * applies.
3407 */
3408 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3409 struct stktable *t;
3410 struct stksess *ts;
3411 struct stktable_key *key;
3412 void *ptr;
3413
3414 t = rule->arg.trk_ctr.table.t;
3415 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3416 rule->arg.trk_ctr.expr, NULL);
3417
3418 if (key && (ts = stktable_get_entry(t, key))) {
3419 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3420
3421 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3422
3423 /* let's count a new HTTP request as it's the first time we do it */
3424 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3425 if (ptr)
3426 stktable_data_cast(ptr, http_req_cnt)++;
3427
3428 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3429 if (ptr)
3430 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3431 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3432
3433 /* When the client triggers a 4xx from the server, it's most often due
3434 * to a missing object or permission. These events should be tracked
3435 * because if they happen often, it may indicate a brute force or a
3436 * vulnerability scan. Normally this is done when receiving the response
3437 * but here we're tracking after this ought to have been done so we have
3438 * to do it on purpose.
3439 */
3440 if ((unsigned)(txn->status - 400) < 100) {
3441 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3442 if (ptr)
3443 stktable_data_cast(ptr, http_err_cnt)++;
3444
3445 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3446 if (ptr)
3447 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3448 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3449 }
3450
3451 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3452
3453 /* If data was modified, we need to touch to re-schedule sync */
3454 stktable_touch_local(t, ts, 0);
3455
3456 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3457 if (sess->fe != s->be)
3458 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3459 }
3460 }
3461 break;
3462
3463 case ACT_CUSTOM:
3464 if ((s->req.flags & CF_READ_ERROR) ||
3465 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003466 (px->options & PR_O_ABRT_CLOSE)))
3467 act_flags |= ACT_FLAG_FINAL;
3468
3469 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3470 case ACT_RET_ERR:
3471 case ACT_RET_CONT:
3472 break;
3473 case ACT_RET_STOP:
3474 rule_ret = HTTP_RULE_RES_STOP;
3475 goto end;
3476 case ACT_RET_YIELD:
3477 s->current_rule = rule;
3478 rule_ret = HTTP_RULE_RES_YIELD;
3479 goto end;
3480 }
3481 break;
3482
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003483 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003484 default:
3485 break;
3486 }
3487 }
3488
3489 end:
3490 /* we reached the end of the rules, nothing to report */
3491 return rule_ret;
3492}
3493
Christopher Faulet33640082018-10-24 11:53:01 +02003494/* Iterate the same filter through all request headers.
3495 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3496 * Since it can manage the switch to another backend, it updates the per-proxy
3497 * DENY stats.
3498 */
3499static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3500{
3501 struct http_txn *txn = s->txn;
3502 struct htx *htx;
3503 struct buffer *hdr = get_trash_chunk();
3504 int32_t pos;
3505
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003506 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003507
Christopher Fauleta3f15502019-05-13 15:27:23 +02003508 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003509 struct htx_blk *blk = htx_get_blk(htx, pos);
3510 enum htx_blk_type type;
3511 struct ist n, v;
3512
3513 next_hdr:
3514 type = htx_get_blk_type(blk);
3515 if (type == HTX_BLK_EOH)
3516 break;
3517 if (type != HTX_BLK_HDR)
3518 continue;
3519
3520 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3521 return 1;
3522 else if (unlikely(txn->flags & TX_CLALLOW) &&
3523 (exp->action == ACT_ALLOW ||
3524 exp->action == ACT_DENY ||
3525 exp->action == ACT_TARPIT))
3526 return 0;
3527
3528 n = htx_get_blk_name(htx, blk);
3529 v = htx_get_blk_value(htx, blk);
3530
Christopher Faulet02e771a2019-02-26 15:36:05 +01003531 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003532 hdr->area[hdr->data++] = ':';
3533 hdr->area[hdr->data++] = ' ';
3534 chunk_memcat(hdr, v.ptr, v.len);
3535
3536 /* Now we have one header in <hdr> */
3537
3538 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3539 struct http_hdr_ctx ctx;
3540 int len;
3541
3542 switch (exp->action) {
3543 case ACT_ALLOW:
3544 txn->flags |= TX_CLALLOW;
3545 goto end;
3546
3547 case ACT_DENY:
3548 txn->flags |= TX_CLDENY;
3549 goto end;
3550
3551 case ACT_TARPIT:
3552 txn->flags |= TX_CLTARPIT;
3553 goto end;
3554
3555 case ACT_REPLACE:
3556 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3557 if (len < 0)
3558 return -1;
3559
3560 http_parse_header(ist2(trash.area, len), &n, &v);
3561 ctx.blk = blk;
3562 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003563 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003564 if (!http_replace_header(htx, &ctx, n, v))
3565 return -1;
3566 if (!ctx.blk)
3567 goto end;
3568 pos = htx_get_blk_pos(htx, blk);
3569 break;
3570
3571 case ACT_REMOVE:
3572 ctx.blk = blk;
3573 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003574 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003575 if (!http_remove_header(htx, &ctx))
3576 return -1;
3577 if (!ctx.blk)
3578 goto end;
3579 pos = htx_get_blk_pos(htx, blk);
3580 goto next_hdr;
3581
3582 }
3583 }
3584 }
3585 end:
3586 return 0;
3587}
3588
3589/* Apply the filter to the request line.
3590 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3591 * or -1 if a replacement resulted in an invalid request line.
3592 * Since it can manage the switch to another backend, it updates the per-proxy
3593 * DENY stats.
3594 */
3595static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3596{
3597 struct http_txn *txn = s->txn;
3598 struct htx *htx;
3599 struct buffer *reqline = get_trash_chunk();
3600 int done;
3601
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003602 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003603
3604 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3605 return 1;
3606 else if (unlikely(txn->flags & TX_CLALLOW) &&
3607 (exp->action == ACT_ALLOW ||
3608 exp->action == ACT_DENY ||
3609 exp->action == ACT_TARPIT))
3610 return 0;
3611 else if (exp->action == ACT_REMOVE)
3612 return 0;
3613
3614 done = 0;
3615
Christopher Faulet297fbb42019-05-13 14:41:27 +02003616 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003617
3618 /* Now we have the request line between cur_ptr and cur_end */
3619 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003620 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003621 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003622 int len;
3623
3624 switch (exp->action) {
3625 case ACT_ALLOW:
3626 txn->flags |= TX_CLALLOW;
3627 done = 1;
3628 break;
3629
3630 case ACT_DENY:
3631 txn->flags |= TX_CLDENY;
3632 done = 1;
3633 break;
3634
3635 case ACT_TARPIT:
3636 txn->flags |= TX_CLTARPIT;
3637 done = 1;
3638 break;
3639
3640 case ACT_REPLACE:
3641 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3642 if (len < 0)
3643 return -1;
3644
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003645 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3646 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3647 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003648 return -1;
3649 done = 1;
3650 break;
3651 }
3652 }
3653 return done;
3654}
3655
3656/*
3657 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3658 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3659 * unparsable request. Since it can manage the switch to another backend, it
3660 * updates the per-proxy DENY stats.
3661 */
3662static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3663{
3664 struct session *sess = s->sess;
3665 struct http_txn *txn = s->txn;
3666 struct hdr_exp *exp;
3667
3668 for (exp = px->req_exp; exp; exp = exp->next) {
3669 int ret;
3670
3671 /*
3672 * The interleaving of transformations and verdicts
3673 * makes it difficult to decide to continue or stop
3674 * the evaluation.
3675 */
3676
3677 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3678 break;
3679
3680 if ((txn->flags & TX_CLALLOW) &&
3681 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3682 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3683 continue;
3684
3685 /* if this filter had a condition, evaluate it now and skip to
3686 * next filter if the condition does not match.
3687 */
3688 if (exp->cond) {
3689 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3690 ret = acl_pass(ret);
3691 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3692 ret = !ret;
3693
3694 if (!ret)
3695 continue;
3696 }
3697
3698 /* Apply the filter to the request line. */
3699 ret = htx_apply_filter_to_req_line(s, req, exp);
3700 if (unlikely(ret < 0))
3701 return -1;
3702
3703 if (likely(ret == 0)) {
3704 /* The filter did not match the request, it can be
3705 * iterated through all headers.
3706 */
3707 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3708 return -1;
3709 }
3710 }
3711 return 0;
3712}
3713
3714/* Iterate the same filter through all response headers contained in <res>.
3715 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3716 */
3717static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3718{
3719 struct http_txn *txn = s->txn;
3720 struct htx *htx;
3721 struct buffer *hdr = get_trash_chunk();
3722 int32_t pos;
3723
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003724 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003725
Christopher Fauleta3f15502019-05-13 15:27:23 +02003726 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003727 struct htx_blk *blk = htx_get_blk(htx, pos);
3728 enum htx_blk_type type;
3729 struct ist n, v;
3730
3731 next_hdr:
3732 type = htx_get_blk_type(blk);
3733 if (type == HTX_BLK_EOH)
3734 break;
3735 if (type != HTX_BLK_HDR)
3736 continue;
3737
3738 if (unlikely(txn->flags & TX_SVDENY))
3739 return 1;
3740 else if (unlikely(txn->flags & TX_SVALLOW) &&
3741 (exp->action == ACT_ALLOW ||
3742 exp->action == ACT_DENY))
3743 return 0;
3744
3745 n = htx_get_blk_name(htx, blk);
3746 v = htx_get_blk_value(htx, blk);
3747
Christopher Faulet02e771a2019-02-26 15:36:05 +01003748 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003749 hdr->area[hdr->data++] = ':';
3750 hdr->area[hdr->data++] = ' ';
3751 chunk_memcat(hdr, v.ptr, v.len);
3752
3753 /* Now we have one header in <hdr> */
3754
3755 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3756 struct http_hdr_ctx ctx;
3757 int len;
3758
3759 switch (exp->action) {
3760 case ACT_ALLOW:
3761 txn->flags |= TX_SVALLOW;
3762 goto end;
3763 break;
3764
3765 case ACT_DENY:
3766 txn->flags |= TX_SVDENY;
3767 goto end;
3768 break;
3769
3770 case ACT_REPLACE:
3771 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3772 if (len < 0)
3773 return -1;
3774
3775 http_parse_header(ist2(trash.area, len), &n, &v);
3776 ctx.blk = blk;
3777 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003778 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003779 if (!http_replace_header(htx, &ctx, n, v))
3780 return -1;
3781 if (!ctx.blk)
3782 goto end;
3783 pos = htx_get_blk_pos(htx, blk);
3784 break;
3785
3786 case ACT_REMOVE:
3787 ctx.blk = blk;
3788 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003789 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003790 if (!http_remove_header(htx, &ctx))
3791 return -1;
3792 if (!ctx.blk)
3793 goto end;
3794 pos = htx_get_blk_pos(htx, blk);
3795 goto next_hdr;
3796 }
3797 }
3798
3799 }
3800 end:
3801 return 0;
3802}
3803
3804/* Apply the filter to the status line in the response buffer <res>.
3805 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3806 * or -1 if a replacement resulted in an invalid status line.
3807 */
3808static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3809{
3810 struct http_txn *txn = s->txn;
3811 struct htx *htx;
3812 struct buffer *resline = get_trash_chunk();
3813 int done;
3814
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003815 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003816
3817 if (unlikely(txn->flags & TX_SVDENY))
3818 return 1;
3819 else if (unlikely(txn->flags & TX_SVALLOW) &&
3820 (exp->action == ACT_ALLOW ||
3821 exp->action == ACT_DENY))
3822 return 0;
3823 else if (exp->action == ACT_REMOVE)
3824 return 0;
3825
3826 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003827 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003828
3829 /* Now we have the status line between cur_ptr and cur_end */
3830 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003831 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003832 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003833 int len;
3834
3835 switch (exp->action) {
3836 case ACT_ALLOW:
3837 txn->flags |= TX_SVALLOW;
3838 done = 1;
3839 break;
3840
3841 case ACT_DENY:
3842 txn->flags |= TX_SVDENY;
3843 done = 1;
3844 break;
3845
3846 case ACT_REPLACE:
3847 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3848 if (len < 0)
3849 return -1;
3850
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003851 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3852 sl->info.res.status = strl2ui(code.ptr, code.len);
3853 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003854 return -1;
3855
3856 done = 1;
3857 return 1;
3858 }
3859 }
3860 return done;
3861}
3862
3863/*
3864 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3865 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3866 * unparsable response.
3867 */
3868static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3869{
3870 struct session *sess = s->sess;
3871 struct http_txn *txn = s->txn;
3872 struct hdr_exp *exp;
3873
3874 for (exp = px->rsp_exp; exp; exp = exp->next) {
3875 int ret;
3876
3877 /*
3878 * The interleaving of transformations and verdicts
3879 * makes it difficult to decide to continue or stop
3880 * the evaluation.
3881 */
3882
3883 if (txn->flags & TX_SVDENY)
3884 break;
3885
3886 if ((txn->flags & TX_SVALLOW) &&
3887 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3888 exp->action == ACT_PASS)) {
3889 exp = exp->next;
3890 continue;
3891 }
3892
3893 /* if this filter had a condition, evaluate it now and skip to
3894 * next filter if the condition does not match.
3895 */
3896 if (exp->cond) {
3897 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3898 ret = acl_pass(ret);
3899 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3900 ret = !ret;
3901 if (!ret)
3902 continue;
3903 }
3904
3905 /* Apply the filter to the status line. */
3906 ret = htx_apply_filter_to_sts_line(s, res, exp);
3907 if (unlikely(ret < 0))
3908 return -1;
3909
3910 if (likely(ret == 0)) {
3911 /* The filter did not match the response, it can be
3912 * iterated through all headers.
3913 */
3914 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3915 return -1;
3916 }
3917 }
3918 return 0;
3919}
3920
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003921/*
3922 * Manage client-side cookie. It can impact performance by about 2% so it is
3923 * desirable to call it only when needed. This code is quite complex because
3924 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3925 * highly recommended not to touch this part without a good reason !
3926 */
3927static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3928{
3929 struct session *sess = s->sess;
3930 struct http_txn *txn = s->txn;
3931 struct htx *htx;
3932 struct http_hdr_ctx ctx;
3933 char *hdr_beg, *hdr_end, *del_from;
3934 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3935 int preserve_hdr;
3936
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003937 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003938 ctx.blk = NULL;
3939 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3940 del_from = NULL; /* nothing to be deleted */
3941 preserve_hdr = 0; /* assume we may kill the whole header */
3942
3943 /* Now look for cookies. Conforming to RFC2109, we have to support
3944 * attributes whose name begin with a '$', and associate them with
3945 * the right cookie, if we want to delete this cookie.
3946 * So there are 3 cases for each cookie read :
3947 * 1) it's a special attribute, beginning with a '$' : ignore it.
3948 * 2) it's a server id cookie that we *MAY* want to delete : save
3949 * some pointers on it (last semi-colon, beginning of cookie...)
3950 * 3) it's an application cookie : we *MAY* have to delete a previous
3951 * "special" cookie.
3952 * At the end of loop, if a "special" cookie remains, we may have to
3953 * remove it. If no application cookie persists in the header, we
3954 * *MUST* delete it.
3955 *
3956 * Note: RFC2965 is unclear about the processing of spaces around
3957 * the equal sign in the ATTR=VALUE form. A careful inspection of
3958 * the RFC explicitly allows spaces before it, and not within the
3959 * tokens (attrs or values). An inspection of RFC2109 allows that
3960 * too but section 10.1.3 lets one think that spaces may be allowed
3961 * after the equal sign too, resulting in some (rare) buggy
3962 * implementations trying to do that. So let's do what servers do.
3963 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3964 * allowed quoted strings in values, with any possible character
3965 * after a backslash, including control chars and delimitors, which
3966 * causes parsing to become ambiguous. Browsers also allow spaces
3967 * within values even without quotes.
3968 *
3969 * We have to keep multiple pointers in order to support cookie
3970 * removal at the beginning, middle or end of header without
3971 * corrupting the header. All of these headers are valid :
3972 *
3973 * hdr_beg hdr_end
3974 * | |
3975 * v |
3976 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3977 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3978 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3979 * | | | | | | |
3980 * | | | | | | |
3981 * | | | | | | +--> next
3982 * | | | | | +----> val_end
3983 * | | | | +-----------> val_beg
3984 * | | | +--------------> equal
3985 * | | +----------------> att_end
3986 * | +---------------------> att_beg
3987 * +--------------------------> prev
3988 *
3989 */
3990 hdr_beg = ctx.value.ptr;
3991 hdr_end = hdr_beg + ctx.value.len;
3992 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3993 /* Iterate through all cookies on this line */
3994
3995 /* find att_beg */
3996 att_beg = prev;
3997 if (prev > hdr_beg)
3998 att_beg++;
3999
4000 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4001 att_beg++;
4002
4003 /* find att_end : this is the first character after the last non
4004 * space before the equal. It may be equal to hdr_end.
4005 */
4006 equal = att_end = att_beg;
4007 while (equal < hdr_end) {
4008 if (*equal == '=' || *equal == ',' || *equal == ';')
4009 break;
4010 if (HTTP_IS_SPHT(*equal++))
4011 continue;
4012 att_end = equal;
4013 }
4014
4015 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4016 * is between <att_beg> and <equal>, both may be identical.
4017 */
4018 /* look for end of cookie if there is an equal sign */
4019 if (equal < hdr_end && *equal == '=') {
4020 /* look for the beginning of the value */
4021 val_beg = equal + 1;
4022 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4023 val_beg++;
4024
4025 /* find the end of the value, respecting quotes */
4026 next = http_find_cookie_value_end(val_beg, hdr_end);
4027
4028 /* make val_end point to the first white space or delimitor after the value */
4029 val_end = next;
4030 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4031 val_end--;
4032 }
4033 else
4034 val_beg = val_end = next = equal;
4035
4036 /* We have nothing to do with attributes beginning with
4037 * '$'. However, they will automatically be removed if a
4038 * header before them is removed, since they're supposed
4039 * to be linked together.
4040 */
4041 if (*att_beg == '$')
4042 continue;
4043
4044 /* Ignore cookies with no equal sign */
4045 if (equal == next) {
4046 /* This is not our cookie, so we must preserve it. But if we already
4047 * scheduled another cookie for removal, we cannot remove the
4048 * complete header, but we can remove the previous block itself.
4049 */
4050 preserve_hdr = 1;
4051 if (del_from != NULL) {
4052 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4053 val_end += delta;
4054 next += delta;
4055 hdr_end += delta;
4056 prev = del_from;
4057 del_from = NULL;
4058 }
4059 continue;
4060 }
4061
4062 /* if there are spaces around the equal sign, we need to
4063 * strip them otherwise we'll get trouble for cookie captures,
4064 * or even for rewrites. Since this happens extremely rarely,
4065 * it does not hurt performance.
4066 */
4067 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4068 int stripped_before = 0;
4069 int stripped_after = 0;
4070
4071 if (att_end != equal) {
4072 memmove(att_end, equal, hdr_end - equal);
4073 stripped_before = (att_end - equal);
4074 equal += stripped_before;
4075 val_beg += stripped_before;
4076 }
4077
4078 if (val_beg > equal + 1) {
4079 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4080 stripped_after = (equal + 1) - val_beg;
4081 val_beg += stripped_after;
4082 stripped_before += stripped_after;
4083 }
4084
4085 val_end += stripped_before;
4086 next += stripped_before;
4087 hdr_end += stripped_before;
4088 }
4089 /* now everything is as on the diagram above */
4090
4091 /* First, let's see if we want to capture this cookie. We check
4092 * that we don't already have a client side cookie, because we
4093 * can only capture one. Also as an optimisation, we ignore
4094 * cookies shorter than the declared name.
4095 */
4096 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4097 (val_end - att_beg >= sess->fe->capture_namelen) &&
4098 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4099 int log_len = val_end - att_beg;
4100
4101 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4102 ha_alert("HTTP logging : out of memory.\n");
4103 } else {
4104 if (log_len > sess->fe->capture_len)
4105 log_len = sess->fe->capture_len;
4106 memcpy(txn->cli_cookie, att_beg, log_len);
4107 txn->cli_cookie[log_len] = 0;
4108 }
4109 }
4110
4111 /* Persistence cookies in passive, rewrite or insert mode have the
4112 * following form :
4113 *
4114 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4115 *
4116 * For cookies in prefix mode, the form is :
4117 *
4118 * Cookie: NAME=SRV~VALUE
4119 */
4120 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4121 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4122 struct server *srv = s->be->srv;
4123 char *delim;
4124
4125 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4126 * have the server ID between val_beg and delim, and the original cookie between
4127 * delim+1 and val_end. Otherwise, delim==val_end :
4128 *
4129 * hdr_beg
4130 * |
4131 * v
4132 * NAME=SRV; # in all but prefix modes
4133 * NAME=SRV~OPAQUE ; # in prefix mode
4134 * || || | |+-> next
4135 * || || | +--> val_end
4136 * || || +---------> delim
4137 * || |+------------> val_beg
4138 * || +-------------> att_end = equal
4139 * |+-----------------> att_beg
4140 * +------------------> prev
4141 *
4142 */
4143 if (s->be->ck_opts & PR_CK_PFX) {
4144 for (delim = val_beg; delim < val_end; delim++)
4145 if (*delim == COOKIE_DELIM)
4146 break;
4147 }
4148 else {
4149 char *vbar1;
4150 delim = val_end;
4151 /* Now check if the cookie contains a date field, which would
4152 * appear after a vertical bar ('|') just after the server name
4153 * and before the delimiter.
4154 */
4155 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4156 if (vbar1) {
4157 /* OK, so left of the bar is the server's cookie and
4158 * right is the last seen date. It is a base64 encoded
4159 * 30-bit value representing the UNIX date since the
4160 * epoch in 4-second quantities.
4161 */
4162 int val;
4163 delim = vbar1++;
4164 if (val_end - vbar1 >= 5) {
4165 val = b64tos30(vbar1);
4166 if (val > 0)
4167 txn->cookie_last_date = val << 2;
4168 }
4169 /* look for a second vertical bar */
4170 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4171 if (vbar1 && (val_end - vbar1 > 5)) {
4172 val = b64tos30(vbar1 + 1);
4173 if (val > 0)
4174 txn->cookie_first_date = val << 2;
4175 }
4176 }
4177 }
4178
4179 /* if the cookie has an expiration date and the proxy wants to check
4180 * it, then we do that now. We first check if the cookie is too old,
4181 * then only if it has expired. We detect strict overflow because the
4182 * time resolution here is not great (4 seconds). Cookies with dates
4183 * in the future are ignored if their offset is beyond one day. This
4184 * allows an admin to fix timezone issues without expiring everyone
4185 * and at the same time avoids keeping unwanted side effects for too
4186 * long.
4187 */
4188 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4189 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4190 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4191 txn->flags &= ~TX_CK_MASK;
4192 txn->flags |= TX_CK_OLD;
4193 delim = val_beg; // let's pretend we have not found the cookie
4194 txn->cookie_first_date = 0;
4195 txn->cookie_last_date = 0;
4196 }
4197 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4198 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4199 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4200 txn->flags &= ~TX_CK_MASK;
4201 txn->flags |= TX_CK_EXPIRED;
4202 delim = val_beg; // let's pretend we have not found the cookie
4203 txn->cookie_first_date = 0;
4204 txn->cookie_last_date = 0;
4205 }
4206
4207 /* Here, we'll look for the first running server which supports the cookie.
4208 * This allows to share a same cookie between several servers, for example
4209 * to dedicate backup servers to specific servers only.
4210 * However, to prevent clients from sticking to cookie-less backup server
4211 * when they have incidentely learned an empty cookie, we simply ignore
4212 * empty cookies and mark them as invalid.
4213 * The same behaviour is applied when persistence must be ignored.
4214 */
4215 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4216 srv = NULL;
4217
4218 while (srv) {
4219 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4220 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4221 if ((srv->cur_state != SRV_ST_STOPPED) ||
4222 (s->be->options & PR_O_PERSIST) ||
4223 (s->flags & SF_FORCE_PRST)) {
4224 /* we found the server and we can use it */
4225 txn->flags &= ~TX_CK_MASK;
4226 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4227 s->flags |= SF_DIRECT | SF_ASSIGNED;
4228 s->target = &srv->obj_type;
4229 break;
4230 } else {
4231 /* we found a server, but it's down,
4232 * mark it as such and go on in case
4233 * another one is available.
4234 */
4235 txn->flags &= ~TX_CK_MASK;
4236 txn->flags |= TX_CK_DOWN;
4237 }
4238 }
4239 srv = srv->next;
4240 }
4241
4242 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4243 /* no server matched this cookie or we deliberately skipped it */
4244 txn->flags &= ~TX_CK_MASK;
4245 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4246 txn->flags |= TX_CK_UNUSED;
4247 else
4248 txn->flags |= TX_CK_INVALID;
4249 }
4250
4251 /* depending on the cookie mode, we may have to either :
4252 * - delete the complete cookie if we're in insert+indirect mode, so that
4253 * the server never sees it ;
4254 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004255 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004256 * if we're in cookie prefix mode
4257 */
4258 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4259 int delta; /* negative */
4260
4261 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4262 delta = val_beg - (delim + 1);
4263 val_end += delta;
4264 next += delta;
4265 hdr_end += delta;
4266 del_from = NULL;
4267 preserve_hdr = 1; /* we want to keep this cookie */
4268 }
4269 else if (del_from == NULL &&
4270 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4271 del_from = prev;
4272 }
4273 }
4274 else {
4275 /* This is not our cookie, so we must preserve it. But if we already
4276 * scheduled another cookie for removal, we cannot remove the
4277 * complete header, but we can remove the previous block itself.
4278 */
4279 preserve_hdr = 1;
4280
4281 if (del_from != NULL) {
4282 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4283 if (att_beg >= del_from)
4284 att_beg += delta;
4285 if (att_end >= del_from)
4286 att_end += delta;
4287 val_beg += delta;
4288 val_end += delta;
4289 next += delta;
4290 hdr_end += delta;
4291 prev = del_from;
4292 del_from = NULL;
4293 }
4294 }
4295
4296 /* continue with next cookie on this header line */
4297 att_beg = next;
4298 } /* for each cookie */
4299
4300
4301 /* There are no more cookies on this line.
4302 * We may still have one (or several) marked for deletion at the
4303 * end of the line. We must do this now in two ways :
4304 * - if some cookies must be preserved, we only delete from the
4305 * mark to the end of line ;
4306 * - if nothing needs to be preserved, simply delete the whole header
4307 */
4308 if (del_from) {
4309 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4310 }
4311 if ((hdr_end - hdr_beg) != ctx.value.len) {
4312 if (hdr_beg != hdr_end) {
4313 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004314 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004315 }
4316 else
4317 http_remove_header(htx, &ctx);
4318 }
4319 } /* for each "Cookie header */
4320}
4321
4322/*
4323 * Manage server-side cookies. It can impact performance by about 2% so it is
4324 * desirable to call it only when needed. This function is also used when we
4325 * just need to know if there is a cookie (eg: for check-cache).
4326 */
4327static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4328{
4329 struct session *sess = s->sess;
4330 struct http_txn *txn = s->txn;
4331 struct htx *htx;
4332 struct http_hdr_ctx ctx;
4333 struct server *srv;
4334 char *hdr_beg, *hdr_end;
4335 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004336 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004337
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004338 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004339
4340 ctx.blk = NULL;
4341 while (1) {
4342 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4343 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4344 break;
4345 is_cookie2 = 1;
4346 }
4347
4348 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4349 * <prev> points to the colon.
4350 */
4351 txn->flags |= TX_SCK_PRESENT;
4352
4353 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4354 * check-cache is enabled) and we are not interested in checking
4355 * them. Warning, the cookie capture is declared in the frontend.
4356 */
4357 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4358 break;
4359
4360 /* OK so now we know we have to process this response cookie.
4361 * The format of the Set-Cookie header is slightly different
4362 * from the format of the Cookie header in that it does not
4363 * support the comma as a cookie delimiter (thus the header
4364 * cannot be folded) because the Expires attribute described in
4365 * the original Netscape's spec may contain an unquoted date
4366 * with a comma inside. We have to live with this because
4367 * many browsers don't support Max-Age and some browsers don't
4368 * support quoted strings. However the Set-Cookie2 header is
4369 * clean.
4370 *
4371 * We have to keep multiple pointers in order to support cookie
4372 * removal at the beginning, middle or end of header without
4373 * corrupting the header (in case of set-cookie2). A special
4374 * pointer, <scav> points to the beginning of the set-cookie-av
4375 * fields after the first semi-colon. The <next> pointer points
4376 * either to the end of line (set-cookie) or next unquoted comma
4377 * (set-cookie2). All of these headers are valid :
4378 *
4379 * hdr_beg hdr_end
4380 * | |
4381 * v |
4382 * NAME1 = VALUE 1 ; Secure; Path="/" |
4383 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4384 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4385 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4386 * | | | | | | | |
4387 * | | | | | | | +-> next
4388 * | | | | | | +------------> scav
4389 * | | | | | +--------------> val_end
4390 * | | | | +--------------------> val_beg
4391 * | | | +----------------------> equal
4392 * | | +------------------------> att_end
4393 * | +----------------------------> att_beg
4394 * +------------------------------> prev
4395 * -------------------------------> hdr_beg
4396 */
4397 hdr_beg = ctx.value.ptr;
4398 hdr_end = hdr_beg + ctx.value.len;
4399 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4400
4401 /* Iterate through all cookies on this line */
4402
4403 /* find att_beg */
4404 att_beg = prev;
4405 if (prev > hdr_beg)
4406 att_beg++;
4407
4408 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4409 att_beg++;
4410
4411 /* find att_end : this is the first character after the last non
4412 * space before the equal. It may be equal to hdr_end.
4413 */
4414 equal = att_end = att_beg;
4415
4416 while (equal < hdr_end) {
4417 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4418 break;
4419 if (HTTP_IS_SPHT(*equal++))
4420 continue;
4421 att_end = equal;
4422 }
4423
4424 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4425 * is between <att_beg> and <equal>, both may be identical.
4426 */
4427
4428 /* look for end of cookie if there is an equal sign */
4429 if (equal < hdr_end && *equal == '=') {
4430 /* look for the beginning of the value */
4431 val_beg = equal + 1;
4432 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4433 val_beg++;
4434
4435 /* find the end of the value, respecting quotes */
4436 next = http_find_cookie_value_end(val_beg, hdr_end);
4437
4438 /* make val_end point to the first white space or delimitor after the value */
4439 val_end = next;
4440 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4441 val_end--;
4442 }
4443 else {
4444 /* <equal> points to next comma, semi-colon or EOL */
4445 val_beg = val_end = next = equal;
4446 }
4447
4448 if (next < hdr_end) {
4449 /* Set-Cookie2 supports multiple cookies, and <next> points to
4450 * a colon or semi-colon before the end. So skip all attr-value
4451 * pairs and look for the next comma. For Set-Cookie, since
4452 * commas are permitted in values, skip to the end.
4453 */
4454 if (is_cookie2)
4455 next = http_find_hdr_value_end(next, hdr_end);
4456 else
4457 next = hdr_end;
4458 }
4459
4460 /* Now everything is as on the diagram above */
4461
4462 /* Ignore cookies with no equal sign */
4463 if (equal == val_end)
4464 continue;
4465
4466 /* If there are spaces around the equal sign, we need to
4467 * strip them otherwise we'll get trouble for cookie captures,
4468 * or even for rewrites. Since this happens extremely rarely,
4469 * it does not hurt performance.
4470 */
4471 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4472 int stripped_before = 0;
4473 int stripped_after = 0;
4474
4475 if (att_end != equal) {
4476 memmove(att_end, equal, hdr_end - equal);
4477 stripped_before = (att_end - equal);
4478 equal += stripped_before;
4479 val_beg += stripped_before;
4480 }
4481
4482 if (val_beg > equal + 1) {
4483 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4484 stripped_after = (equal + 1) - val_beg;
4485 val_beg += stripped_after;
4486 stripped_before += stripped_after;
4487 }
4488
4489 val_end += stripped_before;
4490 next += stripped_before;
4491 hdr_end += stripped_before;
4492
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004493 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4494 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004495 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004496 }
4497
4498 /* First, let's see if we want to capture this cookie. We check
4499 * that we don't already have a server side cookie, because we
4500 * can only capture one. Also as an optimisation, we ignore
4501 * cookies shorter than the declared name.
4502 */
4503 if (sess->fe->capture_name != NULL &&
4504 txn->srv_cookie == NULL &&
4505 (val_end - att_beg >= sess->fe->capture_namelen) &&
4506 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4507 int log_len = val_end - att_beg;
4508 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4509 ha_alert("HTTP logging : out of memory.\n");
4510 }
4511 else {
4512 if (log_len > sess->fe->capture_len)
4513 log_len = sess->fe->capture_len;
4514 memcpy(txn->srv_cookie, att_beg, log_len);
4515 txn->srv_cookie[log_len] = 0;
4516 }
4517 }
4518
4519 srv = objt_server(s->target);
4520 /* now check if we need to process it for persistence */
4521 if (!(s->flags & SF_IGNORE_PRST) &&
4522 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4523 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4524 /* assume passive cookie by default */
4525 txn->flags &= ~TX_SCK_MASK;
4526 txn->flags |= TX_SCK_FOUND;
4527
4528 /* If the cookie is in insert mode on a known server, we'll delete
4529 * this occurrence because we'll insert another one later.
4530 * We'll delete it too if the "indirect" option is set and we're in
4531 * a direct access.
4532 */
4533 if (s->be->ck_opts & PR_CK_PSV) {
4534 /* The "preserve" flag was set, we don't want to touch the
4535 * server's cookie.
4536 */
4537 }
4538 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4539 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4540 /* this cookie must be deleted */
4541 if (prev == hdr_beg && next == hdr_end) {
4542 /* whole header */
4543 http_remove_header(htx, &ctx);
4544 /* note: while both invalid now, <next> and <hdr_end>
4545 * are still equal, so the for() will stop as expected.
4546 */
4547 } else {
4548 /* just remove the value */
4549 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4550 next = prev;
4551 hdr_end += delta;
4552 }
4553 txn->flags &= ~TX_SCK_MASK;
4554 txn->flags |= TX_SCK_DELETED;
4555 /* and go on with next cookie */
4556 }
4557 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4558 /* replace bytes val_beg->val_end with the cookie name associated
4559 * with this server since we know it.
4560 */
4561 int sliding, delta;
4562
4563 ctx.value = ist2(val_beg, val_end - val_beg);
4564 ctx.lws_before = ctx.lws_after = 0;
4565 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4566 delta = srv->cklen - (val_end - val_beg);
4567 sliding = (ctx.value.ptr - val_beg);
4568 hdr_beg += sliding;
4569 val_beg += sliding;
4570 next += sliding + delta;
4571 hdr_end += sliding + delta;
4572
4573 txn->flags &= ~TX_SCK_MASK;
4574 txn->flags |= TX_SCK_REPLACED;
4575 }
4576 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4577 /* insert the cookie name associated with this server
4578 * before existing cookie, and insert a delimiter between them..
4579 */
4580 int sliding, delta;
4581 ctx.value = ist2(val_beg, 0);
4582 ctx.lws_before = ctx.lws_after = 0;
4583 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4584 delta = srv->cklen + 1;
4585 sliding = (ctx.value.ptr - val_beg);
4586 hdr_beg += sliding;
4587 val_beg += sliding;
4588 next += sliding + delta;
4589 hdr_end += sliding + delta;
4590
4591 val_beg[srv->cklen] = COOKIE_DELIM;
4592 txn->flags &= ~TX_SCK_MASK;
4593 txn->flags |= TX_SCK_REPLACED;
4594 }
4595 }
4596 /* that's done for this cookie, check the next one on the same
4597 * line when next != hdr_end (only if is_cookie2).
4598 */
4599 }
4600 }
4601}
4602
Christopher Faulet25a02f62018-10-24 12:00:25 +02004603/*
4604 * Parses the Cache-Control and Pragma request header fields to determine if
4605 * the request may be served from the cache and/or if it is cacheable. Updates
4606 * s->txn->flags.
4607 */
4608void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4609{
4610 struct http_txn *txn = s->txn;
4611 struct htx *htx;
4612 int32_t pos;
4613 int pragma_found, cc_found, i;
4614
4615 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4616 return; /* nothing more to do here */
4617
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004618 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004619 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004620 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004621 struct htx_blk *blk = htx_get_blk(htx, pos);
4622 enum htx_blk_type type = htx_get_blk_type(blk);
4623 struct ist n, v;
4624
4625 if (type == HTX_BLK_EOH)
4626 break;
4627 if (type != HTX_BLK_HDR)
4628 continue;
4629
4630 n = htx_get_blk_name(htx, blk);
4631 v = htx_get_blk_value(htx, blk);
4632
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004633 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004634 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4635 pragma_found = 1;
4636 continue;
4637 }
4638 }
4639
4640 /* Don't use the cache and don't try to store if we found the
4641 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004642 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004643 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4644 txn->flags |= TX_CACHE_IGNORE;
4645 continue;
4646 }
4647
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004648 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004649 continue;
4650
4651 /* OK, right now we know we have a cache-control header */
4652 cc_found = 1;
4653 if (!v.len) /* no info */
4654 continue;
4655
4656 i = 0;
4657 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4658 !isspace((unsigned char)*(v.ptr+i)))
4659 i++;
4660
4661 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4662 * values after max-age, max-stale nor min-fresh, we simply don't
4663 * use the cache when they're specified.
4664 */
4665 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4666 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4667 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4668 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4669 txn->flags |= TX_CACHE_IGNORE;
4670 continue;
4671 }
4672
4673 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4674 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4675 continue;
4676 }
4677 }
4678
4679 /* RFC7234#5.4:
4680 * When the Cache-Control header field is also present and
4681 * understood in a request, Pragma is ignored.
4682 * When the Cache-Control header field is not present in a
4683 * request, caches MUST consider the no-cache request
4684 * pragma-directive as having the same effect as if
4685 * "Cache-Control: no-cache" were present.
4686 */
4687 if (!cc_found && pragma_found)
4688 txn->flags |= TX_CACHE_IGNORE;
4689}
4690
4691/*
4692 * Check if response is cacheable or not. Updates s->txn->flags.
4693 */
4694void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4695{
4696 struct http_txn *txn = s->txn;
4697 struct htx *htx;
4698 int32_t pos;
4699 int i;
4700
4701 if (txn->status < 200) {
4702 /* do not try to cache interim responses! */
4703 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4704 return;
4705 }
4706
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004707 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004708 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004709 struct htx_blk *blk = htx_get_blk(htx, pos);
4710 enum htx_blk_type type = htx_get_blk_type(blk);
4711 struct ist n, v;
4712
4713 if (type == HTX_BLK_EOH)
4714 break;
4715 if (type != HTX_BLK_HDR)
4716 continue;
4717
4718 n = htx_get_blk_name(htx, blk);
4719 v = htx_get_blk_value(htx, blk);
4720
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004721 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004722 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4723 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4724 return;
4725 }
4726 }
4727
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004728 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004729 continue;
4730
4731 /* OK, right now we know we have a cache-control header */
4732 if (!v.len) /* no info */
4733 continue;
4734
4735 i = 0;
4736 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4737 !isspace((unsigned char)*(v.ptr+i)))
4738 i++;
4739
4740 /* we have a complete value between v.ptr and (v.ptr+i) */
4741 if (i < v.len && *(v.ptr + i) == '=') {
4742 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4743 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4744 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4745 continue;
4746 }
4747
4748 /* we have something of the form no-cache="set-cookie" */
4749 if ((v.len >= 21) &&
4750 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4751 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4752 txn->flags &= ~TX_CACHE_COOK;
4753 continue;
4754 }
4755
4756 /* OK, so we know that either p2 points to the end of string or to a comma */
4757 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4758 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4759 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4760 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4761 return;
4762 }
4763
4764 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4765 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4766 continue;
4767 }
4768 }
4769}
4770
Christopher Faulet64159df2018-10-24 21:15:35 +02004771/* send a server's name with an outgoing request over an established connection.
4772 * Note: this function is designed to be called once the request has been
4773 * scheduled for being forwarded. This is the reason why the number of forwarded
4774 * bytes have to be adjusted.
4775 */
4776int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4777{
4778 struct htx *htx;
4779 struct http_hdr_ctx ctx;
4780 struct ist hdr;
4781 uint32_t data;
4782
4783 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004784 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004785 data = htx->data;
4786
4787 ctx.blk = NULL;
4788 while (http_find_header(htx, hdr, &ctx, 1))
4789 http_remove_header(htx, &ctx);
4790 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4791
4792 if (co_data(&s->req)) {
4793 if (data >= htx->data)
4794 c_rew(&s->req, data - htx->data);
4795 else
4796 c_adv(&s->req, htx->data - data);
4797 }
4798 return 0;
4799}
4800
Christopher Faulet377c5a52018-10-24 21:21:30 +02004801/*
4802 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4803 * for the current backend.
4804 *
4805 * It is assumed that the request is either a HEAD, GET, or POST and that the
4806 * uri_auth field is valid.
4807 *
4808 * Returns 1 if stats should be provided, otherwise 0.
4809 */
4810static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4811{
4812 struct uri_auth *uri_auth = backend->uri_auth;
4813 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004814 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004815 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004816
4817 if (!uri_auth)
4818 return 0;
4819
4820 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4821 return 0;
4822
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004823 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004824 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004825 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004826
4827 /* check URI size */
4828 if (uri_auth->uri_len > uri.len)
4829 return 0;
4830
4831 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4832 return 0;
4833
4834 return 1;
4835}
4836
4837/* This function prepares an applet to handle the stats. It can deal with the
4838 * "100-continue" expectation, check that admin rules are met for POST requests,
4839 * and program a response message if something was unexpected. It cannot fail
4840 * and always relies on the stats applet to complete the job. It does not touch
4841 * analysers nor counters, which are left to the caller. It does not touch
4842 * s->target which is supposed to already point to the stats applet. The caller
4843 * is expected to have already assigned an appctx to the stream.
4844 */
4845static int htx_handle_stats(struct stream *s, struct channel *req)
4846{
4847 struct stats_admin_rule *stats_admin_rule;
4848 struct stream_interface *si = &s->si[1];
4849 struct session *sess = s->sess;
4850 struct http_txn *txn = s->txn;
4851 struct http_msg *msg = &txn->req;
4852 struct uri_auth *uri_auth = s->be->uri_auth;
4853 const char *h, *lookup, *end;
4854 struct appctx *appctx;
4855 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004856 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004857
4858 appctx = si_appctx(si);
4859 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4860 appctx->st1 = appctx->st2 = 0;
4861 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4862 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4863 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4864 appctx->ctx.stats.flags |= STAT_CHUNKED;
4865
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004866 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004867 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004868 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4869 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004870
4871 for (h = lookup; h <= end - 3; h++) {
4872 if (memcmp(h, ";up", 3) == 0) {
4873 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4874 break;
4875 }
4876 }
4877
4878 if (uri_auth->refresh) {
4879 for (h = lookup; h <= end - 10; h++) {
4880 if (memcmp(h, ";norefresh", 10) == 0) {
4881 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4882 break;
4883 }
4884 }
4885 }
4886
4887 for (h = lookup; h <= end - 4; h++) {
4888 if (memcmp(h, ";csv", 4) == 0) {
4889 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4890 break;
4891 }
4892 }
4893
4894 for (h = lookup; h <= end - 6; h++) {
4895 if (memcmp(h, ";typed", 6) == 0) {
4896 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4897 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4898 break;
4899 }
4900 }
4901
4902 for (h = lookup; h <= end - 8; h++) {
4903 if (memcmp(h, ";st=", 4) == 0) {
4904 int i;
4905 h += 4;
4906 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4907 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4908 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4909 appctx->ctx.stats.st_code = i;
4910 break;
4911 }
4912 }
4913 break;
4914 }
4915 }
4916
4917 appctx->ctx.stats.scope_str = 0;
4918 appctx->ctx.stats.scope_len = 0;
4919 for (h = lookup; h <= end - 8; h++) {
4920 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4921 int itx = 0;
4922 const char *h2;
4923 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4924 const char *err;
4925
4926 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4927 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004928 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4929 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004930 if (*h == ';' || *h == '&' || *h == ' ')
4931 break;
4932 itx++;
4933 h++;
4934 }
4935
4936 if (itx > STAT_SCOPE_TXT_MAXLEN)
4937 itx = STAT_SCOPE_TXT_MAXLEN;
4938 appctx->ctx.stats.scope_len = itx;
4939
4940 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4941 memcpy(scope_txt, h2, itx);
4942 scope_txt[itx] = '\0';
4943 err = invalid_char(scope_txt);
4944 if (err) {
4945 /* bad char in search text => clear scope */
4946 appctx->ctx.stats.scope_str = 0;
4947 appctx->ctx.stats.scope_len = 0;
4948 }
4949 break;
4950 }
4951 }
4952
4953 /* now check whether we have some admin rules for this request */
4954 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4955 int ret = 1;
4956
4957 if (stats_admin_rule->cond) {
4958 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4959 ret = acl_pass(ret);
4960 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4961 ret = !ret;
4962 }
4963
4964 if (ret) {
4965 /* no rule, or the rule matches */
4966 appctx->ctx.stats.flags |= STAT_ADMIN;
4967 break;
4968 }
4969 }
4970
Christopher Faulet5d45e382019-02-27 15:15:23 +01004971 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4972 appctx->st0 = STAT_HTTP_HEAD;
4973 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004974 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004975 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004976 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004977 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004978 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4979 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4980 appctx->st0 = STAT_HTTP_LAST;
4981 }
4982 }
4983 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004984 /* Unsupported method */
4985 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4986 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4987 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004988 }
4989
4990 s->task->nice = -32; /* small boost for HTTP statistics */
4991 return 1;
4992}
4993
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004994void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4995{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004996 struct channel *req = &s->req;
4997 struct channel *res = &s->res;
4998 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004999 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005000 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005001 struct ist path, location;
5002 unsigned int flags;
5003 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005004
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005005 /*
5006 * Create the location
5007 */
5008 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005009
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005010 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005011 /* special prefix "/" means don't change URL */
5012 srv = __objt_server(s->target);
5013 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5014 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5015 return;
5016 }
5017
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005018 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005019 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005020 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005021 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005022 if (!path.ptr)
5023 return;
5024
5025 if (!chunk_memcat(&trash, path.ptr, path.len))
5026 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005027 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005028
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005029 /*
5030 * Create the 302 respone
5031 */
5032 htx = htx_from_buf(&res->buf);
5033 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5034 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5035 ist("HTTP/1.1"), ist("302"), ist("Found"));
5036 if (!sl)
5037 goto fail;
5038 sl->info.res.status = 302;
5039 s->txn->status = 302;
5040
5041 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5042 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5043 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5044 !htx_add_header(htx, ist("Location"), location))
5045 goto fail;
5046
5047 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5048 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005049
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005050 /*
5051 * Send the message
5052 */
5053 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005054 c_adv(res, data);
5055 res->total += data;
5056
5057 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005058 si_shutr(si);
5059 si_shutw(si);
5060 si->err_type = SI_ET_NONE;
5061 si->state = SI_ST_CLO;
5062
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005063 channel_auto_read(req);
5064 channel_abort(req);
5065 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005066 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005067 channel_auto_read(res);
5068 channel_auto_close(res);
5069
5070 if (!(s->flags & SF_ERR_MASK))
5071 s->flags |= SF_ERR_LOCAL;
5072 if (!(s->flags & SF_FINST_MASK))
5073 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005074
5075 /* FIXME: we should increase a counter of redirects per server and per backend. */
5076 srv_inc_sess_ctr(srv);
5077 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005078 return;
5079
5080 fail:
5081 /* If an error occurred, remove the incomplete HTTP response from the
5082 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005083 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005084}
5085
Christopher Fauletf2824e62018-10-01 12:12:37 +02005086/* This function terminates the request because it was completly analyzed or
5087 * because an error was triggered during the body forwarding.
5088 */
5089static void htx_end_request(struct stream *s)
5090{
5091 struct channel *chn = &s->req;
5092 struct http_txn *txn = s->txn;
5093
5094 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5095 now_ms, __FUNCTION__, s,
5096 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5097 s->req.analysers, s->res.analysers);
5098
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005099 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5100 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005101 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005102 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005103 goto end;
5104 }
5105
5106 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5107 return;
5108
5109 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005110 /* No need to read anymore, the request was completely parsed.
5111 * We can shut the read side unless we want to abort_on_close,
5112 * or we have a POST request. The issue with POST requests is
5113 * that some browsers still send a CRLF after the request, and
5114 * this CRLF must be read so that it does not remain in the kernel
5115 * buffers, otherwise a close could cause an RST on some systems
5116 * (eg: Linux).
5117 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005118 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005119 channel_dont_read(chn);
5120
5121 /* if the server closes the connection, we want to immediately react
5122 * and close the socket to save packets and syscalls.
5123 */
5124 s->si[1].flags |= SI_FL_NOHALF;
5125
5126 /* In any case we've finished parsing the request so we must
5127 * disable Nagle when sending data because 1) we're not going
5128 * to shut this side, and 2) the server is waiting for us to
5129 * send pending data.
5130 */
5131 chn->flags |= CF_NEVER_WAIT;
5132
Christopher Fauletd01ce402019-01-02 17:44:13 +01005133 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5134 /* The server has not finished to respond, so we
5135 * don't want to move in order not to upset it.
5136 */
5137 return;
5138 }
5139
Christopher Fauletf2824e62018-10-01 12:12:37 +02005140 /* When we get here, it means that both the request and the
5141 * response have finished receiving. Depending on the connection
5142 * mode, we'll have to wait for the last bytes to leave in either
5143 * direction, and sometimes for a close to be effective.
5144 */
5145 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5146 /* Tunnel mode will not have any analyser so it needs to
5147 * poll for reads.
5148 */
5149 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005150 if (b_data(&chn->buf))
5151 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005152 txn->req.msg_state = HTTP_MSG_TUNNEL;
5153 }
5154 else {
5155 /* we're not expecting any new data to come for this
5156 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005157 *
5158 * However, there is an exception if the response
5159 * length is undefined. In this case, we need to wait
5160 * the close from the server. The response will be
5161 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005162 */
5163 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5164 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005165 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005166
5167 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5168 channel_shutr_now(chn);
5169 channel_shutw_now(chn);
5170 }
5171 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005172 goto check_channel_flags;
5173 }
5174
5175 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5176 http_msg_closing:
5177 /* nothing else to forward, just waiting for the output buffer
5178 * to be empty and for the shutw_now to take effect.
5179 */
5180 if (channel_is_empty(chn)) {
5181 txn->req.msg_state = HTTP_MSG_CLOSED;
5182 goto http_msg_closed;
5183 }
5184 else if (chn->flags & CF_SHUTW) {
5185 txn->req.err_state = txn->req.msg_state;
5186 txn->req.msg_state = HTTP_MSG_ERROR;
5187 goto end;
5188 }
5189 return;
5190 }
5191
5192 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5193 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005194 /* if we don't know whether the server will close, we need to hard close */
5195 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5196 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005197 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005198 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005199 channel_dont_read(chn);
5200 goto end;
5201 }
5202
5203 check_channel_flags:
5204 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5205 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5206 /* if we've just closed an output, let's switch */
5207 txn->req.msg_state = HTTP_MSG_CLOSING;
5208 goto http_msg_closing;
5209 }
5210
5211 end:
5212 chn->analysers &= AN_REQ_FLT_END;
5213 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5214 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5215 channel_auto_close(chn);
5216 channel_auto_read(chn);
5217}
5218
5219
5220/* This function terminates the response because it was completly analyzed or
5221 * because an error was triggered during the body forwarding.
5222 */
5223static void htx_end_response(struct stream *s)
5224{
5225 struct channel *chn = &s->res;
5226 struct http_txn *txn = s->txn;
5227
5228 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5229 now_ms, __FUNCTION__, s,
5230 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5231 s->req.analysers, s->res.analysers);
5232
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005233 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5234 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005235 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005236 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005237 goto end;
5238 }
5239
5240 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5241 return;
5242
5243 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5244 /* In theory, we don't need to read anymore, but we must
5245 * still monitor the server connection for a possible close
5246 * while the request is being uploaded, so we don't disable
5247 * reading.
5248 */
5249 /* channel_dont_read(chn); */
5250
5251 if (txn->req.msg_state < HTTP_MSG_DONE) {
5252 /* The client seems to still be sending data, probably
5253 * because we got an error response during an upload.
5254 * We have the choice of either breaking the connection
5255 * or letting it pass through. Let's do the later.
5256 */
5257 return;
5258 }
5259
5260 /* When we get here, it means that both the request and the
5261 * response have finished receiving. Depending on the connection
5262 * mode, we'll have to wait for the last bytes to leave in either
5263 * direction, and sometimes for a close to be effective.
5264 */
5265 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5266 channel_auto_read(chn);
5267 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005268 if (b_data(&chn->buf))
5269 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005270 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5271 }
5272 else {
5273 /* we're not expecting any new data to come for this
5274 * transaction, so we can close it.
5275 */
5276 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5277 channel_shutr_now(chn);
5278 channel_shutw_now(chn);
5279 }
5280 }
5281 goto check_channel_flags;
5282 }
5283
5284 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5285 http_msg_closing:
5286 /* nothing else to forward, just waiting for the output buffer
5287 * to be empty and for the shutw_now to take effect.
5288 */
5289 if (channel_is_empty(chn)) {
5290 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5291 goto http_msg_closed;
5292 }
5293 else if (chn->flags & CF_SHUTW) {
5294 txn->rsp.err_state = txn->rsp.msg_state;
5295 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005296 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005297 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005298 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005299 goto end;
5300 }
5301 return;
5302 }
5303
5304 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5305 http_msg_closed:
5306 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005307 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005308 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005309 goto end;
5310 }
5311
5312 check_channel_flags:
5313 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5314 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5315 /* if we've just closed an output, let's switch */
5316 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5317 goto http_msg_closing;
5318 }
5319
5320 end:
5321 chn->analysers &= AN_RES_FLT_END;
5322 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5323 chn->analysers |= AN_RES_FLT_XFER_DATA;
5324 channel_auto_close(chn);
5325 channel_auto_read(chn);
5326}
5327
Christopher Faulet0f226952018-10-22 09:29:56 +02005328void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5329 int finst, const struct buffer *msg)
5330{
5331 channel_auto_read(si_oc(si));
5332 channel_abort(si_oc(si));
5333 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005334 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005335 channel_auto_close(si_ic(si));
5336 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005337
5338 /* <msg> is an HTX structure. So we copy it in the response's
5339 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005340 if (msg) {
5341 struct channel *chn = si_ic(si);
5342 struct htx *htx;
5343
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005344 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005345 chn->buf.data = msg->data;
5346 memcpy(chn->buf.area, msg->area, msg->data);
5347 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005348 c_adv(chn, htx->data);
5349 chn->total += htx->data;
5350 }
5351 if (!(s->flags & SF_ERR_MASK))
5352 s->flags |= err;
5353 if (!(s->flags & SF_FINST_MASK))
5354 s->flags |= finst;
5355}
5356
5357void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5358{
5359 channel_auto_read(&s->req);
5360 channel_abort(&s->req);
5361 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005362 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5363 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005364
5365 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005366
5367 /* <msg> is an HTX structure. So we copy it in the response's
5368 * channel */
5369 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005370 if (msg) {
5371 struct channel *chn = &s->res;
5372 struct htx *htx;
5373
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005374 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005375 chn->buf.data = msg->data;
5376 memcpy(chn->buf.area, msg->area, msg->data);
5377 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005378 c_adv(chn, htx->data);
5379 chn->total += htx->data;
5380 }
5381
5382 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5383 channel_auto_read(&s->res);
5384 channel_auto_close(&s->res);
5385 channel_shutr_now(&s->res);
5386}
5387
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005388struct buffer *htx_error_message(struct stream *s)
5389{
5390 const int msgnum = http_get_status_idx(s->txn->status);
5391
5392 if (s->be->errmsg[msgnum].area)
5393 return &s->be->errmsg[msgnum];
5394 else if (strm_fe(s)->errmsg[msgnum].area)
5395 return &strm_fe(s)->errmsg[msgnum];
5396 else
5397 return &htx_err_chunks[msgnum];
5398}
5399
5400
Christopher Faulet4a28a532019-03-01 11:19:40 +01005401/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5402 * on success and -1 on error.
5403 */
5404static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5405{
5406 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5407 * then we must send an HTTP/1.1 100 Continue intermediate response.
5408 */
5409 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5410 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5411 struct ist hdr = { .ptr = "Expect", .len = 6 };
5412 struct http_hdr_ctx ctx;
5413
5414 ctx.blk = NULL;
5415 /* Expect is allowed in 1.1, look for it */
5416 if (http_find_header(htx, hdr, &ctx, 0) &&
5417 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5418 if (htx_reply_100_continue(s) == -1)
5419 return -1;
5420 http_remove_header(htx, &ctx);
5421 }
5422 }
5423 return 0;
5424}
5425
Christopher Faulet23a3c792018-11-28 10:01:23 +01005426/* Send a 100-Continue response to the client. It returns 0 on success and -1
5427 * on error. The response channel is updated accordingly.
5428 */
5429static int htx_reply_100_continue(struct stream *s)
5430{
5431 struct channel *res = &s->res;
5432 struct htx *htx = htx_from_buf(&res->buf);
5433 struct htx_sl *sl;
5434 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5435 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5436 size_t data;
5437
5438 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5439 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5440 if (!sl)
5441 goto fail;
5442 sl->info.res.status = 100;
5443
5444 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5445 goto fail;
5446
5447 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005448 c_adv(res, data);
5449 res->total += data;
5450 return 0;
5451
5452 fail:
5453 /* If an error occurred, remove the incomplete HTTP response from the
5454 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005455 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005456 return -1;
5457}
5458
Christopher Faulet12c51e22018-11-28 15:59:42 +01005459
5460/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5461 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5462 * error. The response channel is updated accordingly.
5463 */
5464static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5465{
5466 struct channel *res = &s->res;
5467 struct htx *htx = htx_from_buf(&res->buf);
5468 struct htx_sl *sl;
5469 struct ist code, body;
5470 int status;
5471 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5472 size_t data;
5473
5474 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5475 status = 401;
5476 code = ist("401");
5477 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5478 "You need a valid user and password to access this content.\n"
5479 "</body></html>\n");
5480 }
5481 else {
5482 status = 407;
5483 code = ist("407");
5484 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5485 "You need a valid user and password to access this content.\n"
5486 "</body></html>\n");
5487 }
5488
5489 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5490 ist("HTTP/1.1"), code, ist("Unauthorized"));
5491 if (!sl)
5492 goto fail;
5493 sl->info.res.status = status;
5494 s->txn->status = status;
5495
5496 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5497 goto fail;
5498
5499 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5500 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005501 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5502 goto fail;
5503 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5504 goto fail;
5505 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005506 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005507 if (!htx_add_endof(htx, HTX_BLK_EOH))
5508 goto fail;
5509
5510 while (body.len) {
5511 size_t sent = htx_add_data(htx, body);
5512 if (!sent)
5513 goto fail;
5514 body.ptr += sent;
5515 body.len -= sent;
5516 }
5517
5518 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005519 goto fail;
5520
5521 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005522 c_adv(res, data);
5523 res->total += data;
5524
5525 channel_auto_read(&s->req);
5526 channel_abort(&s->req);
5527 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005528 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005529
5530 res->wex = tick_add_ifset(now_ms, res->wto);
5531 channel_auto_read(res);
5532 channel_auto_close(res);
5533 channel_shutr_now(res);
5534 return 0;
5535
5536 fail:
5537 /* If an error occurred, remove the incomplete HTTP response from the
5538 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005539 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005540 return -1;
5541}
5542
Christopher Faulet0f226952018-10-22 09:29:56 +02005543/*
5544 * Capture headers from message <htx> according to header list <cap_hdr>, and
5545 * fill the <cap> pointers appropriately.
5546 */
5547static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5548{
5549 struct cap_hdr *h;
5550 int32_t pos;
5551
Christopher Fauleta3f15502019-05-13 15:27:23 +02005552 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005553 struct htx_blk *blk = htx_get_blk(htx, pos);
5554 enum htx_blk_type type = htx_get_blk_type(blk);
5555 struct ist n, v;
5556
5557 if (type == HTX_BLK_EOH)
5558 break;
5559 if (type != HTX_BLK_HDR)
5560 continue;
5561
5562 n = htx_get_blk_name(htx, blk);
5563
5564 for (h = cap_hdr; h; h = h->next) {
5565 if (h->namelen && (h->namelen == n.len) &&
5566 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5567 if (cap[h->index] == NULL)
5568 cap[h->index] =
5569 pool_alloc(h->pool);
5570
5571 if (cap[h->index] == NULL) {
5572 ha_alert("HTTP capture : out of memory.\n");
5573 break;
5574 }
5575
5576 v = htx_get_blk_value(htx, blk);
5577 if (v.len > h->len)
5578 v.len = h->len;
5579
5580 memcpy(cap[h->index], v.ptr, v.len);
5581 cap[h->index][v.len]=0;
5582 }
5583 }
5584 }
5585}
5586
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005587/* Delete a value in a header between delimiters <from> and <next>. The header
5588 * itself is delimited by <start> and <end> pointers. The number of characters
5589 * displaced is returned, and the pointer to the first delimiter is updated if
5590 * required. The function tries as much as possible to respect the following
5591 * principles :
5592 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5593 * in which case <next> is simply removed
5594 * - set exactly one space character after the new first delimiter, unless there
5595 * are not enough characters in the block being moved to do so.
5596 * - remove unneeded spaces before the previous delimiter and after the new
5597 * one.
5598 *
5599 * It is the caller's responsibility to ensure that :
5600 * - <from> points to a valid delimiter or <start> ;
5601 * - <next> points to a valid delimiter or <end> ;
5602 * - there are non-space chars before <from>.
5603 */
5604static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5605{
5606 char *prev = *from;
5607
5608 if (prev == start) {
5609 /* We're removing the first value. eat the semicolon, if <next>
5610 * is lower than <end> */
5611 if (next < end)
5612 next++;
5613
5614 while (next < end && HTTP_IS_SPHT(*next))
5615 next++;
5616 }
5617 else {
5618 /* Remove useless spaces before the old delimiter. */
5619 while (HTTP_IS_SPHT(*(prev-1)))
5620 prev--;
5621 *from = prev;
5622
5623 /* copy the delimiter and if possible a space if we're
5624 * not at the end of the line.
5625 */
5626 if (next < end) {
5627 *prev++ = *next++;
5628 if (prev + 1 < next)
5629 *prev++ = ' ';
5630 while (next < end && HTTP_IS_SPHT(*next))
5631 next++;
5632 }
5633 }
5634 memmove(prev, next, end - next);
5635 return (prev - next);
5636}
5637
Christopher Faulet0f226952018-10-22 09:29:56 +02005638
5639/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005640 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005641 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005642static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005643{
5644 struct ist dst = ist2(str, 0);
5645
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005646 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005647 goto end;
5648 if (dst.len + 1 > len)
5649 goto end;
5650 dst.ptr[dst.len++] = ' ';
5651
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005652 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005653 goto end;
5654 if (dst.len + 1 > len)
5655 goto end;
5656 dst.ptr[dst.len++] = ' ';
5657
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005658 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005659 end:
5660 return dst.len;
5661}
5662
Christopher Fauletf0523542018-10-24 11:06:58 +02005663/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005664 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005665 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005666static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005667{
5668 struct ist dst = ist2(str, 0);
5669
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005670 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005671 goto end;
5672 if (dst.len + 1 > len)
5673 goto end;
5674 dst.ptr[dst.len++] = ' ';
5675
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005676 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005677 goto end;
5678 if (dst.len + 1 > len)
5679 goto end;
5680 dst.ptr[dst.len++] = ' ';
5681
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005682 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005683 end:
5684 return dst.len;
5685}
5686
5687
Christopher Faulet0f226952018-10-22 09:29:56 +02005688/*
5689 * Print a debug line with a start line.
5690 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005691static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005692{
5693 struct session *sess = strm_sess(s);
5694 int max;
5695
5696 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5697 dir,
5698 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5699 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5700
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005701 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005702 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005703 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005704 trash.area[trash.data++] = ' ';
5705
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005706 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005707 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005708 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005709 trash.area[trash.data++] = ' ';
5710
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005711 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005712 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005713 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005714 trash.area[trash.data++] = '\n';
5715
5716 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5717}
5718
5719/*
5720 * Print a debug line with a header.
5721 */
5722static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5723{
5724 struct session *sess = strm_sess(s);
5725 int max;
5726
5727 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5728 dir,
5729 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5730 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5731
5732 max = n.len;
5733 UBOUND(max, trash.size - trash.data - 3);
5734 chunk_memcat(&trash, n.ptr, max);
5735 trash.area[trash.data++] = ':';
5736 trash.area[trash.data++] = ' ';
5737
5738 max = v.len;
5739 UBOUND(max, trash.size - trash.data - 1);
5740 chunk_memcat(&trash, v.ptr, max);
5741 trash.area[trash.data++] = '\n';
5742
5743 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5744}
5745
5746
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005747__attribute__((constructor))
5748static void __htx_protocol_init(void)
5749{
5750}
5751
5752
5753/*
5754 * Local variables:
5755 * c-indent-level: 8
5756 * c-basic-offset: 8
5757 * End:
5758 */