1 /*
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 
13 #include <haproxy/acl.h>
14 #include <haproxy/action-t.h>
15 #include <haproxy/api.h>
16 #include <haproxy/backend.h>
17 #include <haproxy/base64.h>
18 #include <haproxy/capture-t.h>
19 #include <haproxy/cfgparse.h>
20 #include <haproxy/channel.h>
21 #include <haproxy/check.h>
22 #include <haproxy/connection.h>
23 #include <haproxy/errors.h>
24 #include <haproxy/filters.h>
25 #include <haproxy/http.h>
26 #include <haproxy/http_ana.h>
27 #include <haproxy/http_htx.h>
28 #include <haproxy/htx.h>
29 #include <haproxy/log.h>
30 #include <haproxy/net_helper.h>
31 #include <haproxy/proxy.h>
32 #include <haproxy/regex.h>
33 #include <haproxy/server-t.h>
34 #include <haproxy/stats.h>
35 #include <haproxy/stream.h>
36 #include <haproxy/stream_interface.h>
37 #include <haproxy/trace.h>
38 #include <haproxy/uri_auth-t.h>
39 #include <haproxy/vars.h>
40 
41 
42 #define TRACE_SOURCE &trace_strm
43 
44 extern const char *stat_status_codes[];
45 
46 struct pool_head *pool_head_requri __read_mostly = NULL;
47 struct pool_head *pool_head_capture __read_mostly = NULL;
48 
49 
50 static void http_end_request(struct stream *s);
51 static void http_end_response(struct stream *s);
52 
53 static void http_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr);
54 static int http_del_hdr_value(char *start, char *end, char **from, char *next);
55 static size_t http_fmt_req_line(const struct htx_sl *sl, char *str, size_t len);
56 static void http_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl);
57 static void http_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v);
58 
59 static enum rule_result http_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s);
60 static enum rule_result http_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s);
61 
62 static void http_manage_client_side_cookies(struct stream *s, struct channel *req);
63 static void http_manage_server_side_cookies(struct stream *s, struct channel *res);
64 
65 static int http_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend);
66 static int http_handle_stats(struct stream *s, struct channel *req);
67 
68 static int http_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg);
69 static int http_reply_100_continue(struct stream *s);
70 
71 /* This stream analyser waits for a complete HTTP request. It returns 1 if the
72  * processing can continue on next analysers, or zero if it either needs more
73  * data or wants to immediately abort the request (eg: timeout, error, ...). It
74  * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
75  * when it has nothing left to do, and may remove any analyser when it wants to
76  * abort.
77  */
http_wait_for_request(struct stream * s,struct channel * req,int an_bit)78 int http_wait_for_request(struct stream *s, struct channel *req, int an_bit)
79 {
80 
81 	/*
82 	 * We will analyze a complete HTTP request to check the its syntax.
83 	 *
84 	 * Once the start line and all headers are received, we may perform a
85 	 * capture of the error (if any), and we will set a few fields. We also
86 	 * check for monitor-uri, logging and finally headers capture.
87 	 */
88 	struct session *sess = s->sess;
89 	struct http_txn *txn = s->txn;
90 	struct http_msg *msg = &txn->req;
91 	struct htx *htx;
92 	struct htx_sl *sl;
93 
94 	DBG_TRACE_ENTER(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn, msg);
95 
96 	if (unlikely(!IS_HTX_STRM(s))) {
97 		/* It is only possible when a TCP stream is upgrade to HTTP.
98 		 * There is a transition period during which there is no
99 		 * data. The stream is still in raw mode and SF_IGNORE flag is
100 		 * still set. When this happens, the new mux is responsible to
101 		 * handle all errors. Thus we may leave immediately.
102 		 */
103 		BUG_ON(!(s->flags & SF_IGNORE) || !c_empty(&s->req));
104 
105 		/* Don't connect for now */
106 		channel_dont_connect(req);
107 
108 		/* A SHUTR at this stage means we are performing a "destructive"
109 		 * HTTP upgrade (TCP>H2). In this case, we can leave.
110 		 */
111 		if (req->flags & CF_SHUTR) {
112 			s->logs.logwait = 0;
113                         s->logs.level = 0;
114 			channel_abort(&s->req);
115 			channel_abort(&s->res);
116 			req->analysers &= AN_REQ_FLT_END;
117 			req->analyse_exp = TICK_ETERNITY;
118 			DBG_TRACE_LEAVE(STRM_EV_STRM_ANA, s);
119 			return 1;
120 		}
121 		DBG_TRACE_LEAVE(STRM_EV_STRM_ANA, s);
122 		return 0;
123 	}
124 
125 	htx = htxbuf(&req->buf);
126 
127 	/* Parsing errors are caught here */
128 	if (htx->flags & (HTX_FL_PARSING_ERROR|HTX_FL_PROCESSING_ERROR)) {
129 		stream_inc_http_req_ctr(s);
130 		proxy_inc_fe_req_ctr(sess->listener, sess->fe);
131 		if (htx->flags & HTX_FL_PARSING_ERROR) {
132 			stream_inc_http_err_ctr(s);
133 			goto return_bad_req;
134 		}
135 		else
136 			goto return_int_err;
137 	}
138 
139 	/* we're speaking HTTP here, so let's speak HTTP to the client */
140 	s->srv_error = http_return_srv_error;
141 
142 	msg->msg_state = HTTP_MSG_BODY;
143 	stream_inc_http_req_ctr(s);
144 	proxy_inc_fe_req_ctr(sess->listener, sess->fe); /* one more valid request for this FE */
145 
146 	/* kill the pending keep-alive timeout */
147 	req->analyse_exp = TICK_ETERNITY;
148 
149 	BUG_ON(htx_get_first_type(htx) != HTX_BLK_REQ_SL);
150 	sl = http_get_stline(htx);
151 
152 	/* 0: we might have to print this header in debug mode */
153 	if (unlikely((global.mode & MODE_DEBUG) &&
154 		     (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
155 		int32_t pos;
156 
157 		http_debug_stline("clireq", s, sl);
158 
159 		for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
160 			struct htx_blk *blk = htx_get_blk(htx, pos);
161 			enum htx_blk_type type = htx_get_blk_type(blk);
162 
163 			if (type == HTX_BLK_EOH)
164 				break;
165 			if (type != HTX_BLK_HDR)
166 				continue;
167 
168 			http_debug_hdr("clihdr", s,
169 				       htx_get_blk_name(htx, blk),
170 				       htx_get_blk_value(htx, blk));
171 		}
172 	}
173 
174 	/*
175 	 * 1: identify the method and the version. Also set HTTP flags
176 	 */
177 	txn->meth = sl->info.req.meth;
178 	if (sl->flags & HTX_SL_F_VER_11)
179                 msg->flags |= HTTP_MSGF_VER_11;
180 	msg->flags |= HTTP_MSGF_XFER_LEN;
181 	if (sl->flags & HTX_SL_F_CLEN)
182 		msg->flags |= HTTP_MSGF_CNT_LEN;
183 	else if (sl->flags & HTX_SL_F_CHNK)
184 		msg->flags |= HTTP_MSGF_TE_CHNK;
185 	if (sl->flags & HTX_SL_F_BODYLESS)
186 		msg->flags |= HTTP_MSGF_BODYLESS;
187 	if (sl->flags & HTX_SL_F_CONN_UPG)
188 		msg->flags |= HTTP_MSGF_CONN_UPG;
189 
190 	/* we can make use of server redirect on GET and HEAD */
191 	if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
192 		s->flags |= SF_REDIRECTABLE;
193 	else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
194 		/* PRI is reserved for the HTTP/2 preface */
195 		goto return_bad_req;
196 	}
197 
198 	/*
199 	 * 2: check if the URI matches the monitor_uri.  We have to do this for
200 	 * every request which gets in, because the monitor-uri is defined by
201 	 * the frontend. If the monitor-uri starts with a '/', the matching is
202 	 * done against the request's path. Otherwise, the request's uri is
203 	 * used. It is a workaround to let HTTP/2 health-checks work as
204 	 * expected.
205 	 */
206 	if (unlikely((sess->fe->monitor_uri_len != 0) &&
207 		     ((*sess->fe->monitor_uri == '/' && isteq(http_get_path(htx_sl_req_uri(sl)),
208 							      ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len))) ||
209 		      isteq(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len))))) {
210 		/*
211 		 * We have found the monitor URI
212 		 */
213 		struct acl_cond *cond;
214 
215 		s->flags |= SF_MONITOR;
216 		_HA_ATOMIC_INC(&sess->fe->fe_counters.intercepted_req);
217 
218 		/* Check if we want to fail this monitor request or not */
219 		list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
220 			int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
221 
222 			ret = acl_pass(ret);
223 			if (cond->pol == ACL_COND_UNLESS)
224 				ret = !ret;
225 
226 			if (ret) {
227 				/* we fail this request, let's return 503 service unavail */
228 				txn->status = 503;
229 				if (!(s->flags & SF_ERR_MASK))
230 					s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
231 				goto return_prx_cond;
232 			}
233 		}
234 
235 		/* nothing to fail, let's reply normally */
236 		txn->status = 200;
237 		if (!(s->flags & SF_ERR_MASK))
238 			s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
239 		goto return_prx_cond;
240 	}
241 
242 	/*
243 	 * 3: Maybe we have to copy the original REQURI for the logs ?
244 	 * Note: we cannot log anymore if the request has been
245 	 * classified as invalid.
246 	 */
247 	if (unlikely(s->logs.logwait & LW_REQ)) {
248 		/* we have a complete HTTP request that we must log */
249 		if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
250 			size_t len;
251 
252 			len = http_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
253 			txn->uri[len] = 0;
254 
255 			if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
256 				s->do_log(s);
257 		} else {
258 			ha_alert("HTTP logging : out of memory.\n");
259 		}
260 	}
261 
262 	/* if the frontend has "option http-use-proxy-header", we'll check if
263 	 * we have what looks like a proxied connection instead of a connection,
264 	 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
265 	 * Note that this is *not* RFC-compliant, however browsers and proxies
266 	 * happen to do that despite being non-standard :-(
267 	 * We consider that a request not beginning with either '/' or '*' is
268 	 * a proxied connection, which covers both "scheme://location" and
269 	 * CONNECT ip:port.
270 	 */
271 	if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
272 	    *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
273 		txn->flags |= TX_USE_PX_CONN;
274 
275 	/* 5: we may need to capture headers */
276 	if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
277 		http_capture_headers(htx, s->req_cap, sess->fe->req_cap);
278 
279 	/* we may have to wait for the request's body */
280 	if (s->be->options & PR_O_WREQ_BODY)
281 		req->analysers |= AN_REQ_HTTP_BODY;
282 
283 	/*
284 	 * RFC7234#4:
285 	 *   A cache MUST write through requests with methods
286 	 *   that are unsafe (Section 4.2.1 of [RFC7231]) to
287 	 *   the origin server; i.e., a cache is not allowed
288 	 *   to generate a reply to such a request before
289 	 *   having forwarded the request and having received
290 	 *   a corresponding response.
291 	 *
292 	 * RFC7231#4.2.1:
293 	 *   Of the request methods defined by this
294 	 *   specification, the GET, HEAD, OPTIONS, and TRACE
295 	 *   methods are defined to be safe.
296 	 */
297 	if (likely(txn->meth == HTTP_METH_GET ||
298 		   txn->meth == HTTP_METH_HEAD ||
299 		   txn->meth == HTTP_METH_OPTIONS ||
300 		   txn->meth == HTTP_METH_TRACE))
301 		txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
302 
303 	/* end of job, return OK */
304 	req->analysers &= ~an_bit;
305 	req->analyse_exp = TICK_ETERNITY;
306 
307 	DBG_TRACE_LEAVE(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
308 	return 1;
309 
310  return_int_err:
311 	txn->status = 500;
312 	if (!(s->flags & SF_ERR_MASK))
313 		s->flags |= SF_ERR_INTERNAL;
314 	_HA_ATOMIC_INC(&sess->fe->fe_counters.internal_errors);
315 	if (sess->listener && sess->listener->counters)
316 		_HA_ATOMIC_INC(&sess->listener->counters->internal_errors);
317 	goto return_prx_cond;
318 
319  return_bad_req:
320 	txn->status = 400;
321 	_HA_ATOMIC_INC(&sess->fe->fe_counters.failed_req);
322 	if (sess->listener && sess->listener->counters)
323 		_HA_ATOMIC_INC(&sess->listener->counters->failed_req);
324 	/* fall through */
325 
326  return_prx_cond:
327 	http_reply_and_close(s, txn->status, http_error_message(s));
328 
329 	if (!(s->flags & SF_ERR_MASK))
330 		s->flags |= SF_ERR_PRXCOND;
331 	if (!(s->flags & SF_FINST_MASK))
332 		s->flags |= SF_FINST_R;
333 
334 	DBG_TRACE_DEVEL("leaving on error",
335 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
336 	return 0;
337 }
338 
339 
340 /* This stream analyser runs all HTTP request processing which is common to
341  * frontends and backends, which means blocking ACLs, filters, connection-close,
342  * reqadd, stats and redirects. This is performed for the designated proxy.
343  * It returns 1 if the processing can continue on next analysers, or zero if it
344  * either needs more data or wants to immediately abort the request (eg: deny,
345  * error, ...).
346  */
http_process_req_common(struct stream * s,struct channel * req,int an_bit,struct proxy * px)347 int http_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
348 {
349 	struct session *sess = s->sess;
350 	struct http_txn *txn = s->txn;
351 	struct http_msg *msg = &txn->req;
352 	struct htx *htx;
353 	struct redirect_rule *rule;
354 	enum rule_result verdict;
355 	struct connection *conn = objt_conn(sess->origin);
356 
357 	DBG_TRACE_ENTER(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn, msg);
358 
359 	htx = htxbuf(&req->buf);
360 
361 	/* just in case we have some per-backend tracking. Only called the first
362 	 * execution of the analyser. */
363 	if (!s->current_rule || s->current_rule_list != &px->http_req_rules)
364 		stream_inc_be_http_req_ctr(s);
365 
366 	/* evaluate http-request rules */
367 	if (!LIST_ISEMPTY(&px->http_req_rules)) {
368 		verdict = http_req_get_intercept_rule(px, &px->http_req_rules, s);
369 
370 		switch (verdict) {
371 		case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
372 			goto return_prx_yield;
373 
374 		case HTTP_RULE_RES_CONT:
375 		case HTTP_RULE_RES_STOP: /* nothing to do */
376 			break;
377 
378 		case HTTP_RULE_RES_DENY: /* deny or tarpit */
379 			if (txn->flags & TX_CLTARPIT)
380 				goto tarpit;
381 			goto deny;
382 
383 		case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
384 			goto return_prx_cond;
385 
386 		case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
387 			goto done;
388 
389 		case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
390 			goto return_bad_req;
391 
392 		case HTTP_RULE_RES_ERROR: /* failed with a bad request */
393 			goto return_int_err;
394 		}
395 	}
396 
397 	if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
398 	    (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS))) {
399 		struct http_hdr_ctx ctx;
400 
401 		ctx.blk = NULL;
402 		if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
403 			if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
404 				goto return_int_err;
405 		}
406 	}
407 
408 	/* OK at this stage, we know that the request was accepted according to
409 	 * the http-request rules, we can check for the stats. Note that the
410 	 * URI is detected *before* the req* rules in order not to be affected
411 	 * by a possible reqrep, while they are processed *after* so that a
412 	 * reqdeny can still block them. This clearly needs to change in 1.6!
413 	 */
414 	if (!s->target && http_stats_check_uri(s, txn, px)) {
415 		s->target = &http_stats_applet.obj_type;
416 		if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
417 			s->logs.tv_request = now;
418 			if (!(s->flags & SF_ERR_MASK))
419 				s->flags |= SF_ERR_RESOURCE;
420 			goto return_int_err;
421 		}
422 
423 		/* parse the whole stats request and extract the relevant information */
424 		http_handle_stats(s, req);
425 		verdict = http_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s);
426 		/* not all actions implemented: deny, allow, auth */
427 
428 		if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
429 			goto deny;
430 
431 		if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
432 			goto return_prx_cond;
433 
434 		if (verdict == HTTP_RULE_RES_BADREQ) /* failed with a bad request */
435 			goto return_bad_req;
436 
437 		if (verdict == HTTP_RULE_RES_ERROR) /* failed with a bad request */
438 			goto return_int_err;
439 	}
440 
441 	/* Proceed with the applets now. */
442 	if (unlikely(objt_applet(s->target))) {
443 		if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
444 			_HA_ATOMIC_INC(&sess->fe->fe_counters.intercepted_req);
445 
446 		if (http_handle_expect_hdr(s, htx, msg) == -1)
447 			goto return_int_err;
448 
449 		if (!(s->flags & SF_ERR_MASK))      // this is not really an error but it is
450 			s->flags |= SF_ERR_LOCAL;   // to mark that it comes from the proxy
451 		if (!(s->flags & SF_FINST_MASK))
452 			s->flags |= SF_FINST_R;
453 
454 		if (HAS_FILTERS(s))
455 			req->analysers |= AN_REQ_FLT_HTTP_HDRS;
456 
457 		/* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
458 		req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
459 		req->analysers &= ~AN_REQ_FLT_XFER_DATA;
460 		req->analysers |= AN_REQ_HTTP_XFER_BODY;
461 
462 		req->flags |= CF_SEND_DONTWAIT;
463 		s->flags |= SF_ASSIGNED;
464 		goto done;
465 	}
466 
467 	/* check whether we have some ACLs set to redirect this request */
468 	list_for_each_entry(rule, &px->redirect_rules, list) {
469 		if (rule->cond) {
470 			int ret;
471 
472 			ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
473 			ret = acl_pass(ret);
474 			if (rule->cond->pol == ACL_COND_UNLESS)
475 				ret = !ret;
476 			if (!ret)
477 				continue;
478 		}
479 		if (!http_apply_redirect_rule(rule, s, txn))
480 			goto return_int_err;
481 		goto done;
482 	}
483 
484 	/* POST requests may be accompanied with an "Expect: 100-Continue" header.
485 	 * If this happens, then the data will not come immediately, so we must
486 	 * send all what we have without waiting. Note that due to the small gain
487 	 * in waiting for the body of the request, it's easier to simply put the
488 	 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
489 	 * itself once used.
490 	 */
491 	req->flags |= CF_SEND_DONTWAIT;
492 
493  done:	/* done with this analyser, continue with next ones that the calling
494 	 * points will have set, if any.
495 	 */
496 	req->analyse_exp = TICK_ETERNITY;
497  done_without_exp: /* done with this analyser, but don't reset the analyse_exp. */
498 	req->analysers &= ~an_bit;
499 	DBG_TRACE_LEAVE(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
500 	return 1;
501 
502  tarpit:
503 	/* Allow cookie logging
504 	 */
505 	if (s->be->cookie_name || sess->fe->capture_name)
506 		http_manage_client_side_cookies(s, req);
507 
508 	/* When a connection is tarpitted, we use the tarpit timeout,
509 	 * which may be the same as the connect timeout if unspecified.
510 	 * If unset, then set it to zero because we really want it to
511 	 * eventually expire. We build the tarpit as an analyser.
512 	 */
513 	channel_htx_erase(&s->req, htx);
514 
515 	/* wipe the request out so that we can drop the connection early
516 	 * if the client closes first.
517 	 */
518 	channel_dont_connect(req);
519 
520 	req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
521 	req->analysers |= AN_REQ_HTTP_TARPIT;
522 	req->analyse_exp = tick_add_ifset(now_ms,  s->be->timeout.tarpit);
523 	if (!req->analyse_exp)
524 		req->analyse_exp = tick_add(now_ms, 0);
525 	stream_inc_http_err_ctr(s);
526 	_HA_ATOMIC_INC(&sess->fe->fe_counters.denied_req);
527 	if (s->flags & SF_BE_ASSIGNED)
528 		_HA_ATOMIC_INC(&s->be->be_counters.denied_req);
529 	if (sess->listener && sess->listener->counters)
530 		_HA_ATOMIC_INC(&sess->listener->counters->denied_req);
531 	goto done_without_exp;
532 
533  deny:	/* this request was blocked (denied) */
534 
535 	/* Allow cookie logging
536 	 */
537 	if (s->be->cookie_name || sess->fe->capture_name)
538 		http_manage_client_side_cookies(s, req);
539 
540 	s->logs.tv_request = now;
541 	stream_inc_http_err_ctr(s);
542 	_HA_ATOMIC_INC(&sess->fe->fe_counters.denied_req);
543 	if (s->flags & SF_BE_ASSIGNED)
544 		_HA_ATOMIC_INC(&s->be->be_counters.denied_req);
545 	if (sess->listener && sess->listener->counters)
546 		_HA_ATOMIC_INC(&sess->listener->counters->denied_req);
547 	goto return_prx_err;
548 
549  return_int_err:
550 	txn->status = 500;
551 	if (!(s->flags & SF_ERR_MASK))
552 		s->flags |= SF_ERR_INTERNAL;
553 	_HA_ATOMIC_INC(&sess->fe->fe_counters.internal_errors);
554 	if (s->flags & SF_BE_ASSIGNED)
555 		_HA_ATOMIC_INC(&s->be->be_counters.internal_errors);
556 	if (sess->listener && sess->listener->counters)
557 		_HA_ATOMIC_INC(&sess->listener->counters->internal_errors);
558 	goto return_prx_err;
559 
560  return_bad_req:
561 	txn->status = 400;
562 	_HA_ATOMIC_INC(&sess->fe->fe_counters.failed_req);
563 	if (sess->listener && sess->listener->counters)
564 		_HA_ATOMIC_INC(&sess->listener->counters->failed_req);
565 	/* fall through */
566 
567  return_prx_err:
568 	http_reply_and_close(s, txn->status, http_error_message(s));
569 	/* fall through */
570 
571  return_prx_cond:
572 	if (!(s->flags & SF_ERR_MASK))
573 		s->flags |= SF_ERR_PRXCOND;
574 	if (!(s->flags & SF_FINST_MASK))
575 		s->flags |= SF_FINST_R;
576 
577 	req->analysers &= AN_REQ_FLT_END;
578 	req->analyse_exp = TICK_ETERNITY;
579 	DBG_TRACE_DEVEL("leaving on error",
580 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
581 	return 0;
582 
583  return_prx_yield:
584 	channel_dont_connect(req);
585 	DBG_TRACE_DEVEL("waiting for more data",
586 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
587 	return 0;
588 }
589 
590 /* This function performs all the processing enabled for the current request.
591  * It returns 1 if the processing can continue on next analysers, or zero if it
592  * needs more data, encounters an error, or wants to immediately abort the
593  * request. It relies on buffers flags, and updates s->req.analysers.
594  */
http_process_request(struct stream * s,struct channel * req,int an_bit)595 int http_process_request(struct stream *s, struct channel *req, int an_bit)
596 {
597 	struct session *sess = s->sess;
598 	struct http_txn *txn = s->txn;
599 	struct htx *htx;
600 	struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
601 
602 	DBG_TRACE_ENTER(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
603 
604 	/*
605 	 * Right now, we know that we have processed the entire headers
606 	 * and that unwanted requests have been filtered out. We can do
607 	 * whatever we want with the remaining request. Also, now we
608 	 * may have separate values for ->fe, ->be.
609 	 */
610 	htx = htxbuf(&req->buf);
611 
612 	/*
613 	 * If HTTP PROXY is set we simply get remote server address parsing
614 	 * incoming request.
615 	 */
616 	if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
617 		struct htx_sl *sl;
618 		struct ist uri, path;
619 
620 		if (!sockaddr_alloc(&s->target_addr, NULL, 0)) {
621 			if (!(s->flags & SF_ERR_MASK))
622 				s->flags |= SF_ERR_RESOURCE;
623 			goto return_int_err;
624 		}
625 		sl = http_get_stline(htx);
626 		uri = htx_sl_req_uri(sl);
627 		path = http_get_path(uri);
628 
629 		if (url2sa(uri.ptr, uri.len - path.len, s->target_addr, NULL) == -1)
630 			goto return_bad_req;
631 
632 		s->target = &s->be->obj_type;
633 		s->flags |= SF_ADDR_SET | SF_ASSIGNED;
634 
635 		/* if the path was found, we have to remove everything between
636 		 * uri.ptr and path.ptr (excluded). If it was not found, we need
637 		 * to replace from all the uri by a single "/".
638 		 *
639 		 * Instead of rewriting the whole start line, we just update
640 		 * the star-line URI. Some space will be lost but it should be
641 		 * insignificant.
642 		 */
643 		istcpy(&uri, (path.len ? path : ist("/")), uri.len);
644 	}
645 
646 	/*
647 	 * 7: Now we can work with the cookies.
648 	 * Note that doing so might move headers in the request, but
649 	 * the fields will stay coherent and the URI will not move.
650 	 * This should only be performed in the backend.
651 	 */
652 	if (s->be->cookie_name || sess->fe->capture_name)
653 		http_manage_client_side_cookies(s, req);
654 
655 	/* 8: Generate unique ID if a "unique-id-format" is defined.
656 	 *
657 	 * A unique ID is generated even when it is not sent to ensure that the ID can make use of
658 	 * fetches only available in the HTTP request processing stage.
659 	 */
660 	if (!LIST_ISEMPTY(&sess->fe->format_unique_id)) {
661 		struct ist unique_id = stream_generate_unique_id(s, &sess->fe->format_unique_id);
662 
663 		if (!isttest(unique_id)) {
664 			if (!(s->flags & SF_ERR_MASK))
665 				s->flags |= SF_ERR_RESOURCE;
666 			goto return_int_err;
667 		}
668 
669 		/* send unique ID if a "unique-id-header" is defined */
670 		if (isttest(sess->fe->header_unique_id) &&
671 		    unlikely(!http_add_header(htx, sess->fe->header_unique_id, s->unique_id)))
672 				goto return_int_err;
673 	}
674 
675 	/*
676 	 * 9: add X-Forwarded-For if either the frontend or the backend
677 	 * asks for it.
678 	 */
679 	if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
680 		struct http_hdr_ctx ctx = { .blk = NULL };
681 		struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
682 				      s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
683 
684 		if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
685 		    http_find_header(htx, hdr, &ctx, 0)) {
686 			/* The header is set to be added only if none is present
687 			 * and we found it, so don't do anything.
688 			 */
689 		}
690 		else if (cli_conn && conn_get_src(cli_conn) && cli_conn->src->ss_family == AF_INET) {
691 			/* Add an X-Forwarded-For header unless the source IP is
692 			 * in the 'except' network range.
693 			 */
694 			if (ipcmp2net(cli_conn->src, &sess->fe->except_xff_net) &&
695 			    ipcmp2net(cli_conn->src, &s->be->except_xff_net)) {
696 				unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)cli_conn->src)->sin_addr;
697 
698 				/* Note: we rely on the backend to get the header name to be used for
699 				 * x-forwarded-for, because the header is really meant for the backends.
700 				 * However, if the backend did not specify any option, we have to rely
701 				 * on the frontend's header name.
702 				 */
703 				chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
704 				if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
705 					goto return_int_err;
706 			}
707 		}
708 		else if (cli_conn && conn_get_src(cli_conn) && cli_conn->src->ss_family == AF_INET6) {
709 			/* Add an X-Forwarded-For header unless the source IP is
710 			 * in the 'except' network range.
711 			 */
712 			if (ipcmp2net(cli_conn->src, &sess->fe->except_xff_net) &&
713 			    ipcmp2net(cli_conn->src, &s->be->except_xff_net)) {
714 				char pn[INET6_ADDRSTRLEN];
715 
716 				inet_ntop(AF_INET6,
717 					  (const void *)&((struct sockaddr_in6 *)(cli_conn->src))->sin6_addr,
718 					  pn, sizeof(pn));
719 
720 				/* Note: we rely on the backend to get the header name to be used for
721 				 * x-forwarded-for, because the header is really meant for the backends.
722 				 * However, if the backend did not specify any option, we have to rely
723 				 * on the frontend's header name.
724 				 */
725 				chunk_printf(&trash, "%s", pn);
726 				if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
727 					goto return_int_err;
728 			}
729 		}
730 	}
731 
732 	/*
733 	 * 10: add X-Original-To if either the frontend or the backend
734 	 * asks for it.
735 	 */
736 	if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
737 		struct ist hdr = ist2(s->be->orgto_hdr_len ? s->be->orgto_hdr_name : sess->fe->orgto_hdr_name,
738 				      s->be->orgto_hdr_len ? s->be->orgto_hdr_len  : sess->fe->orgto_hdr_len);
739 
740 		if (cli_conn && conn_get_dst(cli_conn) && cli_conn->dst->ss_family == AF_INET) {
741 			/* Add an X-Original-To header unless the destination IP is
742 			 * in the 'except' network range.
743 			 */
744 			if (ipcmp2net(cli_conn->dst, &sess->fe->except_xot_net) &&
745 			    ipcmp2net(cli_conn->dst, &s->be->except_xot_net)) {
746 				unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)cli_conn->dst)->sin_addr;
747 
748 				/* Note: we rely on the backend to get the header name to be used for
749 				 * x-original-to, because the header is really meant for the backends.
750 				 * However, if the backend did not specify any option, we have to rely
751 				 * on the frontend's header name.
752 				 */
753 				chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
754 				if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
755 					goto return_int_err;
756 			}
757 		}
758 		else if (cli_conn && conn_get_dst(cli_conn) && cli_conn->dst->ss_family == AF_INET6) {
759 			/* Add an X-Original-To header unless the source IP is
760 			 * in the 'except' network range.
761 			 */
762 			if (ipcmp2net(cli_conn->dst, &sess->fe->except_xot_net) &&
763 			    ipcmp2net(cli_conn->dst, &s->be->except_xot_net)) {
764 				char pn[INET6_ADDRSTRLEN];
765 
766 				inet_ntop(AF_INET6,
767 					  (const void *)&((struct sockaddr_in6 *)(cli_conn->dst))->sin6_addr,
768 					  pn, sizeof(pn));
769 
770 				/* Note: we rely on the backend to get the header name to be used for
771 				 * x-forwarded-for, because the header is really meant for the backends.
772 				 * However, if the backend did not specify any option, we have to rely
773 				 * on the frontend's header name.
774 				 */
775 				chunk_printf(&trash, "%s", pn);
776 				if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
777 					goto return_int_err;
778 			}
779 		}
780 	}
781 
782 	/* Filter the request headers if there are filters attached to the
783 	 * stream.
784 	 */
785 	if (HAS_FILTERS(s))
786 		req->analysers |= AN_REQ_FLT_HTTP_HDRS;
787 
788 	/* If we have no server assigned yet and we're balancing on url_param
789 	 * with a POST request, we may be interested in checking the body for
790 	 * that parameter. This will be done in another analyser.
791 	 */
792 	if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
793 	    s->txn->meth == HTTP_METH_POST &&
794 	    (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
795 		channel_dont_connect(req);
796 		req->analysers |= AN_REQ_HTTP_BODY;
797 	}
798 
799 	req->analysers &= ~AN_REQ_FLT_XFER_DATA;
800 	req->analysers |= AN_REQ_HTTP_XFER_BODY;
801 
802 	/* We expect some data from the client. Unless we know for sure
803 	 * we already have a full request, we have to re-enable quick-ack
804 	 * in case we previously disabled it, otherwise we might cause
805 	 * the client to delay further data.
806 	 */
807 	if ((sess->listener && (sess->listener->options & LI_O_NOQUICKACK)) && !(htx->flags & HTX_FL_EOM))
808 		conn_set_quickack(cli_conn, 1);
809 
810 	/*************************************************************
811 	 * OK, that's finished for the headers. We have done what we *
812 	 * could. Let's switch to the DATA state.                    *
813 	 ************************************************************/
814 	req->analyse_exp = TICK_ETERNITY;
815 	req->analysers &= ~an_bit;
816 
817 	s->logs.tv_request = now;
818 	/* OK let's go on with the BODY now */
819 	DBG_TRACE_LEAVE(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
820 	return 1;
821 
822  return_int_err:
823 	txn->status = 500;
824 	if (!(s->flags & SF_ERR_MASK))
825 		s->flags |= SF_ERR_INTERNAL;
826 	_HA_ATOMIC_INC(&sess->fe->fe_counters.internal_errors);
827 	if (s->flags & SF_BE_ASSIGNED)
828 		_HA_ATOMIC_INC(&s->be->be_counters.internal_errors);
829 	if (sess->listener && sess->listener->counters)
830 		_HA_ATOMIC_INC(&sess->listener->counters->internal_errors);
831 	goto return_prx_cond;
832 
833  return_bad_req: /* let's centralize all bad requests */
834 	txn->status = 400;
835 	_HA_ATOMIC_INC(&sess->fe->fe_counters.failed_req);
836 	if (sess->listener && sess->listener->counters)
837 		_HA_ATOMIC_INC(&sess->listener->counters->failed_req);
838 	/* fall through */
839 
840  return_prx_cond:
841 	http_reply_and_close(s, txn->status, http_error_message(s));
842 
843 	if (!(s->flags & SF_ERR_MASK))
844 		s->flags |= SF_ERR_PRXCOND;
845 	if (!(s->flags & SF_FINST_MASK))
846 		s->flags |= SF_FINST_R;
847 
848 	DBG_TRACE_DEVEL("leaving on error",
849 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
850 	return 0;
851 }
852 
853 /* This function is an analyser which processes the HTTP tarpit. It always
854  * returns zero, at the beginning because it prevents any other processing
855  * from occurring, and at the end because it terminates the request.
856  */
http_process_tarpit(struct stream * s,struct channel * req,int an_bit)857 int http_process_tarpit(struct stream *s, struct channel *req, int an_bit)
858 {
859 	struct http_txn *txn = s->txn;
860 
861 	DBG_TRACE_ENTER(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn, &txn->req);
862 	/* This connection is being tarpitted. The CLIENT side has
863 	 * already set the connect expiration date to the right
864 	 * timeout. We just have to check that the client is still
865 	 * there and that the timeout has not expired.
866 	 */
867 	channel_dont_connect(req);
868 	if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
869 	    !tick_is_expired(req->analyse_exp, now_ms)) {
870 		/* Be sure to drain all data from the request channel */
871 		channel_htx_erase(req, htxbuf(&req->buf));
872 		DBG_TRACE_DEVEL("waiting for tarpit timeout expiry",
873 				STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
874 		return 0;
875 	}
876 
877 
878 	/* We will set the queue timer to the time spent, just for
879 	 * logging purposes. We fake a 500 server error, so that the
880 	 * attacker will not suspect his connection has been tarpitted.
881 	 * It will not cause trouble to the logs because we can exclude
882 	 * the tarpitted connections by filtering on the 'PT' status flags.
883 	 */
884 	s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
885 
886 	http_reply_and_close(s, txn->status, (!(req->flags & CF_READ_ERROR) ? http_error_message(s) : NULL));
887 
888 	if (!(s->flags & SF_ERR_MASK))
889 		s->flags |= SF_ERR_PRXCOND;
890 	if (!(s->flags & SF_FINST_MASK))
891 		s->flags |= SF_FINST_T;
892 
893 	DBG_TRACE_LEAVE(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
894 	return 0;
895 }
896 
897 /* This function is an analyser which waits for the HTTP request body. It waits
898  * for either the buffer to be full, or the full advertised contents to have
899  * reached the buffer. It must only be called after the standard HTTP request
900  * processing has occurred, because it expects the request to be parsed and will
901  * look for the Expect header. It may send a 100-Continue interim response. It
902  * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
903  * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
904  * needs to read more data, or 1 once it has completed its analysis.
905  */
http_wait_for_request_body(struct stream * s,struct channel * req,int an_bit)906 int http_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
907 {
908 	struct session *sess = s->sess;
909 	struct http_txn *txn = s->txn;
910 	struct http_msg *msg = &s->txn->req;
911 
912 	DBG_TRACE_ENTER(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn, msg);
913 
914 
915 	switch (http_wait_for_msg_body(s, req, s->be->timeout.httpreq, 0)) {
916 	case HTTP_RULE_RES_CONT:
917 		goto http_end;
918 	case HTTP_RULE_RES_YIELD:
919 		goto missing_data_or_waiting;
920 	case HTTP_RULE_RES_BADREQ:
921 		goto return_bad_req;
922 	case HTTP_RULE_RES_ERROR:
923 		goto return_int_err;
924 	case HTTP_RULE_RES_ABRT:
925 		goto return_prx_cond;
926 	default:
927 		goto return_int_err;
928 	}
929 
930  http_end:
931 	/* The situation will not evolve, so let's give up on the analysis. */
932 	s->logs.tv_request = now;  /* update the request timer to reflect full request */
933 	req->analysers &= ~an_bit;
934 	req->analyse_exp = TICK_ETERNITY;
935 	DBG_TRACE_LEAVE(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
936 	return 1;
937 
938  missing_data_or_waiting:
939 	channel_dont_connect(req);
940 	DBG_TRACE_DEVEL("waiting for more data",
941 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
942 	return 0;
943 
944  return_int_err:
945 	txn->status = 500;
946 	if (!(s->flags & SF_ERR_MASK))
947 		s->flags |= SF_ERR_INTERNAL;
948 	_HA_ATOMIC_INC(&sess->fe->fe_counters.internal_errors);
949 	if (s->flags & SF_BE_ASSIGNED)
950 		_HA_ATOMIC_INC(&s->be->be_counters.internal_errors);
951 	if (sess->listener && sess->listener->counters)
952 		_HA_ATOMIC_INC(&sess->listener->counters->internal_errors);
953 	goto return_prx_err;
954 
955  return_bad_req: /* let's centralize all bad requests */
956 	txn->status = 400;
957 	_HA_ATOMIC_INC(&sess->fe->fe_counters.failed_req);
958 	if (sess->listener && sess->listener->counters)
959 		_HA_ATOMIC_INC(&sess->listener->counters->failed_req);
960 	/* fall through */
961 
962  return_prx_err:
963 	http_reply_and_close(s, txn->status, http_error_message(s));
964 	/* fall through */
965 
966  return_prx_cond:
967 	if (!(s->flags & SF_ERR_MASK))
968 		s->flags |= SF_ERR_PRXCOND;
969 	if (!(s->flags & SF_FINST_MASK))
970 		s->flags |= (msg->msg_state < HTTP_MSG_DATA ? SF_FINST_R : SF_FINST_D);
971 
972 	req->analysers &= AN_REQ_FLT_END;
973 	req->analyse_exp = TICK_ETERNITY;
974 	DBG_TRACE_DEVEL("leaving on error",
975 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
976 	return 0;
977 }
978 
979 /* This function is an analyser which forwards request body (including chunk
980  * sizes if any). It is called as soon as we must forward, even if we forward
981  * zero byte. The only situation where it must not be called is when we're in
982  * tunnel mode and we want to forward till the close. It's used both to forward
983  * remaining data and to resync after end of body. It expects the msg_state to
984  * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
985  * read more data, or 1 once we can go on with next request or end the stream.
986  * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
987  * bytes of pending data + the headers if not already done.
988  */
http_request_forward_body(struct stream * s,struct channel * req,int an_bit)989 int http_request_forward_body(struct stream *s, struct channel *req, int an_bit)
990 {
991 	struct session *sess = s->sess;
992 	struct http_txn *txn = s->txn;
993 	struct http_msg *msg = &txn->req;
994 	struct htx *htx;
995 	short status = 0;
996 	int ret;
997 
998 	DBG_TRACE_ENTER(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn, msg);
999 
1000 	htx = htxbuf(&req->buf);
1001 
1002 	if (htx->flags & HTX_FL_PARSING_ERROR)
1003 		goto return_bad_req;
1004 	if (htx->flags & HTX_FL_PROCESSING_ERROR)
1005 		goto return_int_err;
1006 
1007 	if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1008 	    ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1009 		/* Output closed while we were sending data. We must abort and
1010 		 * wake the other side up.
1011 		 *
1012 		 * If we have finished to send the request and the response is
1013 		 * still in progress, don't catch write error on the request
1014 		 * side if it is in fact a read error on the server side.
1015 		 */
1016 		if (msg->msg_state == HTTP_MSG_DONE && (s->res.flags & CF_READ_ERROR) && s->res.analysers)
1017 			return 0;
1018 
1019 		/* Don't abort yet if we had L7 retries activated and it
1020 		 * was a write error, we may recover.
1021 		 */
1022 		if (!(req->flags & (CF_READ_ERROR | CF_READ_TIMEOUT)) &&
1023 		    (s->si[1].flags & SI_FL_L7_RETRY)) {
1024 			DBG_TRACE_DEVEL("leaving on L7 retry",
1025 					STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
1026 			return 0;
1027 		}
1028 		msg->msg_state = HTTP_MSG_ERROR;
1029 		http_end_request(s);
1030 		http_end_response(s);
1031 		DBG_TRACE_DEVEL("leaving on error",
1032 				STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
1033 		return 1;
1034 	}
1035 
1036 	/* Note that we don't have to send 100-continue back because we don't
1037 	 * need the data to complete our job, and it's up to the server to
1038 	 * decide whether to return 100, 417 or anything else in return of
1039 	 * an "Expect: 100-continue" header.
1040 	 */
1041 	if (msg->msg_state == HTTP_MSG_BODY)
1042 		msg->msg_state = HTTP_MSG_DATA;
1043 
1044 	/* in most states, we should abort in case of early close */
1045 	channel_auto_close(req);
1046 
1047 	if (req->to_forward) {
1048 		if (req->to_forward == CHN_INFINITE_FORWARD) {
1049 			if (req->flags & CF_EOI)
1050 				msg->msg_state = HTTP_MSG_ENDING;
1051 		}
1052 		else {
1053 			/* We can't process the buffer's contents yet */
1054 			req->flags |= CF_WAKE_WRITE;
1055 			goto missing_data_or_waiting;
1056 		}
1057 	}
1058 
1059 	if (msg->msg_state >= HTTP_MSG_ENDING)
1060 		goto ending;
1061 
1062 	if (txn->meth == HTTP_METH_CONNECT) {
1063 		msg->msg_state = HTTP_MSG_ENDING;
1064 		goto ending;
1065 	}
1066 
1067 	/* Forward input data. We get it by removing all outgoing data not
1068 	 * forwarded yet from HTX data size. If there are some data filters, we
1069 	 * let them decide the amount of data to forward.
1070 	 */
1071 	if (HAS_REQ_DATA_FILTERS(s)) {
1072 		ret  = flt_http_payload(s, msg, htx->data);
1073 		if (ret < 0)
1074 			goto return_bad_req;
1075 		c_adv(req, ret);
1076 	}
1077 	else {
1078 		c_adv(req, htx->data - co_data(req));
1079 		if (msg->flags & HTTP_MSGF_XFER_LEN)
1080 			channel_htx_forward_forever(req, htx);
1081 	}
1082 
1083 	if (htx->data != co_data(req))
1084 		goto missing_data_or_waiting;
1085 
1086 	/* Check if the end-of-message is reached and if so, switch the message
1087 	 * in HTTP_MSG_ENDING state. Then if all data was marked to be
1088 	 * forwarded, set the state to HTTP_MSG_DONE.
1089 	 */
1090 	if (!(htx->flags & HTX_FL_EOM))
1091 		goto missing_data_or_waiting;
1092 
1093 	msg->msg_state = HTTP_MSG_ENDING;
1094 
1095   ending:
1096 	req->flags &= ~CF_EXPECT_MORE; /* no more data are expected */
1097 
1098 	/* other states, ENDING...TUNNEL */
1099 	if (msg->msg_state >= HTTP_MSG_DONE)
1100 		goto done;
1101 
1102 	if (HAS_REQ_DATA_FILTERS(s)) {
1103 		ret = flt_http_end(s, msg);
1104 		if (ret <= 0) {
1105 			if (!ret)
1106 				goto missing_data_or_waiting;
1107 			goto return_bad_req;
1108 		}
1109 	}
1110 
1111 	if (txn->meth == HTTP_METH_CONNECT)
1112 		msg->msg_state = HTTP_MSG_TUNNEL;
1113 	else {
1114 		msg->msg_state = HTTP_MSG_DONE;
1115 		req->to_forward = 0;
1116 	}
1117 
1118   done:
1119 	/* we don't want to forward closes on DONE except in tunnel mode. */
1120 	if (!(txn->flags & TX_CON_WANT_TUN))
1121 		channel_dont_close(req);
1122 
1123 	http_end_request(s);
1124 	if (!(req->analysers & an_bit)) {
1125 		http_end_response(s);
1126 		if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1127 			if (req->flags & CF_SHUTW) {
1128 				/* request errors are most likely due to the
1129 				 * server aborting the transfer. */
1130 				goto return_srv_abort;
1131 			}
1132 			goto return_bad_req;
1133 		}
1134 		DBG_TRACE_LEAVE(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
1135 		return 1;
1136 	}
1137 
1138 	/* If "option abortonclose" is set on the backend, we want to monitor
1139 	 * the client's connection and forward any shutdown notification to the
1140 	 * server, which will decide whether to close or to go on processing the
1141 	 * request. We only do that in tunnel mode, and not in other modes since
1142 	 * it can be abused to exhaust source ports. */
1143 	if (s->be->options & PR_O_ABRT_CLOSE) {
1144 		channel_auto_read(req);
1145 		if ((req->flags & (CF_SHUTR|CF_READ_NULL)) && !(txn->flags & TX_CON_WANT_TUN))
1146 			s->si[1].flags |= SI_FL_NOLINGER;
1147 		channel_auto_close(req);
1148 	}
1149 	else if (s->txn->meth == HTTP_METH_POST) {
1150 		/* POST requests may require to read extra CRLF sent by broken
1151 		 * browsers and which could cause an RST to be sent upon close
1152 		 * on some systems (eg: Linux). */
1153 		channel_auto_read(req);
1154 	}
1155 	DBG_TRACE_DEVEL("waiting for the end of the HTTP txn",
1156 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
1157 	return 0;
1158 
1159  missing_data_or_waiting:
1160 	/* stop waiting for data if the input is closed before the end */
1161 	if (msg->msg_state < HTTP_MSG_ENDING && req->flags & CF_SHUTR)
1162 		goto return_cli_abort;
1163 
1164  waiting:
1165 	/* waiting for the last bits to leave the buffer */
1166 	if (req->flags & CF_SHUTW)
1167 		goto return_srv_abort;
1168 
1169 	/* When TE: chunked is used, we need to get there again to parse remaining
1170 	 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1171 	 * And when content-length is used, we never want to let the possible
1172 	 * shutdown be forwarded to the other side, as the state machine will
1173 	 * take care of it once the client responds. It's also important to
1174 	 * prevent TIME_WAITs from accumulating on the backend side, and for
1175 	 * HTTP/2 where the last frame comes with a shutdown.
1176 	 */
1177 	if (msg->flags & HTTP_MSGF_XFER_LEN)
1178 		channel_dont_close(req);
1179 
1180 	/* We know that more data are expected, but we couldn't send more that
1181 	 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1182 	 * system knows it must not set a PUSH on this first part. Interactive
1183 	 * modes are already handled by the stream sock layer. We must not do
1184 	 * this in content-length mode because it could present the MSG_MORE
1185 	 * flag with the last block of forwarded data, which would cause an
1186 	 * additional delay to be observed by the receiver.
1187 	 */
1188 	if (HAS_REQ_DATA_FILTERS(s))
1189 		req->flags |= CF_EXPECT_MORE;
1190 
1191 	DBG_TRACE_DEVEL("waiting for more data to forward",
1192 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
1193 	return 0;
1194 
1195   return_cli_abort:
1196 	_HA_ATOMIC_INC(&sess->fe->fe_counters.cli_aborts);
1197 	_HA_ATOMIC_INC(&s->be->be_counters.cli_aborts);
1198 	if (sess->listener && sess->listener->counters)
1199 		_HA_ATOMIC_INC(&sess->listener->counters->cli_aborts);
1200 	if (objt_server(s->target))
1201 		_HA_ATOMIC_INC(&__objt_server(s->target)->counters.cli_aborts);
1202 	if (!(s->flags & SF_ERR_MASK))
1203 		s->flags |= SF_ERR_CLICL;
1204 	status = 400;
1205 	goto return_prx_cond;
1206 
1207   return_srv_abort:
1208 	_HA_ATOMIC_INC(&sess->fe->fe_counters.srv_aborts);
1209 	_HA_ATOMIC_INC(&s->be->be_counters.srv_aborts);
1210 	if (sess->listener && sess->listener->counters)
1211 		_HA_ATOMIC_INC(&sess->listener->counters->srv_aborts);
1212 	if (objt_server(s->target))
1213 		_HA_ATOMIC_INC(&__objt_server(s->target)->counters.srv_aborts);
1214 	if (!(s->flags & SF_ERR_MASK))
1215 		s->flags |= SF_ERR_SRVCL;
1216 	status = 502;
1217 	goto return_prx_cond;
1218 
1219   return_int_err:
1220 	if (!(s->flags & SF_ERR_MASK))
1221 		s->flags |= SF_ERR_INTERNAL;
1222 	_HA_ATOMIC_INC(&sess->fe->fe_counters.internal_errors);
1223 	_HA_ATOMIC_INC(&s->be->be_counters.internal_errors);
1224 	if (sess->listener && sess->listener->counters)
1225 		_HA_ATOMIC_INC(&sess->listener->counters->internal_errors);
1226 	if (objt_server(s->target))
1227 		_HA_ATOMIC_INC(&__objt_server(s->target)->counters.internal_errors);
1228 	status = 500;
1229 	goto return_prx_cond;
1230 
1231   return_bad_req:
1232 	_HA_ATOMIC_INC(&sess->fe->fe_counters.failed_req);
1233 	if (sess->listener && sess->listener->counters)
1234 		_HA_ATOMIC_INC(&sess->listener->counters->failed_req);
1235 	status = 400;
1236 	/* fall through */
1237 
1238   return_prx_cond:
1239 	if (txn->status > 0) {
1240 		/* Note: we don't send any error if some data were already sent */
1241 		http_reply_and_close(s, txn->status, NULL);
1242 	} else {
1243 		txn->status = status;
1244 		http_reply_and_close(s, txn->status, http_error_message(s));
1245 	}
1246 	if (!(s->flags & SF_ERR_MASK))
1247 		s->flags |= SF_ERR_PRXCOND;
1248 	if (!(s->flags & SF_FINST_MASK))
1249 		s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
1250 	DBG_TRACE_DEVEL("leaving on error ",
1251 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
1252 	return 0;
1253 }
1254 
1255 /* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1256 /* Returns 0 if we can attempt to retry, -1 otherwise */
do_l7_retry(struct stream * s,struct stream_interface * si)1257 static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1258 {
1259 	struct channel *req, *res;
1260 	int co_data;
1261 
1262 	si->conn_retries--;
1263 	if (si->conn_retries < 0)
1264 		return -1;
1265 
1266 	if (objt_server(s->target)) {
1267 		if (s->flags & SF_CURR_SESS) {
1268 			s->flags &= ~SF_CURR_SESS;
1269 			_HA_ATOMIC_DEC(&__objt_server(s->target)->cur_sess);
1270 		}
1271 		_HA_ATOMIC_INC(&__objt_server(s->target)->counters.retries);
1272 	}
1273 	_HA_ATOMIC_INC(&s->be->be_counters.retries);
1274 
1275 	req = &s->req;
1276 	res = &s->res;
1277 	/* Remove any write error from the request, and read error from the response */
1278 	req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1279 	res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1280 	res->analysers = 0;
1281 	si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
1282 	si->err_type = SI_ET_NONE;
1283 	s->flags &= ~(SF_ERR_MASK | SF_FINST_MASK);
1284 	stream_choose_redispatch(s);
1285 	si->exp = TICK_ETERNITY;
1286 	res->rex = TICK_ETERNITY;
1287 	res->to_forward = 0;
1288 	res->analyse_exp = TICK_ETERNITY;
1289 	res->total = 0;
1290 	si_release_endpoint(&s->si[1]);
1291 
1292 	b_free(&req->buf);
1293 	/* Swap the L7 buffer with the channel buffer */
1294 	/* We know we stored the co_data as b_data, so get it there */
1295 	co_data = b_data(&si->l7_buffer);
1296 	b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1297 	b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1298 	co_set_data(req, co_data);
1299 
1300 	DBG_TRACE_DEVEL("perform a L7 retry", STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, s->txn);
1301 
1302 	b_reset(&res->buf);
1303 	co_set_data(res, 0);
1304 	return 0;
1305 }
1306 
1307 /* This stream analyser waits for a complete HTTP response. It returns 1 if the
1308  * processing can continue on next analysers, or zero if it either needs more
1309  * data or wants to immediately abort the response (eg: timeout, error, ...). It
1310  * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1311  * when it has nothing left to do, and may remove any analyser when it wants to
1312  * abort.
1313  */
http_wait_for_response(struct stream * s,struct channel * rep,int an_bit)1314 int http_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1315 {
1316 	/*
1317 	 * We will analyze a complete HTTP response to check the its syntax.
1318 	 *
1319 	 * Once the start line and all headers are received, we may perform a
1320 	 * capture of the error (if any), and we will set a few fields. We also
1321 	 * logging and finally headers capture.
1322 	 */
1323 	struct session *sess = s->sess;
1324 	struct http_txn *txn = s->txn;
1325 	struct http_msg *msg = &txn->rsp;
1326 	struct htx *htx;
1327 	struct stream_interface *si_b = &s->si[1];
1328 	struct connection *srv_conn;
1329 	struct htx_sl *sl;
1330 	int n;
1331 
1332 	DBG_TRACE_ENTER(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn, msg);
1333 
1334 	htx = htxbuf(&rep->buf);
1335 
1336 	/* Parsing errors are caught here */
1337 	if (htx->flags & HTX_FL_PARSING_ERROR)
1338 		goto return_bad_res;
1339 	if (htx->flags & HTX_FL_PROCESSING_ERROR)
1340 		goto return_int_err;
1341 
1342 	/*
1343 	 * Now we quickly check if we have found a full valid response.
1344 	 * If not so, we check the FD and buffer states before leaving.
1345 	 * A full response is indicated by the fact that we have seen
1346 	 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1347 	 * responses are checked first.
1348 	 *
1349 	 * Depending on whether the client is still there or not, we
1350 	 * may send an error response back or not. Note that normally
1351 	 * we should only check for HTTP status there, and check I/O
1352 	 * errors somewhere else.
1353 	 */
1354   next_one:
1355 	if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
1356 		/* 1: have we encountered a read error ? */
1357 		if (rep->flags & CF_READ_ERROR) {
1358 			struct connection *conn = NULL;
1359 
1360 			if (objt_cs(s->si[1].end))
1361 				conn = __objt_cs(s->si[1].end)->conn;
1362 
1363 			/* Perform a L7 retry because server refuses the early data. */
1364 			if ((si_b->flags & SI_FL_L7_RETRY) &&
1365 			    (s->be->retry_type & PR_RE_EARLY_ERROR) &&
1366 			    conn && conn->err_code == CO_ER_SSL_EARLY_FAILED &&
1367 			    do_l7_retry(s, si_b) == 0) {
1368 				DBG_TRACE_DEVEL("leaving on L7 retry",
1369 						STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
1370 				return 0;
1371 			}
1372 
1373 			if (txn->flags & TX_NOT_FIRST)
1374 				goto abort_keep_alive;
1375 
1376 			_HA_ATOMIC_INC(&s->be->be_counters.failed_resp);
1377 			if (objt_server(s->target)) {
1378 				_HA_ATOMIC_INC(&__objt_server(s->target)->counters.failed_resp);
1379 				health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
1380 			}
1381 
1382 			/* if the server refused the early data, just send a 425 */
1383 			if (conn && conn->err_code == CO_ER_SSL_EARLY_FAILED)
1384 				txn->status = 425;
1385 			else {
1386 				txn->status = 502;
1387 				stream_inc_http_fail_ctr(s);
1388 			}
1389 
1390 			s->si[1].flags |= SI_FL_NOLINGER;
1391 			http_reply_and_close(s, txn->status, http_error_message(s));
1392 
1393 			if (!(s->flags & SF_ERR_MASK))
1394 				s->flags |= SF_ERR_SRVCL;
1395 			if (!(s->flags & SF_FINST_MASK))
1396 				s->flags |= SF_FINST_H;
1397 			DBG_TRACE_DEVEL("leaving on error",
1398 					STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
1399 			return 0;
1400 		}
1401 
1402 		/* 2: read timeout : return a 504 to the client. */
1403 		else if (rep->flags & CF_READ_TIMEOUT) {
1404 			if ((si_b->flags & SI_FL_L7_RETRY) &&
1405 			    (s->be->retry_type & PR_RE_TIMEOUT)) {
1406 				if (co_data(rep) || do_l7_retry(s, si_b) == 0) {
1407 					DBG_TRACE_DEVEL("leaving on L7 retry",
1408 							STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
1409 					return 0;
1410 				}
1411 			}
1412 			_HA_ATOMIC_INC(&s->be->be_counters.failed_resp);
1413 			if (objt_server(s->target)) {
1414 				_HA_ATOMIC_INC(&__objt_server(s->target)->counters.failed_resp);
1415 				health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
1416 			}
1417 
1418 			txn->status = 504;
1419 			stream_inc_http_fail_ctr(s);
1420 			s->si[1].flags |= SI_FL_NOLINGER;
1421 			http_reply_and_close(s, txn->status, http_error_message(s));
1422 
1423 			if (!(s->flags & SF_ERR_MASK))
1424 				s->flags |= SF_ERR_SRVTO;
1425 			if (!(s->flags & SF_FINST_MASK))
1426 				s->flags |= SF_FINST_H;
1427 			DBG_TRACE_DEVEL("leaving on error",
1428 					STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
1429 			return 0;
1430 		}
1431 
1432 		/* 3: client abort with an abortonclose */
1433 		else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
1434 			_HA_ATOMIC_INC(&sess->fe->fe_counters.cli_aborts);
1435 			_HA_ATOMIC_INC(&s->be->be_counters.cli_aborts);
1436 			if (sess->listener && sess->listener->counters)
1437 				_HA_ATOMIC_INC(&sess->listener->counters->cli_aborts);
1438 			if (objt_server(s->target))
1439 				_HA_ATOMIC_INC(&__objt_server(s->target)->counters.cli_aborts);
1440 
1441 			txn->status = 400;
1442 			http_reply_and_close(s, txn->status, http_error_message(s));
1443 
1444 			if (!(s->flags & SF_ERR_MASK))
1445 				s->flags |= SF_ERR_CLICL;
1446 			if (!(s->flags & SF_FINST_MASK))
1447 				s->flags |= SF_FINST_H;
1448 
1449 			/* process_stream() will take care of the error */
1450 			DBG_TRACE_DEVEL("leaving on error",
1451 					STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
1452 			return 0;
1453 		}
1454 
1455 		/* 4: close from server, capture the response if the server has started to respond */
1456 		else if (rep->flags & CF_SHUTR) {
1457 			if ((si_b->flags & SI_FL_L7_RETRY) &&
1458 			    (s->be->retry_type & PR_RE_DISCONNECTED)) {
1459 				if (co_data(rep) || do_l7_retry(s, si_b) == 0) {
1460 					DBG_TRACE_DEVEL("leaving on L7 retry",
1461 							STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
1462 					return 0;
1463 				}
1464 			}
1465 
1466 			if (txn->flags & TX_NOT_FIRST)
1467 				goto abort_keep_alive;
1468 
1469 			_HA_ATOMIC_INC(&s->be->be_counters.failed_resp);
1470 			if (objt_server(s->target)) {
1471 				_HA_ATOMIC_INC(&__objt_server(s->target)->counters.failed_resp);
1472 				health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
1473 			}
1474 
1475 			txn->status = 502;
1476 			stream_inc_http_fail_ctr(s);
1477 			s->si[1].flags |= SI_FL_NOLINGER;
1478 			http_reply_and_close(s, txn->status, http_error_message(s));
1479 
1480 			if (!(s->flags & SF_ERR_MASK))
1481 				s->flags |= SF_ERR_SRVCL;
1482 			if (!(s->flags & SF_FINST_MASK))
1483 				s->flags |= SF_FINST_H;
1484 			DBG_TRACE_DEVEL("leaving on error",
1485 					STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
1486 			return 0;
1487 		}
1488 
1489 		/* 5: write error to client (we don't send any message then) */
1490 		else if (rep->flags & CF_WRITE_ERROR) {
1491 			if (txn->flags & TX_NOT_FIRST)
1492 				goto abort_keep_alive;
1493 
1494 			_HA_ATOMIC_INC(&s->be->be_counters.failed_resp);
1495 			if (objt_server(s->target))
1496 				_HA_ATOMIC_INC(&__objt_server(s->target)->counters.failed_resp);
1497 			rep->analysers &= AN_RES_FLT_END;
1498 
1499 			if (!(s->flags & SF_ERR_MASK))
1500 				s->flags |= SF_ERR_CLICL;
1501 			if (!(s->flags & SF_FINST_MASK))
1502 				s->flags |= SF_FINST_H;
1503 
1504 			/* process_stream() will take care of the error */
1505 			DBG_TRACE_DEVEL("leaving on error",
1506 					STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
1507 			return 0;
1508 		}
1509 
1510 		channel_dont_close(rep);
1511 		rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1512 		DBG_TRACE_DEVEL("waiting for more data",
1513 				STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
1514 		return 0;
1515 	}
1516 
1517 	/* More interesting part now : we know that we have a complete
1518 	 * response which at least looks like HTTP. We have an indicator
1519 	 * of each header's length, so we can parse them quickly.
1520 	 */
1521 	BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
1522 	sl = http_get_stline(htx);
1523 
1524 	/* Perform a L7 retry because of the status code */
1525 	if ((si_b->flags & SI_FL_L7_RETRY) &&
1526 	    l7_status_match(s->be, sl->info.res.status) &&
1527 	    do_l7_retry(s, si_b) == 0) {
1528 		DBG_TRACE_DEVEL("leaving on L7 retry", STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
1529 		return 0;
1530 	}
1531 
1532 	/* Now, L7 buffer is useless, it can be released */
1533 	b_free(&s->si[1].l7_buffer);
1534 
1535 	msg->msg_state = HTTP_MSG_BODY;
1536 
1537 
1538 	/* 0: we might have to print this header in debug mode */
1539 	if (unlikely((global.mode & MODE_DEBUG) &&
1540 		     (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1541 		int32_t pos;
1542 
1543 		http_debug_stline("srvrep", s, sl);
1544 
1545 		for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1546 			struct htx_blk *blk = htx_get_blk(htx, pos);
1547 			enum htx_blk_type type = htx_get_blk_type(blk);
1548 
1549 			if (type == HTX_BLK_EOH)
1550 				break;
1551 			if (type != HTX_BLK_HDR)
1552 				continue;
1553 
1554 			http_debug_hdr("srvhdr", s,
1555 				       htx_get_blk_name(htx, blk),
1556 				       htx_get_blk_value(htx, blk));
1557 		}
1558 	}
1559 
1560 	/* 1: get the status code and the version. Also set HTTP flags */
1561 	txn->status = sl->info.res.status;
1562 	if (sl->flags & HTX_SL_F_VER_11)
1563                 msg->flags |= HTTP_MSGF_VER_11;
1564 	if (sl->flags & HTX_SL_F_XFER_LEN) {
1565 		msg->flags |= HTTP_MSGF_XFER_LEN;
1566 		if (sl->flags & HTX_SL_F_CLEN)
1567 			msg->flags |= HTTP_MSGF_CNT_LEN;
1568 		else if (sl->flags & HTX_SL_F_CHNK)
1569 			msg->flags |= HTTP_MSGF_TE_CHNK;
1570 	}
1571 	if (sl->flags & HTX_SL_F_BODYLESS)
1572 		msg->flags |= HTTP_MSGF_BODYLESS;
1573 	if (sl->flags & HTX_SL_F_CONN_UPG)
1574 		msg->flags |= HTTP_MSGF_CONN_UPG;
1575 
1576 	n = txn->status / 100;
1577 	if (n < 1 || n > 5)
1578 		n = 0;
1579 
1580 	/* when the client triggers a 4xx from the server, it's most often due
1581 	 * to a missing object or permission. These events should be tracked
1582 	 * because if they happen often, it may indicate a brute force or a
1583 	 * vulnerability scan.
1584 	 */
1585 	if (n == 4)
1586 		stream_inc_http_err_ctr(s);
1587 
1588 	if (n == 5 && txn->status != 501 && txn->status != 505)
1589 		stream_inc_http_fail_ctr(s);
1590 
1591 	if (objt_server(s->target)) {
1592 		_HA_ATOMIC_INC(&__objt_server(s->target)->counters.p.http.rsp[n]);
1593 		_HA_ATOMIC_INC(&__objt_server(s->target)->counters.p.http.cum_req);
1594 	}
1595 
1596 	/* Adjust server's health based on status code. Note: status codes 501
1597 	 * and 505 are triggered on demand by client request, so we must not
1598 	 * count them as server failures.
1599 	 */
1600 	if (objt_server(s->target)) {
1601 		if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
1602 			health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
1603 		else
1604 			health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
1605 	}
1606 
1607 	/*
1608 	 * We may be facing a 100-continue response, or any other informational
1609 	 * 1xx response which is non-final, in which case this is not the right
1610 	 * response, and we're waiting for the next one. Let's allow this response
1611 	 * to go to the client and wait for the next one. There's an exception for
1612 	 * 101 which is used later in the code to switch protocols.
1613 	 */
1614 	if (txn->status < 200 &&
1615 	    (txn->status == 100 || txn->status >= 102)) {
1616 		FLT_STRM_CB(s, flt_http_reset(s, msg));
1617 		htx->first = channel_htx_fwd_headers(rep, htx);
1618 		msg->msg_state = HTTP_MSG_RPBEFORE;
1619 		msg->flags = 0;
1620 		txn->status = 0;
1621 		s->logs.t_data = -1; /* was not a response yet */
1622 		rep->flags |= CF_SEND_DONTWAIT; /* Send ASAP informational messages */
1623 		goto next_one;
1624 	}
1625 
1626 	/* A 101-switching-protocols must contains a Connection header with the
1627 	 * "upgrade" option and the request too. It means both are agree to
1628 	 * upgrade. It is not so strict because there is no test on the Upgrade
1629 	 * header content. But it is probably stronger enough for now.
1630 	 */
1631 	if (txn->status == 101 &&
1632 	    (!(txn->req.flags & HTTP_MSGF_CONN_UPG) || !(txn->rsp.flags & HTTP_MSGF_CONN_UPG)))
1633 		goto return_bad_res;
1634 
1635 	/*
1636 	 * 2: check for cacheability.
1637 	 */
1638 
1639 	switch (txn->status) {
1640 	case 200:
1641 	case 203:
1642 	case 204:
1643 	case 206:
1644 	case 300:
1645 	case 301:
1646 	case 404:
1647 	case 405:
1648 	case 410:
1649 	case 414:
1650 	case 501:
1651 		break;
1652 	default:
1653 		/* RFC7231#6.1:
1654 		 *   Responses with status codes that are defined as
1655 		 *   cacheable by default (e.g., 200, 203, 204, 206,
1656 		 *   300, 301, 404, 405, 410, 414, and 501 in this
1657 		 *   specification) can be reused by a cache with
1658 		 *   heuristic expiration unless otherwise indicated
1659 		 *   by the method definition or explicit cache
1660 		 *   controls [RFC7234]; all other status codes are
1661 		 *   not cacheable by default.
1662 		 */
1663 		txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1664 		break;
1665 	}
1666 
1667 	/*
1668 	 * 3: we may need to capture headers
1669 	 */
1670 	s->logs.logwait &= ~LW_RESP;
1671 	if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
1672 		http_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
1673 
1674 	/* Skip parsing if no content length is possible. */
1675 	if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status >= 200 && txn->status < 300) ||
1676 		     txn->status == 101)) {
1677 		/* Either we've established an explicit tunnel, or we're
1678 		 * switching the protocol. In both cases, we're very unlikely
1679 		 * to understand the next protocols. We have to switch to tunnel
1680 		 * mode, so that we transfer the request and responses then let
1681 		 * this protocol pass unmodified. When we later implement specific
1682 		 * parsers for such protocols, we'll want to check the Upgrade
1683 		 * header which contains information about that protocol for
1684 		 * responses with status 101 (eg: see RFC2817 about TLS).
1685 		 */
1686 		txn->flags |= TX_CON_WANT_TUN;
1687 	}
1688 
1689 	/* check for NTML authentication headers in 401 (WWW-Authenticate) and
1690 	 * 407 (Proxy-Authenticate) responses and set the connection to private
1691 	 */
1692 	srv_conn = cs_conn(objt_cs(s->si[1].end));
1693 	if (srv_conn) {
1694 		struct ist hdr;
1695 		struct http_hdr_ctx ctx;
1696 
1697 		if (txn->status == 401)
1698 			hdr = ist("WWW-Authenticate");
1699 		else if (txn->status == 407)
1700 			hdr = ist("Proxy-Authenticate");
1701 		else
1702 			goto end;
1703 
1704 		ctx.blk = NULL;
1705 		while (http_find_header(htx, hdr, &ctx, 0)) {
1706 			/* If www-authenticate contains "Negotiate", "Nego2", or "NTLM",
1707 			 * possibly followed by blanks and a base64 string, the connection
1708 			 * is private. Since it's a mess to deal with, we only check for
1709 			 * values starting with "NTLM" or "Nego". Note that often multiple
1710 			 * headers are sent by the server there.
1711 			 */
1712 			if ((ctx.value.len >= 4 && strncasecmp(ctx.value.ptr, "Nego", 4) == 0) ||
1713 			    (ctx.value.len >= 4 && strncasecmp(ctx.value.ptr, "NTLM", 4) == 0)) {
1714 				sess->flags |= SESS_FL_PREFER_LAST;
1715 				conn_set_owner(srv_conn, sess, NULL);
1716 				conn_set_private(srv_conn);
1717 				/* If it fail now, the same will be done in mux->detach() callback */
1718 				session_add_conn(srv_conn->owner, srv_conn, srv_conn->target);
1719 				break;
1720 			}
1721 		}
1722 	}
1723 
1724   end:
1725 	/* we want to have the response time before we start processing it */
1726 	s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1727 
1728 	/* end of job, return OK */
1729 	rep->analysers &= ~an_bit;
1730 	rep->analyse_exp = TICK_ETERNITY;
1731 	channel_auto_close(rep);
1732 	DBG_TRACE_LEAVE(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
1733 	return 1;
1734 
1735  return_int_err:
1736 	_HA_ATOMIC_INC(&sess->fe->fe_counters.internal_errors);
1737 	_HA_ATOMIC_INC(&s->be->be_counters.internal_errors);
1738 	if (sess->listener && sess->listener->counters)
1739 		_HA_ATOMIC_INC(&sess->listener->counters->internal_errors);
1740 	if (objt_server(s->target))
1741 		_HA_ATOMIC_INC(&__objt_server(s->target)->counters.internal_errors);
1742 	txn->status = 500;
1743 	if (!(s->flags & SF_ERR_MASK))
1744 		s->flags |= SF_ERR_INTERNAL;
1745 	goto return_prx_cond;
1746 
1747   return_bad_res:
1748 	_HA_ATOMIC_INC(&s->be->be_counters.failed_resp);
1749 	if (objt_server(s->target)) {
1750 		_HA_ATOMIC_INC(&__objt_server(s->target)->counters.failed_resp);
1751 		health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
1752 	}
1753 	if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
1754 	    (si_b->flags & SI_FL_L7_RETRY) &&
1755 	    do_l7_retry(s, si_b) == 0) {
1756 		DBG_TRACE_DEVEL("leaving on L7 retry",
1757 				STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
1758 		return 0;
1759 	}
1760 	txn->status = 502;
1761 	stream_inc_http_fail_ctr(s);
1762 	/* fall through */
1763 
1764  return_prx_cond:
1765 	http_reply_and_close(s, txn->status, http_error_message(s));
1766 
1767 	if (!(s->flags & SF_ERR_MASK))
1768 		s->flags |= SF_ERR_PRXCOND;
1769 	if (!(s->flags & SF_FINST_MASK))
1770 		s->flags |= SF_FINST_H;
1771 
1772 	s->si[1].flags |= SI_FL_NOLINGER;
1773 	DBG_TRACE_DEVEL("leaving on error",
1774 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
1775 	return 0;
1776 
1777  abort_keep_alive:
1778 	/* A keep-alive request to the server failed on a network error.
1779 	 * The client is required to retry. We need to close without returning
1780 	 * any other information so that the client retries.
1781 	 */
1782 	txn->status = 0;
1783 	s->logs.logwait = 0;
1784 	s->logs.level = 0;
1785 	s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
1786 	http_reply_and_close(s, txn->status, NULL);
1787 	DBG_TRACE_DEVEL("leaving by closing K/A connection",
1788 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
1789 	return 0;
1790 }
1791 
1792 /* This function performs all the processing enabled for the current response.
1793  * It normally returns 1 unless it wants to break. It relies on buffers flags,
1794  * and updates s->res.analysers. It might make sense to explode it into several
1795  * other functions. It works like process_request (see indications above).
1796  */
http_process_res_common(struct stream * s,struct channel * rep,int an_bit,struct proxy * px)1797 int http_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1798 {
1799 	struct session *sess = s->sess;
1800 	struct http_txn *txn = s->txn;
1801 	struct http_msg *msg = &txn->rsp;
1802 	struct htx *htx;
1803 	struct proxy *cur_proxy;
1804 	enum rule_result ret = HTTP_RULE_RES_CONT;
1805 
1806 	if (unlikely(msg->msg_state < HTTP_MSG_BODY))	/* we need more data */
1807 		return 0;
1808 
1809 	DBG_TRACE_ENTER(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn, msg);
1810 
1811 	htx = htxbuf(&rep->buf);
1812 
1813 	/* The stats applet needs to adjust the Connection header but we don't
1814 	 * apply any filter there.
1815 	 */
1816 	if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1817 		rep->analysers &= ~an_bit;
1818 		rep->analyse_exp = TICK_ETERNITY;
1819 		goto end;
1820 	}
1821 
1822 	/*
1823 	 * We will have to evaluate the filters.
1824 	 * As opposed to version 1.2, now they will be evaluated in the
1825 	 * filters order and not in the header order. This means that
1826 	 * each filter has to be validated among all headers.
1827 	 *
1828 	 * Filters are tried with ->be first, then with ->fe if it is
1829 	 * different from ->be.
1830 	 *
1831 	 * Maybe we are in resume condiion. In this case I choose the
1832 	 * "struct proxy" which contains the rule list matching the resume
1833 	 * pointer. If none of these "struct proxy" match, I initialise
1834 	 * the process with the first one.
1835 	 *
1836 	 * In fact, I check only correspondence between the current list
1837 	 * pointer and the ->fe rule list. If it doesn't match, I initialize
1838 	 * the loop with the ->be.
1839 	 */
1840 	if (s->current_rule_list == &sess->fe->http_res_rules)
1841 		cur_proxy = sess->fe;
1842 	else
1843 		cur_proxy = s->be;
1844 	while (1) {
1845 		/* evaluate http-response rules */
1846 		if (ret == HTTP_RULE_RES_CONT || ret == HTTP_RULE_RES_STOP) {
1847 			ret = http_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
1848 
1849 			switch (ret) {
1850 			case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
1851 				goto return_prx_yield;
1852 
1853 			case HTTP_RULE_RES_CONT:
1854 			case HTTP_RULE_RES_STOP: /* nothing to do */
1855 				break;
1856 
1857 			case HTTP_RULE_RES_DENY: /* deny or tarpit */
1858 				goto deny;
1859 
1860 			case HTTP_RULE_RES_ABRT: /* abort request, response already sent */
1861 				goto return_prx_cond;
1862 
1863 			case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
1864 				goto done;
1865 
1866 			case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
1867 				goto return_bad_res;
1868 
1869 			case HTTP_RULE_RES_ERROR: /* failed with a bad request */
1870 				goto return_int_err;
1871 			}
1872 
1873 		}
1874 
1875 		/* check whether we're already working on the frontend */
1876 		if (cur_proxy == sess->fe)
1877 			break;
1878 		cur_proxy = sess->fe;
1879 	}
1880 
1881 	/* OK that's all we can do for 1xx responses */
1882 	if (unlikely(txn->status < 200 && txn->status != 101))
1883 		goto end;
1884 
1885 	/*
1886 	 * Now check for a server cookie.
1887 	 */
1888 	if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
1889 		http_manage_server_side_cookies(s, rep);
1890 
1891 	/*
1892 	 * Check for cache-control or pragma headers if required.
1893 	 */
1894 	if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1895 		http_check_response_for_cacheability(s, rep);
1896 
1897 	/*
1898 	 * Add server cookie in the response if needed
1899 	 */
1900 	if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1901 	    !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1902 	    (!(s->flags & SF_DIRECT) ||
1903 	     ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1904 	      (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1905 	     (s->be->cookie_maxlife && !txn->cookie_first_date) ||  // set the first_date
1906 	     (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1907 	    (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1908 	    !(s->flags & SF_IGNORE_PRST)) {
1909 		/* the server is known, it's not the one the client requested, or the
1910 		 * cookie's last seen date needs to be refreshed. We have to
1911 		 * insert a set-cookie here, except if we want to insert only on POST
1912 		 * requests and this one isn't. Note that servers which don't have cookies
1913 		 * (eg: some backup servers) will return a full cookie removal request.
1914 		 */
1915 		if (!__objt_server(s->target)->cookie) {
1916 			chunk_printf(&trash,
1917 				     "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
1918 				     s->be->cookie_name);
1919 		}
1920 		else {
1921 			chunk_printf(&trash, "%s=%s", s->be->cookie_name, __objt_server(s->target)->cookie);
1922 
1923 			if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1924 				/* emit last_date, which is mandatory */
1925 				trash.area[trash.data++] = COOKIE_DELIM_DATE;
1926 				s30tob64((date.tv_sec+3) >> 2,
1927 					 trash.area + trash.data);
1928 				trash.data += 5;
1929 
1930 				if (s->be->cookie_maxlife) {
1931 					/* emit first_date, which is either the original one or
1932 					 * the current date.
1933 					 */
1934 					trash.area[trash.data++] = COOKIE_DELIM_DATE;
1935 					s30tob64(txn->cookie_first_date ?
1936 						 txn->cookie_first_date >> 2 :
1937 						 (date.tv_sec+3) >> 2,
1938 						 trash.area + trash.data);
1939 					trash.data += 5;
1940 				}
1941 			}
1942 			chunk_appendf(&trash, "; path=/");
1943 		}
1944 
1945 		if (s->be->cookie_domain)
1946 			chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1947 
1948 		if (s->be->ck_opts & PR_CK_HTTPONLY)
1949 			chunk_appendf(&trash, "; HttpOnly");
1950 
1951 		if (s->be->ck_opts & PR_CK_SECURE)
1952 			chunk_appendf(&trash, "; Secure");
1953 
1954 		if (s->be->cookie_attrs)
1955 			chunk_appendf(&trash, "; %s", s->be->cookie_attrs);
1956 
1957 		if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
1958 			goto return_int_err;
1959 
1960 		txn->flags &= ~TX_SCK_MASK;
1961 		if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
1962 			/* the server did not change, only the date was updated */
1963 			txn->flags |= TX_SCK_UPDATED;
1964 		else
1965 			txn->flags |= TX_SCK_INSERTED;
1966 
1967 		/* Here, we will tell an eventual cache on the client side that we don't
1968 		 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
1969 		 * Some caches understand the correct form: 'no-cache="set-cookie"', but
1970 		 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
1971 		 */
1972 		if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
1973 
1974 			txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
1975 
1976 			if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
1977 				goto return_int_err;
1978 		}
1979 	}
1980 
1981 	/*
1982 	 * Check if result will be cacheable with a cookie.
1983 	 * We'll block the response if security checks have caught
1984 	 * nasty things such as a cacheable cookie.
1985 	 */
1986 	if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
1987 	     (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
1988 	    (s->be->options & PR_O_CHK_CACHE)) {
1989 		/* we're in presence of a cacheable response containing
1990 		 * a set-cookie header. We'll block it as requested by
1991 		 * the 'checkcache' option, and send an alert.
1992 		 */
1993 		ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
1994 			 s->be->id, objt_server(s->target) ? __objt_server(s->target)->id : "<dispatch>");
1995 		send_log(s->be, LOG_ALERT,
1996 			 "Blocking cacheable cookie in response from instance %s, server %s.\n",
1997 			 s->be->id, objt_server(s->target) ? __objt_server(s->target)->id : "<dispatch>");
1998 		goto deny;
1999 	}
2000 
2001   end:
2002 	/*
2003 	 * Evaluate after-response rules before forwarding the response. rules
2004 	 * from the backend are evaluated first, then one from the frontend if
2005 	 * it differs.
2006 	 */
2007 	if (!http_eval_after_res_rules(s))
2008 		goto return_int_err;
2009 
2010 	/* Filter the response headers if there are filters attached to the
2011 	 * stream.
2012 	 */
2013 	if (HAS_FILTERS(s))
2014 		rep->analysers |= AN_RES_FLT_HTTP_HDRS;
2015 
2016 	/* Always enter in the body analyzer */
2017 	rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2018 	rep->analysers |= AN_RES_HTTP_XFER_BODY;
2019 
2020 	/* if the user wants to log as soon as possible, without counting
2021 	 * bytes from the server, then this is the right moment. We have
2022 	 * to temporarily assign bytes_out to log what we currently have.
2023 	 */
2024 	if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2025 		s->logs.t_close = s->logs.t_data; /* to get a valid end date */
2026 		s->logs.bytes_out = htx->data;
2027 		s->do_log(s);
2028 		s->logs.bytes_out = 0;
2029 	}
2030 
2031  done:
2032 	DBG_TRACE_LEAVE(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
2033 	rep->analysers &= ~an_bit;
2034 	rep->analyse_exp = TICK_ETERNITY;
2035 	return 1;
2036 
2037  deny:
2038 	_HA_ATOMIC_INC(&sess->fe->fe_counters.denied_resp);
2039 	_HA_ATOMIC_INC(&s->be->be_counters.denied_resp);
2040 	if (sess->listener && sess->listener->counters)
2041 		_HA_ATOMIC_INC(&sess->listener->counters->denied_resp);
2042 	if (objt_server(s->target))
2043 		_HA_ATOMIC_INC(&__objt_server(s->target)->counters.denied_resp);
2044 	goto return_prx_err;
2045 
2046  return_int_err:
2047 	txn->status = 500;
2048 	if (!(s->flags & SF_ERR_MASK))
2049 		s->flags |= SF_ERR_INTERNAL;
2050 	_HA_ATOMIC_INC(&sess->fe->fe_counters.internal_errors);
2051 	_HA_ATOMIC_INC(&s->be->be_counters.internal_errors);
2052 	if (sess->listener && sess->listener->counters)
2053 		_HA_ATOMIC_INC(&sess->listener->counters->internal_errors);
2054 	if (objt_server(s->target))
2055 		_HA_ATOMIC_INC(&__objt_server(s->target)->counters.internal_errors);
2056 	goto return_prx_err;
2057 
2058  return_bad_res:
2059 	txn->status = 502;
2060 	stream_inc_http_fail_ctr(s);
2061 	_HA_ATOMIC_INC(&s->be->be_counters.failed_resp);
2062 	if (objt_server(s->target)) {
2063 		_HA_ATOMIC_INC(&__objt_server(s->target)->counters.failed_resp);
2064 		health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2065 	}
2066 	/* fall through */
2067 
2068  return_prx_err:
2069 	http_reply_and_close(s, txn->status, http_error_message(s));
2070 	/* fall through */
2071 
2072  return_prx_cond:
2073 	s->logs.t_data = -1; /* was not a valid response */
2074 	s->si[1].flags |= SI_FL_NOLINGER;
2075 
2076 	if (!(s->flags & SF_ERR_MASK))
2077 		s->flags |= SF_ERR_PRXCOND;
2078 	if (!(s->flags & SF_FINST_MASK))
2079 		s->flags |= SF_FINST_H;
2080 
2081 	rep->analysers &= AN_RES_FLT_END;
2082 	s->req.analysers &= AN_REQ_FLT_END;
2083 	rep->analyse_exp = TICK_ETERNITY;
2084 	DBG_TRACE_DEVEL("leaving on error",
2085 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
2086 	return 0;
2087 
2088  return_prx_yield:
2089 	channel_dont_close(rep);
2090 	DBG_TRACE_DEVEL("waiting for more data",
2091 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
2092 	return 0;
2093 }
2094 
2095 /* This function is an analyser which forwards response body (including chunk
2096  * sizes if any). It is called as soon as we must forward, even if we forward
2097  * zero byte. The only situation where it must not be called is when we're in
2098  * tunnel mode and we want to forward till the close. It's used both to forward
2099  * remaining data and to resync after end of body. It expects the msg_state to
2100  * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2101  * read more data, or 1 once we can go on with next request or end the stream.
2102  *
2103  * It is capable of compressing response data both in content-length mode and
2104  * in chunked mode. The state machines follows different flows depending on
2105  * whether content-length and chunked modes are used, since there are no
2106  * trailers in content-length :
2107  *
2108  *       chk-mode        cl-mode
2109  *          ,----- BODY -----.
2110  *         /                  \
2111  *        V     size > 0       V    chk-mode
2112  *  .--> SIZE -------------> DATA -------------> CRLF
2113  *  |     | size == 0          | last byte         |
2114  *  |     v      final crlf    v inspected         |
2115  *  |  TRAILERS -----------> DONE                  |
2116  *  |                                              |
2117  *  `----------------------------------------------'
2118  *
2119  * Compression only happens in the DATA state, and must be flushed in final
2120  * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2121  * is performed at once on final states for all bytes parsed, or when leaving
2122  * on missing data.
2123  */
http_response_forward_body(struct stream * s,struct channel * res,int an_bit)2124 int http_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2125 {
2126 	struct session *sess = s->sess;
2127 	struct http_txn *txn = s->txn;
2128 	struct http_msg *msg = &s->txn->rsp;
2129 	struct htx *htx;
2130 	int ret;
2131 
2132 	DBG_TRACE_ENTER(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn, msg);
2133 
2134 	htx = htxbuf(&res->buf);
2135 
2136 	if (htx->flags & HTX_FL_PARSING_ERROR)
2137 		goto return_bad_res;
2138 	if (htx->flags & HTX_FL_PROCESSING_ERROR)
2139 		goto return_int_err;
2140 
2141 	if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
2142 	    ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
2143 		/* Output closed while we were sending data. We must abort and
2144 		 * wake the other side up.
2145 		 */
2146 		msg->msg_state = HTTP_MSG_ERROR;
2147 		http_end_response(s);
2148 		http_end_request(s);
2149 		DBG_TRACE_DEVEL("leaving on error",
2150 				STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
2151 		return 1;
2152 	}
2153 
2154 	if (msg->msg_state == HTTP_MSG_BODY)
2155 		msg->msg_state = HTTP_MSG_DATA;
2156 
2157 	/* in most states, we should abort in case of early close */
2158 	channel_auto_close(res);
2159 
2160 	if (res->to_forward) {
2161 		if (res->to_forward == CHN_INFINITE_FORWARD) {
2162 			if (res->flags & CF_EOI)
2163 				msg->msg_state = HTTP_MSG_ENDING;
2164 		}
2165 		else {
2166 			/* We can't process the buffer's contents yet */
2167 			res->flags |= CF_WAKE_WRITE;
2168 			goto missing_data_or_waiting;
2169 		}
2170 	}
2171 
2172 	if (msg->msg_state >= HTTP_MSG_ENDING)
2173 		goto ending;
2174 
2175 	if ((txn->meth == HTTP_METH_CONNECT && txn->status >= 200 && txn->status < 300) || txn->status == 101 ||
2176 	    (!(msg->flags & HTTP_MSGF_XFER_LEN) && !HAS_RSP_DATA_FILTERS(s))) {
2177 		msg->msg_state = HTTP_MSG_ENDING;
2178 		goto ending;
2179 	}
2180 
2181 	/* Forward input data. We get it by removing all outgoing data not
2182 	 * forwarded yet from HTX data size. If there are some data filters, we
2183 	 * let them decide the amount of data to forward.
2184 	 */
2185 	if (HAS_RSP_DATA_FILTERS(s)) {
2186 		ret  = flt_http_payload(s, msg, htx->data);
2187 		if (ret < 0)
2188 			goto return_bad_res;
2189 		c_adv(res, ret);
2190 	}
2191 	else {
2192 		c_adv(res, htx->data - co_data(res));
2193 		if (msg->flags & HTTP_MSGF_XFER_LEN)
2194 			channel_htx_forward_forever(res, htx);
2195 	}
2196 
2197 	if (htx->data != co_data(res))
2198 		goto missing_data_or_waiting;
2199 
2200 	if (!(msg->flags & HTTP_MSGF_XFER_LEN) && res->flags & CF_SHUTR) {
2201 		msg->msg_state = HTTP_MSG_ENDING;
2202 		goto ending;
2203 	}
2204 
2205 	/* Check if the end-of-message is reached and if so, switch the message
2206 	 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2207 	 * forwarded, set the state to HTTP_MSG_DONE.
2208 	 */
2209 	if (!(htx->flags & HTX_FL_EOM))
2210 		goto missing_data_or_waiting;
2211 
2212 	msg->msg_state = HTTP_MSG_ENDING;
2213 
2214   ending:
2215 	res->flags &= ~CF_EXPECT_MORE; /* no more data are expected */
2216 
2217 	/* other states, ENDING...TUNNEL */
2218 	if (msg->msg_state >= HTTP_MSG_DONE)
2219 		goto done;
2220 
2221 	if (HAS_RSP_DATA_FILTERS(s)) {
2222 		ret = flt_http_end(s, msg);
2223 		if (ret <= 0) {
2224 			if (!ret)
2225 				goto missing_data_or_waiting;
2226 			goto return_bad_res;
2227 		}
2228 	}
2229 
2230 	if ((txn->meth == HTTP_METH_CONNECT && txn->status >= 200 && txn->status < 300) || txn->status == 101 ||
2231 	    !(msg->flags & HTTP_MSGF_XFER_LEN)) {
2232 		msg->msg_state = HTTP_MSG_TUNNEL;
2233 		goto ending;
2234 	}
2235 	else {
2236 		msg->msg_state = HTTP_MSG_DONE;
2237 		res->to_forward = 0;
2238 	}
2239 
2240   done:
2241 
2242 	channel_dont_close(res);
2243 
2244 	http_end_response(s);
2245 	if (!(res->analysers & an_bit)) {
2246 		http_end_request(s);
2247 		if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2248 			if (res->flags & CF_SHUTW) {
2249 				/* response errors are most likely due to the
2250 				 * client aborting the transfer. */
2251 				goto return_cli_abort;
2252 			}
2253 			goto return_bad_res;
2254 		}
2255 		DBG_TRACE_LEAVE(STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
2256 		return 1;
2257 	}
2258 	DBG_TRACE_DEVEL("waiting for the end of the HTTP txn",
2259 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
2260 	return 0;
2261 
2262   missing_data_or_waiting:
2263 	if (res->flags & CF_SHUTW)
2264 		goto return_cli_abort;
2265 
2266 	/* stop waiting for data if the input is closed before the end. If the
2267 	 * client side was already closed, it means that the client has aborted,
2268 	 * so we don't want to count this as a server abort. Otherwise it's a
2269 	 * server abort.
2270 	 */
2271 	if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
2272 		if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
2273 			goto return_cli_abort;
2274 		/* If we have some pending data, we continue the processing */
2275 		if (htx_is_empty(htx))
2276 			goto return_srv_abort;
2277 	}
2278 
2279 	/* When TE: chunked is used, we need to get there again to parse
2280 	 * remaining chunks even if the server has closed, so we don't want to
2281 	 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2282 	 * are filters registered on the stream, we don't want to forward a
2283 	 * close
2284 	 */
2285 	if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
2286 		channel_dont_close(res);
2287 
2288 	/* We know that more data are expected, but we couldn't send more that
2289 	 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2290 	 * system knows it must not set a PUSH on this first part. Interactive
2291 	 * modes are already handled by the stream sock layer. We must not do
2292 	 * this in content-length mode because it could present the MSG_MORE
2293 	 * flag with the last block of forwarded data, which would cause an
2294 	 * additional delay to be observed by the receiver.
2295 	 */
2296 	if (HAS_RSP_DATA_FILTERS(s))
2297 		res->flags |= CF_EXPECT_MORE;
2298 
2299 	/* the stream handler will take care of timeouts and errors */
2300 	DBG_TRACE_DEVEL("waiting for more data to forward",
2301 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA, s, txn);
2302 	return 0;
2303 
2304   return_srv_abort:
2305 	_HA_ATOMIC_INC(&sess->fe->fe_counters.srv_aborts);
2306 	_HA_ATOMIC_INC(&s->be->be_counters.srv_aborts);
2307 	if (sess->listener && sess->listener->counters)
2308 		_HA_ATOMIC_INC(&sess->listener->counters->srv_aborts);
2309 	if (objt_server(s->target))
2310 		_HA_ATOMIC_INC(&__objt_server(s->target)->counters.srv_aborts);
2311 	stream_inc_http_fail_ctr(s);
2312 	if (!(s->flags & SF_ERR_MASK))
2313 		s->flags |= SF_ERR_SRVCL;
2314 	goto return_error;
2315 
2316   return_cli_abort:
2317 	_HA_ATOMIC_INC(&sess->fe->fe_counters.cli_aborts);
2318 	_HA_ATOMIC_INC(&s->be->be_counters.cli_aborts);
2319 	if (sess->listener && sess->listener->counters)
2320 		_HA_ATOMIC_INC(&sess->listener->counters->cli_aborts);
2321 	if (objt_server(s->target))
2322 		_HA_ATOMIC_INC(&__objt_server(s->target)->counters.cli_aborts);
2323 	if (!(s->flags & SF_ERR_MASK))
2324 		s->flags |= SF_ERR_CLICL;
2325 	goto return_error;
2326 
2327   return_int_err:
2328 	_HA_ATOMIC_INC(&sess->fe->fe_counters.internal_errors);
2329 	_HA_ATOMIC_INC(&s->be->be_counters.internal_errors);
2330 	if (sess->listener && sess->listener->counters)
2331 		_HA_ATOMIC_INC(&sess->listener->counters->internal_errors);
2332 	if (objt_server(s->target))
2333 		_HA_ATOMIC_INC(&__objt_server(s->target)->counters.internal_errors);
2334 	if (!(s->flags & SF_ERR_MASK))
2335 		s->flags |= SF_ERR_INTERNAL;
2336 	goto return_error;
2337 
2338   return_bad_res:
2339 	_HA_ATOMIC_INC(&s->be->be_counters.failed_resp);
2340 	if (objt_server(s->target)) {
2341 		_HA_ATOMIC_INC(&__objt_server(s->target)->counters.failed_resp);
2342 		health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2343 	}
2344 	stream_inc_http_fail_ctr(s);
2345 	if (!(s->flags & SF_ERR_MASK))
2346 		s->flags |= SF_ERR_SRVCL;
2347 	/* fall through */
2348 
2349    return_error:
2350 	/* don't send any error message as we're in the body */
2351 	http_reply_and_close(s, txn->status, NULL);
2352 	if (!(s->flags & SF_FINST_MASK))
2353 		s->flags |= SF_FINST_D;
2354 	DBG_TRACE_DEVEL("leaving on error",
2355 			STRM_EV_STRM_ANA|STRM_EV_HTTP_ANA|STRM_EV_HTTP_ERR, s, txn);
2356 	return 0;
2357 }
2358 
2359 /* Perform an HTTP redirect based on the information in <rule>. The function
2360  * returns zero on success, or zero in case of a, irrecoverable error such
2361  * as too large a request to build a valid response.
2362  */
http_apply_redirect_rule(struct redirect_rule * rule,struct stream * s,struct http_txn * txn)2363 int http_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2364 {
2365 	struct channel *req = &s->req;
2366 	struct channel *res = &s->res;
2367 	struct htx *htx;
2368 	struct htx_sl *sl;
2369 	struct buffer *chunk;
2370 	struct ist status, reason, location;
2371 	unsigned int flags;
2372 	int close = 0; /* Try to keep the connection alive byt default */
2373 
2374 	chunk = alloc_trash_chunk();
2375 	if (!chunk) {
2376 		if (!(s->flags & SF_ERR_MASK))
2377 			s->flags |= SF_ERR_RESOURCE;
2378 		goto fail;
2379 	}
2380 
2381 	/*
2382 	 * Create the location
2383 	 */
2384 	htx = htxbuf(&req->buf);
2385 	switch(rule->type) {
2386 		case REDIRECT_TYPE_SCHEME: {
2387 			struct http_hdr_ctx ctx;
2388 			struct ist path, host;
2389 
2390 			host = ist("");
2391 			ctx.blk = NULL;
2392 			if (http_find_header(htx, ist("Host"), &ctx, 0))
2393 				host = ctx.value;
2394 
2395 			sl = http_get_stline(htx);
2396 			path = http_get_path(htx_sl_req_uri(sl));
2397 			/* build message using path */
2398 			if (isttest(path)) {
2399 				if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2400 					int qs = 0;
2401 					while (qs < path.len) {
2402 						if (*(path.ptr + qs) == '?') {
2403 							path.len = qs;
2404 							break;
2405 						}
2406 						qs++;
2407 					}
2408 				}
2409 			}
2410 			else
2411 				path = ist("/");
2412 
2413 			if (rule->rdr_str) { /* this is an old "redirect" rule */
2414 				/* add scheme */
2415 				if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2416 					goto fail;
2417 			}
2418 			else {
2419 				/* add scheme with executing log format */
2420 				chunk->data += build_logline(s, chunk->area + chunk->data,
2421 							     chunk->size - chunk->data,
2422 							     &rule->rdr_fmt);
2423 			}
2424 			/* add "://" + host + path */
2425 			if (!chunk_memcat(chunk, "://", 3) ||
2426 			    !chunk_memcat(chunk, host.ptr, host.len) ||
2427 			    !chunk_memcat(chunk, path.ptr, path.len))
2428 				goto fail;
2429 
2430 			/* append a slash at the end of the location if needed and missing */
2431 			if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2432 			    (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2433 				if (chunk->data + 1 >= chunk->size)
2434 					goto fail;
2435 				chunk->area[chunk->data++] = '/';
2436 			}
2437 			break;
2438 		}
2439 
2440 		case REDIRECT_TYPE_PREFIX: {
2441 			struct ist path;
2442 
2443 			sl = http_get_stline(htx);
2444 			path = http_get_path(htx_sl_req_uri(sl));
2445 			/* build message using path */
2446 			if (isttest(path)) {
2447 				if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2448 					int qs = 0;
2449 					while (qs < path.len) {
2450 						if (*(path.ptr + qs) == '?') {
2451 							path.len = qs;
2452 							break;
2453 						}
2454 						qs++;
2455 					}
2456 				}
2457 			}
2458 			else
2459 				path = ist("/");
2460 
2461 			if (rule->rdr_str) { /* this is an old "redirect" rule */
2462 				/* add prefix. Note that if prefix == "/", we don't want to
2463 				 * add anything, otherwise it makes it hard for the user to
2464 				 * configure a self-redirection.
2465 				 */
2466 				if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2467 					if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2468 						goto fail;
2469 				}
2470 			}
2471 			else {
2472 				/* add prefix with executing log format */
2473 				chunk->data += build_logline(s, chunk->area + chunk->data,
2474 							     chunk->size - chunk->data,
2475 							     &rule->rdr_fmt);
2476 			}
2477 
2478 			/* add path */
2479 			if (!chunk_memcat(chunk, path.ptr, path.len))
2480 				goto fail;
2481 
2482 			/* append a slash at the end of the location if needed and missing */
2483 			if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2484 			    (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2485 				if (chunk->data + 1 >= chunk->size)
2486 					goto fail;
2487 				chunk->area[chunk->data++] = '/';
2488 			}
2489 			break;
2490 		}
2491 		case REDIRECT_TYPE_LOCATION:
2492 		default:
2493 			if (rule->rdr_str) { /* this is an old "redirect" rule */
2494 				/* add location */
2495 				if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2496 					goto fail;
2497 			}
2498 			else {
2499 				/* add location with executing log format */
2500 				chunk->data += build_logline(s, chunk->area + chunk->data,
2501 							     chunk->size - chunk->data,
2502 							     &rule->rdr_fmt);
2503 			}
2504 			break;
2505 	}
2506 	location = ist2(chunk->area, chunk->data);
2507 
2508 	/*
2509 	 * Create the 30x response
2510 	 */
2511 	switch (rule->code) {
2512 		case 308:
2513 			status = ist("308");
2514 			reason = ist("Permanent Redirect");
2515 			break;
2516 		case 307:
2517 			status = ist("307");
2518 			reason = ist("Temporary Redirect");
2519 			break;
2520 		case 303:
2521 			status = ist("303");
2522 			reason = ist("See Other");
2523 			break;
2524 		case 301:
2525 			status = ist("301");
2526 			reason = ist("Moved Permanently");
2527 			break;
2528 		case 302:
2529 		default:
2530 			status = ist("302");
2531 			reason = ist("Found");
2532 			break;
2533 	}
2534 
2535 	if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2536 		close = 1;
2537 
2538 	htx = htx_from_buf(&res->buf);
2539 	/* Trim any possible response */
2540 	channel_htx_truncate(&s->res, htx);
2541 	flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2542 	sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2543 	if (!sl)
2544 		goto fail;
2545 	sl->info.res.status = rule->code;
2546 	s->txn->status = rule->code;
2547 
2548 	if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2549 		goto fail;
2550 
2551 	if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
2552 	    !htx_add_header(htx, ist("Location"), location))
2553 		goto fail;
2554 
2555 	if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2556 		if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2557 			goto fail;
2558 	}
2559 
2560 	if (rule->cookie_len) {
2561 		if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2562 			goto fail;
2563 	}
2564 
2565 	if (!htx_add_endof(htx, HTX_BLK_EOH))
2566 		goto fail;
2567 
2568 	htx->flags |= HTX_FL_EOM;
2569 	htx_to_buf(htx, &res->buf);
2570 	if (!http_forward_proxy_resp(s, 1))
2571 		goto fail;
2572 
2573 	if (rule->flags & REDIRECT_FLAG_FROM_REQ) {
2574 		/* let's log the request time */
2575 		s->logs.tv_request = now;
2576 		req->analysers &= AN_REQ_FLT_END;
2577 
2578 		if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
2579 			_HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
2580 	}
2581 
2582 	if (!(s->flags & SF_ERR_MASK))
2583 		s->flags |= SF_ERR_LOCAL;
2584 	if (!(s->flags & SF_FINST_MASK))
2585 		s->flags |= ((rule->flags & REDIRECT_FLAG_FROM_REQ) ? SF_FINST_R : SF_FINST_H);
2586 
2587 	free_trash_chunk(chunk);
2588 	return 1;
2589 
2590   fail:
2591 	/* If an error occurred, remove the incomplete HTTP response from the
2592 	 * buffer */
2593 	channel_htx_truncate(res, htxbuf(&res->buf));
2594 	free_trash_chunk(chunk);
2595 	return 0;
2596 }
2597 
2598 /* Replace all headers matching the name <name>. The header value is replaced if
2599  * it matches the regex <re>. <str> is used for the replacement. If <full> is
2600  * set to 1, the full-line is matched and replaced. Otherwise, comma-separated
2601  * values are evaluated one by one. It returns 0 on success and -1 on error.
2602  */
http_replace_hdrs(struct stream * s,struct htx * htx,struct ist name,const char * str,struct my_regex * re,int full)2603 int http_replace_hdrs(struct stream* s, struct htx *htx, struct ist name,
2604 		     const char *str, struct my_regex *re, int full)
2605 {
2606 	struct http_hdr_ctx ctx;
2607 	struct buffer *output = get_trash_chunk();
2608 
2609 	ctx.blk = NULL;
2610 	while (http_find_header(htx, name, &ctx, full)) {
2611 		if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2612 			continue;
2613 
2614 		output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2615 		if (output->data == -1)
2616 			return -1;
2617 		if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2618 			return -1;
2619 	}
2620 	return 0;
2621 }
2622 
2623 /* This function executes one of the set-{method,path,query,uri} actions. It
2624  * takes the string from the variable 'replace' with length 'len', then modifies
2625  * the relevant part of the request line accordingly. Then it updates various
2626  * pointers to the next elements which were moved, and the total buffer length.
2627  * It finds the action to be performed in p[2], previously filled by function
2628  * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2629  * error, though this can be revisited when this code is finally exploited.
2630  *
2631  * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2632  * query string, 3 to replace uri or 4 to replace the path+query.
2633  *
2634  * In query string case, the mark question '?' must be set at the start of the
2635  * string by the caller, event if the replacement query string is empty.
2636  */
http_req_replace_stline(int action,const char * replace,int len,struct proxy * px,struct stream * s)2637 int http_req_replace_stline(int action, const char *replace, int len,
2638 			    struct proxy *px, struct stream *s)
2639 {
2640 	struct htx *htx = htxbuf(&s->req.buf);
2641 
2642 	switch (action) {
2643 		case 0: // method
2644 			if (!http_replace_req_meth(htx, ist2(replace, len)))
2645 				return -1;
2646 			break;
2647 
2648 		case 1: // path
2649 			if (!http_replace_req_path(htx, ist2(replace, len), 0))
2650 				return -1;
2651 			break;
2652 
2653 		case 2: // query
2654 			if (!http_replace_req_query(htx, ist2(replace, len)))
2655 				return -1;
2656 			break;
2657 
2658 		case 3: // uri
2659 			if (!http_replace_req_uri(htx, ist2(replace, len)))
2660 				return -1;
2661 			break;
2662 
2663 		case 4: // path + query
2664 			if (!http_replace_req_path(htx, ist2(replace, len), 1))
2665 				return -1;
2666 			break;
2667 
2668 		default:
2669 			return -1;
2670 	}
2671 	return 0;
2672 }
2673 
2674 /* This function replace the HTTP status code and the associated message. The
2675  * variable <status> contains the new status code. This function never fails. It
2676  * returns 0 in case of success, -1 in case of internal error.
2677  */
http_res_set_status(unsigned int status,struct ist reason,struct stream * s)2678 int http_res_set_status(unsigned int status, struct ist reason, struct stream *s)
2679 {
2680 	struct htx *htx = htxbuf(&s->res.buf);
2681 	char *res;
2682 
2683 	chunk_reset(&trash);
2684 	res = ultoa_o(status, trash.area, trash.size);
2685 	trash.data = res - trash.area;
2686 
2687 	/* Do we have a custom reason format string? */
2688 	if (!isttest(reason)) {
2689 		const char *str = http_get_reason(status);
2690 		reason = ist(str);
2691 	}
2692 
2693 	if (!http_replace_res_status(htx, ist2(trash.area, trash.data), reason))
2694 		return -1;
2695 	return 0;
2696 }
2697 
2698 /* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2699  * transaction <txn>. Returns the verdict of the first rule that prevents
2700  * further processing of the request (auth, deny, ...), and defaults to
2701  * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2702  * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2703  * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2704  * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2705  * status.
2706  */
http_req_get_intercept_rule(struct proxy * px,struct list * rules,struct stream * s)2707 static enum rule_result http_req_get_intercept_rule(struct proxy *px, struct list *rules,
2708 						    struct stream *s)
2709 {
2710 	struct session *sess = strm_sess(s);
2711 	struct http_txn *txn = s->txn;
2712 	struct act_rule *rule;
2713 	enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2714 	int act_opts = 0;
2715 
2716 	/* If "the current_rule_list" match the executed rule list, we are in
2717 	 * resume condition. If a resume is needed it is always in the action
2718 	 * and never in the ACL or converters. In this case, we initialise the
2719 	 * current rule, and go to the action execution point.
2720 	 */
2721 	if (s->current_rule) {
2722 		rule = s->current_rule;
2723 		s->current_rule = NULL;
2724 		if (s->current_rule_list == rules)
2725 			goto resume_execution;
2726 	}
2727 	s->current_rule_list = rules;
2728 
2729 	/* start the ruleset evaluation in strict mode */
2730 	txn->req.flags &= ~HTTP_MSGF_SOFT_RW;
2731 
2732 	list_for_each_entry(rule, rules, list) {
2733 		/* check optional condition */
2734 		if (rule->cond) {
2735 			int ret;
2736 
2737 			ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2738 			ret = acl_pass(ret);
2739 
2740 			if (rule->cond->pol == ACL_COND_UNLESS)
2741 				ret = !ret;
2742 
2743 			if (!ret) /* condition not matched */
2744 				continue;
2745 		}
2746 
2747 		act_opts |= ACT_OPT_FIRST;
2748   resume_execution:
2749 		if (rule->kw->flags & KWF_EXPERIMENTAL)
2750 			mark_tainted(TAINTED_ACTION_EXP_EXECUTED);
2751 
2752 		/* Always call the action function if defined */
2753 		if (rule->action_ptr) {
2754 			if ((s->req.flags & CF_READ_ERROR) ||
2755 			    ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
2756 			     (px->options & PR_O_ABRT_CLOSE)))
2757 				act_opts |= ACT_OPT_FINAL;
2758 
2759 			switch (rule->action_ptr(rule, px, sess, s, act_opts)) {
2760 				case ACT_RET_CONT:
2761 					break;
2762 				case ACT_RET_STOP:
2763 					rule_ret = HTTP_RULE_RES_STOP;
2764 					goto end;
2765 				case ACT_RET_YIELD:
2766 					s->current_rule = rule;
2767 					rule_ret = HTTP_RULE_RES_YIELD;
2768 					goto end;
2769 				case ACT_RET_ERR:
2770 					rule_ret = HTTP_RULE_RES_ERROR;
2771 					goto end;
2772 				case ACT_RET_DONE:
2773 					rule_ret = HTTP_RULE_RES_DONE;
2774 					goto end;
2775 				case ACT_RET_DENY:
2776 					if (txn->status == -1)
2777 						txn->status = 403;
2778 					rule_ret = HTTP_RULE_RES_DENY;
2779 					goto end;
2780 				case ACT_RET_ABRT:
2781 					rule_ret = HTTP_RULE_RES_ABRT;
2782 					goto end;
2783 				case ACT_RET_INV:
2784 					rule_ret = HTTP_RULE_RES_BADREQ;
2785 					goto end;
2786 			}
2787 			continue; /* eval the next rule */
2788 		}
2789 
2790 		/* If not action function defined, check for known actions */
2791 		switch (rule->action) {
2792 			case ACT_ACTION_ALLOW:
2793 				rule_ret = HTTP_RULE_RES_STOP;
2794 				goto end;
2795 
2796 			case ACT_ACTION_DENY:
2797 				txn->status = rule->arg.http_reply->status;
2798 				txn->http_reply = rule->arg.http_reply;
2799 				rule_ret = HTTP_RULE_RES_DENY;
2800 				goto end;
2801 
2802 			case ACT_HTTP_REQ_TARPIT:
2803 				txn->flags |= TX_CLTARPIT;
2804 				txn->status = rule->arg.http_reply->status;
2805 				txn->http_reply = rule->arg.http_reply;
2806 				rule_ret = HTTP_RULE_RES_DENY;
2807 				goto end;
2808 
2809 			case ACT_HTTP_REDIR:
2810 				rule_ret = HTTP_RULE_RES_ABRT;
2811 				if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
2812 					rule_ret = HTTP_RULE_RES_ERROR;
2813 				goto end;
2814 
2815 			case ACT_HTTP_SET_NICE:
2816 				s->task->nice = rule->arg.http.i;
2817 				break;
2818 
2819 			case ACT_HTTP_SET_TOS:
2820 				conn_set_tos(objt_conn(sess->origin), rule->arg.http.i);
2821 				break;
2822 
2823 			case ACT_HTTP_SET_MARK:
2824 				conn_set_mark(objt_conn(sess->origin), rule->arg.http.i);
2825 				break;
2826 
2827 			case ACT_HTTP_SET_LOGL:
2828 				s->logs.level = rule->arg.http.i;
2829 				break;
2830 
2831 			/* other flags exists, but normally, they never be matched. */
2832 			default:
2833 				break;
2834 		}
2835 	}
2836 
2837   end:
2838 	/* if the ruleset evaluation is finished reset the strict mode */
2839 	if (rule_ret != HTTP_RULE_RES_YIELD)
2840 		txn->req.flags &= ~HTTP_MSGF_SOFT_RW;
2841 
2842 	/* we reached the end of the rules, nothing to report */
2843 	return rule_ret;
2844 }
2845 
2846 /* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
2847  * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
2848  * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
2849  * is returned, the process can continue the evaluation of next rule list. If
2850  * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
2851  * is returned, it means the operation could not be processed and a server error
2852  * must be returned. If *YIELD is returned, the caller must call again the
2853  * function with the same context.
2854  */
http_res_get_intercept_rule(struct proxy * px,struct list * rules,struct stream * s)2855 static enum rule_result http_res_get_intercept_rule(struct proxy *px, struct list *rules,
2856 						    struct stream *s)
2857 {
2858 	struct session *sess = strm_sess(s);
2859 	struct http_txn *txn = s->txn;
2860 	struct act_rule *rule;
2861 	enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2862 	int act_opts = 0;
2863 
2864 	/* If "the current_rule_list" match the executed rule list, we are in
2865 	 * resume condition. If a resume is needed it is always in the action
2866 	 * and never in the ACL or converters. In this case, we initialise the
2867 	 * current rule, and go to the action execution point.
2868 	 */
2869 	if (s->current_rule) {
2870 		rule = s->current_rule;
2871 		s->current_rule = NULL;
2872 		if (s->current_rule_list == rules)
2873 			goto resume_execution;
2874 	}
2875 	s->current_rule_list = rules;
2876 
2877 	/* start the ruleset evaluation in strict mode */
2878 	txn->rsp.flags &= ~HTTP_MSGF_SOFT_RW;
2879 
2880 	list_for_each_entry(rule, rules, list) {
2881 		/* check optional condition */
2882 		if (rule->cond) {
2883 			int ret;
2884 
2885 			ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
2886 			ret = acl_pass(ret);
2887 
2888 			if (rule->cond->pol == ACL_COND_UNLESS)
2889 				ret = !ret;
2890 
2891 			if (!ret) /* condition not matched */
2892 				continue;
2893 		}
2894 
2895 		act_opts |= ACT_OPT_FIRST;
2896 resume_execution:
2897 		if (rule->kw->flags & KWF_EXPERIMENTAL)
2898 			mark_tainted(TAINTED_ACTION_EXP_EXECUTED);
2899 
2900 		/* Always call the action function if defined */
2901 		if (rule->action_ptr) {
2902 			if ((s->req.flags & CF_READ_ERROR) ||
2903 			    ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
2904 			     (px->options & PR_O_ABRT_CLOSE)))
2905 				act_opts |= ACT_OPT_FINAL;
2906 
2907 			switch (rule->action_ptr(rule, px, sess, s, act_opts)) {
2908 				case ACT_RET_CONT:
2909 					break;
2910 				case ACT_RET_STOP:
2911 					rule_ret = HTTP_RULE_RES_STOP;
2912 					goto end;
2913 				case ACT_RET_YIELD:
2914 					s->current_rule = rule;
2915 					rule_ret = HTTP_RULE_RES_YIELD;
2916 					goto end;
2917 				case ACT_RET_ERR:
2918 					rule_ret = HTTP_RULE_RES_ERROR;
2919 					goto end;
2920 				case ACT_RET_DONE:
2921 					rule_ret = HTTP_RULE_RES_DONE;
2922 					goto end;
2923 				case ACT_RET_DENY:
2924 					if (txn->status == -1)
2925 						txn->status = 502;
2926 					rule_ret = HTTP_RULE_RES_DENY;
2927 					goto end;
2928 				case ACT_RET_ABRT:
2929 					rule_ret = HTTP_RULE_RES_ABRT;
2930 					goto end;
2931 				case ACT_RET_INV:
2932 					rule_ret = HTTP_RULE_RES_BADREQ;
2933 					goto end;
2934 			}
2935 			continue; /* eval the next rule */
2936 		}
2937 
2938 		/* If not action function defined, check for known actions */
2939 		switch (rule->action) {
2940 			case ACT_ACTION_ALLOW:
2941 				rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
2942 				goto end;
2943 
2944 			case ACT_ACTION_DENY:
2945 				txn->status = rule->arg.http_reply->status;
2946 				txn->http_reply = rule->arg.http_reply;
2947 				rule_ret = HTTP_RULE_RES_DENY;
2948 				goto end;
2949 
2950 			case ACT_HTTP_SET_NICE:
2951 				s->task->nice = rule->arg.http.i;
2952 				break;
2953 
2954 			case ACT_HTTP_SET_TOS:
2955 				conn_set_tos(objt_conn(sess->origin), rule->arg.http.i);
2956 				break;
2957 
2958 			case ACT_HTTP_SET_MARK:
2959 				conn_set_mark(objt_conn(sess->origin), rule->arg.http.i);
2960 				break;
2961 
2962 			case ACT_HTTP_SET_LOGL:
2963 				s->logs.level = rule->arg.http.i;
2964 				break;
2965 
2966 			case ACT_HTTP_REDIR:
2967 				rule_ret = HTTP_RULE_RES_ABRT;
2968 				if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
2969 					rule_ret = HTTP_RULE_RES_ERROR;
2970 				goto end;
2971 
2972 			/* other flags exists, but normally, they never be matched. */
2973 			default:
2974 				break;
2975 		}
2976 	}
2977 
2978   end:
2979 	/* if the ruleset evaluation is finished reset the strict mode */
2980 	if (rule_ret != HTTP_RULE_RES_YIELD)
2981 		txn->rsp.flags &= ~HTTP_MSGF_SOFT_RW;
2982 
2983 	/* we reached the end of the rules, nothing to report */
2984 	return rule_ret;
2985 }
2986 
2987 /* Executes backend and frontend http-after-response rules for the stream <s>,
2988  * in that order. it return 1 on success and 0 on error. It is the caller
2989  * responsibility to catch error or ignore it. If it catches it, this function
2990  * may be called a second time, for the internal error.
2991  */
http_eval_after_res_rules(struct stream * s)2992 int http_eval_after_res_rules(struct stream *s)
2993 {
2994 	struct session *sess = s->sess;
2995 	enum rule_result ret = HTTP_RULE_RES_CONT;
2996 
2997 	/* Eval after-response ruleset only if the reply is not const */
2998 	if (s->txn->flags & TX_CONST_REPLY)
2999 		goto end;
3000 
3001 	/* prune the request variables if not already done and swap to the response variables. */
3002 	if (s->vars_reqres.scope != SCOPE_RES) {
3003 		if (!LIST_ISEMPTY(&s->vars_reqres.head))
3004 			vars_prune(&s->vars_reqres, s->sess, s);
3005 		vars_init(&s->vars_reqres, SCOPE_RES);
3006 	}
3007 
3008 	ret = http_res_get_intercept_rule(s->be, &s->be->http_after_res_rules, s);
3009 	if ((ret == HTTP_RULE_RES_CONT || ret == HTTP_RULE_RES_STOP) && sess->fe != s->be)
3010 		ret = http_res_get_intercept_rule(sess->fe, &sess->fe->http_after_res_rules, s);
3011 
3012   end:
3013 	/* All other codes than CONTINUE, STOP or DONE are forbidden */
3014 	return (ret == HTTP_RULE_RES_CONT || ret == HTTP_RULE_RES_STOP || ret == HTTP_RULE_RES_DONE);
3015 }
3016 
3017 /*
3018  * Manage client-side cookie. It can impact performance by about 2% so it is
3019  * desirable to call it only when needed. This code is quite complex because
3020  * of the multiple very crappy and ambiguous syntaxes we have to support. it
3021  * highly recommended not to touch this part without a good reason !
3022  */
http_manage_client_side_cookies(struct stream * s,struct channel * req)3023 static void http_manage_client_side_cookies(struct stream *s, struct channel *req)
3024 {
3025 	struct session *sess = s->sess;
3026 	struct http_txn *txn = s->txn;
3027 	struct htx *htx;
3028 	struct http_hdr_ctx ctx;
3029 	char *hdr_beg, *hdr_end, *del_from;
3030 	char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3031 	int preserve_hdr;
3032 
3033 	htx = htxbuf(&req->buf);
3034 	ctx.blk = NULL;
3035 	while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3036 		int is_first = 1;
3037 		del_from = NULL;  /* nothing to be deleted */
3038 		preserve_hdr = 0; /* assume we may kill the whole header */
3039 
3040 		/* Now look for cookies. Conforming to RFC2109, we have to support
3041 		 * attributes whose name begin with a '$', and associate them with
3042 		 * the right cookie, if we want to delete this cookie.
3043 		 * So there are 3 cases for each cookie read :
3044 		 * 1) it's a special attribute, beginning with a '$' : ignore it.
3045 		 * 2) it's a server id cookie that we *MAY* want to delete : save
3046 		 *    some pointers on it (last semi-colon, beginning of cookie...)
3047 		 * 3) it's an application cookie : we *MAY* have to delete a previous
3048 		 *    "special" cookie.
3049 		 * At the end of loop, if a "special" cookie remains, we may have to
3050 		 * remove it. If no application cookie persists in the header, we
3051 		 * *MUST* delete it.
3052 		 *
3053 		 * Note: RFC2965 is unclear about the processing of spaces around
3054 		 * the equal sign in the ATTR=VALUE form. A careful inspection of
3055 		 * the RFC explicitly allows spaces before it, and not within the
3056 		 * tokens (attrs or values). An inspection of RFC2109 allows that
3057 		 * too but section 10.1.3 lets one think that spaces may be allowed
3058 		 * after the equal sign too, resulting in some (rare) buggy
3059 		 * implementations trying to do that. So let's do what servers do.
3060 		 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3061 		 * allowed quoted strings in values, with any possible character
3062 		 * after a backslash, including control chars and delimiters, which
3063 		 * causes parsing to become ambiguous. Browsers also allow spaces
3064 		 * within values even without quotes.
3065 		 *
3066 		 * We have to keep multiple pointers in order to support cookie
3067 		 * removal at the beginning, middle or end of header without
3068 		 * corrupting the header. All of these headers are valid :
3069 		 *
3070 		 * hdr_beg                                               hdr_end
3071 		 * |                                                        |
3072 		 * v                                                        |
3073 		 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3                   |
3074 		 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3                    v
3075 		 *      NAME1  =  VALUE 1  ; NAME2 = VALUE2 ; NAME3 = VALUE3
3076 		 * |    |    | |  |      | |
3077 		 * |    |    | |  |      | |
3078 		 * |    |    | |  |      | +--> next
3079 		 * |    |    | |  |      +----> val_end
3080 		 * |    |    | |  +-----------> val_beg
3081 		 * |    |    | +--------------> equal
3082 		 * |    |    +----------------> att_end
3083 		 * |    +---------------------> att_beg
3084 		 * +--------------------------> prev
3085 		 *
3086 		 */
3087 		hdr_beg = ctx.value.ptr;
3088 		hdr_end = hdr_beg + ctx.value.len;
3089 		for (prev = hdr_beg; prev < hdr_end; prev = next) {
3090 			/* Iterate through all cookies on this line */
3091 
3092 			/* find att_beg */
3093 			att_beg = prev;
3094 			if (!is_first)
3095 				att_beg++;
3096 			is_first = 0;
3097 
3098 			while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3099 				att_beg++;
3100 
3101 			/* find att_end : this is the first character after the last non
3102 			 * space before the equal. It may be equal to hdr_end.
3103 			 */
3104 			equal = att_end = att_beg;
3105 			while (equal < hdr_end) {
3106 				if (*equal == '=' || *equal == ',' || *equal == ';')
3107 					break;
3108 				if (HTTP_IS_SPHT(*equal++))
3109 					continue;
3110 				att_end = equal;
3111 			}
3112 
3113 			/* here, <equal> points to '=', a delimiter or the end. <att_end>
3114 			 * is between <att_beg> and <equal>, both may be identical.
3115 			 */
3116 			/* look for end of cookie if there is an equal sign */
3117 			if (equal < hdr_end && *equal == '=') {
3118 				/* look for the beginning of the value */
3119 				val_beg = equal + 1;
3120 				while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3121 					val_beg++;
3122 
3123 				/* find the end of the value, respecting quotes */
3124 				next = http_find_cookie_value_end(val_beg, hdr_end);
3125 
3126 				/* make val_end point to the first white space or delimiter after the value */
3127 				val_end = next;
3128 				while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3129 					val_end--;
3130 			}
3131 			else
3132 				val_beg = val_end = next = equal;
3133 
3134 			/* We have nothing to do with attributes beginning with
3135 			 * '$'. However, they will automatically be removed if a
3136 			 * header before them is removed, since they're supposed
3137 			 * to be linked together.
3138 			 */
3139 			if (*att_beg == '$')
3140 				continue;
3141 
3142 			/* Ignore cookies with no equal sign */
3143 			if (equal == next) {
3144 				/* This is not our cookie, so we must preserve it. But if we already
3145 				 * scheduled another cookie for removal, we cannot remove the
3146 				 * complete header, but we can remove the previous block itself.
3147 				 */
3148 				preserve_hdr = 1;
3149 				if (del_from != NULL) {
3150 					int delta = http_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
3151 					val_end  += delta;
3152 					next     += delta;
3153 					hdr_end  += delta;
3154 					prev     = del_from;
3155 					del_from = NULL;
3156 				}
3157 				continue;
3158 			}
3159 
3160 			/* if there are spaces around the equal sign, we need to
3161 			 * strip them otherwise we'll get trouble for cookie captures,
3162 			 * or even for rewrites. Since this happens extremely rarely,
3163 			 * it does not hurt performance.
3164 			 */
3165 			if (unlikely(att_end != equal || val_beg > equal + 1)) {
3166 				int stripped_before = 0;
3167 				int stripped_after = 0;
3168 
3169 				if (att_end != equal) {
3170 					memmove(att_end, equal, hdr_end - equal);
3171 					stripped_before = (att_end - equal);
3172 					equal   += stripped_before;
3173 					val_beg += stripped_before;
3174 				}
3175 
3176 				if (val_beg > equal + 1) {
3177 					memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
3178 					stripped_after = (equal + 1) - val_beg;
3179 					val_beg += stripped_after;
3180 					stripped_before += stripped_after;
3181 				}
3182 
3183 				val_end      += stripped_before;
3184 				next         += stripped_before;
3185 				hdr_end      += stripped_before;
3186 			}
3187 			/* now everything is as on the diagram above */
3188 
3189 			/* First, let's see if we want to capture this cookie. We check
3190 			 * that we don't already have a client side cookie, because we
3191 			 * can only capture one. Also as an optimisation, we ignore
3192 			 * cookies shorter than the declared name.
3193 			 */
3194 			if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
3195 			    (val_end - att_beg >= sess->fe->capture_namelen) &&
3196 			    memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
3197 				int log_len = val_end - att_beg;
3198 
3199 				if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
3200 					ha_alert("HTTP logging : out of memory.\n");
3201 				} else {
3202 					if (log_len > sess->fe->capture_len)
3203 						log_len = sess->fe->capture_len;
3204 					memcpy(txn->cli_cookie, att_beg, log_len);
3205 					txn->cli_cookie[log_len] = 0;
3206 				}
3207 			}
3208 
3209 			/* Persistence cookies in passive, rewrite or insert mode have the
3210 			 * following form :
3211 			 *
3212 			 *    Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
3213 			 *
3214 			 * For cookies in prefix mode, the form is :
3215 			 *
3216 			 *    Cookie: NAME=SRV~VALUE
3217 			 */
3218 			if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
3219 			    (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
3220 				struct server *srv = s->be->srv;
3221 				char *delim;
3222 
3223 				/* if we're in cookie prefix mode, we'll search the delimiter so that we
3224 				 * have the server ID between val_beg and delim, and the original cookie between
3225 				 * delim+1 and val_end. Otherwise, delim==val_end :
3226 				 *
3227 				 * hdr_beg
3228 				 * |
3229 				 * v
3230 				 * NAME=SRV;          # in all but prefix modes
3231 				 * NAME=SRV~OPAQUE ;  # in prefix mode
3232 				 * ||   ||  |      |+-> next
3233 				 * ||   ||  |      +--> val_end
3234 				 * ||   ||  +---------> delim
3235 				 * ||   |+------------> val_beg
3236 				 * ||   +-------------> att_end = equal
3237 				 * |+-----------------> att_beg
3238 				 * +------------------> prev
3239 				 *
3240 				 */
3241 				if (s->be->ck_opts & PR_CK_PFX) {
3242 					for (delim = val_beg; delim < val_end; delim++)
3243 						if (*delim == COOKIE_DELIM)
3244 							break;
3245 				}
3246 				else {
3247 					char *vbar1;
3248 					delim = val_end;
3249 					/* Now check if the cookie contains a date field, which would
3250 					 * appear after a vertical bar ('|') just after the server name
3251 					 * and before the delimiter.
3252 					 */
3253 					vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
3254 					if (vbar1) {
3255 						/* OK, so left of the bar is the server's cookie and
3256 						 * right is the last seen date. It is a base64 encoded
3257 						 * 30-bit value representing the UNIX date since the
3258 						 * epoch in 4-second quantities.
3259 						 */
3260 						int val;
3261 						delim = vbar1++;
3262 						if (val_end - vbar1 >= 5) {
3263 							val = b64tos30(vbar1);
3264 							if (val > 0)
3265 								txn->cookie_last_date = val << 2;
3266 						}
3267 						/* look for a second vertical bar */
3268 						vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
3269 						if (vbar1 && (val_end - vbar1 > 5)) {
3270 							val = b64tos30(vbar1 + 1);
3271 							if (val > 0)
3272 								txn->cookie_first_date = val << 2;
3273 						}
3274 					}
3275 				}
3276 
3277 				/* if the cookie has an expiration date and the proxy wants to check
3278 				 * it, then we do that now. We first check if the cookie is too old,
3279 				 * then only if it has expired. We detect strict overflow because the
3280 				 * time resolution here is not great (4 seconds). Cookies with dates
3281 				 * in the future are ignored if their offset is beyond one day. This
3282 				 * allows an admin to fix timezone issues without expiring everyone
3283 				 * and at the same time avoids keeping unwanted side effects for too
3284 				 * long.
3285 				 */
3286 				if (txn->cookie_first_date && s->be->cookie_maxlife &&
3287 				    (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
3288 				     ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
3289 					txn->flags &= ~TX_CK_MASK;
3290 					txn->flags |= TX_CK_OLD;
3291 					delim = val_beg; // let's pretend we have not found the cookie
3292 					txn->cookie_first_date = 0;
3293 					txn->cookie_last_date = 0;
3294 				}
3295 				else if (txn->cookie_last_date && s->be->cookie_maxidle &&
3296 					 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
3297 					  ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
3298 					txn->flags &= ~TX_CK_MASK;
3299 					txn->flags |= TX_CK_EXPIRED;
3300 					delim = val_beg; // let's pretend we have not found the cookie
3301 					txn->cookie_first_date = 0;
3302 					txn->cookie_last_date = 0;
3303 				}
3304 
3305 				/* Here, we'll look for the first running server which supports the cookie.
3306 				 * This allows to share a same cookie between several servers, for example
3307 				 * to dedicate backup servers to specific servers only.
3308 				 * However, to prevent clients from sticking to cookie-less backup server
3309 				 * when they have incidentely learned an empty cookie, we simply ignore
3310 				 * empty cookies and mark them as invalid.
3311 				 * The same behaviour is applied when persistence must be ignored.
3312 				 */
3313 				if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
3314 					srv = NULL;
3315 
3316 				while (srv) {
3317 					if (srv->cookie && (srv->cklen == delim - val_beg) &&
3318 					    !memcmp(val_beg, srv->cookie, delim - val_beg)) {
3319 						if ((srv->cur_state != SRV_ST_STOPPED) ||
3320 						    (s->be->options & PR_O_PERSIST) ||
3321 						    (s->flags & SF_FORCE_PRST)) {
3322 							/* we found the server and we can use it */
3323 							txn->flags &= ~TX_CK_MASK;
3324 							txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
3325 							s->flags |= SF_DIRECT | SF_ASSIGNED;
3326 							s->target = &srv->obj_type;
3327 							break;
3328 						} else {
3329 							/* we found a server, but it's down,
3330 							 * mark it as such and go on in case
3331 							 * another one is available.
3332 							 */
3333 							txn->flags &= ~TX_CK_MASK;
3334 							txn->flags |= TX_CK_DOWN;
3335 						}
3336 					}
3337 					srv = srv->next;
3338 				}
3339 
3340 				if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
3341 					/* no server matched this cookie or we deliberately skipped it */
3342 					txn->flags &= ~TX_CK_MASK;
3343 					if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
3344 						txn->flags |= TX_CK_UNUSED;
3345 					else
3346 						txn->flags |= TX_CK_INVALID;
3347 				}
3348 
3349 				/* depending on the cookie mode, we may have to either :
3350 				 * - delete the complete cookie if we're in insert+indirect mode, so that
3351 				 *   the server never sees it ;
3352 				 * - remove the server id from the cookie value, and tag the cookie as an
3353 				 *   application cookie so that it does not get accidentally removed later,
3354 				 *   if we're in cookie prefix mode
3355 				 */
3356 				if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
3357 					int delta; /* negative */
3358 
3359 					memmove(val_beg, delim + 1, hdr_end - (delim + 1));
3360 					delta = val_beg - (delim + 1);
3361 					val_end  += delta;
3362 					next     += delta;
3363 					hdr_end  += delta;
3364 					del_from = NULL;
3365 					preserve_hdr = 1; /* we want to keep this cookie */
3366 				}
3367 				else if (del_from == NULL &&
3368 					 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
3369 					del_from = prev;
3370 				}
3371 			}
3372 			else {
3373 				/* This is not our cookie, so we must preserve it. But if we already
3374 				 * scheduled another cookie for removal, we cannot remove the
3375 				 * complete header, but we can remove the previous block itself.
3376 				 */
3377 				preserve_hdr = 1;
3378 
3379 				if (del_from != NULL) {
3380 					int delta = http_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
3381 					if (att_beg >= del_from)
3382 						att_beg += delta;
3383 					if (att_end >= del_from)
3384 						att_end += delta;
3385 					val_beg  += delta;
3386 					val_end  += delta;
3387 					next     += delta;
3388 					hdr_end  += delta;
3389 					prev     = del_from;
3390 					del_from = NULL;
3391 				}
3392 			}
3393 
3394 		} /* for each cookie */
3395 
3396 
3397 		/* There are no more cookies on this line.
3398 		 * We may still have one (or several) marked for deletion at the
3399 		 * end of the line. We must do this now in two ways :
3400 		 *  - if some cookies must be preserved, we only delete from the
3401 		 *    mark to the end of line ;
3402 		 *  - if nothing needs to be preserved, simply delete the whole header
3403 		 */
3404 		if (del_from) {
3405 			hdr_end = (preserve_hdr ? del_from : hdr_beg);
3406 		}
3407 		if ((hdr_end - hdr_beg) != ctx.value.len) {
3408 			if (hdr_beg != hdr_end)
3409 				htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
3410 			else
3411 				http_remove_header(htx, &ctx);
3412 		}
3413 	} /* for each "Cookie header */
3414 }
3415 
3416 /*
3417  * Manage server-side cookies. It can impact performance by about 2% so it is
3418  * desirable to call it only when needed. This function is also used when we
3419  * just need to know if there is a cookie (eg: for check-cache).
3420  */
http_manage_server_side_cookies(struct stream * s,struct channel * res)3421 static void http_manage_server_side_cookies(struct stream *s, struct channel *res)
3422 {
3423 	struct session *sess = s->sess;
3424 	struct http_txn *txn = s->txn;
3425 	struct htx *htx;
3426 	struct http_hdr_ctx ctx;
3427 	struct server *srv;
3428 	char *hdr_beg, *hdr_end;
3429 	char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3430 	int is_cookie2 = 0;
3431 
3432 	htx = htxbuf(&res->buf);
3433 
3434 	ctx.blk = NULL;
3435 	while (1) {
3436 		int is_first = 1;
3437 
3438 		if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
3439 			if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
3440 				break;
3441 			is_cookie2 = 1;
3442 		}
3443 
3444 		/* OK, right now we know we have a Set-Cookie* at hdr_beg, and
3445 		 * <prev> points to the colon.
3446 		 */
3447 		txn->flags |= TX_SCK_PRESENT;
3448 
3449 		/* Maybe we only wanted to see if there was a Set-Cookie (eg:
3450 		 * check-cache is enabled) and we are not interested in checking
3451 		 * them. Warning, the cookie capture is declared in the frontend.
3452 		 */
3453 		if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
3454 			break;
3455 
3456 		/* OK so now we know we have to process this response cookie.
3457 		 * The format of the Set-Cookie header is slightly different
3458 		 * from the format of the Cookie header in that it does not
3459 		 * support the comma as a cookie delimiter (thus the header
3460 		 * cannot be folded) because the Expires attribute described in
3461 		 * the original Netscape's spec may contain an unquoted date
3462 		 * with a comma inside. We have to live with this because
3463 		 * many browsers don't support Max-Age and some browsers don't
3464 		 * support quoted strings. However the Set-Cookie2 header is
3465 		 * clean.
3466 		 *
3467 		 * We have to keep multiple pointers in order to support cookie
3468 		 * removal at the beginning, middle or end of header without
3469 		 * corrupting the header (in case of set-cookie2). A special
3470 		 * pointer, <scav> points to the beginning of the set-cookie-av
3471 		 * fields after the first semi-colon. The <next> pointer points
3472 		 * either to the end of line (set-cookie) or next unquoted comma
3473 		 * (set-cookie2). All of these headers are valid :
3474 		 *
3475 		 * hdr_beg                                                  hdr_end
3476 		 * |                                                           |
3477 		 * v                                                           |
3478 		 * NAME1  =  VALUE 1  ; Secure; Path="/"                       |
3479 		 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT   v
3480 		 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
3481 		 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
3482 		 * | |   | | |     | |          |
3483 		 * | |   | | |     | |          +-> next
3484 		 * | |   | | |     | +------------> scav
3485 		 * | |   | | |     +--------------> val_end
3486 		 * | |   | | +--------------------> val_beg
3487 		 * | |   | +----------------------> equal
3488 		 * | |   +------------------------> att_end
3489 		 * | +----------------------------> att_beg
3490 		 * +------------------------------> prev
3491 		 * -------------------------------> hdr_beg
3492 		 */
3493 		hdr_beg = ctx.value.ptr;
3494 		hdr_end = hdr_beg + ctx.value.len;
3495 		for (prev = hdr_beg; prev < hdr_end; prev = next) {
3496 
3497 			/* Iterate through all cookies on this line */
3498 
3499 			/* find att_beg */
3500 			att_beg = prev;
3501 			if (!is_first)
3502 				att_beg++;
3503 			is_first = 0;
3504 
3505 			while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3506 				att_beg++;
3507 
3508 			/* find att_end : this is the first character after the last non
3509 			 * space before the equal. It may be equal to hdr_end.
3510 			 */
3511 			equal = att_end = att_beg;
3512 
3513 			while (equal < hdr_end) {
3514 				if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
3515 					break;
3516 				if (HTTP_IS_SPHT(*equal++))
3517 					continue;
3518 				att_end = equal;
3519 			}
3520 
3521 			/* here, <equal> points to '=', a delimiter or the end. <att_end>
3522 			 * is between <att_beg> and <equal>, both may be identical.
3523 			 */
3524 
3525 			/* look for end of cookie if there is an equal sign */
3526 			if (equal < hdr_end && *equal == '=') {
3527 				/* look for the beginning of the value */
3528 				val_beg = equal + 1;
3529 				while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3530 					val_beg++;
3531 
3532 				/* find the end of the value, respecting quotes */
3533 				next = http_find_cookie_value_end(val_beg, hdr_end);
3534 
3535 				/* make val_end point to the first white space or delimiter after the value */
3536 				val_end = next;
3537 				while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3538 					val_end--;
3539 			}
3540 			else {
3541 				/* <equal> points to next comma, semi-colon or EOL */
3542 				val_beg = val_end = next = equal;
3543 			}
3544 
3545 			if (next < hdr_end) {
3546 				/* Set-Cookie2 supports multiple cookies, and <next> points to
3547 				 * a colon or semi-colon before the end. So skip all attr-value
3548 				 * pairs and look for the next comma. For Set-Cookie, since
3549 				 * commas are permitted in values, skip to the end.
3550 				 */
3551 				if (is_cookie2)
3552 					next = http_find_hdr_value_end(next, hdr_end);
3553 				else
3554 					next = hdr_end;
3555 			}
3556 
3557 			/* Now everything is as on the diagram above */
3558 
3559 			/* Ignore cookies with no equal sign */
3560 			if (equal == val_end)
3561 				continue;
3562 
3563 			/* If there are spaces around the equal sign, we need to
3564 			 * strip them otherwise we'll get trouble for cookie captures,
3565 			 * or even for rewrites. Since this happens extremely rarely,
3566 			 * it does not hurt performance.
3567 			 */
3568 			if (unlikely(att_end != equal || val_beg > equal + 1)) {
3569 				int stripped_before = 0;
3570 				int stripped_after = 0;
3571 
3572 				if (att_end != equal) {
3573 					memmove(att_end, equal, hdr_end - equal);
3574 					stripped_before = (att_end - equal);
3575 					equal   += stripped_before;
3576 					val_beg += stripped_before;
3577 				}
3578 
3579 				if (val_beg > equal + 1) {
3580 					memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
3581 					stripped_after = (equal + 1) - val_beg;
3582 					val_beg += stripped_after;
3583 					stripped_before += stripped_after;
3584 				}
3585 
3586 				val_end      += stripped_before;
3587 				next         += stripped_before;
3588 				hdr_end      += stripped_before;
3589 
3590 				htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
3591 				ctx.value.len = hdr_end - hdr_beg;
3592 			}
3593 
3594 			/* First, let's see if we want to capture this cookie. We check
3595 			 * that we don't already have a server side cookie, because we
3596 			 * can only capture one. Also as an optimisation, we ignore
3597 			 * cookies shorter than the declared name.
3598 			 */
3599 			if (sess->fe->capture_name != NULL &&
3600 			    txn->srv_cookie == NULL &&
3601 			    (val_end - att_beg >= sess->fe->capture_namelen) &&
3602 			    memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
3603 				int log_len = val_end - att_beg;
3604 				if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
3605 					ha_alert("HTTP logging : out of memory.\n");
3606 				}
3607 				else {
3608 					if (log_len > sess->fe->capture_len)
3609 						log_len = sess->fe->capture_len;
3610 					memcpy(txn->srv_cookie, att_beg, log_len);
3611 					txn->srv_cookie[log_len] = 0;
3612 				}
3613 			}
3614 
3615 			srv = objt_server(s->target);
3616 			/* now check if we need to process it for persistence */
3617 			if (!(s->flags & SF_IGNORE_PRST) &&
3618 			    (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
3619 			    (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
3620 				/* assume passive cookie by default */
3621 				txn->flags &= ~TX_SCK_MASK;
3622 				txn->flags |= TX_SCK_FOUND;
3623 
3624 				/* If the cookie is in insert mode on a known server, we'll delete
3625 				 * this occurrence because we'll insert another one later.
3626 				 * We'll delete it too if the "indirect" option is set and we're in
3627 				 * a direct access.
3628 				 */
3629 				if (s->be->ck_opts & PR_CK_PSV) {
3630 					/* The "preserve" flag was set, we don't want to touch the
3631 					 * server's cookie.
3632 					 */
3633 				}
3634 				else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
3635 				    ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
3636 					/* this cookie must be deleted */
3637 					if (prev == hdr_beg && next == hdr_end) {
3638 						/* whole header */
3639 						http_remove_header(htx, &ctx);
3640 						/* note: while both invalid now, <next> and <hdr_end>
3641 						 * are still equal, so the for() will stop as expected.
3642 						 */
3643 					} else {
3644 						/* just remove the value */
3645 						int delta = http_del_hdr_value(hdr_beg, hdr_end, &prev, next);
3646 						next      = prev;
3647 						hdr_end  += delta;
3648 					}
3649 					txn->flags &= ~TX_SCK_MASK;
3650 					txn->flags |= TX_SCK_DELETED;
3651 					/* and go on with next cookie */
3652 				}
3653 				else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
3654 					/* replace bytes val_beg->val_end with the cookie name associated
3655 					 * with this server since we know it.
3656 					 */
3657 					int sliding, delta;
3658 
3659 					ctx.value = ist2(val_beg, val_end - val_beg);
3660 				        ctx.lws_before = ctx.lws_after = 0;
3661 					http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
3662 					delta     = srv->cklen - (val_end - val_beg);
3663 					sliding   = (ctx.value.ptr - val_beg);
3664 					hdr_beg  += sliding;
3665 					val_beg  += sliding;
3666 					next     += sliding + delta;
3667 					hdr_end  += sliding + delta;
3668 
3669 					txn->flags &= ~TX_SCK_MASK;
3670 					txn->flags |= TX_SCK_REPLACED;
3671 				}
3672 				else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
3673 					/* insert the cookie name associated with this server
3674 					 * before existing cookie, and insert a delimiter between them..
3675 					 */
3676 					int sliding, delta;
3677 					ctx.value = ist2(val_beg, 0);
3678 				        ctx.lws_before = ctx.lws_after = 0;
3679 					http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
3680 					delta     = srv->cklen + 1;
3681 					sliding   = (ctx.value.ptr - val_beg);
3682 					hdr_beg  += sliding;
3683 					val_beg  += sliding;
3684 					next     += sliding + delta;
3685 					hdr_end  += sliding + delta;
3686 
3687 					val_beg[srv->cklen] = COOKIE_DELIM;
3688 					txn->flags &= ~TX_SCK_MASK;
3689 					txn->flags |= TX_SCK_REPLACED;
3690 				}
3691 			}
3692 			/* that's done for this cookie, check the next one on the same
3693 			 * line when next != hdr_end (only if is_cookie2).
3694 			 */
3695 		}
3696 	}
3697 }
3698 
3699 /*
3700  * Parses the Cache-Control and Pragma request header fields to determine if
3701  * the request may be served from the cache and/or if it is cacheable. Updates
3702  * s->txn->flags.
3703  */
http_check_request_for_cacheability(struct stream * s,struct channel * req)3704 void http_check_request_for_cacheability(struct stream *s, struct channel *req)
3705 {
3706 	struct http_txn *txn = s->txn;
3707 	struct htx *htx;
3708 	struct http_hdr_ctx ctx = { .blk = NULL };
3709 	int pragma_found, cc_found;
3710 
3711 	if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
3712 		return; /* nothing more to do here */
3713 
3714 	htx = htxbuf(&req->buf);
3715 	pragma_found = cc_found = 0;
3716 
3717 	/* Check "pragma" header for HTTP/1.0 compatibility. */
3718 	if (http_find_header(htx, ist("pragma"), &ctx, 1)) {
3719 		if (isteqi(ctx.value, ist("no-cache"))) {
3720 			pragma_found = 1;
3721 		}
3722 	}
3723 
3724 	ctx.blk = NULL;
3725 	/* Don't use the cache and don't try to store if we found the
3726 	 * Authorization header */
3727 	if (http_find_header(htx, ist("authorization"), &ctx, 1)) {
3728 		txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
3729 		txn->flags |= TX_CACHE_IGNORE;
3730 	}
3731 
3732 
3733 	/* Look for "cache-control" header and iterate over all the values
3734 	 * until we find one that specifies that caching is possible or not. */
3735 	ctx.blk = NULL;
3736 	while (http_find_header(htx, ist("cache-control"), &ctx, 0)) {
3737 		cc_found = 1;
3738 		/* We don't check the values after max-age, max-stale nor min-fresh,
3739 		 * we simply don't use the cache when they're specified. */
3740 		if (istmatchi(ctx.value, ist("max-age")) ||
3741 		    istmatchi(ctx.value, ist("no-cache")) ||
3742 		    istmatchi(ctx.value, ist("max-stale")) ||
3743 		    istmatchi(ctx.value, ist("min-fresh"))) {
3744 			txn->flags |= TX_CACHE_IGNORE;
3745 			continue;
3746 		}
3747 		if (istmatchi(ctx.value, ist("no-store"))) {
3748 			txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
3749 			continue;
3750 		}
3751 	}
3752 
3753 	/* RFC7234#5.4:
3754 	 *   When the Cache-Control header field is also present and
3755 	 *   understood in a request, Pragma is ignored.
3756 	 *   When the Cache-Control header field is not present in a
3757 	 *   request, caches MUST consider the no-cache request
3758 	 *   pragma-directive as having the same effect as if
3759 	 *   "Cache-Control: no-cache" were present.
3760 	 */
3761 	if (!cc_found && pragma_found)
3762 		txn->flags |= TX_CACHE_IGNORE;
3763 }
3764 
3765 /*
3766  * Check if response is cacheable or not. Updates s->txn->flags.
3767  */
http_check_response_for_cacheability(struct stream * s,struct channel * res)3768 void http_check_response_for_cacheability(struct stream *s, struct channel *res)
3769 {
3770 	struct http_txn *txn = s->txn;
3771 	struct http_hdr_ctx ctx = { .blk = NULL };
3772 	struct htx *htx;
3773 	int has_freshness_info = 0;
3774 	int has_validator = 0;
3775 
3776 	if (txn->status < 200) {
3777 		/* do not try to cache interim responses! */
3778 		txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
3779 		return;
3780 	}
3781 
3782 	htx = htxbuf(&res->buf);
3783 	/* Check "pragma" header for HTTP/1.0 compatibility. */
3784 	if (http_find_header(htx, ist("pragma"), &ctx, 1)) {
3785 		if (isteqi(ctx.value, ist("no-cache"))) {
3786 			txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
3787 			return;
3788 		}
3789 	}
3790 
3791 	/* Look for "cache-control" header and iterate over all the values
3792 	 * until we find one that specifies that caching is possible or not. */
3793 	ctx.blk = NULL;
3794 	while (http_find_header(htx, ist("cache-control"), &ctx, 0)) {
3795 		if (isteqi(ctx.value, ist("public"))) {
3796 			txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
3797 			continue;
3798 		}
3799 		if (isteqi(ctx.value, ist("private")) ||
3800 		    isteqi(ctx.value, ist("no-cache")) ||
3801 		    isteqi(ctx.value, ist("no-store")) ||
3802 		    isteqi(ctx.value, ist("max-age=0")) ||
3803 		    isteqi(ctx.value, ist("s-maxage=0"))) {
3804 			txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
3805 			continue;
3806 		}
3807 		/* We might have a no-cache="set-cookie" form. */
3808 		if (istmatchi(ctx.value, ist("no-cache=\"set-cookie"))) {
3809 			txn->flags &= ~TX_CACHE_COOK;
3810 			continue;
3811 		}
3812 
3813 		if (istmatchi(ctx.value, ist("s-maxage")) ||
3814 		    istmatchi(ctx.value, ist("max-age"))) {
3815 			has_freshness_info = 1;
3816 			continue;
3817 		}
3818 	}
3819 
3820 	/* If no freshness information could be found in Cache-Control values,
3821 	 * look for an Expires header. */
3822 	if (!has_freshness_info) {
3823 		ctx.blk = NULL;
3824 		has_freshness_info = http_find_header(htx, ist("expires"), &ctx, 0);
3825 	}
3826 
3827 	/* If no freshness information could be found in Cache-Control or Expires
3828 	 * values, look for an explicit validator. */
3829 	if (!has_freshness_info) {
3830 		ctx.blk = NULL;
3831 		has_validator = 1;
3832 		if (!http_find_header(htx, ist("etag"), &ctx, 0)) {
3833 			ctx.blk = NULL;
3834 			if (!http_find_header(htx, ist("last-modified"), &ctx, 0))
3835 				has_validator = 0;
3836 		}
3837 	}
3838 
3839 	/* We won't store an entry that has neither a cache validator nor an
3840 	 * explicit expiration time, as suggested in RFC 7234#3. */
3841 	if (!has_freshness_info && !has_validator)
3842 		txn->flags |= TX_CACHE_IGNORE;
3843 }
3844 
3845 /*
3846  * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
3847  * for the current backend.
3848  *
3849  * It is assumed that the request is either a HEAD, GET, or POST and that the
3850  * uri_auth field is valid.
3851  *
3852  * Returns 1 if stats should be provided, otherwise 0.
3853  */
http_stats_check_uri(struct stream * s,struct http_txn * txn,struct proxy * backend)3854 static int http_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
3855 {
3856 	struct uri_auth *uri_auth = backend->uri_auth;
3857 	struct htx *htx;
3858 	struct htx_sl *sl;
3859 	struct ist uri;
3860 
3861 	if (!uri_auth)
3862 		return 0;
3863 
3864 	if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
3865 		return 0;
3866 
3867 	htx = htxbuf(&s->req.buf);
3868 	sl = http_get_stline(htx);
3869 	uri = htx_sl_req_uri(sl);
3870 	if (*uri_auth->uri_prefix == '/')
3871 		uri = http_get_path(uri);
3872 
3873 	/* check URI size */
3874 	if (uri_auth->uri_len > uri.len)
3875 		return 0;
3876 
3877 	if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
3878 		return 0;
3879 
3880 	return 1;
3881 }
3882 
3883 /* This function prepares an applet to handle the stats. It can deal with the
3884  * "100-continue" expectation, check that admin rules are met for POST requests,
3885  * and program a response message if something was unexpected. It cannot fail
3886  * and always relies on the stats applet to complete the job. It does not touch
3887  * analysers nor counters, which are left to the caller. It does not touch
3888  * s->target which is supposed to already point to the stats applet. The caller
3889  * is expected to have already assigned an appctx to the stream.
3890  */
http_handle_stats(struct stream * s,struct channel * req)3891 static int http_handle_stats(struct stream *s, struct channel *req)
3892 {
3893 	struct stats_admin_rule *stats_admin_rule;
3894 	struct stream_interface *si = &s->si[1];
3895 	struct session *sess = s->sess;
3896 	struct http_txn *txn = s->txn;
3897 	struct http_msg *msg = &txn->req;
3898 	struct uri_auth *uri_auth = s->be->uri_auth;
3899 	const char *h, *lookup, *end;
3900 	struct appctx *appctx;
3901 	struct htx *htx;
3902 	struct htx_sl *sl;
3903 
3904 	appctx = si_appctx(si);
3905 	memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
3906 	appctx->st1 = appctx->st2 = 0;
3907 	appctx->ctx.stats.st_code = STAT_STATUS_INIT;
3908 	appctx->ctx.stats.flags |= uri_auth->flags;
3909 	appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
3910 	if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
3911 		appctx->ctx.stats.flags |= STAT_CHUNKED;
3912 
3913 	htx = htxbuf(&req->buf);
3914 	sl = http_get_stline(htx);
3915 	lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
3916 	end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
3917 
3918 	for (h = lookup; h <= end - 3; h++) {
3919 		if (memcmp(h, ";up", 3) == 0) {
3920 			appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
3921 			break;
3922 		}
3923 	}
3924 
3925 	for (h = lookup; h <= end - 9; h++) {
3926 		if (memcmp(h, ";no-maint", 9) == 0) {
3927 			appctx->ctx.stats.flags |= STAT_HIDE_MAINT;
3928 			break;
3929 		}
3930 	}
3931 
3932 	if (uri_auth->refresh) {
3933 		for (h = lookup; h <= end - 10; h++) {
3934 			if (memcmp(h, ";norefresh", 10) == 0) {
3935 				appctx->ctx.stats.flags |= STAT_NO_REFRESH;
3936 				break;
3937 			}
3938 		}
3939 	}
3940 
3941 	for (h = lookup; h <= end - 4; h++) {
3942 		if (memcmp(h, ";csv", 4) == 0) {
3943 			appctx->ctx.stats.flags &= ~(STAT_FMT_MASK|STAT_JSON_SCHM);
3944 			break;
3945 		}
3946 	}
3947 
3948 	for (h = lookup; h <= end - 6; h++) {
3949 		if (memcmp(h, ";typed", 6) == 0) {
3950 			appctx->ctx.stats.flags &= ~(STAT_FMT_MASK|STAT_JSON_SCHM);
3951 			appctx->ctx.stats.flags |= STAT_FMT_TYPED;
3952 			break;
3953 		}
3954 	}
3955 
3956 	for (h = lookup; h <= end - 5; h++) {
3957 		if (memcmp(h, ";json", 5) == 0) {
3958 			appctx->ctx.stats.flags &= ~(STAT_FMT_MASK|STAT_JSON_SCHM);
3959 			appctx->ctx.stats.flags |= STAT_FMT_JSON;
3960 			break;
3961 		}
3962 	}
3963 
3964 	for (h = lookup; h <= end - 12; h++) {
3965 		if (memcmp(h, ";json-schema", 12) == 0) {
3966 			appctx->ctx.stats.flags &= ~STAT_FMT_MASK;
3967 			appctx->ctx.stats.flags |= STAT_JSON_SCHM;
3968 			break;
3969 		}
3970 	}
3971 
3972 	for (h = lookup; h <= end - 8; h++) {
3973 		if (memcmp(h, ";st=", 4) == 0) {
3974 			int i;
3975 			h += 4;
3976 			appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
3977 			for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
3978 				if (strncmp(stat_status_codes[i], h, 4) == 0) {
3979 					appctx->ctx.stats.st_code = i;
3980 					break;
3981 				}
3982 			}
3983 			break;
3984 		}
3985 	}
3986 
3987 	appctx->ctx.stats.scope_str = 0;
3988 	appctx->ctx.stats.scope_len = 0;
3989 	for (h = lookup; h <= end - 8; h++) {
3990 		if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
3991 			int itx = 0;
3992 			const char *h2;
3993 			char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
3994 			const char *err;
3995 
3996 			h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
3997 			h2 = h;
3998 			appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
3999 			while (h < end) {
4000 				if (*h == ';' || *h == '&' || *h == ' ')
4001 					break;
4002 				itx++;
4003 				h++;
4004 			}
4005 
4006 			if (itx > STAT_SCOPE_TXT_MAXLEN)
4007 				itx = STAT_SCOPE_TXT_MAXLEN;
4008 			appctx->ctx.stats.scope_len = itx;
4009 
4010 			/* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4011 			memcpy(scope_txt, h2, itx);
4012 			scope_txt[itx] = '\0';
4013 			err = invalid_char(scope_txt);
4014 			if (err) {
4015 				/* bad char in search text => clear scope */
4016 				appctx->ctx.stats.scope_str = 0;
4017 				appctx->ctx.stats.scope_len = 0;
4018 			}
4019 			break;
4020 		}
4021 	}
4022 
4023 	/* now check whether we have some admin rules for this request */
4024 	list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4025 		int ret = 1;
4026 
4027 		if (stats_admin_rule->cond) {
4028 			ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4029 			ret = acl_pass(ret);
4030 			if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4031 				ret = !ret;
4032 		}
4033 
4034 		if (ret) {
4035 			/* no rule, or the rule matches */
4036 			appctx->ctx.stats.flags |= STAT_ADMIN;
4037 			break;
4038 		}
4039 	}
4040 
4041 	if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4042 		appctx->st0 = STAT_HTTP_HEAD;
4043 	else if (txn->meth == HTTP_METH_POST) {
4044 		if (appctx->ctx.stats.flags & STAT_ADMIN) {
4045 			appctx->st0 = STAT_HTTP_POST;
4046 			if (msg->msg_state < HTTP_MSG_DATA)
4047 				req->analysers |= AN_REQ_HTTP_BODY;
4048 		}
4049 		else {
4050 			/* POST without admin level */
4051 			appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4052 			appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4053 			appctx->st0 = STAT_HTTP_LAST;
4054 		}
4055 	}
4056 	else {
4057 		/* Unsupported method */
4058 		appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4059 		appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4060 		appctx->st0 = STAT_HTTP_LAST;
4061 	}
4062 
4063 	s->task->nice = -32; /* small boost for HTTP statistics */
4064 	return 1;
4065 }
4066 
4067 /* This function waits for the message payload at most <time> milliseconds (may
4068  * be set to TICK_ETERNITY). It stops to wait if at least <bytes> bytes of the
4069  * payload are received (0 means no limit). It returns HTTP_RULE_* depending on
4070  * the result:
4071  *
4072  *   - HTTP_RULE_RES_CONT when  conditions are met to stop waiting
4073  *   - HTTP_RULE_RES_YIELD to wait for more data
4074  *   - HTTP_RULE_RES_ABRT when a timeout occurred.
4075  *   - HTTP_RULE_RES_BADREQ if a parsing error is raised by lower level
4076  *   - HTTP_RULE_RES_ERROR if an internal error occurred
4077  *
4078  * If a timeout occurred, this function is responsible to emit the right response
4079  * to the client, depending on the channel (408 on request side, 504 on response
4080  * side). All other errors must be handled by the caller.
4081  */
http_wait_for_msg_body(struct stream * s,struct channel * chn,unsigned int time,unsigned int bytes)4082 enum rule_result http_wait_for_msg_body(struct stream *s, struct channel *chn,
4083 					unsigned int time, unsigned int bytes)
4084 {
4085 	struct session *sess = s->sess;
4086 	struct http_txn *txn = s->txn;
4087 	struct http_msg *msg = ((chn->flags & CF_ISRESP) ? &txn->rsp : &txn->req);
4088 	struct htx *htx;
4089 	enum rule_result ret = HTTP_RULE_RES_CONT;
4090 
4091 	htx = htxbuf(&chn->buf);
4092 
4093 	if (htx->flags & HTX_FL_PARSING_ERROR) {
4094 		ret = HTTP_RULE_RES_BADREQ;
4095 		goto end;
4096 	}
4097 	if (htx->flags & HTX_FL_PROCESSING_ERROR) {
4098 		ret = HTTP_RULE_RES_ERROR;
4099 		goto end;
4100 	}
4101 
4102 	/* Do nothing for bodyless and CONNECT requests */
4103 	if (txn->meth == HTTP_METH_CONNECT || (msg->flags & HTTP_MSGF_BODYLESS))
4104 		goto end;
4105 
4106 	if (!(chn->flags & CF_ISRESP) && msg->msg_state < HTTP_MSG_DATA) {
4107 		if (http_handle_expect_hdr(s, htx, msg) == -1) {
4108 			ret = HTTP_RULE_RES_ERROR;
4109 			goto end;
4110 		}
4111 	}
4112 
4113 	msg->msg_state = HTTP_MSG_DATA;
4114 
4115 	/* Now we're in HTTP_MSG_DATA. We just need to know if all data have
4116 	 * been received or if the buffer is full.
4117 	 */
4118 	if ((htx->flags & HTX_FL_EOM) ||
4119 	    htx_get_tail_type(htx) > HTX_BLK_DATA ||
4120 	    channel_htx_full(chn, htx, global.tune.maxrewrite) ||
4121 	    si_rx_blocked_room(chn_prod(chn)))
4122 		goto end;
4123 
4124 	if (bytes) {
4125 		struct htx_blk *blk;
4126 		unsigned int len = 0;
4127 
4128 		for (blk = htx_get_first_blk(htx); blk; blk = htx_get_next_blk(htx, blk)) {
4129 			if (htx_get_blk_type(blk) != HTX_BLK_DATA)
4130 				continue;
4131 			len += htx_get_blksz(blk);
4132 			if (len >= bytes)
4133 				goto end;
4134 		}
4135 	}
4136 
4137 	if ((chn->flags & CF_READ_TIMEOUT) || tick_is_expired(chn->analyse_exp, now_ms)) {
4138 		if (!(chn->flags & CF_ISRESP))
4139 			goto abort_req;
4140 		goto abort_res;
4141 	}
4142 
4143 	/* we get here if we need to wait for more data */
4144 	if (!(chn->flags & (CF_SHUTR | CF_READ_ERROR))) {
4145 		if (!tick_isset(chn->analyse_exp))
4146 			chn->analyse_exp = tick_add_ifset(now_ms, time);
4147 		ret = HTTP_RULE_RES_YIELD;
4148 	}
4149 
4150   end:
4151 	return ret;
4152 
4153   abort_req:
4154 	txn->status = 408;
4155 	if (!(s->flags & SF_ERR_MASK))
4156 		s->flags |= SF_ERR_CLITO;
4157 	if (!(s->flags & SF_FINST_MASK))
4158 		s->flags |= SF_FINST_D;
4159 	_HA_ATOMIC_INC(&sess->fe->fe_counters.failed_req);
4160 	if (sess->listener && sess->listener->counters)
4161 		_HA_ATOMIC_INC(&sess->listener->counters->failed_req);
4162 	http_reply_and_close(s, txn->status, http_error_message(s));
4163 	ret = HTTP_RULE_RES_ABRT;
4164 	goto end;
4165 
4166   abort_res:
4167 	txn->status = 504;
4168 	if (!(s->flags & SF_ERR_MASK))
4169 		s->flags |= SF_ERR_SRVTO;
4170 	if (!(s->flags & SF_FINST_MASK))
4171 		s->flags |= SF_FINST_D;
4172 	stream_inc_http_fail_ctr(s);
4173 	http_reply_and_close(s, txn->status, http_error_message(s));
4174 	ret = HTTP_RULE_RES_ABRT;
4175 	goto end;
4176 }
4177 
http_perform_server_redirect(struct stream * s,struct stream_interface * si)4178 void http_perform_server_redirect(struct stream *s, struct stream_interface *si)
4179 {
4180 	struct channel *req = &s->req;
4181 	struct channel *res = &s->res;
4182 	struct server *srv;
4183 	struct htx *htx;
4184 	struct htx_sl *sl;
4185 	struct ist path, location;
4186 	unsigned int flags;
4187 
4188 	/*
4189 	 * Create the location
4190 	 */
4191 	chunk_reset(&trash);
4192 
4193 	/* 1: add the server's prefix */
4194 	/* special prefix "/" means don't change URL */
4195 	srv = __objt_server(s->target);
4196 	if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4197 		if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4198 			return;
4199 	}
4200 
4201 	/* 2: add the request Path */
4202 	htx = htxbuf(&req->buf);
4203 	sl = http_get_stline(htx);
4204 	path = http_get_path(htx_sl_req_uri(sl));
4205 	if (!isttest(path))
4206 		return;
4207 
4208 	if (!chunk_memcat(&trash, path.ptr, path.len))
4209 		return;
4210 	location = ist2(trash.area, trash.data);
4211 
4212 	/*
4213 	 * Create the 302 respone
4214 	 */
4215 	htx = htx_from_buf(&res->buf);
4216 	flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4217 	sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4218 			    ist("HTTP/1.1"), ist("302"), ist("Found"));
4219 	if (!sl)
4220 		goto fail;
4221 	sl->info.res.status = 302;
4222 	s->txn->status = 302;
4223 
4224         if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
4225 	    !htx_add_header(htx, ist("Connection"), ist("close")) ||
4226 	    !htx_add_header(htx, ist("Content-length"), ist("0")) ||
4227 	    !htx_add_header(htx, ist("Location"), location))
4228 		goto fail;
4229 
4230 	if (!htx_add_endof(htx, HTX_BLK_EOH))
4231 		goto fail;
4232 
4233 	htx->flags |= HTX_FL_EOM;
4234 	htx_to_buf(htx, &res->buf);
4235 	if (!http_forward_proxy_resp(s, 1))
4236 		goto fail;
4237 
4238 	/* return without error. */
4239 	si_shutr(si);
4240 	si_shutw(si);
4241 	si->err_type = SI_ET_NONE;
4242 	si->state    = SI_ST_CLO;
4243 
4244 	if (!(s->flags & SF_ERR_MASK))
4245 		s->flags |= SF_ERR_LOCAL;
4246 	if (!(s->flags & SF_FINST_MASK))
4247 		s->flags |= SF_FINST_C;
4248 
4249 	/* FIXME: we should increase a counter of redirects per server and per backend. */
4250 	srv_inc_sess_ctr(srv);
4251 	srv_set_sess_last(srv);
4252 	return;
4253 
4254   fail:
4255 	/* If an error occurred, remove the incomplete HTTP response from the
4256 	 * buffer */
4257 	channel_htx_truncate(res, htx);
4258 }
4259 
4260 /* This function terminates the request because it was completely analyzed or
4261  * because an error was triggered during the body forwarding.
4262  */
http_end_request(struct stream * s)4263 static void http_end_request(struct stream *s)
4264 {
4265 	struct channel *chn = &s->req;
4266 	struct http_txn *txn = s->txn;
4267 
4268 	DBG_TRACE_ENTER(STRM_EV_HTTP_ANA, s, txn);
4269 
4270 	if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
4271 		     txn->rsp.msg_state == HTTP_MSG_ERROR)) {
4272 		channel_abort(chn);
4273 		channel_htx_truncate(chn, htxbuf(&chn->buf));
4274 		goto end;
4275 	}
4276 
4277 	if (unlikely(txn->req.msg_state < HTTP_MSG_DONE)) {
4278 		DBG_TRACE_DEVEL("waiting end of the request", STRM_EV_HTTP_ANA, s, txn);
4279 		return;
4280 	}
4281 
4282 	if (txn->req.msg_state == HTTP_MSG_DONE) {
4283 		/* No need to read anymore, the request was completely parsed.
4284 		 * We can shut the read side unless we want to abort_on_close,
4285 		 * or we have a POST request. The issue with POST requests is
4286 		 * that some browsers still send a CRLF after the request, and
4287 		 * this CRLF must be read so that it does not remain in the kernel
4288 		 * buffers, otherwise a close could cause an RST on some systems
4289 		 * (eg: Linux).
4290 		 */
4291 		if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
4292 			channel_dont_read(chn);
4293 
4294 		/* if the server closes the connection, we want to immediately react
4295 		 * and close the socket to save packets and syscalls.
4296 		 */
4297 		s->si[1].flags |= SI_FL_NOHALF;
4298 
4299 		/* In any case we've finished parsing the request so we must
4300 		 * disable Nagle when sending data because 1) we're not going
4301 		 * to shut this side, and 2) the server is waiting for us to
4302 		 * send pending data.
4303 		 */
4304 		chn->flags |= CF_NEVER_WAIT;
4305 
4306 		if (txn->rsp.msg_state < HTTP_MSG_DONE) {
4307 			/* The server has not finished to respond, so we
4308 			 * don't want to move in order not to upset it.
4309 			 */
4310 			DBG_TRACE_DEVEL("waiting end of the response", STRM_EV_HTTP_ANA, s, txn);
4311 			return;
4312 		}
4313 
4314 		/* When we get here, it means that both the request and the
4315 		 * response have finished receiving. Depending on the connection
4316 		 * mode, we'll have to wait for the last bytes to leave in either
4317 		 * direction, and sometimes for a close to be effective.
4318 		 */
4319 		if (txn->flags & TX_CON_WANT_TUN) {
4320 			/* Tunnel mode will not have any analyser so it needs to
4321 			 * poll for reads.
4322 			 */
4323 			channel_auto_read(chn);
4324 			if (b_data(&chn->buf)) {
4325 				DBG_TRACE_DEVEL("waiting to flush the request", STRM_EV_HTTP_ANA, s, txn);
4326 				return;
4327 			}
4328 			txn->req.msg_state = HTTP_MSG_TUNNEL;
4329 		}
4330 		else {
4331 			/* we're not expecting any new data to come for this
4332 			 * transaction, so we can close it.
4333 			 *
4334 			 *  However, there is an exception if the response
4335 			 *  length is undefined. In this case, we need to wait
4336 			 *  the close from the server. The response will be
4337 			 *  switched in TUNNEL mode until the end.
4338 			 */
4339 			if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
4340 			    txn->rsp.msg_state != HTTP_MSG_CLOSED)
4341 				goto check_channel_flags;
4342 
4343 			if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
4344 				channel_shutr_now(chn);
4345 				channel_shutw_now(chn);
4346 			}
4347 		}
4348 		goto check_channel_flags;
4349 	}
4350 
4351 	if (txn->req.msg_state == HTTP_MSG_CLOSING) {
4352 	  http_msg_closing:
4353 		/* nothing else to forward, just waiting for the output buffer
4354 		 * to be empty and for the shutw_now to take effect.
4355 		 */
4356 		if (channel_is_empty(chn)) {
4357 			txn->req.msg_state = HTTP_MSG_CLOSED;
4358 			goto http_msg_closed;
4359 		}
4360 		else if (chn->flags & CF_SHUTW) {
4361 			txn->req.msg_state = HTTP_MSG_ERROR;
4362 			goto end;
4363 		}
4364 		DBG_TRACE_LEAVE(STRM_EV_HTTP_ANA, s, txn);
4365 		return;
4366 	}
4367 
4368 	if (txn->req.msg_state == HTTP_MSG_CLOSED) {
4369 	  http_msg_closed:
4370 		/* if we don't know whether the server will close, we need to hard close */
4371 		if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
4372 			s->si[1].flags |= SI_FL_NOLINGER;  /* we want to close ASAP */
4373 		/* see above in MSG_DONE why we only do this in these states */
4374 		if (!(s->be->options & PR_O_ABRT_CLOSE))
4375 			channel_dont_read(chn);
4376 		goto end;
4377 	}
4378 
4379   check_channel_flags:
4380 	/* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
4381 	if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
4382 		/* if we've just closed an output, let's switch */
4383 		txn->req.msg_state = HTTP_MSG_CLOSING;
4384 		goto http_msg_closing;
4385 	}
4386 
4387   end:
4388 	chn->analysers &= AN_REQ_FLT_END;
4389 	if (txn->req.msg_state == HTTP_MSG_TUNNEL) {
4390 		chn->flags |= CF_NEVER_WAIT;
4391 		if (HAS_REQ_DATA_FILTERS(s))
4392 			chn->analysers |= AN_REQ_FLT_XFER_DATA;
4393 	}
4394 	channel_auto_close(chn);
4395 	channel_auto_read(chn);
4396 	DBG_TRACE_LEAVE(STRM_EV_HTTP_ANA, s, txn);
4397 }
4398 
4399 
4400 /* This function terminates the response because it was completely analyzed or
4401  * because an error was triggered during the body forwarding.
4402  */
http_end_response(struct stream * s)4403 static void http_end_response(struct stream *s)
4404 {
4405 	struct channel *chn = &s->res;
4406 	struct http_txn *txn = s->txn;
4407 
4408 	DBG_TRACE_ENTER(STRM_EV_HTTP_ANA, s, txn);
4409 
4410 	if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
4411 		     txn->rsp.msg_state == HTTP_MSG_ERROR)) {
4412 		channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
4413 		channel_abort(&s->req);
4414 		goto end;
4415 	}
4416 
4417 	if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE)) {
4418 		DBG_TRACE_DEVEL("waiting end of the response", STRM_EV_HTTP_ANA, s, txn);
4419 		return;
4420 	}
4421 
4422 	if (txn->rsp.msg_state == HTTP_MSG_DONE) {
4423 		/* In theory, we don't need to read anymore, but we must
4424 		 * still monitor the server connection for a possible close
4425 		 * while the request is being uploaded, so we don't disable
4426 		 * reading.
4427 		 */
4428 		/* channel_dont_read(chn); */
4429 
4430 		if (txn->req.msg_state < HTTP_MSG_DONE) {
4431 			/* The client seems to still be sending data, probably
4432 			 * because we got an error response during an upload.
4433 			 * We have the choice of either breaking the connection
4434 			 * or letting it pass through. Let's do the later.
4435 			 */
4436 			DBG_TRACE_DEVEL("waiting end of the request", STRM_EV_HTTP_ANA, s, txn);
4437 			return;
4438 		}
4439 
4440 		/* When we get here, it means that both the request and the
4441 		 * response have finished receiving. Depending on the connection
4442 		 * mode, we'll have to wait for the last bytes to leave in either
4443 		 * direction, and sometimes for a close to be effective.
4444 		 */
4445 		if (txn->flags & TX_CON_WANT_TUN) {
4446 			channel_auto_read(chn);
4447 			if (b_data(&chn->buf)) {
4448 				DBG_TRACE_DEVEL("waiting to flush the respone", STRM_EV_HTTP_ANA, s, txn);
4449 				return;
4450 			}
4451 			txn->rsp.msg_state = HTTP_MSG_TUNNEL;
4452 		}
4453 		else {
4454 			/* we're not expecting any new data to come for this
4455 			 * transaction, so we can close it.
4456 			 */
4457 			if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
4458 				channel_shutr_now(chn);
4459 				channel_shutw_now(chn);
4460 			}
4461 		}
4462 		goto check_channel_flags;
4463 	}
4464 
4465 	if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
4466 	  http_msg_closing:
4467 		/* nothing else to forward, just waiting for the output buffer
4468 		 * to be empty and for the shutw_now to take effect.
4469 		 */
4470 		if (channel_is_empty(chn)) {
4471 			txn->rsp.msg_state = HTTP_MSG_CLOSED;
4472 			goto http_msg_closed;
4473 		}
4474 		else if (chn->flags & CF_SHUTW) {
4475 			txn->rsp.msg_state = HTTP_MSG_ERROR;
4476 			_HA_ATOMIC_INC(&strm_sess(s)->fe->fe_counters.cli_aborts);
4477 			_HA_ATOMIC_INC(&s->be->be_counters.cli_aborts);
4478 			if (strm_sess(s)->listener && strm_sess(s)->listener->counters)
4479 				_HA_ATOMIC_INC(&strm_sess(s)->listener->counters->cli_aborts);
4480 			if (objt_server(s->target))
4481 				_HA_ATOMIC_INC(&__objt_server(s->target)->counters.cli_aborts);
4482 			goto end;
4483 		}
4484 		DBG_TRACE_LEAVE(STRM_EV_HTTP_ANA, s, txn);
4485 		return;
4486 	}
4487 
4488 	if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
4489 	  http_msg_closed:
4490 		/* drop any pending data */
4491 		channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
4492 		channel_abort(&s->req);
4493 		goto end;
4494 	}
4495 
4496   check_channel_flags:
4497 	/* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
4498 	if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
4499 		/* if we've just closed an output, let's switch */
4500 		txn->rsp.msg_state = HTTP_MSG_CLOSING;
4501 		goto http_msg_closing;
4502 	}
4503 
4504   end:
4505 	chn->analysers &= AN_RES_FLT_END;
4506 	if (txn->rsp.msg_state == HTTP_MSG_TUNNEL) {
4507 		chn->flags |= CF_NEVER_WAIT;
4508 		if (HAS_RSP_DATA_FILTERS(s))
4509 			chn->analysers |= AN_RES_FLT_XFER_DATA;
4510 	}
4511 	channel_auto_close(chn);
4512 	channel_auto_read(chn);
4513 	DBG_TRACE_LEAVE(STRM_EV_HTTP_ANA, s, txn);
4514 }
4515 
4516 /* Forward a response generated by HAProxy (error/redirect/return). This
4517  * function forwards all pending incoming data. If <final> is set to 0, nothing
4518  * more is performed. It is used for 1xx informational messages. Otherwise, the
4519  * transaction is terminated and the request is emptied. On success 1 is
4520  * returned. If an error occurred, 0 is returned. If it fails, this function
4521  * only exits. It is the caller responsibility to do the cleanup.
4522  */
http_forward_proxy_resp(struct stream * s,int final)4523 int http_forward_proxy_resp(struct stream *s, int final)
4524 {
4525 	struct channel *req = &s->req;
4526 	struct channel *res = &s->res;
4527 	struct htx *htx = htxbuf(&res->buf);
4528 	size_t data;
4529 
4530 	if (final) {
4531 		htx->flags |= HTX_FL_PROXY_RESP;
4532 
4533 		if (!htx_is_empty(htx) && !http_eval_after_res_rules(s))
4534 			return 0;
4535 
4536 		if (s->txn->meth == HTTP_METH_HEAD)
4537 			htx_skip_msg_payload(htx);
4538 
4539 		channel_auto_read(req);
4540 		channel_abort(req);
4541 		channel_auto_close(req);
4542 		channel_htx_erase(req, htxbuf(&req->buf));
4543 
4544 		res->wex = tick_add_ifset(now_ms, res->wto);
4545 		channel_auto_read(res);
4546 		channel_auto_close(res);
4547 		channel_shutr_now(res);
4548 		res->flags |= CF_EOI; /* The response is terminated, add EOI */
4549 		htxbuf(&res->buf)->flags |= HTX_FL_EOM; /* no more data are expected */
4550 	}
4551 	else {
4552 		/* Send ASAP informational messages. Rely on CF_EOI for final
4553 		 * response.
4554 		 */
4555 		res->flags |= CF_SEND_DONTWAIT;
4556 	}
4557 
4558 	data = htx->data - co_data(res);
4559 	c_adv(res, data);
4560 	htx->first = -1;
4561 	res->total += data;
4562 	return 1;
4563 }
4564 
http_server_error(struct stream * s,struct stream_interface * si,int err,int finst,struct http_reply * msg)4565 void http_server_error(struct stream *s, struct stream_interface *si, int err,
4566 		       int finst, struct http_reply *msg)
4567 {
4568 	http_reply_and_close(s, s->txn->status, msg);
4569 	if (!(s->flags & SF_ERR_MASK))
4570 		s->flags |= err;
4571 	if (!(s->flags & SF_FINST_MASK))
4572 		s->flags |= finst;
4573 }
4574 
http_reply_and_close(struct stream * s,short status,struct http_reply * msg)4575 void http_reply_and_close(struct stream *s, short status, struct http_reply *msg)
4576 {
4577 	if (!msg) {
4578 		channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
4579 		goto end;
4580 	}
4581 
4582 	if (http_reply_message(s, msg) == -1) {
4583 		/* On error, return a 500 error message, but don't rewrite it if
4584 		 * it is already an internal error. If it was already a "const"
4585 		 * 500 error, just fail.
4586 		 */
4587 		if (s->txn->status == 500) {
4588 			if (s->txn->flags & TX_CONST_REPLY)
4589 				goto end;
4590 			s->txn->flags |= TX_CONST_REPLY;
4591 		}
4592 		s->txn->status = 500;
4593 		s->txn->http_reply = NULL;
4594 		return http_reply_and_close(s, s->txn->status, http_error_message(s));
4595 	}
4596 
4597 end:
4598 	s->res.wex = tick_add_ifset(now_ms, s->res.wto);
4599 
4600 	/* At this staged, HTTP analysis is finished */
4601 	s->req.analysers &= AN_REQ_FLT_END;
4602 	s->req.analyse_exp = TICK_ETERNITY;
4603 
4604 	s->res.analysers &= AN_RES_FLT_END;
4605 	s->res.analyse_exp = TICK_ETERNITY;
4606 
4607 	channel_auto_read(&s->req);
4608 	channel_abort(&s->req);
4609 	channel_auto_close(&s->req);
4610 	channel_htx_erase(&s->req, htxbuf(&s->req.buf));
4611 	channel_auto_read(&s->res);
4612 	channel_auto_close(&s->res);
4613 	channel_shutr_now(&s->res);
4614 }
4615 
http_error_message(struct stream * s)4616 struct http_reply *http_error_message(struct stream *s)
4617 {
4618 	const int msgnum = http_get_status_idx(s->txn->status);
4619 
4620 	if (s->txn->http_reply)
4621 		return s->txn->http_reply;
4622 	else if (s->be->replies[msgnum])
4623 		return s->be->replies[msgnum];
4624 	else if (strm_fe(s)->replies[msgnum])
4625 		return strm_fe(s)->replies[msgnum];
4626 	else
4627 		return &http_err_replies[msgnum];
4628 }
4629 
4630 /* Produces an HTX message from an http reply. Depending on the http reply type,
4631  * a, errorfile, an raw file or a log-format string is used. On success, it
4632  * returns 0. If an error occurs -1 is returned. If it fails, this function only
4633  * exits. It is the caller responsibility to do the cleanup.
4634  */
http_reply_to_htx(struct stream * s,struct htx * htx,struct http_reply * reply)4635 int http_reply_to_htx(struct stream *s, struct htx *htx, struct http_reply *reply)
4636 {
4637 	struct buffer *errmsg;
4638 	struct htx_sl *sl;
4639 	struct buffer *body = NULL;
4640 	const char *status, *reason, *clen, *ctype;
4641 	unsigned int slflags;
4642 	int ret = 0;
4643 
4644 	/*
4645 	 * - HTTP_REPLY_ERRFILES unexpected here. handled as no payload if so
4646 	 *
4647 	 * - HTTP_REPLY_INDIRECT: switch on another reply if defined or handled
4648 	 *   as no payload if NULL. the TXN status code is set with the status
4649 	 *   of the original reply.
4650 	 */
4651 
4652 	if (reply->type == HTTP_REPLY_INDIRECT) {
4653 		if (reply->body.reply)
4654 			reply = reply->body.reply;
4655 	}
4656 	if (reply->type == HTTP_REPLY_ERRMSG && !reply->body.errmsg)  {
4657 		/* get default error message */
4658 		if (reply == s->txn->http_reply)
4659 			s->txn->http_reply = NULL;
4660 		reply = http_error_message(s);
4661 		if (reply->type == HTTP_REPLY_INDIRECT) {
4662 			if (reply->body.reply)
4663 				reply = reply->body.reply;
4664 		}
4665 	}
4666 
4667 	if (reply->type == HTTP_REPLY_ERRMSG) {
4668 		/* implicit or explicit error message*/
4669 		errmsg = reply->body.errmsg;
4670 		if (errmsg && !b_is_null(errmsg)) {
4671 			if (!htx_copy_msg(htx, errmsg))
4672 				goto fail;
4673 		}
4674 	}
4675 	else {
4676 		/* no payload, file or log-format string */
4677 		if (reply->type == HTTP_REPLY_RAW) {
4678 			/* file */
4679 			body = &reply->body.obj;
4680 		}
4681 		else if (reply->type == HTTP_REPLY_LOGFMT) {
4682 			/* log-format string */
4683 			body = alloc_trash_chunk();
4684 			if (!body)
4685 				goto fail_alloc;
4686 			body->data = build_logline(s, body->area, body->size, &reply->body.fmt);
4687 		}
4688 		/* else no payload */
4689 
4690 		status = ultoa(reply->status);
4691 		reason = http_get_reason(reply->status);
4692 		slflags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_CLEN);
4693 		if (!body || !b_data(body))
4694 			slflags |= HTX_SL_F_BODYLESS;
4695 		sl = htx_add_stline(htx, HTX_BLK_RES_SL, slflags, ist("HTTP/1.1"), ist(status), ist(reason));
4696 		if (!sl)
4697 			goto fail;
4698 		sl->info.res.status = reply->status;
4699 
4700 		clen = (body ? ultoa(b_data(body)) : "0");
4701 		ctype = reply->ctype;
4702 
4703 		if (!LIST_ISEMPTY(&reply->hdrs)) {
4704 			struct http_reply_hdr *hdr;
4705 			struct buffer *value = alloc_trash_chunk();
4706 
4707 			if (!value)
4708 				goto fail;
4709 
4710 			list_for_each_entry(hdr, &reply->hdrs, list) {
4711 				chunk_reset(value);
4712 				value->data = build_logline(s, value->area, value->size, &hdr->value);
4713 				if (b_data(value) && !htx_add_header(htx, hdr->name, ist2(b_head(value), b_data(value)))) {
4714 					free_trash_chunk(value);
4715 					goto fail;
4716 				}
4717 				chunk_reset(value);
4718 			}
4719 			free_trash_chunk(value);
4720 		}
4721 
4722 		if (!htx_add_header(htx, ist("content-length"), ist(clen)) ||
4723 		    (body && b_data(body) && ctype && !htx_add_header(htx, ist("content-type"), ist(ctype))) ||
4724 		    !htx_add_endof(htx, HTX_BLK_EOH) ||
4725 		    (body && b_data(body) && !htx_add_data_atonce(htx, ist2(b_head(body), b_data(body)))))
4726 			goto fail;
4727 
4728 		htx->flags |= HTX_FL_EOM;
4729 	}
4730 
4731   leave:
4732 	if (reply->type == HTTP_REPLY_LOGFMT)
4733 		free_trash_chunk(body);
4734 	return ret;
4735 
4736   fail_alloc:
4737 	if (!(s->flags & SF_ERR_MASK))
4738 		s->flags |= SF_ERR_RESOURCE;
4739 	/* fall through */
4740   fail:
4741 	ret = -1;
4742 	goto leave;
4743 }
4744 
4745 /* Send an http reply to the client. On success, it returns 0. If an error
4746  * occurs -1 is returned and the response channel is truncated, removing this
4747  * way the faulty reply. This function may fail when the reply is formatted
4748  * (http_reply_to_htx) or when the reply is forwarded
4749  * (http_forward_proxy_resp). On the last case, it is because a
4750  * http-after-response rule fails.
4751  */
http_reply_message(struct stream * s,struct http_reply * reply)4752 int http_reply_message(struct stream *s, struct http_reply *reply)
4753 {
4754 	struct channel *res = &s->res;
4755 	struct htx *htx = htx_from_buf(&res->buf);
4756 
4757 	if (s->txn->status == -1)
4758 		s->txn->status = reply->status;
4759 	channel_htx_truncate(res, htx);
4760 
4761 	if (http_reply_to_htx(s, htx, reply) == -1)
4762 		goto fail;
4763 
4764 	htx_to_buf(htx, &s->res.buf);
4765 	if (!http_forward_proxy_resp(s, 1))
4766 		goto fail;
4767 	return 0;
4768 
4769   fail:
4770 	channel_htx_truncate(res, htx);
4771 	if (!(s->flags & SF_ERR_MASK))
4772 		s->flags |= SF_ERR_PRXCOND;
4773 	return -1;
4774 }
4775 
4776 /* Return the error message corresponding to si->err_type. It is assumed
4777  * that the server side is closed. Note that err_type is actually a
4778  * bitmask, where almost only aborts may be cumulated with other
4779  * values. We consider that aborted operations are more important
4780  * than timeouts or errors due to the fact that nobody else in the
4781  * logs might explain incomplete retries. All others should avoid
4782  * being cumulated. It should normally not be possible to have multiple
4783  * aborts at once, but just in case, the first one in sequence is reported.
4784  * Note that connection errors appearing on the second request of a keep-alive
4785  * connection are not reported since this allows the client to retry.
4786  */
http_return_srv_error(struct stream * s,struct stream_interface * si)4787 void http_return_srv_error(struct stream *s, struct stream_interface *si)
4788 {
4789 	int err_type = si->err_type;
4790 
4791 	/* set s->txn->status for http_error_message(s) */
4792 	s->txn->status = 503;
4793 
4794 	if (err_type & SI_ET_QUEUE_ABRT)
4795 		http_server_error(s, si, SF_ERR_CLICL, SF_FINST_Q,
4796 				  http_error_message(s));
4797 	else if (err_type & SI_ET_CONN_ABRT)
4798 		http_server_error(s, si, SF_ERR_CLICL, SF_FINST_C,
4799 				  (s->txn->flags & TX_NOT_FIRST) ? NULL :
4800 				  http_error_message(s));
4801 	else if (err_type & SI_ET_QUEUE_TO)
4802 		http_server_error(s, si, SF_ERR_SRVTO, SF_FINST_Q,
4803 				  http_error_message(s));
4804 	else if (err_type & SI_ET_QUEUE_ERR)
4805 		http_server_error(s, si, SF_ERR_SRVCL, SF_FINST_Q,
4806 				  http_error_message(s));
4807 	else if (err_type & SI_ET_CONN_TO)
4808 		http_server_error(s, si, SF_ERR_SRVTO, SF_FINST_C,
4809 				  (s->txn->flags & TX_NOT_FIRST) ? NULL :
4810 				  http_error_message(s));
4811 	else if (err_type & SI_ET_CONN_ERR)
4812 		http_server_error(s, si, SF_ERR_SRVCL, SF_FINST_C,
4813 				  (s->flags & SF_SRV_REUSED) ? NULL :
4814 				  http_error_message(s));
4815 	else if (err_type & SI_ET_CONN_RES)
4816 		http_server_error(s, si, SF_ERR_RESOURCE, SF_FINST_C,
4817 				  (s->txn->flags & TX_NOT_FIRST) ? NULL :
4818 				  http_error_message(s));
4819 	else { /* SI_ET_CONN_OTHER and others */
4820 		s->txn->status = 500;
4821 		http_server_error(s, si, SF_ERR_INTERNAL, SF_FINST_C,
4822 				  http_error_message(s));
4823 	}
4824 }
4825 
4826 
4827 /* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
4828  * on success and -1 on error.
4829  */
http_handle_expect_hdr(struct stream * s,struct htx * htx,struct http_msg * msg)4830 static int http_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
4831 {
4832 	/* If we have HTTP/1.1 message with a body and Expect: 100-continue,
4833 	 * then we must send an HTTP/1.1 100 Continue intermediate response.
4834 	 */
4835 	if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
4836 	    (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
4837 		struct ist hdr = { .ptr = "Expect", .len = 6 };
4838 		struct http_hdr_ctx ctx;
4839 
4840 		ctx.blk = NULL;
4841 		/* Expect is allowed in 1.1, look for it */
4842 		if (http_find_header(htx, hdr, &ctx, 0) &&
4843 		    unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
4844 			if (http_reply_100_continue(s) == -1)
4845 				return -1;
4846 			http_remove_header(htx, &ctx);
4847 		}
4848 	}
4849 	return 0;
4850 }
4851 
4852 /* Send a 100-Continue response to the client. It returns 0 on success and -1
4853  * on error. The response channel is updated accordingly.
4854  */
http_reply_100_continue(struct stream * s)4855 static int http_reply_100_continue(struct stream *s)
4856 {
4857 	struct channel *res = &s->res;
4858 	struct htx *htx = htx_from_buf(&res->buf);
4859 	struct htx_sl *sl;
4860 	unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
4861 			      HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4862 
4863 	sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4864 			    ist("HTTP/1.1"), ist("100"), ist("Continue"));
4865 	if (!sl)
4866 		goto fail;
4867 	sl->info.res.status = 100;
4868 
4869 	if (!htx_add_endof(htx, HTX_BLK_EOH))
4870 		goto fail;
4871 
4872 	if (!http_forward_proxy_resp(s, 0))
4873 		goto fail;
4874 	return 0;
4875 
4876   fail:
4877 	/* If an error occurred, remove the incomplete HTTP response from the
4878 	 * buffer */
4879 	channel_htx_truncate(res, htx);
4880 	return -1;
4881 }
4882 
4883 
4884 /*
4885  * Capture headers from message <htx> according to header list <cap_hdr>, and
4886  * fill the <cap> pointers appropriately.
4887  */
http_capture_headers(struct htx * htx,char ** cap,struct cap_hdr * cap_hdr)4888 static void http_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
4889 {
4890 	struct cap_hdr *h;
4891 	int32_t pos;
4892 
4893 	for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4894 		struct htx_blk *blk = htx_get_blk(htx, pos);
4895 		enum htx_blk_type type = htx_get_blk_type(blk);
4896 		struct ist n, v;
4897 
4898 		if (type == HTX_BLK_EOH)
4899 			break;
4900 		if (type != HTX_BLK_HDR)
4901 			continue;
4902 
4903 		n = htx_get_blk_name(htx, blk);
4904 
4905 		for (h = cap_hdr; h; h = h->next) {
4906 			if (h->namelen && (h->namelen == n.len) &&
4907 			    (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
4908 				if (cap[h->index] == NULL)
4909 					cap[h->index] =
4910 						pool_alloc(h->pool);
4911 
4912 				if (cap[h->index] == NULL) {
4913 					ha_alert("HTTP capture : out of memory.\n");
4914 					break;
4915 				}
4916 
4917 				v = htx_get_blk_value(htx, blk);
4918 				if (v.len > h->len)
4919 					v.len = h->len;
4920 
4921 				memcpy(cap[h->index], v.ptr, v.len);
4922 				cap[h->index][v.len]=0;
4923 			}
4924 		}
4925 	}
4926 }
4927 
4928 /* Delete a value in a header between delimiters <from> and <next>. The header
4929  * itself is delimited by <start> and <end> pointers. The number of characters
4930  * displaced is returned, and the pointer to the first delimiter is updated if
4931  * required. The function tries as much as possible to respect the following
4932  * principles :
4933  * - replace <from> delimiter by the <next> one unless <from> points to <start>,
4934  *   in which case <next> is simply removed
4935  * - set exactly one space character after the new first delimiter, unless there
4936  *   are not enough characters in the block being moved to do so.
4937  * - remove unneeded spaces before the previous delimiter and after the new
4938  *   one.
4939  *
4940  * It is the caller's responsibility to ensure that :
4941  *   - <from> points to a valid delimiter or <start> ;
4942  *   - <next> points to a valid delimiter or <end> ;
4943  *   - there are non-space chars before <from>.
4944  */
http_del_hdr_value(char * start,char * end,char ** from,char * next)4945 static int http_del_hdr_value(char *start, char *end, char **from, char *next)
4946 {
4947 	char *prev = *from;
4948 
4949 	if (prev == start) {
4950 		/* We're removing the first value. eat the semicolon, if <next>
4951 		 * is lower than <end> */
4952 		if (next < end)
4953 			next++;
4954 
4955 		while (next < end && HTTP_IS_SPHT(*next))
4956 			next++;
4957 	}
4958 	else {
4959 		/* Remove useless spaces before the old delimiter. */
4960 		while (HTTP_IS_SPHT(*(prev-1)))
4961 			prev--;
4962 		*from = prev;
4963 
4964 		/* copy the delimiter and if possible a space if we're
4965 		 * not at the end of the line.
4966 		 */
4967 		if (next < end) {
4968 			*prev++ = *next++;
4969 			if (prev + 1 < next)
4970 				*prev++ = ' ';
4971 			while (next < end && HTTP_IS_SPHT(*next))
4972 				next++;
4973 		}
4974 	}
4975 	memmove(prev, next, end - next);
4976 	return (prev - next);
4977 }
4978 
4979 
4980 /* Formats the start line of the request (without CRLF) and puts it in <str> and
4981  * return the written length. The line can be truncated if it exceeds <len>.
4982  */
http_fmt_req_line(const struct htx_sl * sl,char * str,size_t len)4983 static size_t http_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
4984 {
4985 	struct ist dst = ist2(str, 0);
4986 
4987 	if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
4988 		goto end;
4989 	if (dst.len + 1 > len)
4990 		goto end;
4991 	dst.ptr[dst.len++] = ' ';
4992 
4993 	if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
4994 		goto end;
4995 	if (dst.len + 1 > len)
4996 		goto end;
4997 	dst.ptr[dst.len++] = ' ';
4998 
4999 	istcat(&dst, htx_sl_req_vsn(sl), len);
5000   end:
5001 	return dst.len;
5002 }
5003 
5004 /*
5005  * Print a debug line with a start line.
5006  */
http_debug_stline(const char * dir,struct stream * s,const struct htx_sl * sl)5007 static void http_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
5008 {
5009         struct session *sess = strm_sess(s);
5010         int max;
5011 
5012         chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5013                      dir,
5014                      objt_conn(sess->origin) ? (unsigned short)__objt_conn(sess->origin)->handle.fd : -1,
5015                      objt_cs(s->si[1].end) ? (unsigned short)__objt_cs(s->si[1].end)->conn->handle.fd : -1);
5016 
5017         max = HTX_SL_P1_LEN(sl);
5018         UBOUND(max, trash.size - trash.data - 3);
5019         chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
5020         trash.area[trash.data++] = ' ';
5021 
5022         max = HTX_SL_P2_LEN(sl);
5023         UBOUND(max, trash.size - trash.data - 2);
5024         chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
5025         trash.area[trash.data++] = ' ';
5026 
5027         max = HTX_SL_P3_LEN(sl);
5028         UBOUND(max, trash.size - trash.data - 1);
5029         chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
5030         trash.area[trash.data++] = '\n';
5031 
5032         DISGUISE(write(1, trash.area, trash.data));
5033 }
5034 
5035 /*
5036  * Print a debug line with a header.
5037  */
http_debug_hdr(const char * dir,struct stream * s,const struct ist n,const struct ist v)5038 static void http_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5039 {
5040         struct session *sess = strm_sess(s);
5041         int max;
5042 
5043         chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5044                      dir,
5045                      objt_conn(sess->origin) ? (unsigned short)__objt_conn(sess->origin)->handle.fd : -1,
5046                      objt_cs(s->si[1].end) ? (unsigned short)__objt_cs(s->si[1].end)->conn->handle.fd : -1);
5047 
5048         max = n.len;
5049         UBOUND(max, trash.size - trash.data - 3);
5050         chunk_memcat(&trash, n.ptr, max);
5051         trash.area[trash.data++] = ':';
5052         trash.area[trash.data++] = ' ';
5053 
5054         max = v.len;
5055         UBOUND(max, trash.size - trash.data - 1);
5056         chunk_memcat(&trash, v.ptr, max);
5057         trash.area[trash.data++] = '\n';
5058 
5059         DISGUISE(write(1, trash.area, trash.data));
5060 }
5061 
5062 /* Allocate a new HTTP transaction for stream <s> unless there is one already.
5063  * In case of allocation failure, everything allocated is freed and NULL is
5064  * returned. Otherwise the new transaction is assigned to the stream and
5065  * returned.
5066  */
http_alloc_txn(struct stream * s)5067 struct http_txn *http_alloc_txn(struct stream *s)
5068 {
5069 	struct http_txn *txn = s->txn;
5070 
5071 	if (txn)
5072 		return txn;
5073 
5074 	txn = pool_alloc(pool_head_http_txn);
5075 	if (!txn)
5076 		return txn;
5077 
5078 	s->txn = txn;
5079 	return txn;
5080 }
5081 
http_txn_reset_req(struct http_txn * txn)5082 void http_txn_reset_req(struct http_txn *txn)
5083 {
5084 	txn->req.flags = 0;
5085 	txn->req.msg_state = HTTP_MSG_RQBEFORE; /* at the very beginning of the request */
5086 }
5087 
http_txn_reset_res(struct http_txn * txn)5088 void http_txn_reset_res(struct http_txn *txn)
5089 {
5090 	txn->rsp.flags = 0;
5091 	txn->rsp.msg_state = HTTP_MSG_RPBEFORE; /* at the very beginning of the response */
5092 }
5093 
5094 /*
5095  * Create and initialize a new HTTP transaction for stream <s>. This should be
5096  * used before processing any new request. It returns the transaction or NLULL
5097  * on error.
5098  */
http_create_txn(struct stream * s)5099 struct http_txn *http_create_txn(struct stream *s)
5100 {
5101 	struct http_txn *txn;
5102 	struct conn_stream *cs = objt_cs(s->si[0].end);
5103 
5104 	txn = pool_alloc(pool_head_http_txn);
5105 	if (!txn)
5106 		return NULL;
5107 	s->txn = txn;
5108 
5109 	txn->flags = ((cs && cs->flags & CS_FL_NOT_FIRST) ? TX_NOT_FIRST : 0);
5110 	txn->status = -1;
5111 	txn->http_reply = NULL;
5112 	write_u32(txn->cache_hash, 0);
5113 
5114 	txn->cookie_first_date = 0;
5115 	txn->cookie_last_date = 0;
5116 
5117 	txn->srv_cookie = NULL;
5118 	txn->cli_cookie = NULL;
5119 	txn->uri = NULL;
5120 
5121 	http_txn_reset_req(txn);
5122 	http_txn_reset_res(txn);
5123 
5124 	txn->req.chn = &s->req;
5125 	txn->rsp.chn = &s->res;
5126 
5127 	txn->auth.method = HTTP_AUTH_UNKNOWN;
5128 
5129 	vars_init(&s->vars_txn,    SCOPE_TXN);
5130 	vars_init(&s->vars_reqres, SCOPE_REQ);
5131 
5132 	return txn;
5133 }
5134 
5135 /* to be used at the end of a transaction */
http_destroy_txn(struct stream * s)5136 void http_destroy_txn(struct stream *s)
5137 {
5138 	struct http_txn *txn = s->txn;
5139 
5140 	/* these ones will have been dynamically allocated */
5141 	pool_free(pool_head_requri, txn->uri);
5142 	pool_free(pool_head_capture, txn->cli_cookie);
5143 	pool_free(pool_head_capture, txn->srv_cookie);
5144 	pool_free(pool_head_uniqueid, s->unique_id.ptr);
5145 
5146 	s->unique_id = IST_NULL;
5147 	txn->uri = NULL;
5148 	txn->srv_cookie = NULL;
5149 	txn->cli_cookie = NULL;
5150 
5151 	if (!LIST_ISEMPTY(&s->vars_txn.head))
5152 		vars_prune(&s->vars_txn, s->sess, s);
5153 	if (!LIST_ISEMPTY(&s->vars_reqres.head))
5154 		vars_prune(&s->vars_reqres, s->sess, s);
5155 
5156 	pool_free(pool_head_http_txn, txn);
5157 	s->txn = NULL;
5158 }
5159 
5160 
5161 DECLARE_POOL(pool_head_http_txn, "http_txn", sizeof(struct http_txn));
5162 
5163 __attribute__((constructor))
__http_protocol_init(void)5164 static void __http_protocol_init(void)
5165 {
5166 }
5167 
5168 
5169 /*
5170  * Local variables:
5171  *  c-indent-level: 8
5172  *  c-basic-offset: 8
5173  * End:
5174  */
5175