blob: dc0762d73f96a06e280d56c6878514137e617a59 [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 Fauletaed82cf2018-11-30 22:22:32 +01001698 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Fauletee1bd4b2019-05-23 10:33:12 +02001699 channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001700 msg->msg_state = HTTP_MSG_RPBEFORE;
1701 txn->status = 0;
1702 s->logs.t_data = -1; /* was not a response yet */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001703 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001704 }
1705
1706 /*
1707 * 2: check for cacheability.
1708 */
1709
1710 switch (txn->status) {
1711 case 200:
1712 case 203:
1713 case 204:
1714 case 206:
1715 case 300:
1716 case 301:
1717 case 404:
1718 case 405:
1719 case 410:
1720 case 414:
1721 case 501:
1722 break;
1723 default:
1724 /* RFC7231#6.1:
1725 * Responses with status codes that are defined as
1726 * cacheable by default (e.g., 200, 203, 204, 206,
1727 * 300, 301, 404, 405, 410, 414, and 501 in this
1728 * specification) can be reused by a cache with
1729 * heuristic expiration unless otherwise indicated
1730 * by the method definition or explicit cache
1731 * controls [RFC7234]; all other status codes are
1732 * not cacheable by default.
1733 */
1734 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1735 break;
1736 }
1737
1738 /*
1739 * 3: we may need to capture headers
1740 */
1741 s->logs.logwait &= ~LW_RESP;
1742 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001743 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001744
Christopher Faulet9768c262018-10-22 09:34:31 +02001745 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001746 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1747 txn->status == 101)) {
1748 /* Either we've established an explicit tunnel, or we're
1749 * switching the protocol. In both cases, we're very unlikely
1750 * to understand the next protocols. We have to switch to tunnel
1751 * mode, so that we transfer the request and responses then let
1752 * this protocol pass unmodified. When we later implement specific
1753 * parsers for such protocols, we'll want to check the Upgrade
1754 * header which contains information about that protocol for
1755 * responses with status 101 (eg: see RFC2817 about TLS).
1756 */
1757 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001758 }
1759
Christopher Faulet61608322018-11-23 16:23:45 +01001760 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1761 * 407 (Proxy-Authenticate) responses and set the connection to private
1762 */
1763 srv_conn = cs_conn(objt_cs(s->si[1].end));
1764 if (srv_conn) {
1765 struct ist hdr;
1766 struct http_hdr_ctx ctx;
1767
1768 if (txn->status == 401)
1769 hdr = ist("WWW-Authenticate");
1770 else if (txn->status == 407)
1771 hdr = ist("Proxy-Authenticate");
1772 else
1773 goto end;
1774
1775 ctx.blk = NULL;
1776 while (http_find_header(htx, hdr, &ctx, 0)) {
1777 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1778 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1779 srv_conn->flags |= CO_FL_PRIVATE;
1780 }
1781 }
1782
1783 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001784 /* we want to have the response time before we start processing it */
1785 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1786
1787 /* end of job, return OK */
1788 rep->analysers &= ~an_bit;
1789 rep->analyse_exp = TICK_ETERNITY;
1790 channel_auto_close(rep);
1791 return 1;
1792
Christopher Faulet47365272018-10-31 17:40:50 +01001793 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001794 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001795 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001796 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001797 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001798 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001799 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001800 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001801 do_l7_retry(s, si_b) == 0)
1802 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001803 txn->status = 502;
1804 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001805 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001806 rep->analysers &= AN_RES_FLT_END;
1807
1808 if (!(s->flags & SF_ERR_MASK))
1809 s->flags |= SF_ERR_PRXCOND;
1810 if (!(s->flags & SF_FINST_MASK))
1811 s->flags |= SF_FINST_H;
1812 return 0;
1813
Christopher Faulete0768eb2018-10-03 16:38:02 +02001814 abort_keep_alive:
1815 /* A keep-alive request to the server failed on a network error.
1816 * The client is required to retry. We need to close without returning
1817 * any other information so that the client retries.
1818 */
1819 txn->status = 0;
1820 rep->analysers &= AN_RES_FLT_END;
1821 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001822 s->logs.logwait = 0;
1823 s->logs.level = 0;
1824 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001825 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001826 return 0;
1827}
1828
1829/* This function performs all the processing enabled for the current response.
1830 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1831 * and updates s->res.analysers. It might make sense to explode it into several
1832 * other functions. It works like process_request (see indications above).
1833 */
1834int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1835{
1836 struct session *sess = s->sess;
1837 struct http_txn *txn = s->txn;
1838 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001839 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001840 struct proxy *cur_proxy;
1841 struct cond_wordlist *wl;
1842 enum rule_result ret = HTTP_RULE_RES_CONT;
1843
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001844 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1845 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001846
Christopher Faulete0768eb2018-10-03 16:38:02 +02001847 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1848 now_ms, __FUNCTION__,
1849 s,
1850 rep,
1851 rep->rex, rep->wex,
1852 rep->flags,
1853 ci_data(rep),
1854 rep->analysers);
1855
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001856 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001857
1858 /* The stats applet needs to adjust the Connection header but we don't
1859 * apply any filter there.
1860 */
1861 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1862 rep->analysers &= ~an_bit;
1863 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001864 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001865 }
1866
1867 /*
1868 * We will have to evaluate the filters.
1869 * As opposed to version 1.2, now they will be evaluated in the
1870 * filters order and not in the header order. This means that
1871 * each filter has to be validated among all headers.
1872 *
1873 * Filters are tried with ->be first, then with ->fe if it is
1874 * different from ->be.
1875 *
1876 * Maybe we are in resume condiion. In this case I choose the
1877 * "struct proxy" which contains the rule list matching the resume
1878 * pointer. If none of theses "struct proxy" match, I initialise
1879 * the process with the first one.
1880 *
1881 * In fact, I check only correspondance betwwen the current list
1882 * pointer and the ->fe rule list. If it doesn't match, I initialize
1883 * the loop with the ->be.
1884 */
1885 if (s->current_rule_list == &sess->fe->http_res_rules)
1886 cur_proxy = sess->fe;
1887 else
1888 cur_proxy = s->be;
1889 while (1) {
1890 struct proxy *rule_set = cur_proxy;
1891
1892 /* evaluate http-response rules */
1893 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001894 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001895
1896 if (ret == HTTP_RULE_RES_BADREQ)
1897 goto return_srv_prx_502;
1898
1899 if (ret == HTTP_RULE_RES_DONE) {
1900 rep->analysers &= ~an_bit;
1901 rep->analyse_exp = TICK_ETERNITY;
1902 return 1;
1903 }
1904 }
1905
1906 /* we need to be called again. */
1907 if (ret == HTTP_RULE_RES_YIELD) {
1908 channel_dont_close(rep);
1909 return 0;
1910 }
1911
1912 /* try headers filters */
1913 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001914 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1915 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001916 }
1917
1918 /* has the response been denied ? */
1919 if (txn->flags & TX_SVDENY) {
1920 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001921 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001922
Olivier Houcharda798bf52019-03-08 18:52:00 +01001923 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1924 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001925 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001926 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001927 goto return_srv_prx_502;
1928 }
1929
1930 /* add response headers from the rule sets in the same order */
1931 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001932 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001933 if (txn->status < 200 && txn->status != 101)
1934 break;
1935 if (wl->cond) {
1936 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1937 ret = acl_pass(ret);
1938 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1939 ret = !ret;
1940 if (!ret)
1941 continue;
1942 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001943
1944 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1945 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001946 goto return_bad_resp;
1947 }
1948
1949 /* check whether we're already working on the frontend */
1950 if (cur_proxy == sess->fe)
1951 break;
1952 cur_proxy = sess->fe;
1953 }
1954
1955 /* After this point, this anayzer can't return yield, so we can
1956 * remove the bit corresponding to this analyzer from the list.
1957 *
1958 * Note that the intermediate returns and goto found previously
1959 * reset the analyzers.
1960 */
1961 rep->analysers &= ~an_bit;
1962 rep->analyse_exp = TICK_ETERNITY;
1963
1964 /* OK that's all we can do for 1xx responses */
1965 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001966 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001967
1968 /*
1969 * Now check for a server cookie.
1970 */
1971 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001972 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001973
1974 /*
1975 * Check for cache-control or pragma headers if required.
1976 */
1977 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1978 check_response_for_cacheability(s, rep);
1979
1980 /*
1981 * Add server cookie in the response if needed
1982 */
1983 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1984 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1985 (!(s->flags & SF_DIRECT) ||
1986 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1987 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1988 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1989 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1990 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1991 !(s->flags & SF_IGNORE_PRST)) {
1992 /* the server is known, it's not the one the client requested, or the
1993 * cookie's last seen date needs to be refreshed. We have to
1994 * insert a set-cookie here, except if we want to insert only on POST
1995 * requests and this one isn't. Note that servers which don't have cookies
1996 * (eg: some backup servers) will return a full cookie removal request.
1997 */
1998 if (!objt_server(s->target)->cookie) {
1999 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002000 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002001 s->be->cookie_name);
2002 }
2003 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002004 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002005
2006 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2007 /* emit last_date, which is mandatory */
2008 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2009 s30tob64((date.tv_sec+3) >> 2,
2010 trash.area + trash.data);
2011 trash.data += 5;
2012
2013 if (s->be->cookie_maxlife) {
2014 /* emit first_date, which is either the original one or
2015 * the current date.
2016 */
2017 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2018 s30tob64(txn->cookie_first_date ?
2019 txn->cookie_first_date >> 2 :
2020 (date.tv_sec+3) >> 2,
2021 trash.area + trash.data);
2022 trash.data += 5;
2023 }
2024 }
2025 chunk_appendf(&trash, "; path=/");
2026 }
2027
2028 if (s->be->cookie_domain)
2029 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2030
2031 if (s->be->ck_opts & PR_CK_HTTPONLY)
2032 chunk_appendf(&trash, "; HttpOnly");
2033
2034 if (s->be->ck_opts & PR_CK_SECURE)
2035 chunk_appendf(&trash, "; Secure");
2036
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002037 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002038 goto return_bad_resp;
2039
2040 txn->flags &= ~TX_SCK_MASK;
2041 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2042 /* the server did not change, only the date was updated */
2043 txn->flags |= TX_SCK_UPDATED;
2044 else
2045 txn->flags |= TX_SCK_INSERTED;
2046
2047 /* Here, we will tell an eventual cache on the client side that we don't
2048 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2049 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2050 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2051 */
2052 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2053
2054 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2055
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002056 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002057 goto return_bad_resp;
2058 }
2059 }
2060
2061 /*
2062 * Check if result will be cacheable with a cookie.
2063 * We'll block the response if security checks have caught
2064 * nasty things such as a cacheable cookie.
2065 */
2066 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2067 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2068 (s->be->options & PR_O_CHK_CACHE)) {
2069 /* we're in presence of a cacheable response containing
2070 * a set-cookie header. We'll block it as requested by
2071 * the 'checkcache' option, and send an alert.
2072 */
2073 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002074 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002075
Olivier Houcharda798bf52019-03-08 18:52:00 +01002076 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2077 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002078 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002079 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002080
2081 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2082 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2083 send_log(s->be, LOG_ALERT,
2084 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2085 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2086 goto return_srv_prx_502;
2087 }
2088
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002089 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002090 /* Always enter in the body analyzer */
2091 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2092 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2093
2094 /* if the user wants to log as soon as possible, without counting
2095 * bytes from the server, then this is the right moment. We have
2096 * to temporarily assign bytes_out to log what we currently have.
2097 */
2098 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2099 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002100 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002101 s->do_log(s);
2102 s->logs.bytes_out = 0;
2103 }
2104 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002105
2106 return_bad_resp:
2107 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002108 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002109 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002110 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002111 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002112
2113 return_srv_prx_502:
2114 rep->analysers &= AN_RES_FLT_END;
2115 txn->status = 502;
2116 s->logs.t_data = -1; /* was not a valid response */
2117 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002118 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002119 if (!(s->flags & SF_ERR_MASK))
2120 s->flags |= SF_ERR_PRXCOND;
2121 if (!(s->flags & SF_FINST_MASK))
2122 s->flags |= SF_FINST_H;
2123 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002124}
2125
2126/* This function is an analyser which forwards response body (including chunk
2127 * sizes if any). It is called as soon as we must forward, even if we forward
2128 * zero byte. The only situation where it must not be called is when we're in
2129 * tunnel mode and we want to forward till the close. It's used both to forward
2130 * remaining data and to resync after end of body. It expects the msg_state to
2131 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2132 * read more data, or 1 once we can go on with next request or end the stream.
2133 *
2134 * It is capable of compressing response data both in content-length mode and
2135 * in chunked mode. The state machines follows different flows depending on
2136 * whether content-length and chunked modes are used, since there are no
2137 * trailers in content-length :
2138 *
2139 * chk-mode cl-mode
2140 * ,----- BODY -----.
2141 * / \
2142 * V size > 0 V chk-mode
2143 * .--> SIZE -------------> DATA -------------> CRLF
2144 * | | size == 0 | last byte |
2145 * | v final crlf v inspected |
2146 * | TRAILERS -----------> DONE |
2147 * | |
2148 * `----------------------------------------------'
2149 *
2150 * Compression only happens in the DATA state, and must be flushed in final
2151 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2152 * is performed at once on final states for all bytes parsed, or when leaving
2153 * on missing data.
2154 */
2155int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2156{
2157 struct session *sess = s->sess;
2158 struct http_txn *txn = s->txn;
2159 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002160 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002161 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002162
2163 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2164 now_ms, __FUNCTION__,
2165 s,
2166 res,
2167 res->rex, res->wex,
2168 res->flags,
2169 ci_data(res),
2170 res->analysers);
2171
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002172 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002173
2174 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002175 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002176 /* Output closed while we were sending data. We must abort and
2177 * wake the other side up.
2178 */
2179 msg->err_state = msg->msg_state;
2180 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002181 htx_end_response(s);
2182 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002183 return 1;
2184 }
2185
Christopher Faulet9768c262018-10-22 09:34:31 +02002186 if (msg->msg_state == HTTP_MSG_BODY)
2187 msg->msg_state = HTTP_MSG_DATA;
2188
Christopher Faulete0768eb2018-10-03 16:38:02 +02002189 /* in most states, we should abort in case of early close */
2190 channel_auto_close(res);
2191
Christopher Faulete0768eb2018-10-03 16:38:02 +02002192 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002193 if (res->to_forward == CHN_INFINITE_FORWARD) {
2194 if (res->flags & (CF_SHUTR|CF_EOI)) {
2195 msg->msg_state = HTTP_MSG_DONE;
2196 res->to_forward = 0;
2197 goto done;
2198 }
2199 }
2200 else {
2201 /* We can't process the buffer's contents yet */
2202 res->flags |= CF_WAKE_WRITE;
2203 goto missing_data_or_waiting;
2204 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002205 }
2206
Christopher Faulet9768c262018-10-22 09:34:31 +02002207 if (msg->msg_state >= HTTP_MSG_DONE)
2208 goto done;
2209
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002210 /* Forward input data. We get it by removing all outgoing data not
2211 * forwarded yet from HTX data size. If there are some data filters, we
2212 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002213 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002214 if (HAS_RSP_DATA_FILTERS(s)) {
2215 ret = flt_http_payload(s, msg, htx->data);
2216 if (ret < 0)
2217 goto return_bad_res;
2218 c_adv(res, ret);
2219 if (htx->data != co_data(res) || htx->extra)
2220 goto missing_data_or_waiting;
2221 }
2222 else {
2223 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002224 if (msg->flags & HTTP_MSGF_XFER_LEN)
2225 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002226 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002227
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002228 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2229 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2230 msg->msg_state = HTTP_MSG_TUNNEL;
2231 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002232 }
2233
Christopher Faulet9768c262018-10-22 09:34:31 +02002234 /* Check if the end-of-message is reached and if so, switch the message
2235 * in HTTP_MSG_DONE state.
2236 */
2237 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2238 goto missing_data_or_waiting;
2239
2240 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002241 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002242
2243 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002244 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002245 channel_dont_close(res);
2246
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002247 if (HAS_RSP_DATA_FILTERS(s)) {
2248 ret = flt_http_end(s, msg);
2249 if (ret <= 0) {
2250 if (!ret)
2251 goto missing_data_or_waiting;
2252 goto return_bad_res;
2253 }
2254 }
2255
Christopher Fauletf2824e62018-10-01 12:12:37 +02002256 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002257 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002258 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002259 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2260 if (res->flags & CF_SHUTW) {
2261 /* response errors are most likely due to the
2262 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002263 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002264 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002265 goto return_bad_res;
2266 }
2267 return 1;
2268 }
2269 return 0;
2270
2271 missing_data_or_waiting:
2272 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002273 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002274
Christopher Faulet47365272018-10-31 17:40:50 +01002275 if (htx->flags & HTX_FL_PARSING_ERROR)
2276 goto return_bad_res;
2277
Christopher Faulete0768eb2018-10-03 16:38:02 +02002278 /* stop waiting for data if the input is closed before the end. If the
2279 * client side was already closed, it means that the client has aborted,
2280 * so we don't want to count this as a server abort. Otherwise it's a
2281 * server abort.
2282 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002283 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002284 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002285 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002286 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002287 if (htx_is_empty(htx))
2288 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002289 }
2290
Christopher Faulete0768eb2018-10-03 16:38:02 +02002291 /* When TE: chunked is used, we need to get there again to parse
2292 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002293 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2294 * are filters registered on the stream, we don't want to forward a
2295 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002296 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002297 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002298 channel_dont_close(res);
2299
2300 /* We know that more data are expected, but we couldn't send more that
2301 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2302 * system knows it must not set a PUSH on this first part. Interactive
2303 * modes are already handled by the stream sock layer. We must not do
2304 * this in content-length mode because it could present the MSG_MORE
2305 * flag with the last block of forwarded data, which would cause an
2306 * additional delay to be observed by the receiver.
2307 */
2308 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2309 res->flags |= CF_EXPECT_MORE;
2310
2311 /* the stream handler will take care of timeouts and errors */
2312 return 0;
2313
Christopher Faulet93e02d82019-03-08 14:18:50 +01002314 return_srv_abort:
2315 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2316 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002317 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002318 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2319 if (!(s->flags & SF_ERR_MASK))
2320 s->flags |= SF_ERR_SRVCL;
2321 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002322
Christopher Faulet93e02d82019-03-08 14:18:50 +01002323 return_cli_abort:
2324 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2325 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002326 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002327 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2328 if (!(s->flags & SF_ERR_MASK))
2329 s->flags |= SF_ERR_CLICL;
2330 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002331
Christopher Faulet93e02d82019-03-08 14:18:50 +01002332 return_bad_res:
2333 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2334 if (objt_server(s->target)) {
2335 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2336 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2337 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002338 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002339 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002340
Christopher Faulet93e02d82019-03-08 14:18:50 +01002341 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002342 txn->rsp.err_state = txn->rsp.msg_state;
2343 txn->rsp.msg_state = HTTP_MSG_ERROR;
2344 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002345 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002346 res->analysers &= AN_RES_FLT_END;
2347 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 +02002348 if (!(s->flags & SF_FINST_MASK))
2349 s->flags |= SF_FINST_D;
2350 return 0;
2351}
2352
Christopher Fauletf2824e62018-10-01 12:12:37 +02002353/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002354 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002355 * as too large a request to build a valid response.
2356 */
2357int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2358{
Christopher Faulet99daf282018-11-28 22:58:13 +01002359 struct channel *req = &s->req;
2360 struct channel *res = &s->res;
2361 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002362 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002363 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002364 struct ist status, reason, location;
2365 unsigned int flags;
2366 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002367 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002368
2369 chunk = alloc_trash_chunk();
2370 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002371 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002372
Christopher Faulet99daf282018-11-28 22:58:13 +01002373 /*
2374 * Create the location
2375 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002376 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002377 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002378 case REDIRECT_TYPE_SCHEME: {
2379 struct http_hdr_ctx ctx;
2380 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002381
Christopher Faulet99daf282018-11-28 22:58:13 +01002382 host = ist("");
2383 ctx.blk = NULL;
2384 if (http_find_header(htx, ist("Host"), &ctx, 0))
2385 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002386
Christopher Faulet297fbb42019-05-13 14:41:27 +02002387 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002388 path = http_get_path(htx_sl_req_uri(sl));
2389 /* build message using path */
2390 if (path.ptr) {
2391 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2392 int qs = 0;
2393 while (qs < path.len) {
2394 if (*(path.ptr + qs) == '?') {
2395 path.len = qs;
2396 break;
2397 }
2398 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002399 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002400 }
2401 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002402 else
2403 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002404
Christopher Faulet99daf282018-11-28 22:58:13 +01002405 if (rule->rdr_str) { /* this is an old "redirect" rule */
2406 /* add scheme */
2407 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2408 goto fail;
2409 }
2410 else {
2411 /* add scheme with executing log format */
2412 chunk->data += build_logline(s, chunk->area + chunk->data,
2413 chunk->size - chunk->data,
2414 &rule->rdr_fmt);
2415 }
2416 /* add "://" + host + path */
2417 if (!chunk_memcat(chunk, "://", 3) ||
2418 !chunk_memcat(chunk, host.ptr, host.len) ||
2419 !chunk_memcat(chunk, path.ptr, path.len))
2420 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002421
Christopher Faulet99daf282018-11-28 22:58:13 +01002422 /* append a slash at the end of the location if needed and missing */
2423 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2424 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2425 if (chunk->data + 1 >= chunk->size)
2426 goto fail;
2427 chunk->area[chunk->data++] = '/';
2428 }
2429 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002430 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002431
Christopher Faulet99daf282018-11-28 22:58:13 +01002432 case REDIRECT_TYPE_PREFIX: {
2433 struct ist path;
2434
Christopher Faulet297fbb42019-05-13 14:41:27 +02002435 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002436 path = http_get_path(htx_sl_req_uri(sl));
2437 /* build message using path */
2438 if (path.ptr) {
2439 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2440 int qs = 0;
2441 while (qs < path.len) {
2442 if (*(path.ptr + qs) == '?') {
2443 path.len = qs;
2444 break;
2445 }
2446 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002447 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002448 }
2449 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002450 else
2451 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002452
Christopher Faulet99daf282018-11-28 22:58:13 +01002453 if (rule->rdr_str) { /* this is an old "redirect" rule */
2454 /* add prefix. Note that if prefix == "/", we don't want to
2455 * add anything, otherwise it makes it hard for the user to
2456 * configure a self-redirection.
2457 */
2458 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2459 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2460 goto fail;
2461 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002462 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002463 else {
2464 /* add prefix with executing log format */
2465 chunk->data += build_logline(s, chunk->area + chunk->data,
2466 chunk->size - chunk->data,
2467 &rule->rdr_fmt);
2468 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002469
Christopher Faulet99daf282018-11-28 22:58:13 +01002470 /* add path */
2471 if (!chunk_memcat(chunk, path.ptr, path.len))
2472 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002473
Christopher Faulet99daf282018-11-28 22:58:13 +01002474 /* append a slash at the end of the location if needed and missing */
2475 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2476 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2477 if (chunk->data + 1 >= chunk->size)
2478 goto fail;
2479 chunk->area[chunk->data++] = '/';
2480 }
2481 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002482 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002483 case REDIRECT_TYPE_LOCATION:
2484 default:
2485 if (rule->rdr_str) { /* this is an old "redirect" rule */
2486 /* add location */
2487 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2488 goto fail;
2489 }
2490 else {
2491 /* add location with executing log format */
2492 chunk->data += build_logline(s, chunk->area + chunk->data,
2493 chunk->size - chunk->data,
2494 &rule->rdr_fmt);
2495 }
2496 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002497 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002498 location = ist2(chunk->area, chunk->data);
2499
2500 /*
2501 * Create the 30x response
2502 */
2503 switch (rule->code) {
2504 case 308:
2505 status = ist("308");
2506 reason = ist("Permanent Redirect");
2507 break;
2508 case 307:
2509 status = ist("307");
2510 reason = ist("Temporary Redirect");
2511 break;
2512 case 303:
2513 status = ist("303");
2514 reason = ist("See Other");
2515 break;
2516 case 301:
2517 status = ist("301");
2518 reason = ist("Moved Permanently");
2519 break;
2520 case 302:
2521 default:
2522 status = ist("302");
2523 reason = ist("Found");
2524 break;
2525 }
2526
Christopher Faulet08e66462019-05-23 16:44:59 +02002527 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2528 close = 1;
2529
Christopher Faulet99daf282018-11-28 22:58:13 +01002530 htx = htx_from_buf(&res->buf);
2531 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2532 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2533 if (!sl)
2534 goto fail;
2535 sl->info.res.status = rule->code;
2536 s->txn->status = rule->code;
2537
Christopher Faulet08e66462019-05-23 16:44:59 +02002538 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2539 goto fail;
2540
2541 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002542 !htx_add_header(htx, ist("Location"), location))
2543 goto fail;
2544
2545 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2546 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2547 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002548 }
2549
2550 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002551 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2552 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002553 }
2554
Christopher Faulet99daf282018-11-28 22:58:13 +01002555 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2556 goto fail;
2557
Christopher Fauletf2824e62018-10-01 12:12:37 +02002558 /* let's log the request time */
2559 s->logs.tv_request = now;
2560
Christopher Faulet99daf282018-11-28 22:58:13 +01002561 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002562 c_adv(res, data);
2563 res->total += data;
2564
2565 channel_auto_read(req);
2566 channel_abort(req);
2567 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002568 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002569
2570 res->wex = tick_add_ifset(now_ms, res->wto);
2571 channel_auto_read(res);
2572 channel_auto_close(res);
2573 channel_shutr_now(res);
2574
2575 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002576
2577 if (!(s->flags & SF_ERR_MASK))
2578 s->flags |= SF_ERR_LOCAL;
2579 if (!(s->flags & SF_FINST_MASK))
2580 s->flags |= SF_FINST_R;
2581
Christopher Faulet99daf282018-11-28 22:58:13 +01002582 free_trash_chunk(chunk);
2583 return 1;
2584
2585 fail:
2586 /* If an error occurred, remove the incomplete HTTP response from the
2587 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002588 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002589 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002590 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002591}
2592
Christopher Faulet72333522018-10-24 11:25:02 +02002593int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2594 struct ist name, const char *str, struct my_regex *re, int action)
2595{
2596 struct http_hdr_ctx ctx;
2597 struct buffer *output = get_trash_chunk();
2598
2599 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2600 ctx.blk = NULL;
2601 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2602 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2603 continue;
2604
2605 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2606 if (output->data == -1)
2607 return -1;
2608 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2609 return -1;
2610 }
2611 return 0;
2612}
2613
2614static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2615 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2616{
2617 struct buffer *replace;
2618 int ret = -1;
2619
2620 replace = alloc_trash_chunk();
2621 if (!replace)
2622 goto leave;
2623
2624 replace->data = build_logline(s, replace->area, replace->size, fmt);
2625 if (replace->data >= replace->size - 1)
2626 goto leave;
2627
2628 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2629
2630 leave:
2631 free_trash_chunk(replace);
2632 return ret;
2633}
2634
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002635
2636/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2637 * on success and -1 on error. The response channel is updated accordingly.
2638 */
2639static int htx_reply_103_early_hints(struct channel *res)
2640{
2641 struct htx *htx = htx_from_buf(&res->buf);
2642 size_t data;
2643
2644 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2645 /* If an error occurred during an Early-hint rule,
2646 * remove the incomplete HTTP 103 response from the
2647 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002648 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002649 return -1;
2650 }
2651
2652 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002653 c_adv(res, data);
2654 res->total += data;
2655 return 0;
2656}
2657
Christopher Faulet6eb92892018-11-15 16:39:29 +01002658/*
2659 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2660 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002661 * If <early_hints> is 0, it is starts a new response by adding the start
2662 * line. If an error occurred -1 is returned. On success 0 is returned. The
2663 * channel is not updated here. It must be done calling the function
2664 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002665 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002666static 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 +01002667{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002668 struct channel *res = &s->res;
2669 struct htx *htx = htx_from_buf(&res->buf);
2670 struct buffer *value = alloc_trash_chunk();
2671
Christopher Faulet6eb92892018-11-15 16:39:29 +01002672 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002673 struct htx_sl *sl;
2674 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2675 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2676
2677 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2678 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2679 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002680 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002681 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002682 }
2683
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002684 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2685 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002686 goto fail;
2687
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002688 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002689 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002690
2691 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002692 /* If an error occurred during an Early-hint rule, remove the incomplete
2693 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002694 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002695 free_trash_chunk(value);
2696 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002697}
2698
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002699/* This function executes one of the set-{method,path,query,uri} actions. It
2700 * takes the string from the variable 'replace' with length 'len', then modifies
2701 * the relevant part of the request line accordingly. Then it updates various
2702 * pointers to the next elements which were moved, and the total buffer length.
2703 * It finds the action to be performed in p[2], previously filled by function
2704 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2705 * error, though this can be revisited when this code is finally exploited.
2706 *
2707 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2708 * query string and 3 to replace uri.
2709 *
2710 * In query string case, the mark question '?' must be set at the start of the
2711 * string by the caller, event if the replacement query string is empty.
2712 */
2713int htx_req_replace_stline(int action, const char *replace, int len,
2714 struct proxy *px, struct stream *s)
2715{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002716 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002717
2718 switch (action) {
2719 case 0: // method
2720 if (!http_replace_req_meth(htx, ist2(replace, len)))
2721 return -1;
2722 break;
2723
2724 case 1: // path
2725 if (!http_replace_req_path(htx, ist2(replace, len)))
2726 return -1;
2727 break;
2728
2729 case 2: // query
2730 if (!http_replace_req_query(htx, ist2(replace, len)))
2731 return -1;
2732 break;
2733
2734 case 3: // uri
2735 if (!http_replace_req_uri(htx, ist2(replace, len)))
2736 return -1;
2737 break;
2738
2739 default:
2740 return -1;
2741 }
2742 return 0;
2743}
2744
2745/* This function replace the HTTP status code and the associated message. The
2746 * variable <status> contains the new status code. This function never fails.
2747 */
2748void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2749{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002750 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002751 char *res;
2752
2753 chunk_reset(&trash);
2754 res = ultoa_o(status, trash.area, trash.size);
2755 trash.data = res - trash.area;
2756
2757 /* Do we have a custom reason format string? */
2758 if (reason == NULL)
2759 reason = http_get_reason(status);
2760
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002761 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002762 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2763}
2764
Christopher Faulet3e964192018-10-24 11:39:23 +02002765/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2766 * transaction <txn>. Returns the verdict of the first rule that prevents
2767 * further processing of the request (auth, deny, ...), and defaults to
2768 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2769 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2770 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2771 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2772 * status.
2773 */
2774static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2775 struct stream *s, int *deny_status)
2776{
2777 struct session *sess = strm_sess(s);
2778 struct http_txn *txn = s->txn;
2779 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002780 struct act_rule *rule;
2781 struct http_hdr_ctx ctx;
2782 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002783 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2784 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002785 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002786
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002787 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002788
2789 /* If "the current_rule_list" match the executed rule list, we are in
2790 * resume condition. If a resume is needed it is always in the action
2791 * and never in the ACL or converters. In this case, we initialise the
2792 * current rule, and go to the action execution point.
2793 */
2794 if (s->current_rule) {
2795 rule = s->current_rule;
2796 s->current_rule = NULL;
2797 if (s->current_rule_list == rules)
2798 goto resume_execution;
2799 }
2800 s->current_rule_list = rules;
2801
2802 list_for_each_entry(rule, rules, list) {
2803 /* check optional condition */
2804 if (rule->cond) {
2805 int ret;
2806
2807 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2808 ret = acl_pass(ret);
2809
2810 if (rule->cond->pol == ACL_COND_UNLESS)
2811 ret = !ret;
2812
2813 if (!ret) /* condition not matched */
2814 continue;
2815 }
2816
2817 act_flags |= ACT_FLAG_FIRST;
2818 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002819 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2820 early_hints = 0;
2821 if (htx_reply_103_early_hints(&s->res) == -1) {
2822 rule_ret = HTTP_RULE_RES_BADREQ;
2823 goto end;
2824 }
2825 }
2826
Christopher Faulet3e964192018-10-24 11:39:23 +02002827 switch (rule->action) {
2828 case ACT_ACTION_ALLOW:
2829 rule_ret = HTTP_RULE_RES_STOP;
2830 goto end;
2831
2832 case ACT_ACTION_DENY:
2833 if (deny_status)
2834 *deny_status = rule->deny_status;
2835 rule_ret = HTTP_RULE_RES_DENY;
2836 goto end;
2837
2838 case ACT_HTTP_REQ_TARPIT:
2839 txn->flags |= TX_CLTARPIT;
2840 if (deny_status)
2841 *deny_status = rule->deny_status;
2842 rule_ret = HTTP_RULE_RES_DENY;
2843 goto end;
2844
2845 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002846 /* Auth might be performed on regular http-req rules as well as on stats */
2847 auth_realm = rule->arg.auth.realm;
2848 if (!auth_realm) {
2849 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2850 auth_realm = STATS_DEFAULT_REALM;
2851 else
2852 auth_realm = px->id;
2853 }
2854 /* send 401/407 depending on whether we use a proxy or not. We still
2855 * count one error, because normal browsing won't significantly
2856 * increase the counter but brute force attempts will.
2857 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002858 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002859 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2860 rule_ret = HTTP_RULE_RES_BADREQ;
2861 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002862 goto end;
2863
2864 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002865 rule_ret = HTTP_RULE_RES_DONE;
2866 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2867 rule_ret = HTTP_RULE_RES_BADREQ;
2868 goto end;
2869
2870 case ACT_HTTP_SET_NICE:
2871 s->task->nice = rule->arg.nice;
2872 break;
2873
2874 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002875 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002876 break;
2877
2878 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002879 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002880 break;
2881
2882 case ACT_HTTP_SET_LOGL:
2883 s->logs.level = rule->arg.loglevel;
2884 break;
2885
2886 case ACT_HTTP_REPLACE_HDR:
2887 case ACT_HTTP_REPLACE_VAL:
2888 if (htx_transform_header(s, &s->req, htx,
2889 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2890 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002891 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002892 rule_ret = HTTP_RULE_RES_BADREQ;
2893 goto end;
2894 }
2895 break;
2896
2897 case ACT_HTTP_DEL_HDR:
2898 /* remove all occurrences of the header */
2899 ctx.blk = NULL;
2900 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2901 http_remove_header(htx, &ctx);
2902 break;
2903
2904 case ACT_HTTP_SET_HDR:
2905 case ACT_HTTP_ADD_HDR: {
2906 /* The scope of the trash buffer must be limited to this function. The
2907 * build_logline() function can execute a lot of other function which
2908 * can use the trash buffer. So for limiting the scope of this global
2909 * buffer, we build first the header value using build_logline, and
2910 * after we store the header name.
2911 */
2912 struct buffer *replace;
2913 struct ist n, v;
2914
2915 replace = alloc_trash_chunk();
2916 if (!replace) {
2917 rule_ret = HTTP_RULE_RES_BADREQ;
2918 goto end;
2919 }
2920
2921 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2922 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2923 v = ist2(replace->area, replace->data);
2924
2925 if (rule->action == ACT_HTTP_SET_HDR) {
2926 /* remove all occurrences of the header */
2927 ctx.blk = NULL;
2928 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2929 http_remove_header(htx, &ctx);
2930 }
2931
2932 if (!http_add_header(htx, n, v)) {
2933 static unsigned char rate_limit = 0;
2934
2935 if ((rate_limit++ & 255) == 0) {
2936 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);
2937 }
2938
Olivier Houcharda798bf52019-03-08 18:52:00 +01002939 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002940 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002941 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002942 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002943 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002944 }
2945 free_trash_chunk(replace);
2946 break;
2947 }
2948
2949 case ACT_HTTP_DEL_ACL:
2950 case ACT_HTTP_DEL_MAP: {
2951 struct pat_ref *ref;
2952 struct buffer *key;
2953
2954 /* collect reference */
2955 ref = pat_ref_lookup(rule->arg.map.ref);
2956 if (!ref)
2957 continue;
2958
2959 /* allocate key */
2960 key = alloc_trash_chunk();
2961 if (!key) {
2962 rule_ret = HTTP_RULE_RES_BADREQ;
2963 goto end;
2964 }
2965
2966 /* collect key */
2967 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2968 key->area[key->data] = '\0';
2969
2970 /* perform update */
2971 /* returned code: 1=ok, 0=ko */
2972 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2973 pat_ref_delete(ref, key->area);
2974 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2975
2976 free_trash_chunk(key);
2977 break;
2978 }
2979
2980 case ACT_HTTP_ADD_ACL: {
2981 struct pat_ref *ref;
2982 struct buffer *key;
2983
2984 /* collect reference */
2985 ref = pat_ref_lookup(rule->arg.map.ref);
2986 if (!ref)
2987 continue;
2988
2989 /* allocate key */
2990 key = alloc_trash_chunk();
2991 if (!key) {
2992 rule_ret = HTTP_RULE_RES_BADREQ;
2993 goto end;
2994 }
2995
2996 /* collect key */
2997 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2998 key->area[key->data] = '\0';
2999
3000 /* perform update */
3001 /* add entry only if it does not already exist */
3002 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3003 if (pat_ref_find_elt(ref, key->area) == NULL)
3004 pat_ref_add(ref, key->area, NULL, NULL);
3005 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3006
3007 free_trash_chunk(key);
3008 break;
3009 }
3010
3011 case ACT_HTTP_SET_MAP: {
3012 struct pat_ref *ref;
3013 struct buffer *key, *value;
3014
3015 /* collect reference */
3016 ref = pat_ref_lookup(rule->arg.map.ref);
3017 if (!ref)
3018 continue;
3019
3020 /* allocate key */
3021 key = alloc_trash_chunk();
3022 if (!key) {
3023 rule_ret = HTTP_RULE_RES_BADREQ;
3024 goto end;
3025 }
3026
3027 /* allocate value */
3028 value = alloc_trash_chunk();
3029 if (!value) {
3030 free_trash_chunk(key);
3031 rule_ret = HTTP_RULE_RES_BADREQ;
3032 goto end;
3033 }
3034
3035 /* collect key */
3036 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3037 key->area[key->data] = '\0';
3038
3039 /* collect value */
3040 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3041 value->area[value->data] = '\0';
3042
3043 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003044 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003045 if (pat_ref_find_elt(ref, key->area) != NULL)
3046 /* update entry if it exists */
3047 pat_ref_set(ref, key->area, value->area, NULL);
3048 else
3049 /* insert a new entry */
3050 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003051 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003052 free_trash_chunk(key);
3053 free_trash_chunk(value);
3054 break;
3055 }
3056
3057 case ACT_HTTP_EARLY_HINT:
3058 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3059 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003060 early_hints = htx_add_early_hint_header(s, early_hints,
3061 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003062 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003063 if (early_hints == -1) {
3064 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003065 goto end;
3066 }
3067 break;
3068
3069 case ACT_CUSTOM:
3070 if ((s->req.flags & CF_READ_ERROR) ||
3071 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003072 (px->options & PR_O_ABRT_CLOSE)))
3073 act_flags |= ACT_FLAG_FINAL;
3074
3075 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3076 case ACT_RET_ERR:
3077 case ACT_RET_CONT:
3078 break;
3079 case ACT_RET_STOP:
3080 rule_ret = HTTP_RULE_RES_DONE;
3081 goto end;
3082 case ACT_RET_YIELD:
3083 s->current_rule = rule;
3084 rule_ret = HTTP_RULE_RES_YIELD;
3085 goto end;
3086 }
3087 break;
3088
3089 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3090 /* Note: only the first valid tracking parameter of each
3091 * applies.
3092 */
3093
3094 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3095 struct stktable *t;
3096 struct stksess *ts;
3097 struct stktable_key *key;
3098 void *ptr1, *ptr2;
3099
3100 t = rule->arg.trk_ctr.table.t;
3101 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3102 rule->arg.trk_ctr.expr, NULL);
3103
3104 if (key && (ts = stktable_get_entry(t, key))) {
3105 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3106
3107 /* let's count a new HTTP request as it's the first time we do it */
3108 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3109 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3110 if (ptr1 || ptr2) {
3111 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3112
3113 if (ptr1)
3114 stktable_data_cast(ptr1, http_req_cnt)++;
3115
3116 if (ptr2)
3117 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3118 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3119
3120 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3121
3122 /* If data was modified, we need to touch to re-schedule sync */
3123 stktable_touch_local(t, ts, 0);
3124 }
3125
3126 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3127 if (sess->fe != s->be)
3128 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3129 }
3130 }
3131 break;
3132
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003133 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003134 default:
3135 break;
3136 }
3137 }
3138
3139 end:
3140 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003141 if (htx_reply_103_early_hints(&s->res) == -1)
3142 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003143 }
3144
3145 /* we reached the end of the rules, nothing to report */
3146 return rule_ret;
3147}
3148
3149/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3150 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3151 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3152 * is returned, the process can continue the evaluation of next rule list. If
3153 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3154 * is returned, it means the operation could not be processed and a server error
3155 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3156 * deny rule. If *YIELD is returned, the caller must call again the function
3157 * with the same context.
3158 */
3159static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3160 struct stream *s)
3161{
3162 struct session *sess = strm_sess(s);
3163 struct http_txn *txn = s->txn;
3164 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003165 struct act_rule *rule;
3166 struct http_hdr_ctx ctx;
3167 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3168 int act_flags = 0;
3169
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003170 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003171
3172 /* If "the current_rule_list" match the executed rule list, we are in
3173 * resume condition. If a resume is needed it is always in the action
3174 * and never in the ACL or converters. In this case, we initialise the
3175 * current rule, and go to the action execution point.
3176 */
3177 if (s->current_rule) {
3178 rule = s->current_rule;
3179 s->current_rule = NULL;
3180 if (s->current_rule_list == rules)
3181 goto resume_execution;
3182 }
3183 s->current_rule_list = rules;
3184
3185 list_for_each_entry(rule, rules, list) {
3186 /* check optional condition */
3187 if (rule->cond) {
3188 int ret;
3189
3190 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3191 ret = acl_pass(ret);
3192
3193 if (rule->cond->pol == ACL_COND_UNLESS)
3194 ret = !ret;
3195
3196 if (!ret) /* condition not matched */
3197 continue;
3198 }
3199
3200 act_flags |= ACT_FLAG_FIRST;
3201resume_execution:
3202 switch (rule->action) {
3203 case ACT_ACTION_ALLOW:
3204 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3205 goto end;
3206
3207 case ACT_ACTION_DENY:
3208 txn->flags |= TX_SVDENY;
3209 rule_ret = HTTP_RULE_RES_STOP;
3210 goto end;
3211
3212 case ACT_HTTP_SET_NICE:
3213 s->task->nice = rule->arg.nice;
3214 break;
3215
3216 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003217 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003218 break;
3219
3220 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003221 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003222 break;
3223
3224 case ACT_HTTP_SET_LOGL:
3225 s->logs.level = rule->arg.loglevel;
3226 break;
3227
3228 case ACT_HTTP_REPLACE_HDR:
3229 case ACT_HTTP_REPLACE_VAL:
3230 if (htx_transform_header(s, &s->res, htx,
3231 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3232 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003233 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003234 rule_ret = HTTP_RULE_RES_BADREQ;
3235 goto end;
3236 }
3237 break;
3238
3239 case ACT_HTTP_DEL_HDR:
3240 /* remove all occurrences of the header */
3241 ctx.blk = NULL;
3242 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3243 http_remove_header(htx, &ctx);
3244 break;
3245
3246 case ACT_HTTP_SET_HDR:
3247 case ACT_HTTP_ADD_HDR: {
3248 struct buffer *replace;
3249 struct ist n, v;
3250
3251 replace = alloc_trash_chunk();
3252 if (!replace) {
3253 rule_ret = HTTP_RULE_RES_BADREQ;
3254 goto end;
3255 }
3256
3257 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3258 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3259 v = ist2(replace->area, replace->data);
3260
3261 if (rule->action == ACT_HTTP_SET_HDR) {
3262 /* remove all occurrences of the header */
3263 ctx.blk = NULL;
3264 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3265 http_remove_header(htx, &ctx);
3266 }
3267
3268 if (!http_add_header(htx, n, v)) {
3269 static unsigned char rate_limit = 0;
3270
3271 if ((rate_limit++ & 255) == 0) {
3272 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);
3273 }
3274
Olivier Houcharda798bf52019-03-08 18:52:00 +01003275 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003276 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003277 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003278 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003279 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003280 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003281 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003282 }
3283 free_trash_chunk(replace);
3284 break;
3285 }
3286
3287 case ACT_HTTP_DEL_ACL:
3288 case ACT_HTTP_DEL_MAP: {
3289 struct pat_ref *ref;
3290 struct buffer *key;
3291
3292 /* collect reference */
3293 ref = pat_ref_lookup(rule->arg.map.ref);
3294 if (!ref)
3295 continue;
3296
3297 /* allocate key */
3298 key = alloc_trash_chunk();
3299 if (!key) {
3300 rule_ret = HTTP_RULE_RES_BADREQ;
3301 goto end;
3302 }
3303
3304 /* collect key */
3305 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3306 key->area[key->data] = '\0';
3307
3308 /* perform update */
3309 /* returned code: 1=ok, 0=ko */
3310 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3311 pat_ref_delete(ref, key->area);
3312 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3313
3314 free_trash_chunk(key);
3315 break;
3316 }
3317
3318 case ACT_HTTP_ADD_ACL: {
3319 struct pat_ref *ref;
3320 struct buffer *key;
3321
3322 /* collect reference */
3323 ref = pat_ref_lookup(rule->arg.map.ref);
3324 if (!ref)
3325 continue;
3326
3327 /* allocate key */
3328 key = alloc_trash_chunk();
3329 if (!key) {
3330 rule_ret = HTTP_RULE_RES_BADREQ;
3331 goto end;
3332 }
3333
3334 /* collect key */
3335 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3336 key->area[key->data] = '\0';
3337
3338 /* perform update */
3339 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003340 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003341 if (pat_ref_find_elt(ref, key->area) == NULL)
3342 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003343 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003344 free_trash_chunk(key);
3345 break;
3346 }
3347
3348 case ACT_HTTP_SET_MAP: {
3349 struct pat_ref *ref;
3350 struct buffer *key, *value;
3351
3352 /* collect reference */
3353 ref = pat_ref_lookup(rule->arg.map.ref);
3354 if (!ref)
3355 continue;
3356
3357 /* allocate key */
3358 key = alloc_trash_chunk();
3359 if (!key) {
3360 rule_ret = HTTP_RULE_RES_BADREQ;
3361 goto end;
3362 }
3363
3364 /* allocate value */
3365 value = alloc_trash_chunk();
3366 if (!value) {
3367 free_trash_chunk(key);
3368 rule_ret = HTTP_RULE_RES_BADREQ;
3369 goto end;
3370 }
3371
3372 /* collect key */
3373 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3374 key->area[key->data] = '\0';
3375
3376 /* collect value */
3377 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3378 value->area[value->data] = '\0';
3379
3380 /* perform update */
3381 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3382 if (pat_ref_find_elt(ref, key->area) != NULL)
3383 /* update entry if it exists */
3384 pat_ref_set(ref, key->area, value->area, NULL);
3385 else
3386 /* insert a new entry */
3387 pat_ref_add(ref, key->area, value->area, NULL);
3388 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3389 free_trash_chunk(key);
3390 free_trash_chunk(value);
3391 break;
3392 }
3393
3394 case ACT_HTTP_REDIR:
3395 rule_ret = HTTP_RULE_RES_DONE;
3396 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3397 rule_ret = HTTP_RULE_RES_BADREQ;
3398 goto end;
3399
3400 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3401 /* Note: only the first valid tracking parameter of each
3402 * applies.
3403 */
3404 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3405 struct stktable *t;
3406 struct stksess *ts;
3407 struct stktable_key *key;
3408 void *ptr;
3409
3410 t = rule->arg.trk_ctr.table.t;
3411 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3412 rule->arg.trk_ctr.expr, NULL);
3413
3414 if (key && (ts = stktable_get_entry(t, key))) {
3415 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3416
3417 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3418
3419 /* let's count a new HTTP request as it's the first time we do it */
3420 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3421 if (ptr)
3422 stktable_data_cast(ptr, http_req_cnt)++;
3423
3424 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3425 if (ptr)
3426 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3427 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3428
3429 /* When the client triggers a 4xx from the server, it's most often due
3430 * to a missing object or permission. These events should be tracked
3431 * because if they happen often, it may indicate a brute force or a
3432 * vulnerability scan. Normally this is done when receiving the response
3433 * but here we're tracking after this ought to have been done so we have
3434 * to do it on purpose.
3435 */
3436 if ((unsigned)(txn->status - 400) < 100) {
3437 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3438 if (ptr)
3439 stktable_data_cast(ptr, http_err_cnt)++;
3440
3441 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3442 if (ptr)
3443 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3444 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3445 }
3446
3447 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3448
3449 /* If data was modified, we need to touch to re-schedule sync */
3450 stktable_touch_local(t, ts, 0);
3451
3452 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3453 if (sess->fe != s->be)
3454 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3455 }
3456 }
3457 break;
3458
3459 case ACT_CUSTOM:
3460 if ((s->req.flags & CF_READ_ERROR) ||
3461 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003462 (px->options & PR_O_ABRT_CLOSE)))
3463 act_flags |= ACT_FLAG_FINAL;
3464
3465 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3466 case ACT_RET_ERR:
3467 case ACT_RET_CONT:
3468 break;
3469 case ACT_RET_STOP:
3470 rule_ret = HTTP_RULE_RES_STOP;
3471 goto end;
3472 case ACT_RET_YIELD:
3473 s->current_rule = rule;
3474 rule_ret = HTTP_RULE_RES_YIELD;
3475 goto end;
3476 }
3477 break;
3478
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003479 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003480 default:
3481 break;
3482 }
3483 }
3484
3485 end:
3486 /* we reached the end of the rules, nothing to report */
3487 return rule_ret;
3488}
3489
Christopher Faulet33640082018-10-24 11:53:01 +02003490/* Iterate the same filter through all request headers.
3491 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3492 * Since it can manage the switch to another backend, it updates the per-proxy
3493 * DENY stats.
3494 */
3495static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3496{
3497 struct http_txn *txn = s->txn;
3498 struct htx *htx;
3499 struct buffer *hdr = get_trash_chunk();
3500 int32_t pos;
3501
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003502 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003503
Christopher Fauleta3f15502019-05-13 15:27:23 +02003504 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003505 struct htx_blk *blk = htx_get_blk(htx, pos);
3506 enum htx_blk_type type;
3507 struct ist n, v;
3508
3509 next_hdr:
3510 type = htx_get_blk_type(blk);
3511 if (type == HTX_BLK_EOH)
3512 break;
3513 if (type != HTX_BLK_HDR)
3514 continue;
3515
3516 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3517 return 1;
3518 else if (unlikely(txn->flags & TX_CLALLOW) &&
3519 (exp->action == ACT_ALLOW ||
3520 exp->action == ACT_DENY ||
3521 exp->action == ACT_TARPIT))
3522 return 0;
3523
3524 n = htx_get_blk_name(htx, blk);
3525 v = htx_get_blk_value(htx, blk);
3526
Christopher Faulet02e771a2019-02-26 15:36:05 +01003527 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003528 hdr->area[hdr->data++] = ':';
3529 hdr->area[hdr->data++] = ' ';
3530 chunk_memcat(hdr, v.ptr, v.len);
3531
3532 /* Now we have one header in <hdr> */
3533
3534 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3535 struct http_hdr_ctx ctx;
3536 int len;
3537
3538 switch (exp->action) {
3539 case ACT_ALLOW:
3540 txn->flags |= TX_CLALLOW;
3541 goto end;
3542
3543 case ACT_DENY:
3544 txn->flags |= TX_CLDENY;
3545 goto end;
3546
3547 case ACT_TARPIT:
3548 txn->flags |= TX_CLTARPIT;
3549 goto end;
3550
3551 case ACT_REPLACE:
3552 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3553 if (len < 0)
3554 return -1;
3555
3556 http_parse_header(ist2(trash.area, len), &n, &v);
3557 ctx.blk = blk;
3558 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003559 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003560 if (!http_replace_header(htx, &ctx, n, v))
3561 return -1;
3562 if (!ctx.blk)
3563 goto end;
3564 pos = htx_get_blk_pos(htx, blk);
3565 break;
3566
3567 case ACT_REMOVE:
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_remove_header(htx, &ctx))
3572 return -1;
3573 if (!ctx.blk)
3574 goto end;
3575 pos = htx_get_blk_pos(htx, blk);
3576 goto next_hdr;
3577
3578 }
3579 }
3580 }
3581 end:
3582 return 0;
3583}
3584
3585/* Apply the filter to the request line.
3586 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3587 * or -1 if a replacement resulted in an invalid request line.
3588 * Since it can manage the switch to another backend, it updates the per-proxy
3589 * DENY stats.
3590 */
3591static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3592{
3593 struct http_txn *txn = s->txn;
3594 struct htx *htx;
3595 struct buffer *reqline = get_trash_chunk();
3596 int done;
3597
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003598 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003599
3600 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3601 return 1;
3602 else if (unlikely(txn->flags & TX_CLALLOW) &&
3603 (exp->action == ACT_ALLOW ||
3604 exp->action == ACT_DENY ||
3605 exp->action == ACT_TARPIT))
3606 return 0;
3607 else if (exp->action == ACT_REMOVE)
3608 return 0;
3609
3610 done = 0;
3611
Christopher Faulet297fbb42019-05-13 14:41:27 +02003612 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003613
3614 /* Now we have the request line between cur_ptr and cur_end */
3615 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003616 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003617 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003618 int len;
3619
3620 switch (exp->action) {
3621 case ACT_ALLOW:
3622 txn->flags |= TX_CLALLOW;
3623 done = 1;
3624 break;
3625
3626 case ACT_DENY:
3627 txn->flags |= TX_CLDENY;
3628 done = 1;
3629 break;
3630
3631 case ACT_TARPIT:
3632 txn->flags |= TX_CLTARPIT;
3633 done = 1;
3634 break;
3635
3636 case ACT_REPLACE:
3637 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3638 if (len < 0)
3639 return -1;
3640
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003641 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3642 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3643 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003644 return -1;
3645 done = 1;
3646 break;
3647 }
3648 }
3649 return done;
3650}
3651
3652/*
3653 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3654 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3655 * unparsable request. Since it can manage the switch to another backend, it
3656 * updates the per-proxy DENY stats.
3657 */
3658static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3659{
3660 struct session *sess = s->sess;
3661 struct http_txn *txn = s->txn;
3662 struct hdr_exp *exp;
3663
3664 for (exp = px->req_exp; exp; exp = exp->next) {
3665 int ret;
3666
3667 /*
3668 * The interleaving of transformations and verdicts
3669 * makes it difficult to decide to continue or stop
3670 * the evaluation.
3671 */
3672
3673 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3674 break;
3675
3676 if ((txn->flags & TX_CLALLOW) &&
3677 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3678 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3679 continue;
3680
3681 /* if this filter had a condition, evaluate it now and skip to
3682 * next filter if the condition does not match.
3683 */
3684 if (exp->cond) {
3685 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3686 ret = acl_pass(ret);
3687 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3688 ret = !ret;
3689
3690 if (!ret)
3691 continue;
3692 }
3693
3694 /* Apply the filter to the request line. */
3695 ret = htx_apply_filter_to_req_line(s, req, exp);
3696 if (unlikely(ret < 0))
3697 return -1;
3698
3699 if (likely(ret == 0)) {
3700 /* The filter did not match the request, it can be
3701 * iterated through all headers.
3702 */
3703 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3704 return -1;
3705 }
3706 }
3707 return 0;
3708}
3709
3710/* Iterate the same filter through all response headers contained in <res>.
3711 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3712 */
3713static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3714{
3715 struct http_txn *txn = s->txn;
3716 struct htx *htx;
3717 struct buffer *hdr = get_trash_chunk();
3718 int32_t pos;
3719
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003720 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003721
Christopher Fauleta3f15502019-05-13 15:27:23 +02003722 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003723 struct htx_blk *blk = htx_get_blk(htx, pos);
3724 enum htx_blk_type type;
3725 struct ist n, v;
3726
3727 next_hdr:
3728 type = htx_get_blk_type(blk);
3729 if (type == HTX_BLK_EOH)
3730 break;
3731 if (type != HTX_BLK_HDR)
3732 continue;
3733
3734 if (unlikely(txn->flags & TX_SVDENY))
3735 return 1;
3736 else if (unlikely(txn->flags & TX_SVALLOW) &&
3737 (exp->action == ACT_ALLOW ||
3738 exp->action == ACT_DENY))
3739 return 0;
3740
3741 n = htx_get_blk_name(htx, blk);
3742 v = htx_get_blk_value(htx, blk);
3743
Christopher Faulet02e771a2019-02-26 15:36:05 +01003744 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003745 hdr->area[hdr->data++] = ':';
3746 hdr->area[hdr->data++] = ' ';
3747 chunk_memcat(hdr, v.ptr, v.len);
3748
3749 /* Now we have one header in <hdr> */
3750
3751 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3752 struct http_hdr_ctx ctx;
3753 int len;
3754
3755 switch (exp->action) {
3756 case ACT_ALLOW:
3757 txn->flags |= TX_SVALLOW;
3758 goto end;
3759 break;
3760
3761 case ACT_DENY:
3762 txn->flags |= TX_SVDENY;
3763 goto end;
3764 break;
3765
3766 case ACT_REPLACE:
3767 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3768 if (len < 0)
3769 return -1;
3770
3771 http_parse_header(ist2(trash.area, len), &n, &v);
3772 ctx.blk = blk;
3773 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003774 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003775 if (!http_replace_header(htx, &ctx, n, v))
3776 return -1;
3777 if (!ctx.blk)
3778 goto end;
3779 pos = htx_get_blk_pos(htx, blk);
3780 break;
3781
3782 case ACT_REMOVE:
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_remove_header(htx, &ctx))
3787 return -1;
3788 if (!ctx.blk)
3789 goto end;
3790 pos = htx_get_blk_pos(htx, blk);
3791 goto next_hdr;
3792 }
3793 }
3794
3795 }
3796 end:
3797 return 0;
3798}
3799
3800/* Apply the filter to the status line in the response buffer <res>.
3801 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3802 * or -1 if a replacement resulted in an invalid status line.
3803 */
3804static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3805{
3806 struct http_txn *txn = s->txn;
3807 struct htx *htx;
3808 struct buffer *resline = get_trash_chunk();
3809 int done;
3810
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003811 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003812
3813 if (unlikely(txn->flags & TX_SVDENY))
3814 return 1;
3815 else if (unlikely(txn->flags & TX_SVALLOW) &&
3816 (exp->action == ACT_ALLOW ||
3817 exp->action == ACT_DENY))
3818 return 0;
3819 else if (exp->action == ACT_REMOVE)
3820 return 0;
3821
3822 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003823 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003824
3825 /* Now we have the status line between cur_ptr and cur_end */
3826 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003827 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003828 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003829 int len;
3830
3831 switch (exp->action) {
3832 case ACT_ALLOW:
3833 txn->flags |= TX_SVALLOW;
3834 done = 1;
3835 break;
3836
3837 case ACT_DENY:
3838 txn->flags |= TX_SVDENY;
3839 done = 1;
3840 break;
3841
3842 case ACT_REPLACE:
3843 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3844 if (len < 0)
3845 return -1;
3846
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003847 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3848 sl->info.res.status = strl2ui(code.ptr, code.len);
3849 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003850 return -1;
3851
3852 done = 1;
3853 return 1;
3854 }
3855 }
3856 return done;
3857}
3858
3859/*
3860 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3861 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3862 * unparsable response.
3863 */
3864static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3865{
3866 struct session *sess = s->sess;
3867 struct http_txn *txn = s->txn;
3868 struct hdr_exp *exp;
3869
3870 for (exp = px->rsp_exp; exp; exp = exp->next) {
3871 int ret;
3872
3873 /*
3874 * The interleaving of transformations and verdicts
3875 * makes it difficult to decide to continue or stop
3876 * the evaluation.
3877 */
3878
3879 if (txn->flags & TX_SVDENY)
3880 break;
3881
3882 if ((txn->flags & TX_SVALLOW) &&
3883 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3884 exp->action == ACT_PASS)) {
3885 exp = exp->next;
3886 continue;
3887 }
3888
3889 /* if this filter had a condition, evaluate it now and skip to
3890 * next filter if the condition does not match.
3891 */
3892 if (exp->cond) {
3893 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3894 ret = acl_pass(ret);
3895 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3896 ret = !ret;
3897 if (!ret)
3898 continue;
3899 }
3900
3901 /* Apply the filter to the status line. */
3902 ret = htx_apply_filter_to_sts_line(s, res, exp);
3903 if (unlikely(ret < 0))
3904 return -1;
3905
3906 if (likely(ret == 0)) {
3907 /* The filter did not match the response, it can be
3908 * iterated through all headers.
3909 */
3910 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3911 return -1;
3912 }
3913 }
3914 return 0;
3915}
3916
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003917/*
3918 * Manage client-side cookie. It can impact performance by about 2% so it is
3919 * desirable to call it only when needed. This code is quite complex because
3920 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3921 * highly recommended not to touch this part without a good reason !
3922 */
3923static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3924{
3925 struct session *sess = s->sess;
3926 struct http_txn *txn = s->txn;
3927 struct htx *htx;
3928 struct http_hdr_ctx ctx;
3929 char *hdr_beg, *hdr_end, *del_from;
3930 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3931 int preserve_hdr;
3932
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003933 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003934 ctx.blk = NULL;
3935 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3936 del_from = NULL; /* nothing to be deleted */
3937 preserve_hdr = 0; /* assume we may kill the whole header */
3938
3939 /* Now look for cookies. Conforming to RFC2109, we have to support
3940 * attributes whose name begin with a '$', and associate them with
3941 * the right cookie, if we want to delete this cookie.
3942 * So there are 3 cases for each cookie read :
3943 * 1) it's a special attribute, beginning with a '$' : ignore it.
3944 * 2) it's a server id cookie that we *MAY* want to delete : save
3945 * some pointers on it (last semi-colon, beginning of cookie...)
3946 * 3) it's an application cookie : we *MAY* have to delete a previous
3947 * "special" cookie.
3948 * At the end of loop, if a "special" cookie remains, we may have to
3949 * remove it. If no application cookie persists in the header, we
3950 * *MUST* delete it.
3951 *
3952 * Note: RFC2965 is unclear about the processing of spaces around
3953 * the equal sign in the ATTR=VALUE form. A careful inspection of
3954 * the RFC explicitly allows spaces before it, and not within the
3955 * tokens (attrs or values). An inspection of RFC2109 allows that
3956 * too but section 10.1.3 lets one think that spaces may be allowed
3957 * after the equal sign too, resulting in some (rare) buggy
3958 * implementations trying to do that. So let's do what servers do.
3959 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3960 * allowed quoted strings in values, with any possible character
3961 * after a backslash, including control chars and delimitors, which
3962 * causes parsing to become ambiguous. Browsers also allow spaces
3963 * within values even without quotes.
3964 *
3965 * We have to keep multiple pointers in order to support cookie
3966 * removal at the beginning, middle or end of header without
3967 * corrupting the header. All of these headers are valid :
3968 *
3969 * hdr_beg hdr_end
3970 * | |
3971 * v |
3972 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3973 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3974 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3975 * | | | | | | |
3976 * | | | | | | |
3977 * | | | | | | +--> next
3978 * | | | | | +----> val_end
3979 * | | | | +-----------> val_beg
3980 * | | | +--------------> equal
3981 * | | +----------------> att_end
3982 * | +---------------------> att_beg
3983 * +--------------------------> prev
3984 *
3985 */
3986 hdr_beg = ctx.value.ptr;
3987 hdr_end = hdr_beg + ctx.value.len;
3988 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3989 /* Iterate through all cookies on this line */
3990
3991 /* find att_beg */
3992 att_beg = prev;
3993 if (prev > hdr_beg)
3994 att_beg++;
3995
3996 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3997 att_beg++;
3998
3999 /* find att_end : this is the first character after the last non
4000 * space before the equal. It may be equal to hdr_end.
4001 */
4002 equal = att_end = att_beg;
4003 while (equal < hdr_end) {
4004 if (*equal == '=' || *equal == ',' || *equal == ';')
4005 break;
4006 if (HTTP_IS_SPHT(*equal++))
4007 continue;
4008 att_end = equal;
4009 }
4010
4011 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4012 * is between <att_beg> and <equal>, both may be identical.
4013 */
4014 /* look for end of cookie if there is an equal sign */
4015 if (equal < hdr_end && *equal == '=') {
4016 /* look for the beginning of the value */
4017 val_beg = equal + 1;
4018 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4019 val_beg++;
4020
4021 /* find the end of the value, respecting quotes */
4022 next = http_find_cookie_value_end(val_beg, hdr_end);
4023
4024 /* make val_end point to the first white space or delimitor after the value */
4025 val_end = next;
4026 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4027 val_end--;
4028 }
4029 else
4030 val_beg = val_end = next = equal;
4031
4032 /* We have nothing to do with attributes beginning with
4033 * '$'. However, they will automatically be removed if a
4034 * header before them is removed, since they're supposed
4035 * to be linked together.
4036 */
4037 if (*att_beg == '$')
4038 continue;
4039
4040 /* Ignore cookies with no equal sign */
4041 if (equal == next) {
4042 /* This is not our cookie, so we must preserve it. But if we already
4043 * scheduled another cookie for removal, we cannot remove the
4044 * complete header, but we can remove the previous block itself.
4045 */
4046 preserve_hdr = 1;
4047 if (del_from != NULL) {
4048 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4049 val_end += delta;
4050 next += delta;
4051 hdr_end += delta;
4052 prev = del_from;
4053 del_from = NULL;
4054 }
4055 continue;
4056 }
4057
4058 /* if there are spaces around the equal sign, we need to
4059 * strip them otherwise we'll get trouble for cookie captures,
4060 * or even for rewrites. Since this happens extremely rarely,
4061 * it does not hurt performance.
4062 */
4063 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4064 int stripped_before = 0;
4065 int stripped_after = 0;
4066
4067 if (att_end != equal) {
4068 memmove(att_end, equal, hdr_end - equal);
4069 stripped_before = (att_end - equal);
4070 equal += stripped_before;
4071 val_beg += stripped_before;
4072 }
4073
4074 if (val_beg > equal + 1) {
4075 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4076 stripped_after = (equal + 1) - val_beg;
4077 val_beg += stripped_after;
4078 stripped_before += stripped_after;
4079 }
4080
4081 val_end += stripped_before;
4082 next += stripped_before;
4083 hdr_end += stripped_before;
4084 }
4085 /* now everything is as on the diagram above */
4086
4087 /* First, let's see if we want to capture this cookie. We check
4088 * that we don't already have a client side cookie, because we
4089 * can only capture one. Also as an optimisation, we ignore
4090 * cookies shorter than the declared name.
4091 */
4092 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4093 (val_end - att_beg >= sess->fe->capture_namelen) &&
4094 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4095 int log_len = val_end - att_beg;
4096
4097 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4098 ha_alert("HTTP logging : out of memory.\n");
4099 } else {
4100 if (log_len > sess->fe->capture_len)
4101 log_len = sess->fe->capture_len;
4102 memcpy(txn->cli_cookie, att_beg, log_len);
4103 txn->cli_cookie[log_len] = 0;
4104 }
4105 }
4106
4107 /* Persistence cookies in passive, rewrite or insert mode have the
4108 * following form :
4109 *
4110 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4111 *
4112 * For cookies in prefix mode, the form is :
4113 *
4114 * Cookie: NAME=SRV~VALUE
4115 */
4116 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4117 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4118 struct server *srv = s->be->srv;
4119 char *delim;
4120
4121 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4122 * have the server ID between val_beg and delim, and the original cookie between
4123 * delim+1 and val_end. Otherwise, delim==val_end :
4124 *
4125 * hdr_beg
4126 * |
4127 * v
4128 * NAME=SRV; # in all but prefix modes
4129 * NAME=SRV~OPAQUE ; # in prefix mode
4130 * || || | |+-> next
4131 * || || | +--> val_end
4132 * || || +---------> delim
4133 * || |+------------> val_beg
4134 * || +-------------> att_end = equal
4135 * |+-----------------> att_beg
4136 * +------------------> prev
4137 *
4138 */
4139 if (s->be->ck_opts & PR_CK_PFX) {
4140 for (delim = val_beg; delim < val_end; delim++)
4141 if (*delim == COOKIE_DELIM)
4142 break;
4143 }
4144 else {
4145 char *vbar1;
4146 delim = val_end;
4147 /* Now check if the cookie contains a date field, which would
4148 * appear after a vertical bar ('|') just after the server name
4149 * and before the delimiter.
4150 */
4151 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4152 if (vbar1) {
4153 /* OK, so left of the bar is the server's cookie and
4154 * right is the last seen date. It is a base64 encoded
4155 * 30-bit value representing the UNIX date since the
4156 * epoch in 4-second quantities.
4157 */
4158 int val;
4159 delim = vbar1++;
4160 if (val_end - vbar1 >= 5) {
4161 val = b64tos30(vbar1);
4162 if (val > 0)
4163 txn->cookie_last_date = val << 2;
4164 }
4165 /* look for a second vertical bar */
4166 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4167 if (vbar1 && (val_end - vbar1 > 5)) {
4168 val = b64tos30(vbar1 + 1);
4169 if (val > 0)
4170 txn->cookie_first_date = val << 2;
4171 }
4172 }
4173 }
4174
4175 /* if the cookie has an expiration date and the proxy wants to check
4176 * it, then we do that now. We first check if the cookie is too old,
4177 * then only if it has expired. We detect strict overflow because the
4178 * time resolution here is not great (4 seconds). Cookies with dates
4179 * in the future are ignored if their offset is beyond one day. This
4180 * allows an admin to fix timezone issues without expiring everyone
4181 * and at the same time avoids keeping unwanted side effects for too
4182 * long.
4183 */
4184 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4185 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4186 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4187 txn->flags &= ~TX_CK_MASK;
4188 txn->flags |= TX_CK_OLD;
4189 delim = val_beg; // let's pretend we have not found the cookie
4190 txn->cookie_first_date = 0;
4191 txn->cookie_last_date = 0;
4192 }
4193 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4194 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4195 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4196 txn->flags &= ~TX_CK_MASK;
4197 txn->flags |= TX_CK_EXPIRED;
4198 delim = val_beg; // let's pretend we have not found the cookie
4199 txn->cookie_first_date = 0;
4200 txn->cookie_last_date = 0;
4201 }
4202
4203 /* Here, we'll look for the first running server which supports the cookie.
4204 * This allows to share a same cookie between several servers, for example
4205 * to dedicate backup servers to specific servers only.
4206 * However, to prevent clients from sticking to cookie-less backup server
4207 * when they have incidentely learned an empty cookie, we simply ignore
4208 * empty cookies and mark them as invalid.
4209 * The same behaviour is applied when persistence must be ignored.
4210 */
4211 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4212 srv = NULL;
4213
4214 while (srv) {
4215 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4216 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4217 if ((srv->cur_state != SRV_ST_STOPPED) ||
4218 (s->be->options & PR_O_PERSIST) ||
4219 (s->flags & SF_FORCE_PRST)) {
4220 /* we found the server and we can use it */
4221 txn->flags &= ~TX_CK_MASK;
4222 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4223 s->flags |= SF_DIRECT | SF_ASSIGNED;
4224 s->target = &srv->obj_type;
4225 break;
4226 } else {
4227 /* we found a server, but it's down,
4228 * mark it as such and go on in case
4229 * another one is available.
4230 */
4231 txn->flags &= ~TX_CK_MASK;
4232 txn->flags |= TX_CK_DOWN;
4233 }
4234 }
4235 srv = srv->next;
4236 }
4237
4238 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4239 /* no server matched this cookie or we deliberately skipped it */
4240 txn->flags &= ~TX_CK_MASK;
4241 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4242 txn->flags |= TX_CK_UNUSED;
4243 else
4244 txn->flags |= TX_CK_INVALID;
4245 }
4246
4247 /* depending on the cookie mode, we may have to either :
4248 * - delete the complete cookie if we're in insert+indirect mode, so that
4249 * the server never sees it ;
4250 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004251 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004252 * if we're in cookie prefix mode
4253 */
4254 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4255 int delta; /* negative */
4256
4257 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4258 delta = val_beg - (delim + 1);
4259 val_end += delta;
4260 next += delta;
4261 hdr_end += delta;
4262 del_from = NULL;
4263 preserve_hdr = 1; /* we want to keep this cookie */
4264 }
4265 else if (del_from == NULL &&
4266 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4267 del_from = prev;
4268 }
4269 }
4270 else {
4271 /* This is not our cookie, so we must preserve it. But if we already
4272 * scheduled another cookie for removal, we cannot remove the
4273 * complete header, but we can remove the previous block itself.
4274 */
4275 preserve_hdr = 1;
4276
4277 if (del_from != NULL) {
4278 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4279 if (att_beg >= del_from)
4280 att_beg += delta;
4281 if (att_end >= del_from)
4282 att_end += delta;
4283 val_beg += delta;
4284 val_end += delta;
4285 next += delta;
4286 hdr_end += delta;
4287 prev = del_from;
4288 del_from = NULL;
4289 }
4290 }
4291
4292 /* continue with next cookie on this header line */
4293 att_beg = next;
4294 } /* for each cookie */
4295
4296
4297 /* There are no more cookies on this line.
4298 * We may still have one (or several) marked for deletion at the
4299 * end of the line. We must do this now in two ways :
4300 * - if some cookies must be preserved, we only delete from the
4301 * mark to the end of line ;
4302 * - if nothing needs to be preserved, simply delete the whole header
4303 */
4304 if (del_from) {
4305 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4306 }
4307 if ((hdr_end - hdr_beg) != ctx.value.len) {
4308 if (hdr_beg != hdr_end) {
4309 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004310 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004311 }
4312 else
4313 http_remove_header(htx, &ctx);
4314 }
4315 } /* for each "Cookie header */
4316}
4317
4318/*
4319 * Manage server-side cookies. It can impact performance by about 2% so it is
4320 * desirable to call it only when needed. This function is also used when we
4321 * just need to know if there is a cookie (eg: for check-cache).
4322 */
4323static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4324{
4325 struct session *sess = s->sess;
4326 struct http_txn *txn = s->txn;
4327 struct htx *htx;
4328 struct http_hdr_ctx ctx;
4329 struct server *srv;
4330 char *hdr_beg, *hdr_end;
4331 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004332 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004333
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004334 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004335
4336 ctx.blk = NULL;
4337 while (1) {
4338 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4339 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4340 break;
4341 is_cookie2 = 1;
4342 }
4343
4344 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4345 * <prev> points to the colon.
4346 */
4347 txn->flags |= TX_SCK_PRESENT;
4348
4349 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4350 * check-cache is enabled) and we are not interested in checking
4351 * them. Warning, the cookie capture is declared in the frontend.
4352 */
4353 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4354 break;
4355
4356 /* OK so now we know we have to process this response cookie.
4357 * The format of the Set-Cookie header is slightly different
4358 * from the format of the Cookie header in that it does not
4359 * support the comma as a cookie delimiter (thus the header
4360 * cannot be folded) because the Expires attribute described in
4361 * the original Netscape's spec may contain an unquoted date
4362 * with a comma inside. We have to live with this because
4363 * many browsers don't support Max-Age and some browsers don't
4364 * support quoted strings. However the Set-Cookie2 header is
4365 * clean.
4366 *
4367 * We have to keep multiple pointers in order to support cookie
4368 * removal at the beginning, middle or end of header without
4369 * corrupting the header (in case of set-cookie2). A special
4370 * pointer, <scav> points to the beginning of the set-cookie-av
4371 * fields after the first semi-colon. The <next> pointer points
4372 * either to the end of line (set-cookie) or next unquoted comma
4373 * (set-cookie2). All of these headers are valid :
4374 *
4375 * hdr_beg hdr_end
4376 * | |
4377 * v |
4378 * NAME1 = VALUE 1 ; Secure; Path="/" |
4379 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4380 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4381 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4382 * | | | | | | | |
4383 * | | | | | | | +-> next
4384 * | | | | | | +------------> scav
4385 * | | | | | +--------------> val_end
4386 * | | | | +--------------------> val_beg
4387 * | | | +----------------------> equal
4388 * | | +------------------------> att_end
4389 * | +----------------------------> att_beg
4390 * +------------------------------> prev
4391 * -------------------------------> hdr_beg
4392 */
4393 hdr_beg = ctx.value.ptr;
4394 hdr_end = hdr_beg + ctx.value.len;
4395 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4396
4397 /* Iterate through all cookies on this line */
4398
4399 /* find att_beg */
4400 att_beg = prev;
4401 if (prev > hdr_beg)
4402 att_beg++;
4403
4404 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4405 att_beg++;
4406
4407 /* find att_end : this is the first character after the last non
4408 * space before the equal. It may be equal to hdr_end.
4409 */
4410 equal = att_end = att_beg;
4411
4412 while (equal < hdr_end) {
4413 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4414 break;
4415 if (HTTP_IS_SPHT(*equal++))
4416 continue;
4417 att_end = equal;
4418 }
4419
4420 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4421 * is between <att_beg> and <equal>, both may be identical.
4422 */
4423
4424 /* look for end of cookie if there is an equal sign */
4425 if (equal < hdr_end && *equal == '=') {
4426 /* look for the beginning of the value */
4427 val_beg = equal + 1;
4428 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4429 val_beg++;
4430
4431 /* find the end of the value, respecting quotes */
4432 next = http_find_cookie_value_end(val_beg, hdr_end);
4433
4434 /* make val_end point to the first white space or delimitor after the value */
4435 val_end = next;
4436 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4437 val_end--;
4438 }
4439 else {
4440 /* <equal> points to next comma, semi-colon or EOL */
4441 val_beg = val_end = next = equal;
4442 }
4443
4444 if (next < hdr_end) {
4445 /* Set-Cookie2 supports multiple cookies, and <next> points to
4446 * a colon or semi-colon before the end. So skip all attr-value
4447 * pairs and look for the next comma. For Set-Cookie, since
4448 * commas are permitted in values, skip to the end.
4449 */
4450 if (is_cookie2)
4451 next = http_find_hdr_value_end(next, hdr_end);
4452 else
4453 next = hdr_end;
4454 }
4455
4456 /* Now everything is as on the diagram above */
4457
4458 /* Ignore cookies with no equal sign */
4459 if (equal == val_end)
4460 continue;
4461
4462 /* If there are spaces around the equal sign, we need to
4463 * strip them otherwise we'll get trouble for cookie captures,
4464 * or even for rewrites. Since this happens extremely rarely,
4465 * it does not hurt performance.
4466 */
4467 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4468 int stripped_before = 0;
4469 int stripped_after = 0;
4470
4471 if (att_end != equal) {
4472 memmove(att_end, equal, hdr_end - equal);
4473 stripped_before = (att_end - equal);
4474 equal += stripped_before;
4475 val_beg += stripped_before;
4476 }
4477
4478 if (val_beg > equal + 1) {
4479 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4480 stripped_after = (equal + 1) - val_beg;
4481 val_beg += stripped_after;
4482 stripped_before += stripped_after;
4483 }
4484
4485 val_end += stripped_before;
4486 next += stripped_before;
4487 hdr_end += stripped_before;
4488
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004489 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4490 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004491 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004492 }
4493
4494 /* First, let's see if we want to capture this cookie. We check
4495 * that we don't already have a server side cookie, because we
4496 * can only capture one. Also as an optimisation, we ignore
4497 * cookies shorter than the declared name.
4498 */
4499 if (sess->fe->capture_name != NULL &&
4500 txn->srv_cookie == NULL &&
4501 (val_end - att_beg >= sess->fe->capture_namelen) &&
4502 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4503 int log_len = val_end - att_beg;
4504 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4505 ha_alert("HTTP logging : out of memory.\n");
4506 }
4507 else {
4508 if (log_len > sess->fe->capture_len)
4509 log_len = sess->fe->capture_len;
4510 memcpy(txn->srv_cookie, att_beg, log_len);
4511 txn->srv_cookie[log_len] = 0;
4512 }
4513 }
4514
4515 srv = objt_server(s->target);
4516 /* now check if we need to process it for persistence */
4517 if (!(s->flags & SF_IGNORE_PRST) &&
4518 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4519 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4520 /* assume passive cookie by default */
4521 txn->flags &= ~TX_SCK_MASK;
4522 txn->flags |= TX_SCK_FOUND;
4523
4524 /* If the cookie is in insert mode on a known server, we'll delete
4525 * this occurrence because we'll insert another one later.
4526 * We'll delete it too if the "indirect" option is set and we're in
4527 * a direct access.
4528 */
4529 if (s->be->ck_opts & PR_CK_PSV) {
4530 /* The "preserve" flag was set, we don't want to touch the
4531 * server's cookie.
4532 */
4533 }
4534 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4535 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4536 /* this cookie must be deleted */
4537 if (prev == hdr_beg && next == hdr_end) {
4538 /* whole header */
4539 http_remove_header(htx, &ctx);
4540 /* note: while both invalid now, <next> and <hdr_end>
4541 * are still equal, so the for() will stop as expected.
4542 */
4543 } else {
4544 /* just remove the value */
4545 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4546 next = prev;
4547 hdr_end += delta;
4548 }
4549 txn->flags &= ~TX_SCK_MASK;
4550 txn->flags |= TX_SCK_DELETED;
4551 /* and go on with next cookie */
4552 }
4553 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4554 /* replace bytes val_beg->val_end with the cookie name associated
4555 * with this server since we know it.
4556 */
4557 int sliding, delta;
4558
4559 ctx.value = ist2(val_beg, val_end - val_beg);
4560 ctx.lws_before = ctx.lws_after = 0;
4561 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4562 delta = srv->cklen - (val_end - val_beg);
4563 sliding = (ctx.value.ptr - val_beg);
4564 hdr_beg += sliding;
4565 val_beg += sliding;
4566 next += sliding + delta;
4567 hdr_end += sliding + delta;
4568
4569 txn->flags &= ~TX_SCK_MASK;
4570 txn->flags |= TX_SCK_REPLACED;
4571 }
4572 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4573 /* insert the cookie name associated with this server
4574 * before existing cookie, and insert a delimiter between them..
4575 */
4576 int sliding, delta;
4577 ctx.value = ist2(val_beg, 0);
4578 ctx.lws_before = ctx.lws_after = 0;
4579 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4580 delta = srv->cklen + 1;
4581 sliding = (ctx.value.ptr - val_beg);
4582 hdr_beg += sliding;
4583 val_beg += sliding;
4584 next += sliding + delta;
4585 hdr_end += sliding + delta;
4586
4587 val_beg[srv->cklen] = COOKIE_DELIM;
4588 txn->flags &= ~TX_SCK_MASK;
4589 txn->flags |= TX_SCK_REPLACED;
4590 }
4591 }
4592 /* that's done for this cookie, check the next one on the same
4593 * line when next != hdr_end (only if is_cookie2).
4594 */
4595 }
4596 }
4597}
4598
Christopher Faulet25a02f62018-10-24 12:00:25 +02004599/*
4600 * Parses the Cache-Control and Pragma request header fields to determine if
4601 * the request may be served from the cache and/or if it is cacheable. Updates
4602 * s->txn->flags.
4603 */
4604void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4605{
4606 struct http_txn *txn = s->txn;
4607 struct htx *htx;
4608 int32_t pos;
4609 int pragma_found, cc_found, i;
4610
4611 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4612 return; /* nothing more to do here */
4613
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004614 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004615 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004616 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004617 struct htx_blk *blk = htx_get_blk(htx, pos);
4618 enum htx_blk_type type = htx_get_blk_type(blk);
4619 struct ist n, v;
4620
4621 if (type == HTX_BLK_EOH)
4622 break;
4623 if (type != HTX_BLK_HDR)
4624 continue;
4625
4626 n = htx_get_blk_name(htx, blk);
4627 v = htx_get_blk_value(htx, blk);
4628
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004629 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004630 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4631 pragma_found = 1;
4632 continue;
4633 }
4634 }
4635
4636 /* Don't use the cache and don't try to store if we found the
4637 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004638 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004639 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4640 txn->flags |= TX_CACHE_IGNORE;
4641 continue;
4642 }
4643
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004644 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004645 continue;
4646
4647 /* OK, right now we know we have a cache-control header */
4648 cc_found = 1;
4649 if (!v.len) /* no info */
4650 continue;
4651
4652 i = 0;
4653 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4654 !isspace((unsigned char)*(v.ptr+i)))
4655 i++;
4656
4657 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4658 * values after max-age, max-stale nor min-fresh, we simply don't
4659 * use the cache when they're specified.
4660 */
4661 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4662 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4663 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4664 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4665 txn->flags |= TX_CACHE_IGNORE;
4666 continue;
4667 }
4668
4669 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4670 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4671 continue;
4672 }
4673 }
4674
4675 /* RFC7234#5.4:
4676 * When the Cache-Control header field is also present and
4677 * understood in a request, Pragma is ignored.
4678 * When the Cache-Control header field is not present in a
4679 * request, caches MUST consider the no-cache request
4680 * pragma-directive as having the same effect as if
4681 * "Cache-Control: no-cache" were present.
4682 */
4683 if (!cc_found && pragma_found)
4684 txn->flags |= TX_CACHE_IGNORE;
4685}
4686
4687/*
4688 * Check if response is cacheable or not. Updates s->txn->flags.
4689 */
4690void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4691{
4692 struct http_txn *txn = s->txn;
4693 struct htx *htx;
4694 int32_t pos;
4695 int i;
4696
4697 if (txn->status < 200) {
4698 /* do not try to cache interim responses! */
4699 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4700 return;
4701 }
4702
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004703 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004704 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004705 struct htx_blk *blk = htx_get_blk(htx, pos);
4706 enum htx_blk_type type = htx_get_blk_type(blk);
4707 struct ist n, v;
4708
4709 if (type == HTX_BLK_EOH)
4710 break;
4711 if (type != HTX_BLK_HDR)
4712 continue;
4713
4714 n = htx_get_blk_name(htx, blk);
4715 v = htx_get_blk_value(htx, blk);
4716
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004717 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004718 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4719 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4720 return;
4721 }
4722 }
4723
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004724 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004725 continue;
4726
4727 /* OK, right now we know we have a cache-control header */
4728 if (!v.len) /* no info */
4729 continue;
4730
4731 i = 0;
4732 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4733 !isspace((unsigned char)*(v.ptr+i)))
4734 i++;
4735
4736 /* we have a complete value between v.ptr and (v.ptr+i) */
4737 if (i < v.len && *(v.ptr + i) == '=') {
4738 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4739 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4740 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4741 continue;
4742 }
4743
4744 /* we have something of the form no-cache="set-cookie" */
4745 if ((v.len >= 21) &&
4746 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4747 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4748 txn->flags &= ~TX_CACHE_COOK;
4749 continue;
4750 }
4751
4752 /* OK, so we know that either p2 points to the end of string or to a comma */
4753 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4754 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4755 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4756 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4757 return;
4758 }
4759
4760 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4761 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4762 continue;
4763 }
4764 }
4765}
4766
Christopher Faulet64159df2018-10-24 21:15:35 +02004767/* send a server's name with an outgoing request over an established connection.
4768 * Note: this function is designed to be called once the request has been
4769 * scheduled for being forwarded. This is the reason why the number of forwarded
4770 * bytes have to be adjusted.
4771 */
4772int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4773{
4774 struct htx *htx;
4775 struct http_hdr_ctx ctx;
4776 struct ist hdr;
4777 uint32_t data;
4778
4779 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004780 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004781 data = htx->data;
4782
4783 ctx.blk = NULL;
4784 while (http_find_header(htx, hdr, &ctx, 1))
4785 http_remove_header(htx, &ctx);
4786 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4787
4788 if (co_data(&s->req)) {
4789 if (data >= htx->data)
4790 c_rew(&s->req, data - htx->data);
4791 else
4792 c_adv(&s->req, htx->data - data);
4793 }
4794 return 0;
4795}
4796
Christopher Faulet377c5a52018-10-24 21:21:30 +02004797/*
4798 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4799 * for the current backend.
4800 *
4801 * It is assumed that the request is either a HEAD, GET, or POST and that the
4802 * uri_auth field is valid.
4803 *
4804 * Returns 1 if stats should be provided, otherwise 0.
4805 */
4806static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4807{
4808 struct uri_auth *uri_auth = backend->uri_auth;
4809 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004810 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004811 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004812
4813 if (!uri_auth)
4814 return 0;
4815
4816 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4817 return 0;
4818
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004819 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004820 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004821 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004822
4823 /* check URI size */
4824 if (uri_auth->uri_len > uri.len)
4825 return 0;
4826
4827 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4828 return 0;
4829
4830 return 1;
4831}
4832
4833/* This function prepares an applet to handle the stats. It can deal with the
4834 * "100-continue" expectation, check that admin rules are met for POST requests,
4835 * and program a response message if something was unexpected. It cannot fail
4836 * and always relies on the stats applet to complete the job. It does not touch
4837 * analysers nor counters, which are left to the caller. It does not touch
4838 * s->target which is supposed to already point to the stats applet. The caller
4839 * is expected to have already assigned an appctx to the stream.
4840 */
4841static int htx_handle_stats(struct stream *s, struct channel *req)
4842{
4843 struct stats_admin_rule *stats_admin_rule;
4844 struct stream_interface *si = &s->si[1];
4845 struct session *sess = s->sess;
4846 struct http_txn *txn = s->txn;
4847 struct http_msg *msg = &txn->req;
4848 struct uri_auth *uri_auth = s->be->uri_auth;
4849 const char *h, *lookup, *end;
4850 struct appctx *appctx;
4851 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004852 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004853
4854 appctx = si_appctx(si);
4855 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4856 appctx->st1 = appctx->st2 = 0;
4857 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4858 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4859 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4860 appctx->ctx.stats.flags |= STAT_CHUNKED;
4861
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004862 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004863 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004864 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4865 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004866
4867 for (h = lookup; h <= end - 3; h++) {
4868 if (memcmp(h, ";up", 3) == 0) {
4869 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4870 break;
4871 }
4872 }
4873
4874 if (uri_auth->refresh) {
4875 for (h = lookup; h <= end - 10; h++) {
4876 if (memcmp(h, ";norefresh", 10) == 0) {
4877 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4878 break;
4879 }
4880 }
4881 }
4882
4883 for (h = lookup; h <= end - 4; h++) {
4884 if (memcmp(h, ";csv", 4) == 0) {
4885 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4886 break;
4887 }
4888 }
4889
4890 for (h = lookup; h <= end - 6; h++) {
4891 if (memcmp(h, ";typed", 6) == 0) {
4892 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4893 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4894 break;
4895 }
4896 }
4897
4898 for (h = lookup; h <= end - 8; h++) {
4899 if (memcmp(h, ";st=", 4) == 0) {
4900 int i;
4901 h += 4;
4902 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4903 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4904 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4905 appctx->ctx.stats.st_code = i;
4906 break;
4907 }
4908 }
4909 break;
4910 }
4911 }
4912
4913 appctx->ctx.stats.scope_str = 0;
4914 appctx->ctx.stats.scope_len = 0;
4915 for (h = lookup; h <= end - 8; h++) {
4916 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4917 int itx = 0;
4918 const char *h2;
4919 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4920 const char *err;
4921
4922 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4923 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004924 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4925 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004926 if (*h == ';' || *h == '&' || *h == ' ')
4927 break;
4928 itx++;
4929 h++;
4930 }
4931
4932 if (itx > STAT_SCOPE_TXT_MAXLEN)
4933 itx = STAT_SCOPE_TXT_MAXLEN;
4934 appctx->ctx.stats.scope_len = itx;
4935
4936 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4937 memcpy(scope_txt, h2, itx);
4938 scope_txt[itx] = '\0';
4939 err = invalid_char(scope_txt);
4940 if (err) {
4941 /* bad char in search text => clear scope */
4942 appctx->ctx.stats.scope_str = 0;
4943 appctx->ctx.stats.scope_len = 0;
4944 }
4945 break;
4946 }
4947 }
4948
4949 /* now check whether we have some admin rules for this request */
4950 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4951 int ret = 1;
4952
4953 if (stats_admin_rule->cond) {
4954 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4955 ret = acl_pass(ret);
4956 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4957 ret = !ret;
4958 }
4959
4960 if (ret) {
4961 /* no rule, or the rule matches */
4962 appctx->ctx.stats.flags |= STAT_ADMIN;
4963 break;
4964 }
4965 }
4966
Christopher Faulet5d45e382019-02-27 15:15:23 +01004967 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4968 appctx->st0 = STAT_HTTP_HEAD;
4969 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004970 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004971 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004972 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004973 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004974 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4975 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4976 appctx->st0 = STAT_HTTP_LAST;
4977 }
4978 }
4979 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004980 /* Unsupported method */
4981 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4982 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4983 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004984 }
4985
4986 s->task->nice = -32; /* small boost for HTTP statistics */
4987 return 1;
4988}
4989
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004990void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4991{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004992 struct channel *req = &s->req;
4993 struct channel *res = &s->res;
4994 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004995 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004996 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004997 struct ist path, location;
4998 unsigned int flags;
4999 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005000
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005001 /*
5002 * Create the location
5003 */
5004 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005005
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005006 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005007 /* special prefix "/" means don't change URL */
5008 srv = __objt_server(s->target);
5009 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5010 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5011 return;
5012 }
5013
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005014 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005015 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005016 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005017 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005018 if (!path.ptr)
5019 return;
5020
5021 if (!chunk_memcat(&trash, path.ptr, path.len))
5022 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005023 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005024
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005025 /*
5026 * Create the 302 respone
5027 */
5028 htx = htx_from_buf(&res->buf);
5029 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5030 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5031 ist("HTTP/1.1"), ist("302"), ist("Found"));
5032 if (!sl)
5033 goto fail;
5034 sl->info.res.status = 302;
5035 s->txn->status = 302;
5036
5037 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5038 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5039 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5040 !htx_add_header(htx, ist("Location"), location))
5041 goto fail;
5042
5043 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5044 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005045
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005046 /*
5047 * Send the message
5048 */
5049 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005050 c_adv(res, data);
5051 res->total += data;
5052
5053 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005054 si_shutr(si);
5055 si_shutw(si);
5056 si->err_type = SI_ET_NONE;
5057 si->state = SI_ST_CLO;
5058
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005059 channel_auto_read(req);
5060 channel_abort(req);
5061 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005062 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005063 channel_auto_read(res);
5064 channel_auto_close(res);
5065
5066 if (!(s->flags & SF_ERR_MASK))
5067 s->flags |= SF_ERR_LOCAL;
5068 if (!(s->flags & SF_FINST_MASK))
5069 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005070
5071 /* FIXME: we should increase a counter of redirects per server and per backend. */
5072 srv_inc_sess_ctr(srv);
5073 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005074 return;
5075
5076 fail:
5077 /* If an error occurred, remove the incomplete HTTP response from the
5078 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005079 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005080}
5081
Christopher Fauletf2824e62018-10-01 12:12:37 +02005082/* This function terminates the request because it was completly analyzed or
5083 * because an error was triggered during the body forwarding.
5084 */
5085static void htx_end_request(struct stream *s)
5086{
5087 struct channel *chn = &s->req;
5088 struct http_txn *txn = s->txn;
5089
5090 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5091 now_ms, __FUNCTION__, s,
5092 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5093 s->req.analysers, s->res.analysers);
5094
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005095 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5096 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005097 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005098 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005099 goto end;
5100 }
5101
5102 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5103 return;
5104
5105 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005106 /* No need to read anymore, the request was completely parsed.
5107 * We can shut the read side unless we want to abort_on_close,
5108 * or we have a POST request. The issue with POST requests is
5109 * that some browsers still send a CRLF after the request, and
5110 * this CRLF must be read so that it does not remain in the kernel
5111 * buffers, otherwise a close could cause an RST on some systems
5112 * (eg: Linux).
5113 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005114 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005115 channel_dont_read(chn);
5116
5117 /* if the server closes the connection, we want to immediately react
5118 * and close the socket to save packets and syscalls.
5119 */
5120 s->si[1].flags |= SI_FL_NOHALF;
5121
5122 /* In any case we've finished parsing the request so we must
5123 * disable Nagle when sending data because 1) we're not going
5124 * to shut this side, and 2) the server is waiting for us to
5125 * send pending data.
5126 */
5127 chn->flags |= CF_NEVER_WAIT;
5128
Christopher Fauletd01ce402019-01-02 17:44:13 +01005129 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5130 /* The server has not finished to respond, so we
5131 * don't want to move in order not to upset it.
5132 */
5133 return;
5134 }
5135
Christopher Fauletf2824e62018-10-01 12:12:37 +02005136 /* When we get here, it means that both the request and the
5137 * response have finished receiving. Depending on the connection
5138 * mode, we'll have to wait for the last bytes to leave in either
5139 * direction, and sometimes for a close to be effective.
5140 */
5141 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5142 /* Tunnel mode will not have any analyser so it needs to
5143 * poll for reads.
5144 */
5145 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005146 if (b_data(&chn->buf))
5147 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005148 txn->req.msg_state = HTTP_MSG_TUNNEL;
5149 }
5150 else {
5151 /* we're not expecting any new data to come for this
5152 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005153 *
5154 * However, there is an exception if the response
5155 * length is undefined. In this case, we need to wait
5156 * the close from the server. The response will be
5157 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005158 */
5159 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5160 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005161 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005162
5163 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5164 channel_shutr_now(chn);
5165 channel_shutw_now(chn);
5166 }
5167 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005168 goto check_channel_flags;
5169 }
5170
5171 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5172 http_msg_closing:
5173 /* nothing else to forward, just waiting for the output buffer
5174 * to be empty and for the shutw_now to take effect.
5175 */
5176 if (channel_is_empty(chn)) {
5177 txn->req.msg_state = HTTP_MSG_CLOSED;
5178 goto http_msg_closed;
5179 }
5180 else if (chn->flags & CF_SHUTW) {
5181 txn->req.err_state = txn->req.msg_state;
5182 txn->req.msg_state = HTTP_MSG_ERROR;
5183 goto end;
5184 }
5185 return;
5186 }
5187
5188 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5189 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005190 /* if we don't know whether the server will close, we need to hard close */
5191 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5192 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005193 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005194 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005195 channel_dont_read(chn);
5196 goto end;
5197 }
5198
5199 check_channel_flags:
5200 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5201 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5202 /* if we've just closed an output, let's switch */
5203 txn->req.msg_state = HTTP_MSG_CLOSING;
5204 goto http_msg_closing;
5205 }
5206
5207 end:
5208 chn->analysers &= AN_REQ_FLT_END;
5209 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5210 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5211 channel_auto_close(chn);
5212 channel_auto_read(chn);
5213}
5214
5215
5216/* This function terminates the response because it was completly analyzed or
5217 * because an error was triggered during the body forwarding.
5218 */
5219static void htx_end_response(struct stream *s)
5220{
5221 struct channel *chn = &s->res;
5222 struct http_txn *txn = s->txn;
5223
5224 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5225 now_ms, __FUNCTION__, s,
5226 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5227 s->req.analysers, s->res.analysers);
5228
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005229 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5230 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005231 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005232 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005233 goto end;
5234 }
5235
5236 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5237 return;
5238
5239 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5240 /* In theory, we don't need to read anymore, but we must
5241 * still monitor the server connection for a possible close
5242 * while the request is being uploaded, so we don't disable
5243 * reading.
5244 */
5245 /* channel_dont_read(chn); */
5246
5247 if (txn->req.msg_state < HTTP_MSG_DONE) {
5248 /* The client seems to still be sending data, probably
5249 * because we got an error response during an upload.
5250 * We have the choice of either breaking the connection
5251 * or letting it pass through. Let's do the later.
5252 */
5253 return;
5254 }
5255
5256 /* When we get here, it means that both the request and the
5257 * response have finished receiving. Depending on the connection
5258 * mode, we'll have to wait for the last bytes to leave in either
5259 * direction, and sometimes for a close to be effective.
5260 */
5261 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5262 channel_auto_read(chn);
5263 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005264 if (b_data(&chn->buf))
5265 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005266 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5267 }
5268 else {
5269 /* we're not expecting any new data to come for this
5270 * transaction, so we can close it.
5271 */
5272 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5273 channel_shutr_now(chn);
5274 channel_shutw_now(chn);
5275 }
5276 }
5277 goto check_channel_flags;
5278 }
5279
5280 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5281 http_msg_closing:
5282 /* nothing else to forward, just waiting for the output buffer
5283 * to be empty and for the shutw_now to take effect.
5284 */
5285 if (channel_is_empty(chn)) {
5286 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5287 goto http_msg_closed;
5288 }
5289 else if (chn->flags & CF_SHUTW) {
5290 txn->rsp.err_state = txn->rsp.msg_state;
5291 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005292 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005293 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005294 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005295 goto end;
5296 }
5297 return;
5298 }
5299
5300 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5301 http_msg_closed:
5302 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005303 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005304 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005305 goto end;
5306 }
5307
5308 check_channel_flags:
5309 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5310 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5311 /* if we've just closed an output, let's switch */
5312 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5313 goto http_msg_closing;
5314 }
5315
5316 end:
5317 chn->analysers &= AN_RES_FLT_END;
5318 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5319 chn->analysers |= AN_RES_FLT_XFER_DATA;
5320 channel_auto_close(chn);
5321 channel_auto_read(chn);
5322}
5323
Christopher Faulet0f226952018-10-22 09:29:56 +02005324void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5325 int finst, const struct buffer *msg)
5326{
5327 channel_auto_read(si_oc(si));
5328 channel_abort(si_oc(si));
5329 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005330 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005331 channel_auto_close(si_ic(si));
5332 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005333
5334 /* <msg> is an HTX structure. So we copy it in the response's
5335 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005336 if (msg) {
5337 struct channel *chn = si_ic(si);
5338 struct htx *htx;
5339
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005340 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005341 chn->buf.data = msg->data;
5342 memcpy(chn->buf.area, msg->area, msg->data);
5343 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005344 c_adv(chn, htx->data);
5345 chn->total += htx->data;
5346 }
5347 if (!(s->flags & SF_ERR_MASK))
5348 s->flags |= err;
5349 if (!(s->flags & SF_FINST_MASK))
5350 s->flags |= finst;
5351}
5352
5353void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5354{
5355 channel_auto_read(&s->req);
5356 channel_abort(&s->req);
5357 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005358 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5359 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005360
5361 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005362
5363 /* <msg> is an HTX structure. So we copy it in the response's
5364 * channel */
5365 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005366 if (msg) {
5367 struct channel *chn = &s->res;
5368 struct htx *htx;
5369
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005370 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005371 chn->buf.data = msg->data;
5372 memcpy(chn->buf.area, msg->area, msg->data);
5373 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005374 c_adv(chn, htx->data);
5375 chn->total += htx->data;
5376 }
5377
5378 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5379 channel_auto_read(&s->res);
5380 channel_auto_close(&s->res);
5381 channel_shutr_now(&s->res);
5382}
5383
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005384struct buffer *htx_error_message(struct stream *s)
5385{
5386 const int msgnum = http_get_status_idx(s->txn->status);
5387
5388 if (s->be->errmsg[msgnum].area)
5389 return &s->be->errmsg[msgnum];
5390 else if (strm_fe(s)->errmsg[msgnum].area)
5391 return &strm_fe(s)->errmsg[msgnum];
5392 else
5393 return &htx_err_chunks[msgnum];
5394}
5395
5396
Christopher Faulet4a28a532019-03-01 11:19:40 +01005397/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5398 * on success and -1 on error.
5399 */
5400static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5401{
5402 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5403 * then we must send an HTTP/1.1 100 Continue intermediate response.
5404 */
5405 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5406 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5407 struct ist hdr = { .ptr = "Expect", .len = 6 };
5408 struct http_hdr_ctx ctx;
5409
5410 ctx.blk = NULL;
5411 /* Expect is allowed in 1.1, look for it */
5412 if (http_find_header(htx, hdr, &ctx, 0) &&
5413 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5414 if (htx_reply_100_continue(s) == -1)
5415 return -1;
5416 http_remove_header(htx, &ctx);
5417 }
5418 }
5419 return 0;
5420}
5421
Christopher Faulet23a3c792018-11-28 10:01:23 +01005422/* Send a 100-Continue response to the client. It returns 0 on success and -1
5423 * on error. The response channel is updated accordingly.
5424 */
5425static int htx_reply_100_continue(struct stream *s)
5426{
5427 struct channel *res = &s->res;
5428 struct htx *htx = htx_from_buf(&res->buf);
5429 struct htx_sl *sl;
5430 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5431 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5432 size_t data;
5433
5434 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5435 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5436 if (!sl)
5437 goto fail;
5438 sl->info.res.status = 100;
5439
5440 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5441 goto fail;
5442
5443 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005444 c_adv(res, data);
5445 res->total += data;
5446 return 0;
5447
5448 fail:
5449 /* If an error occurred, remove the incomplete HTTP response from the
5450 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005451 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005452 return -1;
5453}
5454
Christopher Faulet12c51e22018-11-28 15:59:42 +01005455
5456/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5457 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5458 * error. The response channel is updated accordingly.
5459 */
5460static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5461{
5462 struct channel *res = &s->res;
5463 struct htx *htx = htx_from_buf(&res->buf);
5464 struct htx_sl *sl;
5465 struct ist code, body;
5466 int status;
5467 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5468 size_t data;
5469
5470 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5471 status = 401;
5472 code = ist("401");
5473 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5474 "You need a valid user and password to access this content.\n"
5475 "</body></html>\n");
5476 }
5477 else {
5478 status = 407;
5479 code = ist("407");
5480 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5481 "You need a valid user and password to access this content.\n"
5482 "</body></html>\n");
5483 }
5484
5485 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5486 ist("HTTP/1.1"), code, ist("Unauthorized"));
5487 if (!sl)
5488 goto fail;
5489 sl->info.res.status = status;
5490 s->txn->status = status;
5491
5492 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5493 goto fail;
5494
5495 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5496 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005497 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5498 goto fail;
5499 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5500 goto fail;
5501 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005502 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005503 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5504 goto fail;
5505
5506 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005507 c_adv(res, data);
5508 res->total += data;
5509
5510 channel_auto_read(&s->req);
5511 channel_abort(&s->req);
5512 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005513 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005514
5515 res->wex = tick_add_ifset(now_ms, res->wto);
5516 channel_auto_read(res);
5517 channel_auto_close(res);
5518 channel_shutr_now(res);
5519 return 0;
5520
5521 fail:
5522 /* If an error occurred, remove the incomplete HTTP response from the
5523 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005524 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005525 return -1;
5526}
5527
Christopher Faulet0f226952018-10-22 09:29:56 +02005528/*
5529 * Capture headers from message <htx> according to header list <cap_hdr>, and
5530 * fill the <cap> pointers appropriately.
5531 */
5532static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5533{
5534 struct cap_hdr *h;
5535 int32_t pos;
5536
Christopher Fauleta3f15502019-05-13 15:27:23 +02005537 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005538 struct htx_blk *blk = htx_get_blk(htx, pos);
5539 enum htx_blk_type type = htx_get_blk_type(blk);
5540 struct ist n, v;
5541
5542 if (type == HTX_BLK_EOH)
5543 break;
5544 if (type != HTX_BLK_HDR)
5545 continue;
5546
5547 n = htx_get_blk_name(htx, blk);
5548
5549 for (h = cap_hdr; h; h = h->next) {
5550 if (h->namelen && (h->namelen == n.len) &&
5551 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5552 if (cap[h->index] == NULL)
5553 cap[h->index] =
5554 pool_alloc(h->pool);
5555
5556 if (cap[h->index] == NULL) {
5557 ha_alert("HTTP capture : out of memory.\n");
5558 break;
5559 }
5560
5561 v = htx_get_blk_value(htx, blk);
5562 if (v.len > h->len)
5563 v.len = h->len;
5564
5565 memcpy(cap[h->index], v.ptr, v.len);
5566 cap[h->index][v.len]=0;
5567 }
5568 }
5569 }
5570}
5571
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005572/* Delete a value in a header between delimiters <from> and <next>. The header
5573 * itself is delimited by <start> and <end> pointers. The number of characters
5574 * displaced is returned, and the pointer to the first delimiter is updated if
5575 * required. The function tries as much as possible to respect the following
5576 * principles :
5577 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5578 * in which case <next> is simply removed
5579 * - set exactly one space character after the new first delimiter, unless there
5580 * are not enough characters in the block being moved to do so.
5581 * - remove unneeded spaces before the previous delimiter and after the new
5582 * one.
5583 *
5584 * It is the caller's responsibility to ensure that :
5585 * - <from> points to a valid delimiter or <start> ;
5586 * - <next> points to a valid delimiter or <end> ;
5587 * - there are non-space chars before <from>.
5588 */
5589static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5590{
5591 char *prev = *from;
5592
5593 if (prev == start) {
5594 /* We're removing the first value. eat the semicolon, if <next>
5595 * is lower than <end> */
5596 if (next < end)
5597 next++;
5598
5599 while (next < end && HTTP_IS_SPHT(*next))
5600 next++;
5601 }
5602 else {
5603 /* Remove useless spaces before the old delimiter. */
5604 while (HTTP_IS_SPHT(*(prev-1)))
5605 prev--;
5606 *from = prev;
5607
5608 /* copy the delimiter and if possible a space if we're
5609 * not at the end of the line.
5610 */
5611 if (next < end) {
5612 *prev++ = *next++;
5613 if (prev + 1 < next)
5614 *prev++ = ' ';
5615 while (next < end && HTTP_IS_SPHT(*next))
5616 next++;
5617 }
5618 }
5619 memmove(prev, next, end - next);
5620 return (prev - next);
5621}
5622
Christopher Faulet0f226952018-10-22 09:29:56 +02005623
5624/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005625 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005626 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005627static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005628{
5629 struct ist dst = ist2(str, 0);
5630
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005631 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005632 goto end;
5633 if (dst.len + 1 > len)
5634 goto end;
5635 dst.ptr[dst.len++] = ' ';
5636
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005637 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005638 goto end;
5639 if (dst.len + 1 > len)
5640 goto end;
5641 dst.ptr[dst.len++] = ' ';
5642
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005643 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005644 end:
5645 return dst.len;
5646}
5647
Christopher Fauletf0523542018-10-24 11:06:58 +02005648/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005649 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005650 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005651static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005652{
5653 struct ist dst = ist2(str, 0);
5654
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005655 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005656 goto end;
5657 if (dst.len + 1 > len)
5658 goto end;
5659 dst.ptr[dst.len++] = ' ';
5660
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005661 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005662 goto end;
5663 if (dst.len + 1 > len)
5664 goto end;
5665 dst.ptr[dst.len++] = ' ';
5666
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005667 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005668 end:
5669 return dst.len;
5670}
5671
5672
Christopher Faulet0f226952018-10-22 09:29:56 +02005673/*
5674 * Print a debug line with a start line.
5675 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005676static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005677{
5678 struct session *sess = strm_sess(s);
5679 int max;
5680
5681 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5682 dir,
5683 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5684 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5685
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005686 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005687 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005688 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005689 trash.area[trash.data++] = ' ';
5690
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005691 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005692 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005693 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005694 trash.area[trash.data++] = ' ';
5695
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005696 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005697 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005698 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005699 trash.area[trash.data++] = '\n';
5700
5701 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5702}
5703
5704/*
5705 * Print a debug line with a header.
5706 */
5707static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5708{
5709 struct session *sess = strm_sess(s);
5710 int max;
5711
5712 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5713 dir,
5714 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5715 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5716
5717 max = n.len;
5718 UBOUND(max, trash.size - trash.data - 3);
5719 chunk_memcat(&trash, n.ptr, max);
5720 trash.area[trash.data++] = ':';
5721 trash.area[trash.data++] = ' ';
5722
5723 max = v.len;
5724 UBOUND(max, trash.size - trash.data - 1);
5725 chunk_memcat(&trash, v.ptr, max);
5726 trash.area[trash.data++] = '\n';
5727
5728 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5729}
5730
5731
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005732__attribute__((constructor))
5733static void __htx_protocol_init(void)
5734{
5735}
5736
5737
5738/*
5739 * Local variables:
5740 * c-indent-level: 8
5741 * c-basic-offset: 8
5742 * End:
5743 */