blob: 953b49f98d05a01d60e56d0c5c25c05867bddd32 [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 Fauletb75b5ea2019-05-17 08:37:28 +0200135 if (unlikely(htx_is_empty(htx) || htx->sl_pos == -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 Faulet297fbb42019-05-13 14:41:27 +0200282 sl = http_get_stline(htx);
Christopher Faulet03599112018-11-27 11:21:21 +0100283
Christopher Faulet9768c262018-10-22 09:34:31 +0200284 /* 0: we might have to print this header in debug mode */
285 if (unlikely((global.mode & MODE_DEBUG) &&
286 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
287 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200288
Christopher Faulet03599112018-11-27 11:21:21 +0100289 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200290
Christopher Fauleta3f15502019-05-13 15:27:23 +0200291 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200292 struct htx_blk *blk = htx_get_blk(htx, pos);
293 enum htx_blk_type type = htx_get_blk_type(blk);
294
295 if (type == HTX_BLK_EOH)
296 break;
297 if (type != HTX_BLK_HDR)
298 continue;
299
300 htx_debug_hdr("clihdr", s,
301 htx_get_blk_name(htx, blk),
302 htx_get_blk_value(htx, blk));
303 }
304 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200305
306 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100307 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200308 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100309 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100310 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200311 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100312 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100313 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100314 if (sl->flags & HTX_SL_F_BODYLESS)
315 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200316
317 /* we can make use of server redirect on GET and HEAD */
318 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
319 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100320 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200321 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200322 goto return_bad_req;
323 }
324
325 /*
326 * 2: check if the URI matches the monitor_uri.
327 * We have to do this for every request which gets in, because
328 * the monitor-uri is defined by the frontend.
329 */
330 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100331 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200332 /*
333 * We have found the monitor URI
334 */
335 struct acl_cond *cond;
336
337 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100338 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200339
340 /* Check if we want to fail this monitor request or not */
341 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
342 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
343
344 ret = acl_pass(ret);
345 if (cond->pol == ACL_COND_UNLESS)
346 ret = !ret;
347
348 if (ret) {
349 /* we fail this request, let's return 503 service unavail */
350 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100351 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200352 if (!(s->flags & SF_ERR_MASK))
353 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
354 goto return_prx_cond;
355 }
356 }
357
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800358 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200359 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100360 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200361 if (!(s->flags & SF_ERR_MASK))
362 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
363 goto return_prx_cond;
364 }
365
366 /*
367 * 3: Maybe we have to copy the original REQURI for the logs ?
368 * Note: we cannot log anymore if the request has been
369 * classified as invalid.
370 */
371 if (unlikely(s->logs.logwait & LW_REQ)) {
372 /* we have a complete HTTP request that we must log */
373 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200374 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200375
Christopher Faulet9768c262018-10-22 09:34:31 +0200376 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
377 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200378
379 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
380 s->do_log(s);
381 } else {
382 ha_alert("HTTP logging : out of memory.\n");
383 }
384 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200385
Christopher Faulete0768eb2018-10-03 16:38:02 +0200386 /* if the frontend has "option http-use-proxy-header", we'll check if
387 * we have what looks like a proxied connection instead of a connection,
388 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
389 * Note that this is *not* RFC-compliant, however browsers and proxies
390 * happen to do that despite being non-standard :-(
391 * We consider that a request not beginning with either '/' or '*' is
392 * a proxied connection, which covers both "scheme://location" and
393 * CONNECT ip:port.
394 */
395 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100396 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200397 txn->flags |= TX_USE_PX_CONN;
398
Christopher Faulete0768eb2018-10-03 16:38:02 +0200399 /* 5: we may need to capture headers */
400 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200401 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200402
Christopher Faulet03b9d8b2019-03-26 22:02:00 +0100403 /* by default, close the stream at the end of the transaction. */
404 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200405
406 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200407 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200408 req->analysers |= AN_REQ_HTTP_BODY;
409
410 /*
411 * RFC7234#4:
412 * A cache MUST write through requests with methods
413 * that are unsafe (Section 4.2.1 of [RFC7231]) to
414 * the origin server; i.e., a cache is not allowed
415 * to generate a reply to such a request before
416 * having forwarded the request and having received
417 * a corresponding response.
418 *
419 * RFC7231#4.2.1:
420 * Of the request methods defined by this
421 * specification, the GET, HEAD, OPTIONS, and TRACE
422 * methods are defined to be safe.
423 */
424 if (likely(txn->meth == HTTP_METH_GET ||
425 txn->meth == HTTP_METH_HEAD ||
426 txn->meth == HTTP_METH_OPTIONS ||
427 txn->meth == HTTP_METH_TRACE))
428 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
429
430 /* end of job, return OK */
431 req->analysers &= ~an_bit;
432 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200433
Christopher Faulete0768eb2018-10-03 16:38:02 +0200434 return 1;
435
436 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200437 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200438 txn->req.err_state = txn->req.msg_state;
439 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100440 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100441 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200442 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100443 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200444
445 return_prx_cond:
446 if (!(s->flags & SF_ERR_MASK))
447 s->flags |= SF_ERR_PRXCOND;
448 if (!(s->flags & SF_FINST_MASK))
449 s->flags |= SF_FINST_R;
450
451 req->analysers &= AN_REQ_FLT_END;
452 req->analyse_exp = TICK_ETERNITY;
453 return 0;
454}
455
456
457/* This stream analyser runs all HTTP request processing which is common to
458 * frontends and backends, which means blocking ACLs, filters, connection-close,
459 * reqadd, stats and redirects. This is performed for the designated proxy.
460 * It returns 1 if the processing can continue on next analysers, or zero if it
461 * either needs more data or wants to immediately abort the request (eg: deny,
462 * error, ...).
463 */
464int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
465{
466 struct session *sess = s->sess;
467 struct http_txn *txn = s->txn;
468 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200469 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200470 struct redirect_rule *rule;
471 struct cond_wordlist *wl;
472 enum rule_result verdict;
473 int deny_status = HTTP_ERR_403;
474 struct connection *conn = objt_conn(sess->origin);
475
476 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
477 /* we need more data */
478 goto return_prx_yield;
479 }
480
481 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
482 now_ms, __FUNCTION__,
483 s,
484 req,
485 req->rex, req->wex,
486 req->flags,
487 ci_data(req),
488 req->analysers);
489
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100490 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200491
Christopher Faulet1907ccc2019-04-29 13:12:02 +0200492 /* just in case we have some per-backend tracking. Only called the first
493 * execution of the analyser. */
494 if (!s->current_rule || s->current_rule_list != &px->http_req_rules)
495 stream_inc_be_http_req_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200496
497 /* evaluate http-request rules */
498 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200499 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200500
501 switch (verdict) {
502 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
503 goto return_prx_yield;
504
505 case HTTP_RULE_RES_CONT:
506 case HTTP_RULE_RES_STOP: /* nothing to do */
507 break;
508
509 case HTTP_RULE_RES_DENY: /* deny or tarpit */
510 if (txn->flags & TX_CLTARPIT)
511 goto tarpit;
512 goto deny;
513
514 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
515 goto return_prx_cond;
516
517 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
518 goto done;
519
520 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
521 goto return_bad_req;
522 }
523 }
524
525 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
526 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200527 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200528
Christopher Fauletff2759f2018-10-24 11:13:16 +0200529 ctx.blk = NULL;
530 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
531 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200532 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200533 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200534 }
535
536 /* OK at this stage, we know that the request was accepted according to
537 * the http-request rules, we can check for the stats. Note that the
538 * URI is detected *before* the req* rules in order not to be affected
539 * by a possible reqrep, while they are processed *after* so that a
540 * reqdeny can still block them. This clearly needs to change in 1.6!
541 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200542 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200543 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100544 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200545 txn->status = 500;
546 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100547 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200548
549 if (!(s->flags & SF_ERR_MASK))
550 s->flags |= SF_ERR_RESOURCE;
551 goto return_prx_cond;
552 }
553
554 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200555 htx_handle_stats(s, req);
556 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200557 /* not all actions implemented: deny, allow, auth */
558
559 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
560 goto deny;
561
562 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
563 goto return_prx_cond;
564 }
565
566 /* evaluate the req* rules except reqadd */
567 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200568 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200569 goto return_bad_req;
570
571 if (txn->flags & TX_CLDENY)
572 goto deny;
573
574 if (txn->flags & TX_CLTARPIT) {
575 deny_status = HTTP_ERR_500;
576 goto tarpit;
577 }
578 }
579
580 /* add request headers from the rule sets in the same order */
581 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200582 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200583 if (wl->cond) {
584 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
585 ret = acl_pass(ret);
586 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
587 ret = !ret;
588 if (!ret)
589 continue;
590 }
591
Christopher Fauletff2759f2018-10-24 11:13:16 +0200592 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
593 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200594 goto return_bad_req;
595 }
596
Christopher Faulet2571bc62019-03-01 11:44:26 +0100597 /* Proceed with the applets now. */
598 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200599 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100600 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200601
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100602 if (htx_handle_expect_hdr(s, htx, msg) == -1)
603 goto return_bad_req;
604
Christopher Faulete0768eb2018-10-03 16:38:02 +0200605 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
606 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
607 if (!(s->flags & SF_FINST_MASK))
608 s->flags |= SF_FINST_R;
609
610 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
611 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
612 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
613 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100614
615 req->flags |= CF_SEND_DONTWAIT;
616 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200617 goto done;
618 }
619
620 /* check whether we have some ACLs set to redirect this request */
621 list_for_each_entry(rule, &px->redirect_rules, list) {
622 if (rule->cond) {
623 int ret;
624
625 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
626 ret = acl_pass(ret);
627 if (rule->cond->pol == ACL_COND_UNLESS)
628 ret = !ret;
629 if (!ret)
630 continue;
631 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200632 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200633 goto return_bad_req;
634 goto done;
635 }
636
637 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
638 * If this happens, then the data will not come immediately, so we must
639 * send all what we have without waiting. Note that due to the small gain
640 * in waiting for the body of the request, it's easier to simply put the
641 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
642 * itself once used.
643 */
644 req->flags |= CF_SEND_DONTWAIT;
645
646 done: /* done with this analyser, continue with next ones that the calling
647 * points will have set, if any.
648 */
649 req->analyse_exp = TICK_ETERNITY;
650 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
651 req->analysers &= ~an_bit;
652 return 1;
653
654 tarpit:
655 /* Allow cookie logging
656 */
657 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200658 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200659
660 /* When a connection is tarpitted, we use the tarpit timeout,
661 * which may be the same as the connect timeout if unspecified.
662 * If unset, then set it to zero because we really want it to
663 * eventually expire. We build the tarpit as an analyser.
664 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100665 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200666
667 /* wipe the request out so that we can drop the connection early
668 * if the client closes first.
669 */
670 channel_dont_connect(req);
671
672 txn->status = http_err_codes[deny_status];
673
674 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
675 req->analysers |= AN_REQ_HTTP_TARPIT;
676 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
677 if (!req->analyse_exp)
678 req->analyse_exp = tick_add(now_ms, 0);
679 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100680 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200681 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100682 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200683 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100684 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200685 goto done_without_exp;
686
687 deny: /* this request was blocked (denied) */
688
689 /* Allow cookie logging
690 */
691 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200692 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200693
694 txn->flags |= TX_CLDENY;
695 txn->status = http_err_codes[deny_status];
696 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100697 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200698 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100699 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200700 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100701 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200702 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100703 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200704 goto return_prx_cond;
705
706 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200707 txn->req.err_state = txn->req.msg_state;
708 txn->req.msg_state = HTTP_MSG_ERROR;
709 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100710 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200711
Olivier Houcharda798bf52019-03-08 18:52:00 +0100712 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200713 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100714 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200715
716 return_prx_cond:
717 if (!(s->flags & SF_ERR_MASK))
718 s->flags |= SF_ERR_PRXCOND;
719 if (!(s->flags & SF_FINST_MASK))
720 s->flags |= SF_FINST_R;
721
722 req->analysers &= AN_REQ_FLT_END;
723 req->analyse_exp = TICK_ETERNITY;
724 return 0;
725
726 return_prx_yield:
727 channel_dont_connect(req);
728 return 0;
729}
730
731/* This function performs all the processing enabled for the current request.
732 * It returns 1 if the processing can continue on next analysers, or zero if it
733 * needs more data, encounters an error, or wants to immediately abort the
734 * request. It relies on buffers flags, and updates s->req.analysers.
735 */
736int htx_process_request(struct stream *s, struct channel *req, int an_bit)
737{
738 struct session *sess = s->sess;
739 struct http_txn *txn = s->txn;
740 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200741 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200742 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
743
744 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
745 /* we need more data */
746 channel_dont_connect(req);
747 return 0;
748 }
749
750 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
751 now_ms, __FUNCTION__,
752 s,
753 req,
754 req->rex, req->wex,
755 req->flags,
756 ci_data(req),
757 req->analysers);
758
759 /*
760 * Right now, we know that we have processed the entire headers
761 * and that unwanted requests have been filtered out. We can do
762 * whatever we want with the remaining request. Also, now we
763 * may have separate values for ->fe, ->be.
764 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100765 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200766
767 /*
768 * If HTTP PROXY is set we simply get remote server address parsing
769 * incoming request. Note that this requires that a connection is
770 * allocated on the server side.
771 */
772 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
773 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100774 struct htx_sl *sl;
775 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200776
777 /* Note that for now we don't reuse existing proxy connections */
778 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
779 txn->req.err_state = txn->req.msg_state;
780 txn->req.msg_state = HTTP_MSG_ERROR;
781 txn->status = 500;
782 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100783 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200784
785 if (!(s->flags & SF_ERR_MASK))
786 s->flags |= SF_ERR_RESOURCE;
787 if (!(s->flags & SF_FINST_MASK))
788 s->flags |= SF_FINST_R;
789
790 return 0;
791 }
Christopher Faulet297fbb42019-05-13 14:41:27 +0200792 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100793 uri = htx_sl_req_uri(sl);
794 path = http_get_path(uri);
795 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200796 goto return_bad_req;
797
798 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200799 * uri.ptr and path.ptr (excluded). If it was not found, we need
800 * to replace from all the uri by a single "/".
801 *
802 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100803 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200804 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200805 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100806 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200807 }
808
809 /*
810 * 7: Now we can work with the cookies.
811 * Note that doing so might move headers in the request, but
812 * the fields will stay coherent and the URI will not move.
813 * This should only be performed in the backend.
814 */
815 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100816 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200817
818 /* add unique-id if "header-unique-id" is specified */
819
820 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
821 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
822 goto return_bad_req;
823 s->unique_id[0] = '\0';
824 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
825 }
826
827 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200828 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
829 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
830
831 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200832 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200833 }
834
835 /*
836 * 9: add X-Forwarded-For if either the frontend or the backend
837 * asks for it.
838 */
839 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200840 struct http_hdr_ctx ctx = { .blk = NULL };
841 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
842 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
843
Christopher Faulete0768eb2018-10-03 16:38:02 +0200844 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200845 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200846 /* The header is set to be added only if none is present
847 * and we found it, so don't do anything.
848 */
849 }
850 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
851 /* Add an X-Forwarded-For header unless the source IP is
852 * in the 'except' network range.
853 */
854 if ((!sess->fe->except_mask.s_addr ||
855 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
856 != sess->fe->except_net.s_addr) &&
857 (!s->be->except_mask.s_addr ||
858 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
859 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200860 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200861
862 /* Note: we rely on the backend to get the header name to be used for
863 * x-forwarded-for, because the header is really meant for the backends.
864 * However, if the backend did not specify any option, we have to rely
865 * on the frontend's header name.
866 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200867 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
868 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200869 goto return_bad_req;
870 }
871 }
872 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
873 /* FIXME: for the sake of completeness, we should also support
874 * 'except' here, although it is mostly useless in this case.
875 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200876 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200877
Christopher Faulete0768eb2018-10-03 16:38:02 +0200878 inet_ntop(AF_INET6,
879 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
880 pn, sizeof(pn));
881
882 /* Note: we rely on the backend to get the header name to be used for
883 * x-forwarded-for, because the header is really meant for the backends.
884 * However, if the backend did not specify any option, we have to rely
885 * on the frontend's header name.
886 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200887 chunk_printf(&trash, "%s", pn);
888 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200889 goto return_bad_req;
890 }
891 }
892
893 /*
894 * 10: add X-Original-To if either the frontend or the backend
895 * asks for it.
896 */
897 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
898
899 /* FIXME: don't know if IPv6 can handle that case too. */
900 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
901 /* Add an X-Original-To header unless the destination IP is
902 * in the 'except' network range.
903 */
904 conn_get_to_addr(cli_conn);
905
906 if (cli_conn->addr.to.ss_family == AF_INET &&
907 ((!sess->fe->except_mask_to.s_addr ||
908 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
909 != sess->fe->except_to.s_addr) &&
910 (!s->be->except_mask_to.s_addr ||
911 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
912 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200913 struct ist hdr;
914 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200915
916 /* Note: we rely on the backend to get the header name to be used for
917 * x-original-to, because the header is really meant for the backends.
918 * However, if the backend did not specify any option, we have to rely
919 * on the frontend's header name.
920 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200921 if (s->be->orgto_hdr_len)
922 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
923 else
924 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200925
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200926 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
927 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200928 goto return_bad_req;
929 }
930 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200931 }
932
Christopher Faulete0768eb2018-10-03 16:38:02 +0200933 /* If we have no server assigned yet and we're balancing on url_param
934 * with a POST request, we may be interested in checking the body for
935 * that parameter. This will be done in another analyser.
936 */
937 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100938 s->txn->meth == HTTP_METH_POST &&
939 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200940 channel_dont_connect(req);
941 req->analysers |= AN_REQ_HTTP_BODY;
942 }
943
944 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
945 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100946
Christopher Faulete0768eb2018-10-03 16:38:02 +0200947 /* We expect some data from the client. Unless we know for sure
948 * we already have a full request, we have to re-enable quick-ack
949 * in case we previously disabled it, otherwise we might cause
950 * the client to delay further data.
951 */
952 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200953 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100954 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200955
956 /*************************************************************
957 * OK, that's finished for the headers. We have done what we *
958 * could. Let's switch to the DATA state. *
959 ************************************************************/
960 req->analyse_exp = TICK_ETERNITY;
961 req->analysers &= ~an_bit;
962
963 s->logs.tv_request = now;
964 /* OK let's go on with the BODY now */
965 return 1;
966
967 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200968 txn->req.err_state = txn->req.msg_state;
969 txn->req.msg_state = HTTP_MSG_ERROR;
970 txn->status = 400;
971 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100972 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200973
Olivier Houcharda798bf52019-03-08 18:52:00 +0100974 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200975 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100976 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200977
978 if (!(s->flags & SF_ERR_MASK))
979 s->flags |= SF_ERR_PRXCOND;
980 if (!(s->flags & SF_FINST_MASK))
981 s->flags |= SF_FINST_R;
982 return 0;
983}
984
985/* This function is an analyser which processes the HTTP tarpit. It always
986 * returns zero, at the beginning because it prevents any other processing
987 * from occurring, and at the end because it terminates the request.
988 */
989int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
990{
991 struct http_txn *txn = s->txn;
992
993 /* This connection is being tarpitted. The CLIENT side has
994 * already set the connect expiration date to the right
995 * timeout. We just have to check that the client is still
996 * there and that the timeout has not expired.
997 */
998 channel_dont_connect(req);
999 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1000 !tick_is_expired(req->analyse_exp, now_ms))
1001 return 0;
1002
1003 /* We will set the queue timer to the time spent, just for
1004 * logging purposes. We fake a 500 server error, so that the
1005 * attacker will not suspect his connection has been tarpitted.
1006 * It will not cause trouble to the logs because we can exclude
1007 * the tarpitted connections by filtering on the 'PT' status flags.
1008 */
1009 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1010
1011 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001012 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001013
1014 req->analysers &= AN_REQ_FLT_END;
1015 req->analyse_exp = TICK_ETERNITY;
1016
1017 if (!(s->flags & SF_ERR_MASK))
1018 s->flags |= SF_ERR_PRXCOND;
1019 if (!(s->flags & SF_FINST_MASK))
1020 s->flags |= SF_FINST_T;
1021 return 0;
1022}
1023
1024/* This function is an analyser which waits for the HTTP request body. It waits
1025 * for either the buffer to be full, or the full advertised contents to have
1026 * reached the buffer. It must only be called after the standard HTTP request
1027 * processing has occurred, because it expects the request to be parsed and will
1028 * look for the Expect header. It may send a 100-Continue interim response. It
1029 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1030 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1031 * needs to read more data, or 1 once it has completed its analysis.
1032 */
1033int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1034{
1035 struct session *sess = s->sess;
1036 struct http_txn *txn = s->txn;
1037 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001038 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001039
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001040
1041 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1042 now_ms, __FUNCTION__,
1043 s,
1044 req,
1045 req->rex, req->wex,
1046 req->flags,
1047 ci_data(req),
1048 req->analysers);
1049
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001050 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001051
Willy Tarreau4236f032019-03-05 10:43:32 +01001052 if (htx->flags & HTX_FL_PARSING_ERROR)
1053 goto return_bad_req;
1054
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001055 if (msg->msg_state < HTTP_MSG_BODY)
1056 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001057
Christopher Faulete0768eb2018-10-03 16:38:02 +02001058 /* We have to parse the HTTP request body to find any required data.
1059 * "balance url_param check_post" should have been the only way to get
1060 * into this. We were brought here after HTTP header analysis, so all
1061 * related structures are ready.
1062 */
1063
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001064 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001065 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1066 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001067 }
1068
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001069 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001070
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001071 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1072 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001073 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001074 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001075 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001076 goto http_end;
1077
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001078 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001079 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1080 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001081 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001082
1083 if (!(s->flags & SF_ERR_MASK))
1084 s->flags |= SF_ERR_CLITO;
1085 if (!(s->flags & SF_FINST_MASK))
1086 s->flags |= SF_FINST_D;
1087 goto return_err_msg;
1088 }
1089
1090 /* we get here if we need to wait for more data */
1091 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1092 /* Not enough data. We'll re-use the http-request
1093 * timeout here. Ideally, we should set the timeout
1094 * relative to the accept() date. We just set the
1095 * request timeout once at the beginning of the
1096 * request.
1097 */
1098 channel_dont_connect(req);
1099 if (!tick_isset(req->analyse_exp))
1100 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1101 return 0;
1102 }
1103
1104 http_end:
1105 /* The situation will not evolve, so let's give up on the analysis. */
1106 s->logs.tv_request = now; /* update the request timer to reflect full request */
1107 req->analysers &= ~an_bit;
1108 req->analyse_exp = TICK_ETERNITY;
1109 return 1;
1110
1111 return_bad_req: /* let's centralize all bad requests */
1112 txn->req.err_state = txn->req.msg_state;
1113 txn->req.msg_state = HTTP_MSG_ERROR;
1114 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001115 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001116
1117 if (!(s->flags & SF_ERR_MASK))
1118 s->flags |= SF_ERR_PRXCOND;
1119 if (!(s->flags & SF_FINST_MASK))
1120 s->flags |= SF_FINST_R;
1121
1122 return_err_msg:
1123 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001124 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001125 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001126 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001127 return 0;
1128}
1129
1130/* This function is an analyser which forwards request body (including chunk
1131 * sizes if any). It is called as soon as we must forward, even if we forward
1132 * zero byte. The only situation where it must not be called is when we're in
1133 * tunnel mode and we want to forward till the close. It's used both to forward
1134 * remaining data and to resync after end of body. It expects the msg_state to
1135 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1136 * read more data, or 1 once we can go on with next request or end the stream.
1137 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1138 * bytes of pending data + the headers if not already done.
1139 */
1140int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1141{
1142 struct session *sess = s->sess;
1143 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001144 struct http_msg *msg = &txn->req;
1145 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001146 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001147 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001148
1149 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1150 now_ms, __FUNCTION__,
1151 s,
1152 req,
1153 req->rex, req->wex,
1154 req->flags,
1155 ci_data(req),
1156 req->analysers);
1157
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001158 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001159
1160 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1161 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1162 /* Output closed while we were sending data. We must abort and
1163 * wake the other side up.
1164 */
1165 msg->err_state = msg->msg_state;
1166 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001167 htx_end_request(s);
1168 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001169 return 1;
1170 }
1171
1172 /* Note that we don't have to send 100-continue back because we don't
1173 * need the data to complete our job, and it's up to the server to
1174 * decide whether to return 100, 417 or anything else in return of
1175 * an "Expect: 100-continue" header.
1176 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001177 if (msg->msg_state == HTTP_MSG_BODY)
1178 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001179
1180 /* Some post-connect processing might want us to refrain from starting to
1181 * forward data. Currently, the only reason for this is "balance url_param"
1182 * whichs need to parse/process the request after we've enabled forwarding.
1183 */
1184 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1185 if (!(s->res.flags & CF_READ_ATTACHED)) {
1186 channel_auto_connect(req);
1187 req->flags |= CF_WAKE_CONNECT;
1188 channel_dont_close(req); /* don't fail on early shutr */
1189 goto waiting;
1190 }
1191 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1192 }
1193
1194 /* in most states, we should abort in case of early close */
1195 channel_auto_close(req);
1196
1197 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001198 if (req->to_forward == CHN_INFINITE_FORWARD) {
1199 if (req->flags & (CF_SHUTR|CF_EOI)) {
1200 msg->msg_state = HTTP_MSG_DONE;
1201 req->to_forward = 0;
1202 goto done;
1203 }
1204 }
1205 else {
1206 /* We can't process the buffer's contents yet */
1207 req->flags |= CF_WAKE_WRITE;
1208 goto missing_data_or_waiting;
1209 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001210 }
1211
Christopher Faulet9768c262018-10-22 09:34:31 +02001212 if (msg->msg_state >= HTTP_MSG_DONE)
1213 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001214 /* Forward input data. We get it by removing all outgoing data not
1215 * forwarded yet from HTX data size. If there are some data filters, we
1216 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001217 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001218 if (HAS_REQ_DATA_FILTERS(s)) {
1219 ret = flt_http_payload(s, msg, htx->data);
1220 if (ret < 0)
1221 goto return_bad_req;
1222 c_adv(req, ret);
1223 if (htx->data != co_data(req) || htx->extra)
1224 goto missing_data_or_waiting;
1225 }
1226 else {
1227 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001228 if (msg->flags & HTTP_MSGF_XFER_LEN)
1229 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001230 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001231
Christopher Fauletc62c2b92019-03-28 11:41:39 +01001232 if (txn->meth == HTTP_METH_CONNECT) {
1233 msg->msg_state = HTTP_MSG_TUNNEL;
1234 goto done;
1235 }
1236
Christopher Faulet9768c262018-10-22 09:34:31 +02001237 /* Check if the end-of-message is reached and if so, switch the message
1238 * in HTTP_MSG_DONE state.
1239 */
1240 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1241 goto missing_data_or_waiting;
1242
1243 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01001244 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001245
1246 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001247 /* other states, DONE...TUNNEL */
1248 /* we don't want to forward closes on DONE except in tunnel mode. */
1249 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1250 channel_dont_close(req);
1251
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001252 if (HAS_REQ_DATA_FILTERS(s)) {
1253 ret = flt_http_end(s, msg);
1254 if (ret <= 0) {
1255 if (!ret)
1256 goto missing_data_or_waiting;
1257 goto return_bad_req;
1258 }
1259 }
1260
Christopher Fauletf2824e62018-10-01 12:12:37 +02001261 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001262 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001263 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001264 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1265 if (req->flags & CF_SHUTW) {
1266 /* request errors are most likely due to the
1267 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001268 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001269 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001270 goto return_bad_req;
1271 }
1272 return 1;
1273 }
1274
1275 /* If "option abortonclose" is set on the backend, we want to monitor
1276 * the client's connection and forward any shutdown notification to the
1277 * server, which will decide whether to close or to go on processing the
1278 * request. We only do that in tunnel mode, and not in other modes since
1279 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001280 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001281 channel_auto_read(req);
1282 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1283 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1284 s->si[1].flags |= SI_FL_NOLINGER;
1285 channel_auto_close(req);
1286 }
1287 else if (s->txn->meth == HTTP_METH_POST) {
1288 /* POST requests may require to read extra CRLF sent by broken
1289 * browsers and which could cause an RST to be sent upon close
1290 * on some systems (eg: Linux). */
1291 channel_auto_read(req);
1292 }
1293 return 0;
1294
1295 missing_data_or_waiting:
1296 /* stop waiting for data if the input is closed before the end */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001297 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR)
1298 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001299
1300 waiting:
1301 /* waiting for the last bits to leave the buffer */
1302 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001303 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001304
Christopher Faulet47365272018-10-31 17:40:50 +01001305 if (htx->flags & HTX_FL_PARSING_ERROR)
1306 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001307
Christopher Faulete0768eb2018-10-03 16:38:02 +02001308 /* When TE: chunked is used, we need to get there again to parse remaining
1309 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1310 * And when content-length is used, we never want to let the possible
1311 * shutdown be forwarded to the other side, as the state machine will
1312 * take care of it once the client responds. It's also important to
1313 * prevent TIME_WAITs from accumulating on the backend side, and for
1314 * HTTP/2 where the last frame comes with a shutdown.
1315 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001316 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001317 channel_dont_close(req);
1318
1319 /* We know that more data are expected, but we couldn't send more that
1320 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1321 * system knows it must not set a PUSH on this first part. Interactive
1322 * modes are already handled by the stream sock layer. We must not do
1323 * this in content-length mode because it could present the MSG_MORE
1324 * flag with the last block of forwarded data, which would cause an
1325 * additional delay to be observed by the receiver.
1326 */
1327 if (msg->flags & HTTP_MSGF_TE_CHNK)
1328 req->flags |= CF_EXPECT_MORE;
1329
1330 return 0;
1331
Christopher Faulet93e02d82019-03-08 14:18:50 +01001332 return_cli_abort:
1333 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1334 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1335 if (objt_server(s->target))
1336 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1337 if (!(s->flags & SF_ERR_MASK))
1338 s->flags |= SF_ERR_CLICL;
1339 status = 400;
1340 goto return_error;
1341
1342 return_srv_abort:
1343 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1344 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1345 if (objt_server(s->target))
1346 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1347 if (!(s->flags & SF_ERR_MASK))
1348 s->flags |= SF_ERR_SRVCL;
1349 status = 502;
1350 goto return_error;
1351
1352 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001353 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001354 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001355 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001356 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001357 s->flags |= SF_ERR_CLICL;
1358 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001359
Christopher Faulet93e02d82019-03-08 14:18:50 +01001360 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001361 txn->req.err_state = txn->req.msg_state;
1362 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001363 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001364 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001365 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001366 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001367 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001368 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001369 }
1370 req->analysers &= AN_REQ_FLT_END;
1371 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 +01001372 if (!(s->flags & SF_FINST_MASK))
1373 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001374 return 0;
1375}
1376
Olivier Houcharda254a372019-04-05 15:30:12 +02001377/* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1378/* Returns 0 if we can attempt to retry, -1 otherwise */
1379static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1380{
1381 struct channel *req, *res;
1382 int co_data;
1383
1384 si->conn_retries--;
1385 if (si->conn_retries < 0)
1386 return -1;
1387
Willy Tarreau223995e2019-05-04 10:38:31 +02001388 if (objt_server(s->target))
1389 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
1390 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1391
Olivier Houcharda254a372019-04-05 15:30:12 +02001392 req = &s->req;
1393 res = &s->res;
1394 /* Remove any write error from the request, and read error from the response */
1395 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1396 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1397 res->analysers = 0;
1398 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
1399 si->state = SI_ST_REQ;
1400 si->exp = TICK_ETERNITY;
1401 res->rex = TICK_ETERNITY;
1402 res->to_forward = 0;
1403 res->analyse_exp = TICK_ETERNITY;
1404 res->total = 0;
1405 s->flags &= ~(SF_ASSIGNED | SF_ADDR_SET | SF_ERR_SRVTO | SF_ERR_SRVCL);
1406 si_release_endpoint(&s->si[1]);
1407 b_free(&req->buf);
1408 /* Swap the L7 buffer with the channel buffer */
1409 /* We know we stored the co_data as b_data, so get it there */
1410 co_data = b_data(&si->l7_buffer);
1411 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1412 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1413
1414 co_set_data(req, co_data);
1415 b_reset(&res->buf);
1416 co_set_data(res, 0);
1417 return 0;
1418}
1419
Christopher Faulete0768eb2018-10-03 16:38:02 +02001420/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1421 * processing can continue on next analysers, or zero if it either needs more
1422 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1423 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1424 * when it has nothing left to do, and may remove any analyser when it wants to
1425 * abort.
1426 */
1427int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1428{
Christopher Faulet9768c262018-10-22 09:34:31 +02001429 /*
1430 * We will analyze a complete HTTP response to check the its syntax.
1431 *
1432 * Once the start line and all headers are received, we may perform a
1433 * capture of the error (if any), and we will set a few fields. We also
1434 * logging and finally headers capture.
1435 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001436 struct session *sess = s->sess;
1437 struct http_txn *txn = s->txn;
1438 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001439 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001440 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001441 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001442 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001443 int n;
1444
1445 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1446 now_ms, __FUNCTION__,
1447 s,
1448 rep,
1449 rep->rex, rep->wex,
1450 rep->flags,
1451 ci_data(rep),
1452 rep->analysers);
1453
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001454 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001455
Willy Tarreau4236f032019-03-05 10:43:32 +01001456 /* Parsing errors are caught here */
1457 if (htx->flags & HTX_FL_PARSING_ERROR)
1458 goto return_bad_res;
1459
Christopher Faulete0768eb2018-10-03 16:38:02 +02001460 /*
1461 * Now we quickly check if we have found a full valid response.
1462 * If not so, we check the FD and buffer states before leaving.
1463 * A full response is indicated by the fact that we have seen
1464 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1465 * responses are checked first.
1466 *
1467 * Depending on whether the client is still there or not, we
1468 * may send an error response back or not. Note that normally
1469 * we should only check for HTTP status there, and check I/O
1470 * errors somewhere else.
1471 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001472 next_one:
1473 if (unlikely(htx_is_empty(htx) || htx->sl_pos == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001474 /* 1: have we encountered a read error ? */
1475 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001476 struct connection *conn = NULL;
1477
Olivier Houchard865d8392019-05-03 22:46:27 +02001478 if (objt_cs(s->si[1].end))
1479 conn = objt_cs(s->si[1].end)->conn;
1480
1481 if (si_b->flags & SI_FL_L7_RETRY &&
1482 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001483 /* If we arrive here, then CF_READ_ERROR was
1484 * set by si_cs_recv() because we matched a
1485 * status, overwise it would have removed
1486 * the SI_FL_L7_RETRY flag, so it's ok not
1487 * to check s->be->retry_type.
1488 */
1489 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1490 return 0;
1491 }
1492
Olivier Houchard6db16992019-05-17 15:40:49 +02001493 if (txn->flags & TX_NOT_FIRST)
1494 goto abort_keep_alive;
1495
Olivier Houcharda798bf52019-03-08 18:52:00 +01001496 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001497 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001498 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001499 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001500 }
1501
Christopher Faulete0768eb2018-10-03 16:38:02 +02001502 rep->analysers &= AN_RES_FLT_END;
1503 txn->status = 502;
1504
1505 /* Check to see if the server refused the early data.
1506 * If so, just send a 425
1507 */
Olivier Houchard865d8392019-05-03 22:46:27 +02001508 if (conn->err_code == CO_ER_SSL_EARLY_FAILED) {
1509 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001510 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001511 do_l7_retry(s, si_b) == 0)
1512 return 0;
1513 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001514 }
1515
1516 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001517 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001518
1519 if (!(s->flags & SF_ERR_MASK))
1520 s->flags |= SF_ERR_SRVCL;
1521 if (!(s->flags & SF_FINST_MASK))
1522 s->flags |= SF_FINST_H;
1523 return 0;
1524 }
1525
Christopher Faulet9768c262018-10-22 09:34:31 +02001526 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001527 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001528 if ((si_b->flags & SI_FL_L7_RETRY) &&
1529 (s->be->retry_type & PR_RE_TIMEOUT)) {
1530 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1531 return 0;
1532 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001533 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001535 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001536 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001537 }
1538
Christopher Faulete0768eb2018-10-03 16:38:02 +02001539 rep->analysers &= AN_RES_FLT_END;
1540 txn->status = 504;
1541 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001542 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001543
1544 if (!(s->flags & SF_ERR_MASK))
1545 s->flags |= SF_ERR_SRVTO;
1546 if (!(s->flags & SF_FINST_MASK))
1547 s->flags |= SF_FINST_H;
1548 return 0;
1549 }
1550
Christopher Faulet9768c262018-10-22 09:34:31 +02001551 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001552 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001553 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1554 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001555 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001556 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001557
1558 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001559 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001560 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001561
1562 if (!(s->flags & SF_ERR_MASK))
1563 s->flags |= SF_ERR_CLICL;
1564 if (!(s->flags & SF_FINST_MASK))
1565 s->flags |= SF_FINST_H;
1566
1567 /* process_stream() will take care of the error */
1568 return 0;
1569 }
1570
Christopher Faulet9768c262018-10-22 09:34:31 +02001571 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001572 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001573 if ((si_b->flags & SI_FL_L7_RETRY) &&
1574 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1575 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1576 return 0;
1577 }
1578
Olivier Houchard6db16992019-05-17 15:40:49 +02001579 if (txn->flags & TX_NOT_FIRST)
1580 goto abort_keep_alive;
1581
Olivier Houcharda798bf52019-03-08 18:52:00 +01001582 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001583 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001584 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001585 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001586 }
1587
Christopher Faulete0768eb2018-10-03 16:38:02 +02001588 rep->analysers &= AN_RES_FLT_END;
1589 txn->status = 502;
1590 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001591 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001592
1593 if (!(s->flags & SF_ERR_MASK))
1594 s->flags |= SF_ERR_SRVCL;
1595 if (!(s->flags & SF_FINST_MASK))
1596 s->flags |= SF_FINST_H;
1597 return 0;
1598 }
1599
Christopher Faulet9768c262018-10-22 09:34:31 +02001600 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001601 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001602 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001603 goto abort_keep_alive;
1604
Olivier Houcharda798bf52019-03-08 18:52:00 +01001605 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001606 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001607
1608 if (!(s->flags & SF_ERR_MASK))
1609 s->flags |= SF_ERR_CLICL;
1610 if (!(s->flags & SF_FINST_MASK))
1611 s->flags |= SF_FINST_H;
1612
1613 /* process_stream() will take care of the error */
1614 return 0;
1615 }
1616
1617 channel_dont_close(rep);
1618 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1619 return 0;
1620 }
1621
1622 /* More interesting part now : we know that we have a complete
1623 * response which at least looks like HTTP. We have an indicator
1624 * of each header's length, so we can parse them quickly.
1625 */
1626
Christopher Faulet9768c262018-10-22 09:34:31 +02001627 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet297fbb42019-05-13 14:41:27 +02001628 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001629
Christopher Faulet9768c262018-10-22 09:34:31 +02001630 /* 0: we might have to print this header in debug mode */
1631 if (unlikely((global.mode & MODE_DEBUG) &&
1632 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1633 int32_t pos;
1634
Christopher Faulet03599112018-11-27 11:21:21 +01001635 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001636
Christopher Fauleta3f15502019-05-13 15:27:23 +02001637 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001638 struct htx_blk *blk = htx_get_blk(htx, pos);
1639 enum htx_blk_type type = htx_get_blk_type(blk);
1640
1641 if (type == HTX_BLK_EOH)
1642 break;
1643 if (type != HTX_BLK_HDR)
1644 continue;
1645
1646 htx_debug_hdr("srvhdr", s,
1647 htx_get_blk_name(htx, blk),
1648 htx_get_blk_value(htx, blk));
1649 }
1650 }
1651
Christopher Faulet03599112018-11-27 11:21:21 +01001652 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001653 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001654 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001655 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001656 if (sl->flags & HTX_SL_F_XFER_LEN) {
1657 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001658 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001659 if (sl->flags & HTX_SL_F_BODYLESS)
1660 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001661 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001662
1663 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001664 if (n < 1 || n > 5)
1665 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001666
Christopher Faulete0768eb2018-10-03 16:38:02 +02001667 /* when the client triggers a 4xx from the server, it's most often due
1668 * to a missing object or permission. These events should be tracked
1669 * because if they happen often, it may indicate a brute force or a
1670 * vulnerability scan.
1671 */
1672 if (n == 4)
1673 stream_inc_http_err_ctr(s);
1674
1675 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001676 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001677
Christopher Faulete0768eb2018-10-03 16:38:02 +02001678 /* Adjust server's health based on status code. Note: status codes 501
1679 * and 505 are triggered on demand by client request, so we must not
1680 * count them as server failures.
1681 */
1682 if (objt_server(s->target)) {
1683 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001684 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001685 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001686 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001687 }
1688
1689 /*
1690 * We may be facing a 100-continue response, or any other informational
1691 * 1xx response which is non-final, in which case this is not the right
1692 * response, and we're waiting for the next one. Let's allow this response
1693 * to go to the client and wait for the next one. There's an exception for
1694 * 101 which is used later in the code to switch protocols.
1695 */
1696 if (txn->status < 200 &&
1697 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletf90c24d2019-05-17 09:58:45 +02001698 int32_t pos;
1699
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001700 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001701 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Fauletf90c24d2019-05-17 09:58:45 +02001702 struct htx_blk *blk = htx_get_blk(htx, pos);
1703 enum htx_blk_type type = htx_get_blk_type(blk);
1704
1705 c_adv(rep, htx_get_blksz(blk));
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001706 if (type == HTX_BLK_EOH) {
1707 htx->sl_pos = htx_get_next(htx, pos);
Christopher Fauletf90c24d2019-05-17 09:58:45 +02001708 break;
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001709 }
Christopher Fauletf90c24d2019-05-17 09:58:45 +02001710 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001711 msg->msg_state = HTTP_MSG_RPBEFORE;
1712 txn->status = 0;
1713 s->logs.t_data = -1; /* was not a response yet */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001714 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001715 }
1716
1717 /*
1718 * 2: check for cacheability.
1719 */
1720
1721 switch (txn->status) {
1722 case 200:
1723 case 203:
1724 case 204:
1725 case 206:
1726 case 300:
1727 case 301:
1728 case 404:
1729 case 405:
1730 case 410:
1731 case 414:
1732 case 501:
1733 break;
1734 default:
1735 /* RFC7231#6.1:
1736 * Responses with status codes that are defined as
1737 * cacheable by default (e.g., 200, 203, 204, 206,
1738 * 300, 301, 404, 405, 410, 414, and 501 in this
1739 * specification) can be reused by a cache with
1740 * heuristic expiration unless otherwise indicated
1741 * by the method definition or explicit cache
1742 * controls [RFC7234]; all other status codes are
1743 * not cacheable by default.
1744 */
1745 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1746 break;
1747 }
1748
1749 /*
1750 * 3: we may need to capture headers
1751 */
1752 s->logs.logwait &= ~LW_RESP;
1753 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001754 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001755
Christopher Faulet9768c262018-10-22 09:34:31 +02001756 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001757 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1758 txn->status == 101)) {
1759 /* Either we've established an explicit tunnel, or we're
1760 * switching the protocol. In both cases, we're very unlikely
1761 * to understand the next protocols. We have to switch to tunnel
1762 * mode, so that we transfer the request and responses then let
1763 * this protocol pass unmodified. When we later implement specific
1764 * parsers for such protocols, we'll want to check the Upgrade
1765 * header which contains information about that protocol for
1766 * responses with status 101 (eg: see RFC2817 about TLS).
1767 */
1768 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001769 }
1770
Christopher Faulet61608322018-11-23 16:23:45 +01001771 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1772 * 407 (Proxy-Authenticate) responses and set the connection to private
1773 */
1774 srv_conn = cs_conn(objt_cs(s->si[1].end));
1775 if (srv_conn) {
1776 struct ist hdr;
1777 struct http_hdr_ctx ctx;
1778
1779 if (txn->status == 401)
1780 hdr = ist("WWW-Authenticate");
1781 else if (txn->status == 407)
1782 hdr = ist("Proxy-Authenticate");
1783 else
1784 goto end;
1785
1786 ctx.blk = NULL;
1787 while (http_find_header(htx, hdr, &ctx, 0)) {
1788 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1789 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1790 srv_conn->flags |= CO_FL_PRIVATE;
1791 }
1792 }
1793
1794 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001795 /* we want to have the response time before we start processing it */
1796 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1797
1798 /* end of job, return OK */
1799 rep->analysers &= ~an_bit;
1800 rep->analyse_exp = TICK_ETERNITY;
1801 channel_auto_close(rep);
1802 return 1;
1803
Christopher Faulet47365272018-10-31 17:40:50 +01001804 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001805 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001806 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001807 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001808 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001809 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001810 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001811 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001812 do_l7_retry(s, si_b) == 0)
1813 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001814 txn->status = 502;
1815 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001816 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001817 rep->analysers &= AN_RES_FLT_END;
1818
1819 if (!(s->flags & SF_ERR_MASK))
1820 s->flags |= SF_ERR_PRXCOND;
1821 if (!(s->flags & SF_FINST_MASK))
1822 s->flags |= SF_FINST_H;
1823 return 0;
1824
Christopher Faulete0768eb2018-10-03 16:38:02 +02001825 abort_keep_alive:
1826 /* A keep-alive request to the server failed on a network error.
1827 * The client is required to retry. We need to close without returning
1828 * any other information so that the client retries.
1829 */
1830 txn->status = 0;
1831 rep->analysers &= AN_RES_FLT_END;
1832 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001833 s->logs.logwait = 0;
1834 s->logs.level = 0;
1835 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001836 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001837 return 0;
1838}
1839
1840/* This function performs all the processing enabled for the current response.
1841 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1842 * and updates s->res.analysers. It might make sense to explode it into several
1843 * other functions. It works like process_request (see indications above).
1844 */
1845int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1846{
1847 struct session *sess = s->sess;
1848 struct http_txn *txn = s->txn;
1849 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001850 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001851 struct proxy *cur_proxy;
1852 struct cond_wordlist *wl;
1853 enum rule_result ret = HTTP_RULE_RES_CONT;
1854
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001855 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1856 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001857
Christopher Faulete0768eb2018-10-03 16:38:02 +02001858 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1859 now_ms, __FUNCTION__,
1860 s,
1861 rep,
1862 rep->rex, rep->wex,
1863 rep->flags,
1864 ci_data(rep),
1865 rep->analysers);
1866
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001867 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001868
1869 /* The stats applet needs to adjust the Connection header but we don't
1870 * apply any filter there.
1871 */
1872 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1873 rep->analysers &= ~an_bit;
1874 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001875 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001876 }
1877
1878 /*
1879 * We will have to evaluate the filters.
1880 * As opposed to version 1.2, now they will be evaluated in the
1881 * filters order and not in the header order. This means that
1882 * each filter has to be validated among all headers.
1883 *
1884 * Filters are tried with ->be first, then with ->fe if it is
1885 * different from ->be.
1886 *
1887 * Maybe we are in resume condiion. In this case I choose the
1888 * "struct proxy" which contains the rule list matching the resume
1889 * pointer. If none of theses "struct proxy" match, I initialise
1890 * the process with the first one.
1891 *
1892 * In fact, I check only correspondance betwwen the current list
1893 * pointer and the ->fe rule list. If it doesn't match, I initialize
1894 * the loop with the ->be.
1895 */
1896 if (s->current_rule_list == &sess->fe->http_res_rules)
1897 cur_proxy = sess->fe;
1898 else
1899 cur_proxy = s->be;
1900 while (1) {
1901 struct proxy *rule_set = cur_proxy;
1902
1903 /* evaluate http-response rules */
1904 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001905 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001906
1907 if (ret == HTTP_RULE_RES_BADREQ)
1908 goto return_srv_prx_502;
1909
1910 if (ret == HTTP_RULE_RES_DONE) {
1911 rep->analysers &= ~an_bit;
1912 rep->analyse_exp = TICK_ETERNITY;
1913 return 1;
1914 }
1915 }
1916
1917 /* we need to be called again. */
1918 if (ret == HTTP_RULE_RES_YIELD) {
1919 channel_dont_close(rep);
1920 return 0;
1921 }
1922
1923 /* try headers filters */
1924 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001925 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1926 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001927 }
1928
1929 /* has the response been denied ? */
1930 if (txn->flags & TX_SVDENY) {
1931 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001932 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001933
Olivier Houcharda798bf52019-03-08 18:52:00 +01001934 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1935 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001936 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001937 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001938 goto return_srv_prx_502;
1939 }
1940
1941 /* add response headers from the rule sets in the same order */
1942 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001943 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001944 if (txn->status < 200 && txn->status != 101)
1945 break;
1946 if (wl->cond) {
1947 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1948 ret = acl_pass(ret);
1949 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1950 ret = !ret;
1951 if (!ret)
1952 continue;
1953 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001954
1955 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1956 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001957 goto return_bad_resp;
1958 }
1959
1960 /* check whether we're already working on the frontend */
1961 if (cur_proxy == sess->fe)
1962 break;
1963 cur_proxy = sess->fe;
1964 }
1965
1966 /* After this point, this anayzer can't return yield, so we can
1967 * remove the bit corresponding to this analyzer from the list.
1968 *
1969 * Note that the intermediate returns and goto found previously
1970 * reset the analyzers.
1971 */
1972 rep->analysers &= ~an_bit;
1973 rep->analyse_exp = TICK_ETERNITY;
1974
1975 /* OK that's all we can do for 1xx responses */
1976 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001977 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001978
1979 /*
1980 * Now check for a server cookie.
1981 */
1982 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001983 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001984
1985 /*
1986 * Check for cache-control or pragma headers if required.
1987 */
1988 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1989 check_response_for_cacheability(s, rep);
1990
1991 /*
1992 * Add server cookie in the response if needed
1993 */
1994 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1995 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1996 (!(s->flags & SF_DIRECT) ||
1997 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1998 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1999 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2000 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2001 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2002 !(s->flags & SF_IGNORE_PRST)) {
2003 /* the server is known, it's not the one the client requested, or the
2004 * cookie's last seen date needs to be refreshed. We have to
2005 * insert a set-cookie here, except if we want to insert only on POST
2006 * requests and this one isn't. Note that servers which don't have cookies
2007 * (eg: some backup servers) will return a full cookie removal request.
2008 */
2009 if (!objt_server(s->target)->cookie) {
2010 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002011 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002012 s->be->cookie_name);
2013 }
2014 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002015 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002016
2017 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2018 /* emit last_date, which is mandatory */
2019 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2020 s30tob64((date.tv_sec+3) >> 2,
2021 trash.area + trash.data);
2022 trash.data += 5;
2023
2024 if (s->be->cookie_maxlife) {
2025 /* emit first_date, which is either the original one or
2026 * the current date.
2027 */
2028 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2029 s30tob64(txn->cookie_first_date ?
2030 txn->cookie_first_date >> 2 :
2031 (date.tv_sec+3) >> 2,
2032 trash.area + trash.data);
2033 trash.data += 5;
2034 }
2035 }
2036 chunk_appendf(&trash, "; path=/");
2037 }
2038
2039 if (s->be->cookie_domain)
2040 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2041
2042 if (s->be->ck_opts & PR_CK_HTTPONLY)
2043 chunk_appendf(&trash, "; HttpOnly");
2044
2045 if (s->be->ck_opts & PR_CK_SECURE)
2046 chunk_appendf(&trash, "; Secure");
2047
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002048 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002049 goto return_bad_resp;
2050
2051 txn->flags &= ~TX_SCK_MASK;
2052 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2053 /* the server did not change, only the date was updated */
2054 txn->flags |= TX_SCK_UPDATED;
2055 else
2056 txn->flags |= TX_SCK_INSERTED;
2057
2058 /* Here, we will tell an eventual cache on the client side that we don't
2059 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2060 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2061 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2062 */
2063 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2064
2065 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2066
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002067 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002068 goto return_bad_resp;
2069 }
2070 }
2071
2072 /*
2073 * Check if result will be cacheable with a cookie.
2074 * We'll block the response if security checks have caught
2075 * nasty things such as a cacheable cookie.
2076 */
2077 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2078 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2079 (s->be->options & PR_O_CHK_CACHE)) {
2080 /* we're in presence of a cacheable response containing
2081 * a set-cookie header. We'll block it as requested by
2082 * the 'checkcache' option, and send an alert.
2083 */
2084 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002085 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002086
Olivier Houcharda798bf52019-03-08 18:52:00 +01002087 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2088 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002089 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002090 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002091
2092 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2093 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2094 send_log(s->be, LOG_ALERT,
2095 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2096 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2097 goto return_srv_prx_502;
2098 }
2099
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002100 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002101 /* Always enter in the body analyzer */
2102 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2103 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2104
2105 /* if the user wants to log as soon as possible, without counting
2106 * bytes from the server, then this is the right moment. We have
2107 * to temporarily assign bytes_out to log what we currently have.
2108 */
2109 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2110 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002111 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002112 s->do_log(s);
2113 s->logs.bytes_out = 0;
2114 }
2115 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002116
2117 return_bad_resp:
2118 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002119 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002120 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002121 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002122 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002123
2124 return_srv_prx_502:
2125 rep->analysers &= AN_RES_FLT_END;
2126 txn->status = 502;
2127 s->logs.t_data = -1; /* was not a valid response */
2128 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002129 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002130 if (!(s->flags & SF_ERR_MASK))
2131 s->flags |= SF_ERR_PRXCOND;
2132 if (!(s->flags & SF_FINST_MASK))
2133 s->flags |= SF_FINST_H;
2134 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002135}
2136
2137/* This function is an analyser which forwards response body (including chunk
2138 * sizes if any). It is called as soon as we must forward, even if we forward
2139 * zero byte. The only situation where it must not be called is when we're in
2140 * tunnel mode and we want to forward till the close. It's used both to forward
2141 * remaining data and to resync after end of body. It expects the msg_state to
2142 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2143 * read more data, or 1 once we can go on with next request or end the stream.
2144 *
2145 * It is capable of compressing response data both in content-length mode and
2146 * in chunked mode. The state machines follows different flows depending on
2147 * whether content-length and chunked modes are used, since there are no
2148 * trailers in content-length :
2149 *
2150 * chk-mode cl-mode
2151 * ,----- BODY -----.
2152 * / \
2153 * V size > 0 V chk-mode
2154 * .--> SIZE -------------> DATA -------------> CRLF
2155 * | | size == 0 | last byte |
2156 * | v final crlf v inspected |
2157 * | TRAILERS -----------> DONE |
2158 * | |
2159 * `----------------------------------------------'
2160 *
2161 * Compression only happens in the DATA state, and must be flushed in final
2162 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2163 * is performed at once on final states for all bytes parsed, or when leaving
2164 * on missing data.
2165 */
2166int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2167{
2168 struct session *sess = s->sess;
2169 struct http_txn *txn = s->txn;
2170 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002171 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002172 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002173
2174 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2175 now_ms, __FUNCTION__,
2176 s,
2177 res,
2178 res->rex, res->wex,
2179 res->flags,
2180 ci_data(res),
2181 res->analysers);
2182
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002183 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002184
2185 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002186 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002187 /* Output closed while we were sending data. We must abort and
2188 * wake the other side up.
2189 */
2190 msg->err_state = msg->msg_state;
2191 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002192 htx_end_response(s);
2193 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002194 return 1;
2195 }
2196
Christopher Faulet9768c262018-10-22 09:34:31 +02002197 if (msg->msg_state == HTTP_MSG_BODY)
2198 msg->msg_state = HTTP_MSG_DATA;
2199
Christopher Faulete0768eb2018-10-03 16:38:02 +02002200 /* in most states, we should abort in case of early close */
2201 channel_auto_close(res);
2202
Christopher Faulete0768eb2018-10-03 16:38:02 +02002203 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002204 if (res->to_forward == CHN_INFINITE_FORWARD) {
2205 if (res->flags & (CF_SHUTR|CF_EOI)) {
2206 msg->msg_state = HTTP_MSG_DONE;
2207 res->to_forward = 0;
2208 goto done;
2209 }
2210 }
2211 else {
2212 /* We can't process the buffer's contents yet */
2213 res->flags |= CF_WAKE_WRITE;
2214 goto missing_data_or_waiting;
2215 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002216 }
2217
Christopher Faulet9768c262018-10-22 09:34:31 +02002218 if (msg->msg_state >= HTTP_MSG_DONE)
2219 goto done;
2220
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002221 /* Forward input data. We get it by removing all outgoing data not
2222 * forwarded yet from HTX data size. If there are some data filters, we
2223 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002224 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002225 if (HAS_RSP_DATA_FILTERS(s)) {
2226 ret = flt_http_payload(s, msg, htx->data);
2227 if (ret < 0)
2228 goto return_bad_res;
2229 c_adv(res, ret);
2230 if (htx->data != co_data(res) || htx->extra)
2231 goto missing_data_or_waiting;
2232 }
2233 else {
2234 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002235 if (msg->flags & HTTP_MSGF_XFER_LEN)
2236 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002237 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002238
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002239 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2240 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2241 msg->msg_state = HTTP_MSG_TUNNEL;
2242 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002243 }
2244
Christopher Faulet9768c262018-10-22 09:34:31 +02002245 /* Check if the end-of-message is reached and if so, switch the message
2246 * in HTTP_MSG_DONE state.
2247 */
2248 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2249 goto missing_data_or_waiting;
2250
2251 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002252 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002253
2254 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002255 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002256 channel_dont_close(res);
2257
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002258 if (HAS_RSP_DATA_FILTERS(s)) {
2259 ret = flt_http_end(s, msg);
2260 if (ret <= 0) {
2261 if (!ret)
2262 goto missing_data_or_waiting;
2263 goto return_bad_res;
2264 }
2265 }
2266
Christopher Fauletf2824e62018-10-01 12:12:37 +02002267 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002268 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002269 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002270 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2271 if (res->flags & CF_SHUTW) {
2272 /* response errors are most likely due to the
2273 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002274 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002275 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002276 goto return_bad_res;
2277 }
2278 return 1;
2279 }
2280 return 0;
2281
2282 missing_data_or_waiting:
2283 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002284 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002285
Christopher Faulet47365272018-10-31 17:40:50 +01002286 if (htx->flags & HTX_FL_PARSING_ERROR)
2287 goto return_bad_res;
2288
Christopher Faulete0768eb2018-10-03 16:38:02 +02002289 /* stop waiting for data if the input is closed before the end. If the
2290 * client side was already closed, it means that the client has aborted,
2291 * so we don't want to count this as a server abort. Otherwise it's a
2292 * server abort.
2293 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002294 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002295 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002296 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002297 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002298 if (htx_is_empty(htx))
2299 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002300 }
2301
Christopher Faulete0768eb2018-10-03 16:38:02 +02002302 /* When TE: chunked is used, we need to get there again to parse
2303 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002304 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2305 * are filters registered on the stream, we don't want to forward a
2306 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002307 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002308 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002309 channel_dont_close(res);
2310
2311 /* We know that more data are expected, but we couldn't send more that
2312 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2313 * system knows it must not set a PUSH on this first part. Interactive
2314 * modes are already handled by the stream sock layer. We must not do
2315 * this in content-length mode because it could present the MSG_MORE
2316 * flag with the last block of forwarded data, which would cause an
2317 * additional delay to be observed by the receiver.
2318 */
2319 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2320 res->flags |= CF_EXPECT_MORE;
2321
2322 /* the stream handler will take care of timeouts and errors */
2323 return 0;
2324
Christopher Faulet93e02d82019-03-08 14:18:50 +01002325 return_srv_abort:
2326 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2327 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002328 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002329 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2330 if (!(s->flags & SF_ERR_MASK))
2331 s->flags |= SF_ERR_SRVCL;
2332 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002333
Christopher Faulet93e02d82019-03-08 14:18:50 +01002334 return_cli_abort:
2335 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2336 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002337 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002338 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2339 if (!(s->flags & SF_ERR_MASK))
2340 s->flags |= SF_ERR_CLICL;
2341 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002342
Christopher Faulet93e02d82019-03-08 14:18:50 +01002343 return_bad_res:
2344 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2345 if (objt_server(s->target)) {
2346 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2347 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2348 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002349 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002350 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002351
Christopher Faulet93e02d82019-03-08 14:18:50 +01002352 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002353 txn->rsp.err_state = txn->rsp.msg_state;
2354 txn->rsp.msg_state = HTTP_MSG_ERROR;
2355 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002356 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002357 res->analysers &= AN_RES_FLT_END;
2358 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 +02002359 if (!(s->flags & SF_FINST_MASK))
2360 s->flags |= SF_FINST_D;
2361 return 0;
2362}
2363
Christopher Fauletf2824e62018-10-01 12:12:37 +02002364/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002365 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002366 * as too large a request to build a valid response.
2367 */
2368int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2369{
Christopher Faulet99daf282018-11-28 22:58:13 +01002370 struct channel *req = &s->req;
2371 struct channel *res = &s->res;
2372 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002373 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002374 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002375 struct ist status, reason, location;
2376 unsigned int flags;
2377 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002378 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002379
2380 chunk = alloc_trash_chunk();
2381 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002382 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002383
Christopher Faulet99daf282018-11-28 22:58:13 +01002384 /*
2385 * Create the location
2386 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002387 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002388 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002389 case REDIRECT_TYPE_SCHEME: {
2390 struct http_hdr_ctx ctx;
2391 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002392
Christopher Faulet99daf282018-11-28 22:58:13 +01002393 host = ist("");
2394 ctx.blk = NULL;
2395 if (http_find_header(htx, ist("Host"), &ctx, 0))
2396 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002397
Christopher Faulet297fbb42019-05-13 14:41:27 +02002398 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002399 path = http_get_path(htx_sl_req_uri(sl));
2400 /* build message using path */
2401 if (path.ptr) {
2402 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2403 int qs = 0;
2404 while (qs < path.len) {
2405 if (*(path.ptr + qs) == '?') {
2406 path.len = qs;
2407 break;
2408 }
2409 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002410 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002411 }
2412 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002413 else
2414 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002415
Christopher Faulet99daf282018-11-28 22:58:13 +01002416 if (rule->rdr_str) { /* this is an old "redirect" rule */
2417 /* add scheme */
2418 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2419 goto fail;
2420 }
2421 else {
2422 /* add scheme with executing log format */
2423 chunk->data += build_logline(s, chunk->area + chunk->data,
2424 chunk->size - chunk->data,
2425 &rule->rdr_fmt);
2426 }
2427 /* add "://" + host + path */
2428 if (!chunk_memcat(chunk, "://", 3) ||
2429 !chunk_memcat(chunk, host.ptr, host.len) ||
2430 !chunk_memcat(chunk, path.ptr, path.len))
2431 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002432
Christopher Faulet99daf282018-11-28 22:58:13 +01002433 /* append a slash at the end of the location if needed and missing */
2434 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2435 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2436 if (chunk->data + 1 >= chunk->size)
2437 goto fail;
2438 chunk->area[chunk->data++] = '/';
2439 }
2440 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002441 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002442
Christopher Faulet99daf282018-11-28 22:58:13 +01002443 case REDIRECT_TYPE_PREFIX: {
2444 struct ist path;
2445
Christopher Faulet297fbb42019-05-13 14:41:27 +02002446 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002447 path = http_get_path(htx_sl_req_uri(sl));
2448 /* build message using path */
2449 if (path.ptr) {
2450 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2451 int qs = 0;
2452 while (qs < path.len) {
2453 if (*(path.ptr + qs) == '?') {
2454 path.len = qs;
2455 break;
2456 }
2457 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002458 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002459 }
2460 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002461 else
2462 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002463
Christopher Faulet99daf282018-11-28 22:58:13 +01002464 if (rule->rdr_str) { /* this is an old "redirect" rule */
2465 /* add prefix. Note that if prefix == "/", we don't want to
2466 * add anything, otherwise it makes it hard for the user to
2467 * configure a self-redirection.
2468 */
2469 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2470 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2471 goto fail;
2472 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002473 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002474 else {
2475 /* add prefix with executing log format */
2476 chunk->data += build_logline(s, chunk->area + chunk->data,
2477 chunk->size - chunk->data,
2478 &rule->rdr_fmt);
2479 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002480
Christopher Faulet99daf282018-11-28 22:58:13 +01002481 /* add path */
2482 if (!chunk_memcat(chunk, path.ptr, path.len))
2483 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002484
Christopher Faulet99daf282018-11-28 22:58:13 +01002485 /* append a slash at the end of the location if needed and missing */
2486 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2487 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2488 if (chunk->data + 1 >= chunk->size)
2489 goto fail;
2490 chunk->area[chunk->data++] = '/';
2491 }
2492 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002493 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002494 case REDIRECT_TYPE_LOCATION:
2495 default:
2496 if (rule->rdr_str) { /* this is an old "redirect" rule */
2497 /* add location */
2498 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2499 goto fail;
2500 }
2501 else {
2502 /* add location with executing log format */
2503 chunk->data += build_logline(s, chunk->area + chunk->data,
2504 chunk->size - chunk->data,
2505 &rule->rdr_fmt);
2506 }
2507 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002508 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002509 location = ist2(chunk->area, chunk->data);
2510
2511 /*
2512 * Create the 30x response
2513 */
2514 switch (rule->code) {
2515 case 308:
2516 status = ist("308");
2517 reason = ist("Permanent Redirect");
2518 break;
2519 case 307:
2520 status = ist("307");
2521 reason = ist("Temporary Redirect");
2522 break;
2523 case 303:
2524 status = ist("303");
2525 reason = ist("See Other");
2526 break;
2527 case 301:
2528 status = ist("301");
2529 reason = ist("Moved Permanently");
2530 break;
2531 case 302:
2532 default:
2533 status = ist("302");
2534 reason = ist("Found");
2535 break;
2536 }
2537
Christopher Faulet08e66462019-05-23 16:44:59 +02002538 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2539 close = 1;
2540
Christopher Faulet99daf282018-11-28 22:58:13 +01002541 htx = htx_from_buf(&res->buf);
2542 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2543 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2544 if (!sl)
2545 goto fail;
2546 sl->info.res.status = rule->code;
2547 s->txn->status = rule->code;
2548
Christopher Faulet08e66462019-05-23 16:44:59 +02002549 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2550 goto fail;
2551
2552 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002553 !htx_add_header(htx, ist("Location"), location))
2554 goto fail;
2555
2556 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2557 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2558 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002559 }
2560
2561 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002562 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2563 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002564 }
2565
Christopher Faulet99daf282018-11-28 22:58:13 +01002566 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2567 goto fail;
2568
Christopher Fauletf2824e62018-10-01 12:12:37 +02002569 /* let's log the request time */
2570 s->logs.tv_request = now;
2571
Christopher Faulet99daf282018-11-28 22:58:13 +01002572 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002573 c_adv(res, data);
2574 res->total += data;
2575
2576 channel_auto_read(req);
2577 channel_abort(req);
2578 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002579 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002580
2581 res->wex = tick_add_ifset(now_ms, res->wto);
2582 channel_auto_read(res);
2583 channel_auto_close(res);
2584 channel_shutr_now(res);
2585
2586 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002587
2588 if (!(s->flags & SF_ERR_MASK))
2589 s->flags |= SF_ERR_LOCAL;
2590 if (!(s->flags & SF_FINST_MASK))
2591 s->flags |= SF_FINST_R;
2592
Christopher Faulet99daf282018-11-28 22:58:13 +01002593 free_trash_chunk(chunk);
2594 return 1;
2595
2596 fail:
2597 /* If an error occurred, remove the incomplete HTTP response from the
2598 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002599 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002600 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002601 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002602}
2603
Christopher Faulet72333522018-10-24 11:25:02 +02002604int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2605 struct ist name, const char *str, struct my_regex *re, int action)
2606{
2607 struct http_hdr_ctx ctx;
2608 struct buffer *output = get_trash_chunk();
2609
2610 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2611 ctx.blk = NULL;
2612 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2613 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2614 continue;
2615
2616 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2617 if (output->data == -1)
2618 return -1;
2619 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2620 return -1;
2621 }
2622 return 0;
2623}
2624
2625static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2626 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2627{
2628 struct buffer *replace;
2629 int ret = -1;
2630
2631 replace = alloc_trash_chunk();
2632 if (!replace)
2633 goto leave;
2634
2635 replace->data = build_logline(s, replace->area, replace->size, fmt);
2636 if (replace->data >= replace->size - 1)
2637 goto leave;
2638
2639 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2640
2641 leave:
2642 free_trash_chunk(replace);
2643 return ret;
2644}
2645
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002646
2647/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2648 * on success and -1 on error. The response channel is updated accordingly.
2649 */
2650static int htx_reply_103_early_hints(struct channel *res)
2651{
2652 struct htx *htx = htx_from_buf(&res->buf);
2653 size_t data;
2654
2655 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2656 /* If an error occurred during an Early-hint rule,
2657 * remove the incomplete HTTP 103 response from the
2658 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002659 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002660 return -1;
2661 }
2662
2663 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002664 c_adv(res, data);
2665 res->total += data;
2666 return 0;
2667}
2668
Christopher Faulet6eb92892018-11-15 16:39:29 +01002669/*
2670 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2671 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002672 * If <early_hints> is 0, it is starts a new response by adding the start
2673 * line. If an error occurred -1 is returned. On success 0 is returned. The
2674 * channel is not updated here. It must be done calling the function
2675 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002676 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002677static 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 +01002678{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002679 struct channel *res = &s->res;
2680 struct htx *htx = htx_from_buf(&res->buf);
2681 struct buffer *value = alloc_trash_chunk();
2682
Christopher Faulet6eb92892018-11-15 16:39:29 +01002683 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002684 struct htx_sl *sl;
2685 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2686 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2687
2688 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2689 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2690 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002691 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002692 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002693 }
2694
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002695 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2696 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002697 goto fail;
2698
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002699 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002700 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002701
2702 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002703 /* If an error occurred during an Early-hint rule, remove the incomplete
2704 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002705 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002706 free_trash_chunk(value);
2707 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002708}
2709
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002710/* This function executes one of the set-{method,path,query,uri} actions. It
2711 * takes the string from the variable 'replace' with length 'len', then modifies
2712 * the relevant part of the request line accordingly. Then it updates various
2713 * pointers to the next elements which were moved, and the total buffer length.
2714 * It finds the action to be performed in p[2], previously filled by function
2715 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2716 * error, though this can be revisited when this code is finally exploited.
2717 *
2718 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2719 * query string and 3 to replace uri.
2720 *
2721 * In query string case, the mark question '?' must be set at the start of the
2722 * string by the caller, event if the replacement query string is empty.
2723 */
2724int htx_req_replace_stline(int action, const char *replace, int len,
2725 struct proxy *px, struct stream *s)
2726{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002727 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002728
2729 switch (action) {
2730 case 0: // method
2731 if (!http_replace_req_meth(htx, ist2(replace, len)))
2732 return -1;
2733 break;
2734
2735 case 1: // path
2736 if (!http_replace_req_path(htx, ist2(replace, len)))
2737 return -1;
2738 break;
2739
2740 case 2: // query
2741 if (!http_replace_req_query(htx, ist2(replace, len)))
2742 return -1;
2743 break;
2744
2745 case 3: // uri
2746 if (!http_replace_req_uri(htx, ist2(replace, len)))
2747 return -1;
2748 break;
2749
2750 default:
2751 return -1;
2752 }
2753 return 0;
2754}
2755
2756/* This function replace the HTTP status code and the associated message. The
2757 * variable <status> contains the new status code. This function never fails.
2758 */
2759void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2760{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002761 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002762 char *res;
2763
2764 chunk_reset(&trash);
2765 res = ultoa_o(status, trash.area, trash.size);
2766 trash.data = res - trash.area;
2767
2768 /* Do we have a custom reason format string? */
2769 if (reason == NULL)
2770 reason = http_get_reason(status);
2771
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002772 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002773 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2774}
2775
Christopher Faulet3e964192018-10-24 11:39:23 +02002776/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2777 * transaction <txn>. Returns the verdict of the first rule that prevents
2778 * further processing of the request (auth, deny, ...), and defaults to
2779 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2780 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2781 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2782 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2783 * status.
2784 */
2785static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2786 struct stream *s, int *deny_status)
2787{
2788 struct session *sess = strm_sess(s);
2789 struct http_txn *txn = s->txn;
2790 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002791 struct act_rule *rule;
2792 struct http_hdr_ctx ctx;
2793 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002794 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2795 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002796 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002797
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002798 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002799
2800 /* If "the current_rule_list" match the executed rule list, we are in
2801 * resume condition. If a resume is needed it is always in the action
2802 * and never in the ACL or converters. In this case, we initialise the
2803 * current rule, and go to the action execution point.
2804 */
2805 if (s->current_rule) {
2806 rule = s->current_rule;
2807 s->current_rule = NULL;
2808 if (s->current_rule_list == rules)
2809 goto resume_execution;
2810 }
2811 s->current_rule_list = rules;
2812
2813 list_for_each_entry(rule, rules, list) {
2814 /* check optional condition */
2815 if (rule->cond) {
2816 int ret;
2817
2818 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2819 ret = acl_pass(ret);
2820
2821 if (rule->cond->pol == ACL_COND_UNLESS)
2822 ret = !ret;
2823
2824 if (!ret) /* condition not matched */
2825 continue;
2826 }
2827
2828 act_flags |= ACT_FLAG_FIRST;
2829 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002830 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2831 early_hints = 0;
2832 if (htx_reply_103_early_hints(&s->res) == -1) {
2833 rule_ret = HTTP_RULE_RES_BADREQ;
2834 goto end;
2835 }
2836 }
2837
Christopher Faulet3e964192018-10-24 11:39:23 +02002838 switch (rule->action) {
2839 case ACT_ACTION_ALLOW:
2840 rule_ret = HTTP_RULE_RES_STOP;
2841 goto end;
2842
2843 case ACT_ACTION_DENY:
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_TARPIT:
2850 txn->flags |= TX_CLTARPIT;
2851 if (deny_status)
2852 *deny_status = rule->deny_status;
2853 rule_ret = HTTP_RULE_RES_DENY;
2854 goto end;
2855
2856 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002857 /* Auth might be performed on regular http-req rules as well as on stats */
2858 auth_realm = rule->arg.auth.realm;
2859 if (!auth_realm) {
2860 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2861 auth_realm = STATS_DEFAULT_REALM;
2862 else
2863 auth_realm = px->id;
2864 }
2865 /* send 401/407 depending on whether we use a proxy or not. We still
2866 * count one error, because normal browsing won't significantly
2867 * increase the counter but brute force attempts will.
2868 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002869 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002870 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2871 rule_ret = HTTP_RULE_RES_BADREQ;
2872 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002873 goto end;
2874
2875 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002876 rule_ret = HTTP_RULE_RES_DONE;
2877 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2878 rule_ret = HTTP_RULE_RES_BADREQ;
2879 goto end;
2880
2881 case ACT_HTTP_SET_NICE:
2882 s->task->nice = rule->arg.nice;
2883 break;
2884
2885 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002886 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002887 break;
2888
2889 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002890 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002891 break;
2892
2893 case ACT_HTTP_SET_LOGL:
2894 s->logs.level = rule->arg.loglevel;
2895 break;
2896
2897 case ACT_HTTP_REPLACE_HDR:
2898 case ACT_HTTP_REPLACE_VAL:
2899 if (htx_transform_header(s, &s->req, htx,
2900 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2901 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002902 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002903 rule_ret = HTTP_RULE_RES_BADREQ;
2904 goto end;
2905 }
2906 break;
2907
2908 case ACT_HTTP_DEL_HDR:
2909 /* remove all occurrences of the header */
2910 ctx.blk = NULL;
2911 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2912 http_remove_header(htx, &ctx);
2913 break;
2914
2915 case ACT_HTTP_SET_HDR:
2916 case ACT_HTTP_ADD_HDR: {
2917 /* The scope of the trash buffer must be limited to this function. The
2918 * build_logline() function can execute a lot of other function which
2919 * can use the trash buffer. So for limiting the scope of this global
2920 * buffer, we build first the header value using build_logline, and
2921 * after we store the header name.
2922 */
2923 struct buffer *replace;
2924 struct ist n, v;
2925
2926 replace = alloc_trash_chunk();
2927 if (!replace) {
2928 rule_ret = HTTP_RULE_RES_BADREQ;
2929 goto end;
2930 }
2931
2932 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2933 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2934 v = ist2(replace->area, replace->data);
2935
2936 if (rule->action == ACT_HTTP_SET_HDR) {
2937 /* remove all occurrences of the header */
2938 ctx.blk = NULL;
2939 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2940 http_remove_header(htx, &ctx);
2941 }
2942
2943 if (!http_add_header(htx, n, v)) {
2944 static unsigned char rate_limit = 0;
2945
2946 if ((rate_limit++ & 255) == 0) {
2947 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);
2948 }
2949
Olivier Houcharda798bf52019-03-08 18:52:00 +01002950 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002951 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002952 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002953 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002954 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002955 }
2956 free_trash_chunk(replace);
2957 break;
2958 }
2959
2960 case ACT_HTTP_DEL_ACL:
2961 case ACT_HTTP_DEL_MAP: {
2962 struct pat_ref *ref;
2963 struct buffer *key;
2964
2965 /* collect reference */
2966 ref = pat_ref_lookup(rule->arg.map.ref);
2967 if (!ref)
2968 continue;
2969
2970 /* allocate key */
2971 key = alloc_trash_chunk();
2972 if (!key) {
2973 rule_ret = HTTP_RULE_RES_BADREQ;
2974 goto end;
2975 }
2976
2977 /* collect key */
2978 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2979 key->area[key->data] = '\0';
2980
2981 /* perform update */
2982 /* returned code: 1=ok, 0=ko */
2983 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2984 pat_ref_delete(ref, key->area);
2985 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2986
2987 free_trash_chunk(key);
2988 break;
2989 }
2990
2991 case ACT_HTTP_ADD_ACL: {
2992 struct pat_ref *ref;
2993 struct buffer *key;
2994
2995 /* collect reference */
2996 ref = pat_ref_lookup(rule->arg.map.ref);
2997 if (!ref)
2998 continue;
2999
3000 /* allocate key */
3001 key = alloc_trash_chunk();
3002 if (!key) {
3003 rule_ret = HTTP_RULE_RES_BADREQ;
3004 goto end;
3005 }
3006
3007 /* collect key */
3008 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3009 key->area[key->data] = '\0';
3010
3011 /* perform update */
3012 /* add entry only if it does not already exist */
3013 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3014 if (pat_ref_find_elt(ref, key->area) == NULL)
3015 pat_ref_add(ref, key->area, NULL, NULL);
3016 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3017
3018 free_trash_chunk(key);
3019 break;
3020 }
3021
3022 case ACT_HTTP_SET_MAP: {
3023 struct pat_ref *ref;
3024 struct buffer *key, *value;
3025
3026 /* collect reference */
3027 ref = pat_ref_lookup(rule->arg.map.ref);
3028 if (!ref)
3029 continue;
3030
3031 /* allocate key */
3032 key = alloc_trash_chunk();
3033 if (!key) {
3034 rule_ret = HTTP_RULE_RES_BADREQ;
3035 goto end;
3036 }
3037
3038 /* allocate value */
3039 value = alloc_trash_chunk();
3040 if (!value) {
3041 free_trash_chunk(key);
3042 rule_ret = HTTP_RULE_RES_BADREQ;
3043 goto end;
3044 }
3045
3046 /* collect key */
3047 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3048 key->area[key->data] = '\0';
3049
3050 /* collect value */
3051 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3052 value->area[value->data] = '\0';
3053
3054 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003055 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003056 if (pat_ref_find_elt(ref, key->area) != NULL)
3057 /* update entry if it exists */
3058 pat_ref_set(ref, key->area, value->area, NULL);
3059 else
3060 /* insert a new entry */
3061 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003062 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003063 free_trash_chunk(key);
3064 free_trash_chunk(value);
3065 break;
3066 }
3067
3068 case ACT_HTTP_EARLY_HINT:
3069 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3070 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003071 early_hints = htx_add_early_hint_header(s, early_hints,
3072 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003073 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003074 if (early_hints == -1) {
3075 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003076 goto end;
3077 }
3078 break;
3079
3080 case ACT_CUSTOM:
3081 if ((s->req.flags & CF_READ_ERROR) ||
3082 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003083 (px->options & PR_O_ABRT_CLOSE)))
3084 act_flags |= ACT_FLAG_FINAL;
3085
3086 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3087 case ACT_RET_ERR:
3088 case ACT_RET_CONT:
3089 break;
3090 case ACT_RET_STOP:
3091 rule_ret = HTTP_RULE_RES_DONE;
3092 goto end;
3093 case ACT_RET_YIELD:
3094 s->current_rule = rule;
3095 rule_ret = HTTP_RULE_RES_YIELD;
3096 goto end;
3097 }
3098 break;
3099
3100 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3101 /* Note: only the first valid tracking parameter of each
3102 * applies.
3103 */
3104
3105 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3106 struct stktable *t;
3107 struct stksess *ts;
3108 struct stktable_key *key;
3109 void *ptr1, *ptr2;
3110
3111 t = rule->arg.trk_ctr.table.t;
3112 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3113 rule->arg.trk_ctr.expr, NULL);
3114
3115 if (key && (ts = stktable_get_entry(t, key))) {
3116 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3117
3118 /* let's count a new HTTP request as it's the first time we do it */
3119 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3120 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3121 if (ptr1 || ptr2) {
3122 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3123
3124 if (ptr1)
3125 stktable_data_cast(ptr1, http_req_cnt)++;
3126
3127 if (ptr2)
3128 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3129 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3130
3131 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3132
3133 /* If data was modified, we need to touch to re-schedule sync */
3134 stktable_touch_local(t, ts, 0);
3135 }
3136
3137 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3138 if (sess->fe != s->be)
3139 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3140 }
3141 }
3142 break;
3143
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003144 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003145 default:
3146 break;
3147 }
3148 }
3149
3150 end:
3151 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003152 if (htx_reply_103_early_hints(&s->res) == -1)
3153 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003154 }
3155
3156 /* we reached the end of the rules, nothing to report */
3157 return rule_ret;
3158}
3159
3160/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3161 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3162 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3163 * is returned, the process can continue the evaluation of next rule list. If
3164 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3165 * is returned, it means the operation could not be processed and a server error
3166 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3167 * deny rule. If *YIELD is returned, the caller must call again the function
3168 * with the same context.
3169 */
3170static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3171 struct stream *s)
3172{
3173 struct session *sess = strm_sess(s);
3174 struct http_txn *txn = s->txn;
3175 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003176 struct act_rule *rule;
3177 struct http_hdr_ctx ctx;
3178 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3179 int act_flags = 0;
3180
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003181 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003182
3183 /* If "the current_rule_list" match the executed rule list, we are in
3184 * resume condition. If a resume is needed it is always in the action
3185 * and never in the ACL or converters. In this case, we initialise the
3186 * current rule, and go to the action execution point.
3187 */
3188 if (s->current_rule) {
3189 rule = s->current_rule;
3190 s->current_rule = NULL;
3191 if (s->current_rule_list == rules)
3192 goto resume_execution;
3193 }
3194 s->current_rule_list = rules;
3195
3196 list_for_each_entry(rule, rules, list) {
3197 /* check optional condition */
3198 if (rule->cond) {
3199 int ret;
3200
3201 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3202 ret = acl_pass(ret);
3203
3204 if (rule->cond->pol == ACL_COND_UNLESS)
3205 ret = !ret;
3206
3207 if (!ret) /* condition not matched */
3208 continue;
3209 }
3210
3211 act_flags |= ACT_FLAG_FIRST;
3212resume_execution:
3213 switch (rule->action) {
3214 case ACT_ACTION_ALLOW:
3215 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3216 goto end;
3217
3218 case ACT_ACTION_DENY:
3219 txn->flags |= TX_SVDENY;
3220 rule_ret = HTTP_RULE_RES_STOP;
3221 goto end;
3222
3223 case ACT_HTTP_SET_NICE:
3224 s->task->nice = rule->arg.nice;
3225 break;
3226
3227 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003228 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003229 break;
3230
3231 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003232 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003233 break;
3234
3235 case ACT_HTTP_SET_LOGL:
3236 s->logs.level = rule->arg.loglevel;
3237 break;
3238
3239 case ACT_HTTP_REPLACE_HDR:
3240 case ACT_HTTP_REPLACE_VAL:
3241 if (htx_transform_header(s, &s->res, htx,
3242 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3243 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003244 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003245 rule_ret = HTTP_RULE_RES_BADREQ;
3246 goto end;
3247 }
3248 break;
3249
3250 case ACT_HTTP_DEL_HDR:
3251 /* remove all occurrences of the header */
3252 ctx.blk = NULL;
3253 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3254 http_remove_header(htx, &ctx);
3255 break;
3256
3257 case ACT_HTTP_SET_HDR:
3258 case ACT_HTTP_ADD_HDR: {
3259 struct buffer *replace;
3260 struct ist n, v;
3261
3262 replace = alloc_trash_chunk();
3263 if (!replace) {
3264 rule_ret = HTTP_RULE_RES_BADREQ;
3265 goto end;
3266 }
3267
3268 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3269 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3270 v = ist2(replace->area, replace->data);
3271
3272 if (rule->action == ACT_HTTP_SET_HDR) {
3273 /* remove all occurrences of the header */
3274 ctx.blk = NULL;
3275 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3276 http_remove_header(htx, &ctx);
3277 }
3278
3279 if (!http_add_header(htx, n, v)) {
3280 static unsigned char rate_limit = 0;
3281
3282 if ((rate_limit++ & 255) == 0) {
3283 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);
3284 }
3285
Olivier Houcharda798bf52019-03-08 18:52:00 +01003286 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003287 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003288 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003289 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003290 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003291 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003292 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003293 }
3294 free_trash_chunk(replace);
3295 break;
3296 }
3297
3298 case ACT_HTTP_DEL_ACL:
3299 case ACT_HTTP_DEL_MAP: {
3300 struct pat_ref *ref;
3301 struct buffer *key;
3302
3303 /* collect reference */
3304 ref = pat_ref_lookup(rule->arg.map.ref);
3305 if (!ref)
3306 continue;
3307
3308 /* allocate key */
3309 key = alloc_trash_chunk();
3310 if (!key) {
3311 rule_ret = HTTP_RULE_RES_BADREQ;
3312 goto end;
3313 }
3314
3315 /* collect key */
3316 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3317 key->area[key->data] = '\0';
3318
3319 /* perform update */
3320 /* returned code: 1=ok, 0=ko */
3321 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3322 pat_ref_delete(ref, key->area);
3323 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3324
3325 free_trash_chunk(key);
3326 break;
3327 }
3328
3329 case ACT_HTTP_ADD_ACL: {
3330 struct pat_ref *ref;
3331 struct buffer *key;
3332
3333 /* collect reference */
3334 ref = pat_ref_lookup(rule->arg.map.ref);
3335 if (!ref)
3336 continue;
3337
3338 /* allocate key */
3339 key = alloc_trash_chunk();
3340 if (!key) {
3341 rule_ret = HTTP_RULE_RES_BADREQ;
3342 goto end;
3343 }
3344
3345 /* collect key */
3346 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3347 key->area[key->data] = '\0';
3348
3349 /* perform update */
3350 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003351 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003352 if (pat_ref_find_elt(ref, key->area) == NULL)
3353 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003354 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003355 free_trash_chunk(key);
3356 break;
3357 }
3358
3359 case ACT_HTTP_SET_MAP: {
3360 struct pat_ref *ref;
3361 struct buffer *key, *value;
3362
3363 /* collect reference */
3364 ref = pat_ref_lookup(rule->arg.map.ref);
3365 if (!ref)
3366 continue;
3367
3368 /* allocate key */
3369 key = alloc_trash_chunk();
3370 if (!key) {
3371 rule_ret = HTTP_RULE_RES_BADREQ;
3372 goto end;
3373 }
3374
3375 /* allocate value */
3376 value = alloc_trash_chunk();
3377 if (!value) {
3378 free_trash_chunk(key);
3379 rule_ret = HTTP_RULE_RES_BADREQ;
3380 goto end;
3381 }
3382
3383 /* collect key */
3384 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3385 key->area[key->data] = '\0';
3386
3387 /* collect value */
3388 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3389 value->area[value->data] = '\0';
3390
3391 /* perform update */
3392 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3393 if (pat_ref_find_elt(ref, key->area) != NULL)
3394 /* update entry if it exists */
3395 pat_ref_set(ref, key->area, value->area, NULL);
3396 else
3397 /* insert a new entry */
3398 pat_ref_add(ref, key->area, value->area, NULL);
3399 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3400 free_trash_chunk(key);
3401 free_trash_chunk(value);
3402 break;
3403 }
3404
3405 case ACT_HTTP_REDIR:
3406 rule_ret = HTTP_RULE_RES_DONE;
3407 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3408 rule_ret = HTTP_RULE_RES_BADREQ;
3409 goto end;
3410
3411 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3412 /* Note: only the first valid tracking parameter of each
3413 * applies.
3414 */
3415 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3416 struct stktable *t;
3417 struct stksess *ts;
3418 struct stktable_key *key;
3419 void *ptr;
3420
3421 t = rule->arg.trk_ctr.table.t;
3422 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3423 rule->arg.trk_ctr.expr, NULL);
3424
3425 if (key && (ts = stktable_get_entry(t, key))) {
3426 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3427
3428 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3429
3430 /* let's count a new HTTP request as it's the first time we do it */
3431 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3432 if (ptr)
3433 stktable_data_cast(ptr, http_req_cnt)++;
3434
3435 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3436 if (ptr)
3437 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3438 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3439
3440 /* When the client triggers a 4xx from the server, it's most often due
3441 * to a missing object or permission. These events should be tracked
3442 * because if they happen often, it may indicate a brute force or a
3443 * vulnerability scan. Normally this is done when receiving the response
3444 * but here we're tracking after this ought to have been done so we have
3445 * to do it on purpose.
3446 */
3447 if ((unsigned)(txn->status - 400) < 100) {
3448 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3449 if (ptr)
3450 stktable_data_cast(ptr, http_err_cnt)++;
3451
3452 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3453 if (ptr)
3454 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3455 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3456 }
3457
3458 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3459
3460 /* If data was modified, we need to touch to re-schedule sync */
3461 stktable_touch_local(t, ts, 0);
3462
3463 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3464 if (sess->fe != s->be)
3465 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3466 }
3467 }
3468 break;
3469
3470 case ACT_CUSTOM:
3471 if ((s->req.flags & CF_READ_ERROR) ||
3472 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003473 (px->options & PR_O_ABRT_CLOSE)))
3474 act_flags |= ACT_FLAG_FINAL;
3475
3476 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3477 case ACT_RET_ERR:
3478 case ACT_RET_CONT:
3479 break;
3480 case ACT_RET_STOP:
3481 rule_ret = HTTP_RULE_RES_STOP;
3482 goto end;
3483 case ACT_RET_YIELD:
3484 s->current_rule = rule;
3485 rule_ret = HTTP_RULE_RES_YIELD;
3486 goto end;
3487 }
3488 break;
3489
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003490 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003491 default:
3492 break;
3493 }
3494 }
3495
3496 end:
3497 /* we reached the end of the rules, nothing to report */
3498 return rule_ret;
3499}
3500
Christopher Faulet33640082018-10-24 11:53:01 +02003501/* Iterate the same filter through all request headers.
3502 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3503 * Since it can manage the switch to another backend, it updates the per-proxy
3504 * DENY stats.
3505 */
3506static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3507{
3508 struct http_txn *txn = s->txn;
3509 struct htx *htx;
3510 struct buffer *hdr = get_trash_chunk();
3511 int32_t pos;
3512
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003513 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003514
Christopher Fauleta3f15502019-05-13 15:27:23 +02003515 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003516 struct htx_blk *blk = htx_get_blk(htx, pos);
3517 enum htx_blk_type type;
3518 struct ist n, v;
3519
3520 next_hdr:
3521 type = htx_get_blk_type(blk);
3522 if (type == HTX_BLK_EOH)
3523 break;
3524 if (type != HTX_BLK_HDR)
3525 continue;
3526
3527 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3528 return 1;
3529 else if (unlikely(txn->flags & TX_CLALLOW) &&
3530 (exp->action == ACT_ALLOW ||
3531 exp->action == ACT_DENY ||
3532 exp->action == ACT_TARPIT))
3533 return 0;
3534
3535 n = htx_get_blk_name(htx, blk);
3536 v = htx_get_blk_value(htx, blk);
3537
Christopher Faulet02e771a2019-02-26 15:36:05 +01003538 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003539 hdr->area[hdr->data++] = ':';
3540 hdr->area[hdr->data++] = ' ';
3541 chunk_memcat(hdr, v.ptr, v.len);
3542
3543 /* Now we have one header in <hdr> */
3544
3545 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3546 struct http_hdr_ctx ctx;
3547 int len;
3548
3549 switch (exp->action) {
3550 case ACT_ALLOW:
3551 txn->flags |= TX_CLALLOW;
3552 goto end;
3553
3554 case ACT_DENY:
3555 txn->flags |= TX_CLDENY;
3556 goto end;
3557
3558 case ACT_TARPIT:
3559 txn->flags |= TX_CLTARPIT;
3560 goto end;
3561
3562 case ACT_REPLACE:
3563 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3564 if (len < 0)
3565 return -1;
3566
3567 http_parse_header(ist2(trash.area, len), &n, &v);
3568 ctx.blk = blk;
3569 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003570 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003571 if (!http_replace_header(htx, &ctx, n, v))
3572 return -1;
3573 if (!ctx.blk)
3574 goto end;
3575 pos = htx_get_blk_pos(htx, blk);
3576 break;
3577
3578 case ACT_REMOVE:
3579 ctx.blk = blk;
3580 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003581 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003582 if (!http_remove_header(htx, &ctx))
3583 return -1;
3584 if (!ctx.blk)
3585 goto end;
3586 pos = htx_get_blk_pos(htx, blk);
3587 goto next_hdr;
3588
3589 }
3590 }
3591 }
3592 end:
3593 return 0;
3594}
3595
3596/* Apply the filter to the request line.
3597 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3598 * or -1 if a replacement resulted in an invalid request line.
3599 * Since it can manage the switch to another backend, it updates the per-proxy
3600 * DENY stats.
3601 */
3602static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3603{
3604 struct http_txn *txn = s->txn;
3605 struct htx *htx;
3606 struct buffer *reqline = get_trash_chunk();
3607 int done;
3608
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003609 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003610
3611 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3612 return 1;
3613 else if (unlikely(txn->flags & TX_CLALLOW) &&
3614 (exp->action == ACT_ALLOW ||
3615 exp->action == ACT_DENY ||
3616 exp->action == ACT_TARPIT))
3617 return 0;
3618 else if (exp->action == ACT_REMOVE)
3619 return 0;
3620
3621 done = 0;
3622
Christopher Faulet297fbb42019-05-13 14:41:27 +02003623 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003624
3625 /* Now we have the request line between cur_ptr and cur_end */
3626 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003627 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003628 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003629 int len;
3630
3631 switch (exp->action) {
3632 case ACT_ALLOW:
3633 txn->flags |= TX_CLALLOW;
3634 done = 1;
3635 break;
3636
3637 case ACT_DENY:
3638 txn->flags |= TX_CLDENY;
3639 done = 1;
3640 break;
3641
3642 case ACT_TARPIT:
3643 txn->flags |= TX_CLTARPIT;
3644 done = 1;
3645 break;
3646
3647 case ACT_REPLACE:
3648 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3649 if (len < 0)
3650 return -1;
3651
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003652 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3653 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3654 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003655 return -1;
3656 done = 1;
3657 break;
3658 }
3659 }
3660 return done;
3661}
3662
3663/*
3664 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3665 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3666 * unparsable request. Since it can manage the switch to another backend, it
3667 * updates the per-proxy DENY stats.
3668 */
3669static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3670{
3671 struct session *sess = s->sess;
3672 struct http_txn *txn = s->txn;
3673 struct hdr_exp *exp;
3674
3675 for (exp = px->req_exp; exp; exp = exp->next) {
3676 int ret;
3677
3678 /*
3679 * The interleaving of transformations and verdicts
3680 * makes it difficult to decide to continue or stop
3681 * the evaluation.
3682 */
3683
3684 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3685 break;
3686
3687 if ((txn->flags & TX_CLALLOW) &&
3688 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3689 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3690 continue;
3691
3692 /* if this filter had a condition, evaluate it now and skip to
3693 * next filter if the condition does not match.
3694 */
3695 if (exp->cond) {
3696 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3697 ret = acl_pass(ret);
3698 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3699 ret = !ret;
3700
3701 if (!ret)
3702 continue;
3703 }
3704
3705 /* Apply the filter to the request line. */
3706 ret = htx_apply_filter_to_req_line(s, req, exp);
3707 if (unlikely(ret < 0))
3708 return -1;
3709
3710 if (likely(ret == 0)) {
3711 /* The filter did not match the request, it can be
3712 * iterated through all headers.
3713 */
3714 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3715 return -1;
3716 }
3717 }
3718 return 0;
3719}
3720
3721/* Iterate the same filter through all response headers contained in <res>.
3722 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3723 */
3724static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3725{
3726 struct http_txn *txn = s->txn;
3727 struct htx *htx;
3728 struct buffer *hdr = get_trash_chunk();
3729 int32_t pos;
3730
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003731 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003732
Christopher Fauleta3f15502019-05-13 15:27:23 +02003733 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003734 struct htx_blk *blk = htx_get_blk(htx, pos);
3735 enum htx_blk_type type;
3736 struct ist n, v;
3737
3738 next_hdr:
3739 type = htx_get_blk_type(blk);
3740 if (type == HTX_BLK_EOH)
3741 break;
3742 if (type != HTX_BLK_HDR)
3743 continue;
3744
3745 if (unlikely(txn->flags & TX_SVDENY))
3746 return 1;
3747 else if (unlikely(txn->flags & TX_SVALLOW) &&
3748 (exp->action == ACT_ALLOW ||
3749 exp->action == ACT_DENY))
3750 return 0;
3751
3752 n = htx_get_blk_name(htx, blk);
3753 v = htx_get_blk_value(htx, blk);
3754
Christopher Faulet02e771a2019-02-26 15:36:05 +01003755 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003756 hdr->area[hdr->data++] = ':';
3757 hdr->area[hdr->data++] = ' ';
3758 chunk_memcat(hdr, v.ptr, v.len);
3759
3760 /* Now we have one header in <hdr> */
3761
3762 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3763 struct http_hdr_ctx ctx;
3764 int len;
3765
3766 switch (exp->action) {
3767 case ACT_ALLOW:
3768 txn->flags |= TX_SVALLOW;
3769 goto end;
3770 break;
3771
3772 case ACT_DENY:
3773 txn->flags |= TX_SVDENY;
3774 goto end;
3775 break;
3776
3777 case ACT_REPLACE:
3778 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3779 if (len < 0)
3780 return -1;
3781
3782 http_parse_header(ist2(trash.area, len), &n, &v);
3783 ctx.blk = blk;
3784 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003785 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003786 if (!http_replace_header(htx, &ctx, n, v))
3787 return -1;
3788 if (!ctx.blk)
3789 goto end;
3790 pos = htx_get_blk_pos(htx, blk);
3791 break;
3792
3793 case ACT_REMOVE:
3794 ctx.blk = blk;
3795 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003796 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003797 if (!http_remove_header(htx, &ctx))
3798 return -1;
3799 if (!ctx.blk)
3800 goto end;
3801 pos = htx_get_blk_pos(htx, blk);
3802 goto next_hdr;
3803 }
3804 }
3805
3806 }
3807 end:
3808 return 0;
3809}
3810
3811/* Apply the filter to the status line in the response buffer <res>.
3812 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3813 * or -1 if a replacement resulted in an invalid status line.
3814 */
3815static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3816{
3817 struct http_txn *txn = s->txn;
3818 struct htx *htx;
3819 struct buffer *resline = get_trash_chunk();
3820 int done;
3821
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003822 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003823
3824 if (unlikely(txn->flags & TX_SVDENY))
3825 return 1;
3826 else if (unlikely(txn->flags & TX_SVALLOW) &&
3827 (exp->action == ACT_ALLOW ||
3828 exp->action == ACT_DENY))
3829 return 0;
3830 else if (exp->action == ACT_REMOVE)
3831 return 0;
3832
3833 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003834 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003835
3836 /* Now we have the status line between cur_ptr and cur_end */
3837 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003838 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003839 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003840 int len;
3841
3842 switch (exp->action) {
3843 case ACT_ALLOW:
3844 txn->flags |= TX_SVALLOW;
3845 done = 1;
3846 break;
3847
3848 case ACT_DENY:
3849 txn->flags |= TX_SVDENY;
3850 done = 1;
3851 break;
3852
3853 case ACT_REPLACE:
3854 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3855 if (len < 0)
3856 return -1;
3857
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003858 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3859 sl->info.res.status = strl2ui(code.ptr, code.len);
3860 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003861 return -1;
3862
3863 done = 1;
3864 return 1;
3865 }
3866 }
3867 return done;
3868}
3869
3870/*
3871 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3872 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3873 * unparsable response.
3874 */
3875static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3876{
3877 struct session *sess = s->sess;
3878 struct http_txn *txn = s->txn;
3879 struct hdr_exp *exp;
3880
3881 for (exp = px->rsp_exp; exp; exp = exp->next) {
3882 int ret;
3883
3884 /*
3885 * The interleaving of transformations and verdicts
3886 * makes it difficult to decide to continue or stop
3887 * the evaluation.
3888 */
3889
3890 if (txn->flags & TX_SVDENY)
3891 break;
3892
3893 if ((txn->flags & TX_SVALLOW) &&
3894 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3895 exp->action == ACT_PASS)) {
3896 exp = exp->next;
3897 continue;
3898 }
3899
3900 /* if this filter had a condition, evaluate it now and skip to
3901 * next filter if the condition does not match.
3902 */
3903 if (exp->cond) {
3904 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3905 ret = acl_pass(ret);
3906 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3907 ret = !ret;
3908 if (!ret)
3909 continue;
3910 }
3911
3912 /* Apply the filter to the status line. */
3913 ret = htx_apply_filter_to_sts_line(s, res, exp);
3914 if (unlikely(ret < 0))
3915 return -1;
3916
3917 if (likely(ret == 0)) {
3918 /* The filter did not match the response, it can be
3919 * iterated through all headers.
3920 */
3921 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3922 return -1;
3923 }
3924 }
3925 return 0;
3926}
3927
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003928/*
3929 * Manage client-side cookie. It can impact performance by about 2% so it is
3930 * desirable to call it only when needed. This code is quite complex because
3931 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3932 * highly recommended not to touch this part without a good reason !
3933 */
3934static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3935{
3936 struct session *sess = s->sess;
3937 struct http_txn *txn = s->txn;
3938 struct htx *htx;
3939 struct http_hdr_ctx ctx;
3940 char *hdr_beg, *hdr_end, *del_from;
3941 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3942 int preserve_hdr;
3943
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003944 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003945 ctx.blk = NULL;
3946 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3947 del_from = NULL; /* nothing to be deleted */
3948 preserve_hdr = 0; /* assume we may kill the whole header */
3949
3950 /* Now look for cookies. Conforming to RFC2109, we have to support
3951 * attributes whose name begin with a '$', and associate them with
3952 * the right cookie, if we want to delete this cookie.
3953 * So there are 3 cases for each cookie read :
3954 * 1) it's a special attribute, beginning with a '$' : ignore it.
3955 * 2) it's a server id cookie that we *MAY* want to delete : save
3956 * some pointers on it (last semi-colon, beginning of cookie...)
3957 * 3) it's an application cookie : we *MAY* have to delete a previous
3958 * "special" cookie.
3959 * At the end of loop, if a "special" cookie remains, we may have to
3960 * remove it. If no application cookie persists in the header, we
3961 * *MUST* delete it.
3962 *
3963 * Note: RFC2965 is unclear about the processing of spaces around
3964 * the equal sign in the ATTR=VALUE form. A careful inspection of
3965 * the RFC explicitly allows spaces before it, and not within the
3966 * tokens (attrs or values). An inspection of RFC2109 allows that
3967 * too but section 10.1.3 lets one think that spaces may be allowed
3968 * after the equal sign too, resulting in some (rare) buggy
3969 * implementations trying to do that. So let's do what servers do.
3970 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3971 * allowed quoted strings in values, with any possible character
3972 * after a backslash, including control chars and delimitors, which
3973 * causes parsing to become ambiguous. Browsers also allow spaces
3974 * within values even without quotes.
3975 *
3976 * We have to keep multiple pointers in order to support cookie
3977 * removal at the beginning, middle or end of header without
3978 * corrupting the header. All of these headers are valid :
3979 *
3980 * hdr_beg hdr_end
3981 * | |
3982 * v |
3983 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3984 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3985 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3986 * | | | | | | |
3987 * | | | | | | |
3988 * | | | | | | +--> next
3989 * | | | | | +----> val_end
3990 * | | | | +-----------> val_beg
3991 * | | | +--------------> equal
3992 * | | +----------------> att_end
3993 * | +---------------------> att_beg
3994 * +--------------------------> prev
3995 *
3996 */
3997 hdr_beg = ctx.value.ptr;
3998 hdr_end = hdr_beg + ctx.value.len;
3999 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4000 /* Iterate through all cookies on this line */
4001
4002 /* find att_beg */
4003 att_beg = prev;
4004 if (prev > hdr_beg)
4005 att_beg++;
4006
4007 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4008 att_beg++;
4009
4010 /* find att_end : this is the first character after the last non
4011 * space before the equal. It may be equal to hdr_end.
4012 */
4013 equal = att_end = att_beg;
4014 while (equal < hdr_end) {
4015 if (*equal == '=' || *equal == ',' || *equal == ';')
4016 break;
4017 if (HTTP_IS_SPHT(*equal++))
4018 continue;
4019 att_end = equal;
4020 }
4021
4022 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4023 * is between <att_beg> and <equal>, both may be identical.
4024 */
4025 /* look for end of cookie if there is an equal sign */
4026 if (equal < hdr_end && *equal == '=') {
4027 /* look for the beginning of the value */
4028 val_beg = equal + 1;
4029 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4030 val_beg++;
4031
4032 /* find the end of the value, respecting quotes */
4033 next = http_find_cookie_value_end(val_beg, hdr_end);
4034
4035 /* make val_end point to the first white space or delimitor after the value */
4036 val_end = next;
4037 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4038 val_end--;
4039 }
4040 else
4041 val_beg = val_end = next = equal;
4042
4043 /* We have nothing to do with attributes beginning with
4044 * '$'. However, they will automatically be removed if a
4045 * header before them is removed, since they're supposed
4046 * to be linked together.
4047 */
4048 if (*att_beg == '$')
4049 continue;
4050
4051 /* Ignore cookies with no equal sign */
4052 if (equal == next) {
4053 /* This is not our cookie, so we must preserve it. But if we already
4054 * scheduled another cookie for removal, we cannot remove the
4055 * complete header, but we can remove the previous block itself.
4056 */
4057 preserve_hdr = 1;
4058 if (del_from != NULL) {
4059 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4060 val_end += delta;
4061 next += delta;
4062 hdr_end += delta;
4063 prev = del_from;
4064 del_from = NULL;
4065 }
4066 continue;
4067 }
4068
4069 /* if there are spaces around the equal sign, we need to
4070 * strip them otherwise we'll get trouble for cookie captures,
4071 * or even for rewrites. Since this happens extremely rarely,
4072 * it does not hurt performance.
4073 */
4074 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4075 int stripped_before = 0;
4076 int stripped_after = 0;
4077
4078 if (att_end != equal) {
4079 memmove(att_end, equal, hdr_end - equal);
4080 stripped_before = (att_end - equal);
4081 equal += stripped_before;
4082 val_beg += stripped_before;
4083 }
4084
4085 if (val_beg > equal + 1) {
4086 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4087 stripped_after = (equal + 1) - val_beg;
4088 val_beg += stripped_after;
4089 stripped_before += stripped_after;
4090 }
4091
4092 val_end += stripped_before;
4093 next += stripped_before;
4094 hdr_end += stripped_before;
4095 }
4096 /* now everything is as on the diagram above */
4097
4098 /* First, let's see if we want to capture this cookie. We check
4099 * that we don't already have a client side cookie, because we
4100 * can only capture one. Also as an optimisation, we ignore
4101 * cookies shorter than the declared name.
4102 */
4103 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4104 (val_end - att_beg >= sess->fe->capture_namelen) &&
4105 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4106 int log_len = val_end - att_beg;
4107
4108 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4109 ha_alert("HTTP logging : out of memory.\n");
4110 } else {
4111 if (log_len > sess->fe->capture_len)
4112 log_len = sess->fe->capture_len;
4113 memcpy(txn->cli_cookie, att_beg, log_len);
4114 txn->cli_cookie[log_len] = 0;
4115 }
4116 }
4117
4118 /* Persistence cookies in passive, rewrite or insert mode have the
4119 * following form :
4120 *
4121 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4122 *
4123 * For cookies in prefix mode, the form is :
4124 *
4125 * Cookie: NAME=SRV~VALUE
4126 */
4127 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4128 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4129 struct server *srv = s->be->srv;
4130 char *delim;
4131
4132 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4133 * have the server ID between val_beg and delim, and the original cookie between
4134 * delim+1 and val_end. Otherwise, delim==val_end :
4135 *
4136 * hdr_beg
4137 * |
4138 * v
4139 * NAME=SRV; # in all but prefix modes
4140 * NAME=SRV~OPAQUE ; # in prefix mode
4141 * || || | |+-> next
4142 * || || | +--> val_end
4143 * || || +---------> delim
4144 * || |+------------> val_beg
4145 * || +-------------> att_end = equal
4146 * |+-----------------> att_beg
4147 * +------------------> prev
4148 *
4149 */
4150 if (s->be->ck_opts & PR_CK_PFX) {
4151 for (delim = val_beg; delim < val_end; delim++)
4152 if (*delim == COOKIE_DELIM)
4153 break;
4154 }
4155 else {
4156 char *vbar1;
4157 delim = val_end;
4158 /* Now check if the cookie contains a date field, which would
4159 * appear after a vertical bar ('|') just after the server name
4160 * and before the delimiter.
4161 */
4162 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4163 if (vbar1) {
4164 /* OK, so left of the bar is the server's cookie and
4165 * right is the last seen date. It is a base64 encoded
4166 * 30-bit value representing the UNIX date since the
4167 * epoch in 4-second quantities.
4168 */
4169 int val;
4170 delim = vbar1++;
4171 if (val_end - vbar1 >= 5) {
4172 val = b64tos30(vbar1);
4173 if (val > 0)
4174 txn->cookie_last_date = val << 2;
4175 }
4176 /* look for a second vertical bar */
4177 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4178 if (vbar1 && (val_end - vbar1 > 5)) {
4179 val = b64tos30(vbar1 + 1);
4180 if (val > 0)
4181 txn->cookie_first_date = val << 2;
4182 }
4183 }
4184 }
4185
4186 /* if the cookie has an expiration date and the proxy wants to check
4187 * it, then we do that now. We first check if the cookie is too old,
4188 * then only if it has expired. We detect strict overflow because the
4189 * time resolution here is not great (4 seconds). Cookies with dates
4190 * in the future are ignored if their offset is beyond one day. This
4191 * allows an admin to fix timezone issues without expiring everyone
4192 * and at the same time avoids keeping unwanted side effects for too
4193 * long.
4194 */
4195 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4196 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4197 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4198 txn->flags &= ~TX_CK_MASK;
4199 txn->flags |= TX_CK_OLD;
4200 delim = val_beg; // let's pretend we have not found the cookie
4201 txn->cookie_first_date = 0;
4202 txn->cookie_last_date = 0;
4203 }
4204 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4205 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4206 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4207 txn->flags &= ~TX_CK_MASK;
4208 txn->flags |= TX_CK_EXPIRED;
4209 delim = val_beg; // let's pretend we have not found the cookie
4210 txn->cookie_first_date = 0;
4211 txn->cookie_last_date = 0;
4212 }
4213
4214 /* Here, we'll look for the first running server which supports the cookie.
4215 * This allows to share a same cookie between several servers, for example
4216 * to dedicate backup servers to specific servers only.
4217 * However, to prevent clients from sticking to cookie-less backup server
4218 * when they have incidentely learned an empty cookie, we simply ignore
4219 * empty cookies and mark them as invalid.
4220 * The same behaviour is applied when persistence must be ignored.
4221 */
4222 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4223 srv = NULL;
4224
4225 while (srv) {
4226 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4227 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4228 if ((srv->cur_state != SRV_ST_STOPPED) ||
4229 (s->be->options & PR_O_PERSIST) ||
4230 (s->flags & SF_FORCE_PRST)) {
4231 /* we found the server and we can use it */
4232 txn->flags &= ~TX_CK_MASK;
4233 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4234 s->flags |= SF_DIRECT | SF_ASSIGNED;
4235 s->target = &srv->obj_type;
4236 break;
4237 } else {
4238 /* we found a server, but it's down,
4239 * mark it as such and go on in case
4240 * another one is available.
4241 */
4242 txn->flags &= ~TX_CK_MASK;
4243 txn->flags |= TX_CK_DOWN;
4244 }
4245 }
4246 srv = srv->next;
4247 }
4248
4249 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4250 /* no server matched this cookie or we deliberately skipped it */
4251 txn->flags &= ~TX_CK_MASK;
4252 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4253 txn->flags |= TX_CK_UNUSED;
4254 else
4255 txn->flags |= TX_CK_INVALID;
4256 }
4257
4258 /* depending on the cookie mode, we may have to either :
4259 * - delete the complete cookie if we're in insert+indirect mode, so that
4260 * the server never sees it ;
4261 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004262 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004263 * if we're in cookie prefix mode
4264 */
4265 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4266 int delta; /* negative */
4267
4268 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4269 delta = val_beg - (delim + 1);
4270 val_end += delta;
4271 next += delta;
4272 hdr_end += delta;
4273 del_from = NULL;
4274 preserve_hdr = 1; /* we want to keep this cookie */
4275 }
4276 else if (del_from == NULL &&
4277 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4278 del_from = prev;
4279 }
4280 }
4281 else {
4282 /* This is not our cookie, so we must preserve it. But if we already
4283 * scheduled another cookie for removal, we cannot remove the
4284 * complete header, but we can remove the previous block itself.
4285 */
4286 preserve_hdr = 1;
4287
4288 if (del_from != NULL) {
4289 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4290 if (att_beg >= del_from)
4291 att_beg += delta;
4292 if (att_end >= del_from)
4293 att_end += delta;
4294 val_beg += delta;
4295 val_end += delta;
4296 next += delta;
4297 hdr_end += delta;
4298 prev = del_from;
4299 del_from = NULL;
4300 }
4301 }
4302
4303 /* continue with next cookie on this header line */
4304 att_beg = next;
4305 } /* for each cookie */
4306
4307
4308 /* There are no more cookies on this line.
4309 * We may still have one (or several) marked for deletion at the
4310 * end of the line. We must do this now in two ways :
4311 * - if some cookies must be preserved, we only delete from the
4312 * mark to the end of line ;
4313 * - if nothing needs to be preserved, simply delete the whole header
4314 */
4315 if (del_from) {
4316 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4317 }
4318 if ((hdr_end - hdr_beg) != ctx.value.len) {
4319 if (hdr_beg != hdr_end) {
4320 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004321 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004322 }
4323 else
4324 http_remove_header(htx, &ctx);
4325 }
4326 } /* for each "Cookie header */
4327}
4328
4329/*
4330 * Manage server-side cookies. It can impact performance by about 2% so it is
4331 * desirable to call it only when needed. This function is also used when we
4332 * just need to know if there is a cookie (eg: for check-cache).
4333 */
4334static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4335{
4336 struct session *sess = s->sess;
4337 struct http_txn *txn = s->txn;
4338 struct htx *htx;
4339 struct http_hdr_ctx ctx;
4340 struct server *srv;
4341 char *hdr_beg, *hdr_end;
4342 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004343 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004344
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004345 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004346
4347 ctx.blk = NULL;
4348 while (1) {
4349 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4350 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4351 break;
4352 is_cookie2 = 1;
4353 }
4354
4355 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4356 * <prev> points to the colon.
4357 */
4358 txn->flags |= TX_SCK_PRESENT;
4359
4360 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4361 * check-cache is enabled) and we are not interested in checking
4362 * them. Warning, the cookie capture is declared in the frontend.
4363 */
4364 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4365 break;
4366
4367 /* OK so now we know we have to process this response cookie.
4368 * The format of the Set-Cookie header is slightly different
4369 * from the format of the Cookie header in that it does not
4370 * support the comma as a cookie delimiter (thus the header
4371 * cannot be folded) because the Expires attribute described in
4372 * the original Netscape's spec may contain an unquoted date
4373 * with a comma inside. We have to live with this because
4374 * many browsers don't support Max-Age and some browsers don't
4375 * support quoted strings. However the Set-Cookie2 header is
4376 * clean.
4377 *
4378 * We have to keep multiple pointers in order to support cookie
4379 * removal at the beginning, middle or end of header without
4380 * corrupting the header (in case of set-cookie2). A special
4381 * pointer, <scav> points to the beginning of the set-cookie-av
4382 * fields after the first semi-colon. The <next> pointer points
4383 * either to the end of line (set-cookie) or next unquoted comma
4384 * (set-cookie2). All of these headers are valid :
4385 *
4386 * hdr_beg hdr_end
4387 * | |
4388 * v |
4389 * NAME1 = VALUE 1 ; Secure; Path="/" |
4390 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4391 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4392 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4393 * | | | | | | | |
4394 * | | | | | | | +-> next
4395 * | | | | | | +------------> scav
4396 * | | | | | +--------------> val_end
4397 * | | | | +--------------------> val_beg
4398 * | | | +----------------------> equal
4399 * | | +------------------------> att_end
4400 * | +----------------------------> att_beg
4401 * +------------------------------> prev
4402 * -------------------------------> hdr_beg
4403 */
4404 hdr_beg = ctx.value.ptr;
4405 hdr_end = hdr_beg + ctx.value.len;
4406 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4407
4408 /* Iterate through all cookies on this line */
4409
4410 /* find att_beg */
4411 att_beg = prev;
4412 if (prev > hdr_beg)
4413 att_beg++;
4414
4415 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4416 att_beg++;
4417
4418 /* find att_end : this is the first character after the last non
4419 * space before the equal. It may be equal to hdr_end.
4420 */
4421 equal = att_end = att_beg;
4422
4423 while (equal < hdr_end) {
4424 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4425 break;
4426 if (HTTP_IS_SPHT(*equal++))
4427 continue;
4428 att_end = equal;
4429 }
4430
4431 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4432 * is between <att_beg> and <equal>, both may be identical.
4433 */
4434
4435 /* look for end of cookie if there is an equal sign */
4436 if (equal < hdr_end && *equal == '=') {
4437 /* look for the beginning of the value */
4438 val_beg = equal + 1;
4439 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4440 val_beg++;
4441
4442 /* find the end of the value, respecting quotes */
4443 next = http_find_cookie_value_end(val_beg, hdr_end);
4444
4445 /* make val_end point to the first white space or delimitor after the value */
4446 val_end = next;
4447 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4448 val_end--;
4449 }
4450 else {
4451 /* <equal> points to next comma, semi-colon or EOL */
4452 val_beg = val_end = next = equal;
4453 }
4454
4455 if (next < hdr_end) {
4456 /* Set-Cookie2 supports multiple cookies, and <next> points to
4457 * a colon or semi-colon before the end. So skip all attr-value
4458 * pairs and look for the next comma. For Set-Cookie, since
4459 * commas are permitted in values, skip to the end.
4460 */
4461 if (is_cookie2)
4462 next = http_find_hdr_value_end(next, hdr_end);
4463 else
4464 next = hdr_end;
4465 }
4466
4467 /* Now everything is as on the diagram above */
4468
4469 /* Ignore cookies with no equal sign */
4470 if (equal == val_end)
4471 continue;
4472
4473 /* If there are spaces around the equal sign, we need to
4474 * strip them otherwise we'll get trouble for cookie captures,
4475 * or even for rewrites. Since this happens extremely rarely,
4476 * it does not hurt performance.
4477 */
4478 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4479 int stripped_before = 0;
4480 int stripped_after = 0;
4481
4482 if (att_end != equal) {
4483 memmove(att_end, equal, hdr_end - equal);
4484 stripped_before = (att_end - equal);
4485 equal += stripped_before;
4486 val_beg += stripped_before;
4487 }
4488
4489 if (val_beg > equal + 1) {
4490 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4491 stripped_after = (equal + 1) - val_beg;
4492 val_beg += stripped_after;
4493 stripped_before += stripped_after;
4494 }
4495
4496 val_end += stripped_before;
4497 next += stripped_before;
4498 hdr_end += stripped_before;
4499
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004500 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4501 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004502 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004503 }
4504
4505 /* First, let's see if we want to capture this cookie. We check
4506 * that we don't already have a server side cookie, because we
4507 * can only capture one. Also as an optimisation, we ignore
4508 * cookies shorter than the declared name.
4509 */
4510 if (sess->fe->capture_name != NULL &&
4511 txn->srv_cookie == NULL &&
4512 (val_end - att_beg >= sess->fe->capture_namelen) &&
4513 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4514 int log_len = val_end - att_beg;
4515 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4516 ha_alert("HTTP logging : out of memory.\n");
4517 }
4518 else {
4519 if (log_len > sess->fe->capture_len)
4520 log_len = sess->fe->capture_len;
4521 memcpy(txn->srv_cookie, att_beg, log_len);
4522 txn->srv_cookie[log_len] = 0;
4523 }
4524 }
4525
4526 srv = objt_server(s->target);
4527 /* now check if we need to process it for persistence */
4528 if (!(s->flags & SF_IGNORE_PRST) &&
4529 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4530 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4531 /* assume passive cookie by default */
4532 txn->flags &= ~TX_SCK_MASK;
4533 txn->flags |= TX_SCK_FOUND;
4534
4535 /* If the cookie is in insert mode on a known server, we'll delete
4536 * this occurrence because we'll insert another one later.
4537 * We'll delete it too if the "indirect" option is set and we're in
4538 * a direct access.
4539 */
4540 if (s->be->ck_opts & PR_CK_PSV) {
4541 /* The "preserve" flag was set, we don't want to touch the
4542 * server's cookie.
4543 */
4544 }
4545 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4546 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4547 /* this cookie must be deleted */
4548 if (prev == hdr_beg && next == hdr_end) {
4549 /* whole header */
4550 http_remove_header(htx, &ctx);
4551 /* note: while both invalid now, <next> and <hdr_end>
4552 * are still equal, so the for() will stop as expected.
4553 */
4554 } else {
4555 /* just remove the value */
4556 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4557 next = prev;
4558 hdr_end += delta;
4559 }
4560 txn->flags &= ~TX_SCK_MASK;
4561 txn->flags |= TX_SCK_DELETED;
4562 /* and go on with next cookie */
4563 }
4564 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4565 /* replace bytes val_beg->val_end with the cookie name associated
4566 * with this server since we know it.
4567 */
4568 int sliding, delta;
4569
4570 ctx.value = ist2(val_beg, val_end - val_beg);
4571 ctx.lws_before = ctx.lws_after = 0;
4572 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4573 delta = srv->cklen - (val_end - val_beg);
4574 sliding = (ctx.value.ptr - val_beg);
4575 hdr_beg += sliding;
4576 val_beg += sliding;
4577 next += sliding + delta;
4578 hdr_end += sliding + delta;
4579
4580 txn->flags &= ~TX_SCK_MASK;
4581 txn->flags |= TX_SCK_REPLACED;
4582 }
4583 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4584 /* insert the cookie name associated with this server
4585 * before existing cookie, and insert a delimiter between them..
4586 */
4587 int sliding, delta;
4588 ctx.value = ist2(val_beg, 0);
4589 ctx.lws_before = ctx.lws_after = 0;
4590 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4591 delta = srv->cklen + 1;
4592 sliding = (ctx.value.ptr - val_beg);
4593 hdr_beg += sliding;
4594 val_beg += sliding;
4595 next += sliding + delta;
4596 hdr_end += sliding + delta;
4597
4598 val_beg[srv->cklen] = COOKIE_DELIM;
4599 txn->flags &= ~TX_SCK_MASK;
4600 txn->flags |= TX_SCK_REPLACED;
4601 }
4602 }
4603 /* that's done for this cookie, check the next one on the same
4604 * line when next != hdr_end (only if is_cookie2).
4605 */
4606 }
4607 }
4608}
4609
Christopher Faulet25a02f62018-10-24 12:00:25 +02004610/*
4611 * Parses the Cache-Control and Pragma request header fields to determine if
4612 * the request may be served from the cache and/or if it is cacheable. Updates
4613 * s->txn->flags.
4614 */
4615void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4616{
4617 struct http_txn *txn = s->txn;
4618 struct htx *htx;
4619 int32_t pos;
4620 int pragma_found, cc_found, i;
4621
4622 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4623 return; /* nothing more to do here */
4624
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004625 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004626 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004627 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004628 struct htx_blk *blk = htx_get_blk(htx, pos);
4629 enum htx_blk_type type = htx_get_blk_type(blk);
4630 struct ist n, v;
4631
4632 if (type == HTX_BLK_EOH)
4633 break;
4634 if (type != HTX_BLK_HDR)
4635 continue;
4636
4637 n = htx_get_blk_name(htx, blk);
4638 v = htx_get_blk_value(htx, blk);
4639
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004640 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004641 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4642 pragma_found = 1;
4643 continue;
4644 }
4645 }
4646
4647 /* Don't use the cache and don't try to store if we found the
4648 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004649 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004650 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4651 txn->flags |= TX_CACHE_IGNORE;
4652 continue;
4653 }
4654
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004655 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004656 continue;
4657
4658 /* OK, right now we know we have a cache-control header */
4659 cc_found = 1;
4660 if (!v.len) /* no info */
4661 continue;
4662
4663 i = 0;
4664 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4665 !isspace((unsigned char)*(v.ptr+i)))
4666 i++;
4667
4668 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4669 * values after max-age, max-stale nor min-fresh, we simply don't
4670 * use the cache when they're specified.
4671 */
4672 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4673 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4674 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4675 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4676 txn->flags |= TX_CACHE_IGNORE;
4677 continue;
4678 }
4679
4680 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4681 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4682 continue;
4683 }
4684 }
4685
4686 /* RFC7234#5.4:
4687 * When the Cache-Control header field is also present and
4688 * understood in a request, Pragma is ignored.
4689 * When the Cache-Control header field is not present in a
4690 * request, caches MUST consider the no-cache request
4691 * pragma-directive as having the same effect as if
4692 * "Cache-Control: no-cache" were present.
4693 */
4694 if (!cc_found && pragma_found)
4695 txn->flags |= TX_CACHE_IGNORE;
4696}
4697
4698/*
4699 * Check if response is cacheable or not. Updates s->txn->flags.
4700 */
4701void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4702{
4703 struct http_txn *txn = s->txn;
4704 struct htx *htx;
4705 int32_t pos;
4706 int i;
4707
4708 if (txn->status < 200) {
4709 /* do not try to cache interim responses! */
4710 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4711 return;
4712 }
4713
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004714 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004715 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004716 struct htx_blk *blk = htx_get_blk(htx, pos);
4717 enum htx_blk_type type = htx_get_blk_type(blk);
4718 struct ist n, v;
4719
4720 if (type == HTX_BLK_EOH)
4721 break;
4722 if (type != HTX_BLK_HDR)
4723 continue;
4724
4725 n = htx_get_blk_name(htx, blk);
4726 v = htx_get_blk_value(htx, blk);
4727
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004728 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004729 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4730 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4731 return;
4732 }
4733 }
4734
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004735 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004736 continue;
4737
4738 /* OK, right now we know we have a cache-control header */
4739 if (!v.len) /* no info */
4740 continue;
4741
4742 i = 0;
4743 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4744 !isspace((unsigned char)*(v.ptr+i)))
4745 i++;
4746
4747 /* we have a complete value between v.ptr and (v.ptr+i) */
4748 if (i < v.len && *(v.ptr + i) == '=') {
4749 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4750 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4751 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4752 continue;
4753 }
4754
4755 /* we have something of the form no-cache="set-cookie" */
4756 if ((v.len >= 21) &&
4757 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4758 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4759 txn->flags &= ~TX_CACHE_COOK;
4760 continue;
4761 }
4762
4763 /* OK, so we know that either p2 points to the end of string or to a comma */
4764 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4765 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4766 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4767 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4768 return;
4769 }
4770
4771 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4772 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4773 continue;
4774 }
4775 }
4776}
4777
Christopher Faulet64159df2018-10-24 21:15:35 +02004778/* send a server's name with an outgoing request over an established connection.
4779 * Note: this function is designed to be called once the request has been
4780 * scheduled for being forwarded. This is the reason why the number of forwarded
4781 * bytes have to be adjusted.
4782 */
4783int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4784{
4785 struct htx *htx;
4786 struct http_hdr_ctx ctx;
4787 struct ist hdr;
4788 uint32_t data;
4789
4790 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004791 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004792 data = htx->data;
4793
4794 ctx.blk = NULL;
4795 while (http_find_header(htx, hdr, &ctx, 1))
4796 http_remove_header(htx, &ctx);
4797 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4798
4799 if (co_data(&s->req)) {
4800 if (data >= htx->data)
4801 c_rew(&s->req, data - htx->data);
4802 else
4803 c_adv(&s->req, htx->data - data);
4804 }
4805 return 0;
4806}
4807
Christopher Faulet377c5a52018-10-24 21:21:30 +02004808/*
4809 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4810 * for the current backend.
4811 *
4812 * It is assumed that the request is either a HEAD, GET, or POST and that the
4813 * uri_auth field is valid.
4814 *
4815 * Returns 1 if stats should be provided, otherwise 0.
4816 */
4817static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4818{
4819 struct uri_auth *uri_auth = backend->uri_auth;
4820 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004821 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004822 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004823
4824 if (!uri_auth)
4825 return 0;
4826
4827 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4828 return 0;
4829
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004830 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004831 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004832 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004833
4834 /* check URI size */
4835 if (uri_auth->uri_len > uri.len)
4836 return 0;
4837
4838 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4839 return 0;
4840
4841 return 1;
4842}
4843
4844/* This function prepares an applet to handle the stats. It can deal with the
4845 * "100-continue" expectation, check that admin rules are met for POST requests,
4846 * and program a response message if something was unexpected. It cannot fail
4847 * and always relies on the stats applet to complete the job. It does not touch
4848 * analysers nor counters, which are left to the caller. It does not touch
4849 * s->target which is supposed to already point to the stats applet. The caller
4850 * is expected to have already assigned an appctx to the stream.
4851 */
4852static int htx_handle_stats(struct stream *s, struct channel *req)
4853{
4854 struct stats_admin_rule *stats_admin_rule;
4855 struct stream_interface *si = &s->si[1];
4856 struct session *sess = s->sess;
4857 struct http_txn *txn = s->txn;
4858 struct http_msg *msg = &txn->req;
4859 struct uri_auth *uri_auth = s->be->uri_auth;
4860 const char *h, *lookup, *end;
4861 struct appctx *appctx;
4862 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004863 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004864
4865 appctx = si_appctx(si);
4866 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4867 appctx->st1 = appctx->st2 = 0;
4868 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4869 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4870 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4871 appctx->ctx.stats.flags |= STAT_CHUNKED;
4872
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004873 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004874 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004875 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4876 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004877
4878 for (h = lookup; h <= end - 3; h++) {
4879 if (memcmp(h, ";up", 3) == 0) {
4880 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4881 break;
4882 }
4883 }
4884
4885 if (uri_auth->refresh) {
4886 for (h = lookup; h <= end - 10; h++) {
4887 if (memcmp(h, ";norefresh", 10) == 0) {
4888 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4889 break;
4890 }
4891 }
4892 }
4893
4894 for (h = lookup; h <= end - 4; h++) {
4895 if (memcmp(h, ";csv", 4) == 0) {
4896 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4897 break;
4898 }
4899 }
4900
4901 for (h = lookup; h <= end - 6; h++) {
4902 if (memcmp(h, ";typed", 6) == 0) {
4903 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4904 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4905 break;
4906 }
4907 }
4908
4909 for (h = lookup; h <= end - 8; h++) {
4910 if (memcmp(h, ";st=", 4) == 0) {
4911 int i;
4912 h += 4;
4913 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4914 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4915 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4916 appctx->ctx.stats.st_code = i;
4917 break;
4918 }
4919 }
4920 break;
4921 }
4922 }
4923
4924 appctx->ctx.stats.scope_str = 0;
4925 appctx->ctx.stats.scope_len = 0;
4926 for (h = lookup; h <= end - 8; h++) {
4927 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4928 int itx = 0;
4929 const char *h2;
4930 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4931 const char *err;
4932
4933 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4934 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004935 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4936 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004937 if (*h == ';' || *h == '&' || *h == ' ')
4938 break;
4939 itx++;
4940 h++;
4941 }
4942
4943 if (itx > STAT_SCOPE_TXT_MAXLEN)
4944 itx = STAT_SCOPE_TXT_MAXLEN;
4945 appctx->ctx.stats.scope_len = itx;
4946
4947 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4948 memcpy(scope_txt, h2, itx);
4949 scope_txt[itx] = '\0';
4950 err = invalid_char(scope_txt);
4951 if (err) {
4952 /* bad char in search text => clear scope */
4953 appctx->ctx.stats.scope_str = 0;
4954 appctx->ctx.stats.scope_len = 0;
4955 }
4956 break;
4957 }
4958 }
4959
4960 /* now check whether we have some admin rules for this request */
4961 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4962 int ret = 1;
4963
4964 if (stats_admin_rule->cond) {
4965 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4966 ret = acl_pass(ret);
4967 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4968 ret = !ret;
4969 }
4970
4971 if (ret) {
4972 /* no rule, or the rule matches */
4973 appctx->ctx.stats.flags |= STAT_ADMIN;
4974 break;
4975 }
4976 }
4977
Christopher Faulet5d45e382019-02-27 15:15:23 +01004978 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4979 appctx->st0 = STAT_HTTP_HEAD;
4980 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004981 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004982 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004983 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004984 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004985 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4986 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4987 appctx->st0 = STAT_HTTP_LAST;
4988 }
4989 }
4990 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004991 /* Unsupported method */
4992 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4993 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4994 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004995 }
4996
4997 s->task->nice = -32; /* small boost for HTTP statistics */
4998 return 1;
4999}
5000
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005001void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
5002{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005003 struct channel *req = &s->req;
5004 struct channel *res = &s->res;
5005 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005006 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005007 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005008 struct ist path, location;
5009 unsigned int flags;
5010 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005011
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005012 /*
5013 * Create the location
5014 */
5015 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005016
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005017 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005018 /* special prefix "/" means don't change URL */
5019 srv = __objt_server(s->target);
5020 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5021 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5022 return;
5023 }
5024
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005025 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005026 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005027 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005028 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005029 if (!path.ptr)
5030 return;
5031
5032 if (!chunk_memcat(&trash, path.ptr, path.len))
5033 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005034 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005035
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005036 /*
5037 * Create the 302 respone
5038 */
5039 htx = htx_from_buf(&res->buf);
5040 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5041 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5042 ist("HTTP/1.1"), ist("302"), ist("Found"));
5043 if (!sl)
5044 goto fail;
5045 sl->info.res.status = 302;
5046 s->txn->status = 302;
5047
5048 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5049 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5050 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5051 !htx_add_header(htx, ist("Location"), location))
5052 goto fail;
5053
5054 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5055 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005056
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005057 /*
5058 * Send the message
5059 */
5060 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005061 c_adv(res, data);
5062 res->total += data;
5063
5064 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005065 si_shutr(si);
5066 si_shutw(si);
5067 si->err_type = SI_ET_NONE;
5068 si->state = SI_ST_CLO;
5069
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005070 channel_auto_read(req);
5071 channel_abort(req);
5072 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005073 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005074 channel_auto_read(res);
5075 channel_auto_close(res);
5076
5077 if (!(s->flags & SF_ERR_MASK))
5078 s->flags |= SF_ERR_LOCAL;
5079 if (!(s->flags & SF_FINST_MASK))
5080 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005081
5082 /* FIXME: we should increase a counter of redirects per server and per backend. */
5083 srv_inc_sess_ctr(srv);
5084 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005085 return;
5086
5087 fail:
5088 /* If an error occurred, remove the incomplete HTTP response from the
5089 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005090 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005091}
5092
Christopher Fauletf2824e62018-10-01 12:12:37 +02005093/* This function terminates the request because it was completly analyzed or
5094 * because an error was triggered during the body forwarding.
5095 */
5096static void htx_end_request(struct stream *s)
5097{
5098 struct channel *chn = &s->req;
5099 struct http_txn *txn = s->txn;
5100
5101 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5102 now_ms, __FUNCTION__, s,
5103 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5104 s->req.analysers, s->res.analysers);
5105
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005106 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5107 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005108 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005109 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005110 goto end;
5111 }
5112
5113 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5114 return;
5115
5116 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005117 /* No need to read anymore, the request was completely parsed.
5118 * We can shut the read side unless we want to abort_on_close,
5119 * or we have a POST request. The issue with POST requests is
5120 * that some browsers still send a CRLF after the request, and
5121 * this CRLF must be read so that it does not remain in the kernel
5122 * buffers, otherwise a close could cause an RST on some systems
5123 * (eg: Linux).
5124 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005125 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005126 channel_dont_read(chn);
5127
5128 /* if the server closes the connection, we want to immediately react
5129 * and close the socket to save packets and syscalls.
5130 */
5131 s->si[1].flags |= SI_FL_NOHALF;
5132
5133 /* In any case we've finished parsing the request so we must
5134 * disable Nagle when sending data because 1) we're not going
5135 * to shut this side, and 2) the server is waiting for us to
5136 * send pending data.
5137 */
5138 chn->flags |= CF_NEVER_WAIT;
5139
Christopher Fauletd01ce402019-01-02 17:44:13 +01005140 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5141 /* The server has not finished to respond, so we
5142 * don't want to move in order not to upset it.
5143 */
5144 return;
5145 }
5146
Christopher Fauletf2824e62018-10-01 12:12:37 +02005147 /* When we get here, it means that both the request and the
5148 * response have finished receiving. Depending on the connection
5149 * mode, we'll have to wait for the last bytes to leave in either
5150 * direction, and sometimes for a close to be effective.
5151 */
5152 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5153 /* Tunnel mode will not have any analyser so it needs to
5154 * poll for reads.
5155 */
5156 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005157 if (b_data(&chn->buf))
5158 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005159 txn->req.msg_state = HTTP_MSG_TUNNEL;
5160 }
5161 else {
5162 /* we're not expecting any new data to come for this
5163 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005164 *
5165 * However, there is an exception if the response
5166 * length is undefined. In this case, we need to wait
5167 * the close from the server. The response will be
5168 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005169 */
5170 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5171 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005172 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005173
5174 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5175 channel_shutr_now(chn);
5176 channel_shutw_now(chn);
5177 }
5178 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005179 goto check_channel_flags;
5180 }
5181
5182 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5183 http_msg_closing:
5184 /* nothing else to forward, just waiting for the output buffer
5185 * to be empty and for the shutw_now to take effect.
5186 */
5187 if (channel_is_empty(chn)) {
5188 txn->req.msg_state = HTTP_MSG_CLOSED;
5189 goto http_msg_closed;
5190 }
5191 else if (chn->flags & CF_SHUTW) {
5192 txn->req.err_state = txn->req.msg_state;
5193 txn->req.msg_state = HTTP_MSG_ERROR;
5194 goto end;
5195 }
5196 return;
5197 }
5198
5199 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5200 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005201 /* if we don't know whether the server will close, we need to hard close */
5202 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5203 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005204 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005205 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005206 channel_dont_read(chn);
5207 goto end;
5208 }
5209
5210 check_channel_flags:
5211 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5212 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5213 /* if we've just closed an output, let's switch */
5214 txn->req.msg_state = HTTP_MSG_CLOSING;
5215 goto http_msg_closing;
5216 }
5217
5218 end:
5219 chn->analysers &= AN_REQ_FLT_END;
5220 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5221 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5222 channel_auto_close(chn);
5223 channel_auto_read(chn);
5224}
5225
5226
5227/* This function terminates the response because it was completly analyzed or
5228 * because an error was triggered during the body forwarding.
5229 */
5230static void htx_end_response(struct stream *s)
5231{
5232 struct channel *chn = &s->res;
5233 struct http_txn *txn = s->txn;
5234
5235 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5236 now_ms, __FUNCTION__, s,
5237 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5238 s->req.analysers, s->res.analysers);
5239
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005240 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5241 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005242 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005243 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005244 goto end;
5245 }
5246
5247 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5248 return;
5249
5250 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5251 /* In theory, we don't need to read anymore, but we must
5252 * still monitor the server connection for a possible close
5253 * while the request is being uploaded, so we don't disable
5254 * reading.
5255 */
5256 /* channel_dont_read(chn); */
5257
5258 if (txn->req.msg_state < HTTP_MSG_DONE) {
5259 /* The client seems to still be sending data, probably
5260 * because we got an error response during an upload.
5261 * We have the choice of either breaking the connection
5262 * or letting it pass through. Let's do the later.
5263 */
5264 return;
5265 }
5266
5267 /* When we get here, it means that both the request and the
5268 * response have finished receiving. Depending on the connection
5269 * mode, we'll have to wait for the last bytes to leave in either
5270 * direction, and sometimes for a close to be effective.
5271 */
5272 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5273 channel_auto_read(chn);
5274 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005275 if (b_data(&chn->buf))
5276 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005277 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5278 }
5279 else {
5280 /* we're not expecting any new data to come for this
5281 * transaction, so we can close it.
5282 */
5283 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5284 channel_shutr_now(chn);
5285 channel_shutw_now(chn);
5286 }
5287 }
5288 goto check_channel_flags;
5289 }
5290
5291 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5292 http_msg_closing:
5293 /* nothing else to forward, just waiting for the output buffer
5294 * to be empty and for the shutw_now to take effect.
5295 */
5296 if (channel_is_empty(chn)) {
5297 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5298 goto http_msg_closed;
5299 }
5300 else if (chn->flags & CF_SHUTW) {
5301 txn->rsp.err_state = txn->rsp.msg_state;
5302 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005303 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005304 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005305 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005306 goto end;
5307 }
5308 return;
5309 }
5310
5311 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5312 http_msg_closed:
5313 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005314 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005315 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005316 goto end;
5317 }
5318
5319 check_channel_flags:
5320 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5321 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5322 /* if we've just closed an output, let's switch */
5323 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5324 goto http_msg_closing;
5325 }
5326
5327 end:
5328 chn->analysers &= AN_RES_FLT_END;
5329 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5330 chn->analysers |= AN_RES_FLT_XFER_DATA;
5331 channel_auto_close(chn);
5332 channel_auto_read(chn);
5333}
5334
Christopher Faulet0f226952018-10-22 09:29:56 +02005335void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5336 int finst, const struct buffer *msg)
5337{
5338 channel_auto_read(si_oc(si));
5339 channel_abort(si_oc(si));
5340 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005341 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005342 channel_auto_close(si_ic(si));
5343 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005344
5345 /* <msg> is an HTX structure. So we copy it in the response's
5346 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005347 if (msg) {
5348 struct channel *chn = si_ic(si);
5349 struct htx *htx;
5350
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005351 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005352 chn->buf.data = msg->data;
5353 memcpy(chn->buf.area, msg->area, msg->data);
5354 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005355 c_adv(chn, htx->data);
5356 chn->total += htx->data;
5357 }
5358 if (!(s->flags & SF_ERR_MASK))
5359 s->flags |= err;
5360 if (!(s->flags & SF_FINST_MASK))
5361 s->flags |= finst;
5362}
5363
5364void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5365{
5366 channel_auto_read(&s->req);
5367 channel_abort(&s->req);
5368 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005369 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5370 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005371
5372 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005373
5374 /* <msg> is an HTX structure. So we copy it in the response's
5375 * channel */
5376 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005377 if (msg) {
5378 struct channel *chn = &s->res;
5379 struct htx *htx;
5380
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005381 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005382 chn->buf.data = msg->data;
5383 memcpy(chn->buf.area, msg->area, msg->data);
5384 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005385 c_adv(chn, htx->data);
5386 chn->total += htx->data;
5387 }
5388
5389 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5390 channel_auto_read(&s->res);
5391 channel_auto_close(&s->res);
5392 channel_shutr_now(&s->res);
5393}
5394
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005395struct buffer *htx_error_message(struct stream *s)
5396{
5397 const int msgnum = http_get_status_idx(s->txn->status);
5398
5399 if (s->be->errmsg[msgnum].area)
5400 return &s->be->errmsg[msgnum];
5401 else if (strm_fe(s)->errmsg[msgnum].area)
5402 return &strm_fe(s)->errmsg[msgnum];
5403 else
5404 return &htx_err_chunks[msgnum];
5405}
5406
5407
Christopher Faulet4a28a532019-03-01 11:19:40 +01005408/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5409 * on success and -1 on error.
5410 */
5411static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5412{
5413 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5414 * then we must send an HTTP/1.1 100 Continue intermediate response.
5415 */
5416 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5417 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5418 struct ist hdr = { .ptr = "Expect", .len = 6 };
5419 struct http_hdr_ctx ctx;
5420
5421 ctx.blk = NULL;
5422 /* Expect is allowed in 1.1, look for it */
5423 if (http_find_header(htx, hdr, &ctx, 0) &&
5424 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5425 if (htx_reply_100_continue(s) == -1)
5426 return -1;
5427 http_remove_header(htx, &ctx);
5428 }
5429 }
5430 return 0;
5431}
5432
Christopher Faulet23a3c792018-11-28 10:01:23 +01005433/* Send a 100-Continue response to the client. It returns 0 on success and -1
5434 * on error. The response channel is updated accordingly.
5435 */
5436static int htx_reply_100_continue(struct stream *s)
5437{
5438 struct channel *res = &s->res;
5439 struct htx *htx = htx_from_buf(&res->buf);
5440 struct htx_sl *sl;
5441 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5442 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5443 size_t data;
5444
5445 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5446 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5447 if (!sl)
5448 goto fail;
5449 sl->info.res.status = 100;
5450
5451 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5452 goto fail;
5453
5454 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005455 c_adv(res, data);
5456 res->total += data;
5457 return 0;
5458
5459 fail:
5460 /* If an error occurred, remove the incomplete HTTP response from the
5461 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005462 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005463 return -1;
5464}
5465
Christopher Faulet12c51e22018-11-28 15:59:42 +01005466
5467/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5468 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5469 * error. The response channel is updated accordingly.
5470 */
5471static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5472{
5473 struct channel *res = &s->res;
5474 struct htx *htx = htx_from_buf(&res->buf);
5475 struct htx_sl *sl;
5476 struct ist code, body;
5477 int status;
5478 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5479 size_t data;
5480
5481 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5482 status = 401;
5483 code = ist("401");
5484 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5485 "You need a valid user and password to access this content.\n"
5486 "</body></html>\n");
5487 }
5488 else {
5489 status = 407;
5490 code = ist("407");
5491 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5492 "You need a valid user and password to access this content.\n"
5493 "</body></html>\n");
5494 }
5495
5496 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5497 ist("HTTP/1.1"), code, ist("Unauthorized"));
5498 if (!sl)
5499 goto fail;
5500 sl->info.res.status = status;
5501 s->txn->status = status;
5502
5503 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5504 goto fail;
5505
5506 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5507 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005508 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5509 goto fail;
5510 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5511 goto fail;
5512 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005513 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005514 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5515 goto fail;
5516
5517 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005518 c_adv(res, data);
5519 res->total += data;
5520
5521 channel_auto_read(&s->req);
5522 channel_abort(&s->req);
5523 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005524 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005525
5526 res->wex = tick_add_ifset(now_ms, res->wto);
5527 channel_auto_read(res);
5528 channel_auto_close(res);
5529 channel_shutr_now(res);
5530 return 0;
5531
5532 fail:
5533 /* If an error occurred, remove the incomplete HTTP response from the
5534 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005535 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005536 return -1;
5537}
5538
Christopher Faulet0f226952018-10-22 09:29:56 +02005539/*
5540 * Capture headers from message <htx> according to header list <cap_hdr>, and
5541 * fill the <cap> pointers appropriately.
5542 */
5543static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5544{
5545 struct cap_hdr *h;
5546 int32_t pos;
5547
Christopher Fauleta3f15502019-05-13 15:27:23 +02005548 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005549 struct htx_blk *blk = htx_get_blk(htx, pos);
5550 enum htx_blk_type type = htx_get_blk_type(blk);
5551 struct ist n, v;
5552
5553 if (type == HTX_BLK_EOH)
5554 break;
5555 if (type != HTX_BLK_HDR)
5556 continue;
5557
5558 n = htx_get_blk_name(htx, blk);
5559
5560 for (h = cap_hdr; h; h = h->next) {
5561 if (h->namelen && (h->namelen == n.len) &&
5562 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5563 if (cap[h->index] == NULL)
5564 cap[h->index] =
5565 pool_alloc(h->pool);
5566
5567 if (cap[h->index] == NULL) {
5568 ha_alert("HTTP capture : out of memory.\n");
5569 break;
5570 }
5571
5572 v = htx_get_blk_value(htx, blk);
5573 if (v.len > h->len)
5574 v.len = h->len;
5575
5576 memcpy(cap[h->index], v.ptr, v.len);
5577 cap[h->index][v.len]=0;
5578 }
5579 }
5580 }
5581}
5582
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005583/* Delete a value in a header between delimiters <from> and <next>. The header
5584 * itself is delimited by <start> and <end> pointers. The number of characters
5585 * displaced is returned, and the pointer to the first delimiter is updated if
5586 * required. The function tries as much as possible to respect the following
5587 * principles :
5588 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5589 * in which case <next> is simply removed
5590 * - set exactly one space character after the new first delimiter, unless there
5591 * are not enough characters in the block being moved to do so.
5592 * - remove unneeded spaces before the previous delimiter and after the new
5593 * one.
5594 *
5595 * It is the caller's responsibility to ensure that :
5596 * - <from> points to a valid delimiter or <start> ;
5597 * - <next> points to a valid delimiter or <end> ;
5598 * - there are non-space chars before <from>.
5599 */
5600static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5601{
5602 char *prev = *from;
5603
5604 if (prev == start) {
5605 /* We're removing the first value. eat the semicolon, if <next>
5606 * is lower than <end> */
5607 if (next < end)
5608 next++;
5609
5610 while (next < end && HTTP_IS_SPHT(*next))
5611 next++;
5612 }
5613 else {
5614 /* Remove useless spaces before the old delimiter. */
5615 while (HTTP_IS_SPHT(*(prev-1)))
5616 prev--;
5617 *from = prev;
5618
5619 /* copy the delimiter and if possible a space if we're
5620 * not at the end of the line.
5621 */
5622 if (next < end) {
5623 *prev++ = *next++;
5624 if (prev + 1 < next)
5625 *prev++ = ' ';
5626 while (next < end && HTTP_IS_SPHT(*next))
5627 next++;
5628 }
5629 }
5630 memmove(prev, next, end - next);
5631 return (prev - next);
5632}
5633
Christopher Faulet0f226952018-10-22 09:29:56 +02005634
5635/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005636 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005637 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005638static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005639{
5640 struct ist dst = ist2(str, 0);
5641
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005642 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005643 goto end;
5644 if (dst.len + 1 > len)
5645 goto end;
5646 dst.ptr[dst.len++] = ' ';
5647
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005648 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005649 goto end;
5650 if (dst.len + 1 > len)
5651 goto end;
5652 dst.ptr[dst.len++] = ' ';
5653
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005654 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005655 end:
5656 return dst.len;
5657}
5658
Christopher Fauletf0523542018-10-24 11:06:58 +02005659/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005660 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005661 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005662static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005663{
5664 struct ist dst = ist2(str, 0);
5665
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005666 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005667 goto end;
5668 if (dst.len + 1 > len)
5669 goto end;
5670 dst.ptr[dst.len++] = ' ';
5671
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005672 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005673 goto end;
5674 if (dst.len + 1 > len)
5675 goto end;
5676 dst.ptr[dst.len++] = ' ';
5677
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005678 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005679 end:
5680 return dst.len;
5681}
5682
5683
Christopher Faulet0f226952018-10-22 09:29:56 +02005684/*
5685 * Print a debug line with a start line.
5686 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005687static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005688{
5689 struct session *sess = strm_sess(s);
5690 int max;
5691
5692 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5693 dir,
5694 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5695 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5696
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005697 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005698 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005699 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005700 trash.area[trash.data++] = ' ';
5701
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005702 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005703 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005704 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005705 trash.area[trash.data++] = ' ';
5706
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005707 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005708 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005709 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005710 trash.area[trash.data++] = '\n';
5711
5712 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5713}
5714
5715/*
5716 * Print a debug line with a header.
5717 */
5718static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5719{
5720 struct session *sess = strm_sess(s);
5721 int max;
5722
5723 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5724 dir,
5725 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5726 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5727
5728 max = n.len;
5729 UBOUND(max, trash.size - trash.data - 3);
5730 chunk_memcat(&trash, n.ptr, max);
5731 trash.area[trash.data++] = ':';
5732 trash.area[trash.data++] = ' ';
5733
5734 max = v.len;
5735 UBOUND(max, trash.size - trash.data - 1);
5736 chunk_memcat(&trash, v.ptr, max);
5737 trash.area[trash.data++] = '\n';
5738
5739 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5740}
5741
5742
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005743__attribute__((constructor))
5744static void __htx_protocol_init(void)
5745{
5746}
5747
5748
5749/*
5750 * Local variables:
5751 * c-indent-level: 8
5752 * c-basic-offset: 8
5753 * End:
5754 */