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