blob: 4eb22bc74ca5b75eace1de2e291682e7c80c8bc5 [file] [log] [blame]
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02001/*
2 * HTTP protocol analyzer
3 *
4 * Copyright (C) 2018 HAProxy Technologies, Christopher Faulet <cfaulet@haproxy.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Christopher Faulete0768eb2018-10-03 16:38:02 +020013#include <common/base64.h>
14#include <common/config.h>
15#include <common/debug.h>
16#include <common/uri_auth.h>
17
18#include <types/cache.h>
19
20#include <proto/acl.h>
21#include <proto/channel.h>
22#include <proto/checks.h>
23#include <proto/connection.h>
24#include <proto/filters.h>
25#include <proto/hdr_idx.h>
26#include <proto/log.h>
27#include <proto/proto_http.h>
28#include <proto/proxy.h>
29#include <proto/stream.h>
30#include <proto/stream_interface.h>
31#include <proto/stats.h>
32
Christopher Fauletf2824e62018-10-01 12:12:37 +020033
34static void htx_end_request(struct stream *s);
35static void htx_end_response(struct stream *s);
36
Christopher Faulete0768eb2018-10-03 16:38:02 +020037/* This stream analyser waits for a complete HTTP request. It returns 1 if the
38 * processing can continue on next analysers, or zero if it either needs more
39 * data or wants to immediately abort the request (eg: timeout, error, ...). It
40 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
41 * when it has nothing left to do, and may remove any analyser when it wants to
42 * abort.
43 */
44int htx_wait_for_request(struct stream *s, struct channel *req, int an_bit)
45{
46 /*
47 * We will parse the partial (or complete) lines.
48 * We will check the request syntax, and also join multi-line
49 * headers. An index of all the lines will be elaborated while
50 * parsing.
51 *
52 * For the parsing, we use a 28 states FSM.
53 *
54 * Here is the information we currently have :
55 * ci_head(req) = beginning of request
56 * ci_head(req) + msg->eoh = end of processed headers / start of current one
57 * ci_tail(req) = end of input data
58 * msg->eol = end of current header or line (LF or CRLF)
59 * msg->next = first non-visited byte
60 *
61 * At end of parsing, we may perform a capture of the error (if any), and
62 * we will set a few fields (txn->meth, sn->flags/SF_REDIRECTABLE).
63 * We also check for monitor-uri, logging, HTTP/0.9 to 1.0 conversion, and
64 * finally headers capture.
65 */
66
67 int cur_idx;
68 struct session *sess = s->sess;
69 struct http_txn *txn = s->txn;
70 struct http_msg *msg = &txn->req;
71 struct hdr_ctx ctx;
72
73 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
74 now_ms, __FUNCTION__,
75 s,
76 req,
77 req->rex, req->wex,
78 req->flags,
79 ci_data(req),
80 req->analysers);
81
82 /* we're speaking HTTP here, so let's speak HTTP to the client */
83 s->srv_error = http_return_srv_error;
84
85 /* If there is data available for analysis, log the end of the idle time. */
86 if (c_data(req) && s->logs.t_idle == -1)
87 s->logs.t_idle = tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake;
88
89 /* There's a protected area at the end of the buffer for rewriting
90 * purposes. We don't want to start to parse the request if the
91 * protected area is affected, because we may have to move processed
92 * data later, which is much more complicated.
93 */
94 if (c_data(req) && msg->msg_state < HTTP_MSG_ERROR) {
95 if (txn->flags & TX_NOT_FIRST) {
96 if (unlikely(!channel_is_rewritable(req))) {
97 if (req->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_WRITE_ERROR|CF_WRITE_TIMEOUT))
98 goto failed_keep_alive;
99 /* some data has still not left the buffer, wake us once that's done */
100 channel_dont_connect(req);
101 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
102 req->flags |= CF_WAKE_WRITE;
103 return 0;
104 }
105 if (unlikely(ci_tail(req) < c_ptr(req, msg->next) ||
106 ci_tail(req) > b_wrap(&req->buf) - global.tune.maxrewrite))
107 channel_slow_realign(req, trash.area);
108 }
109
110 if (likely(msg->next < ci_data(req))) /* some unparsed data are available */
111 http_msg_analyzer(msg, &txn->hdr_idx);
112 }
113
114 /* 1: we might have to print this header in debug mode */
115 if (unlikely((global.mode & MODE_DEBUG) &&
116 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) &&
117 msg->msg_state >= HTTP_MSG_BODY)) {
118 char *eol, *sol;
119
120 sol = ci_head(req);
121 /* this is a bit complex : in case of error on the request line,
122 * we know that rq.l is still zero, so we display only the part
123 * up to the end of the line (truncated by debug_hdr).
124 */
125 eol = sol + (msg->sl.rq.l ? msg->sl.rq.l : ci_data(req));
126 debug_hdr("clireq", s, sol, eol);
127
128 sol += hdr_idx_first_pos(&txn->hdr_idx);
129 cur_idx = hdr_idx_first_idx(&txn->hdr_idx);
130
131 while (cur_idx) {
132 eol = sol + txn->hdr_idx.v[cur_idx].len;
133 debug_hdr("clihdr", s, sol, eol);
134 sol = eol + txn->hdr_idx.v[cur_idx].cr + 1;
135 cur_idx = txn->hdr_idx.v[cur_idx].next;
136 }
137 }
138
Christopher Faulete0768eb2018-10-03 16:38:02 +0200139 /*
140 * Now we quickly check if we have found a full valid request.
141 * If not so, we check the FD and buffer states before leaving.
142 * A full request is indicated by the fact that we have seen
143 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
144 * requests are checked first. When waiting for a second request
145 * on a keep-alive stream, if we encounter and error, close, t/o,
146 * we note the error in the stream flags but don't set any state.
147 * Since the error will be noted there, it will not be counted by
148 * process_stream() as a frontend error.
149 * Last, we may increase some tracked counters' http request errors on
150 * the cases that are deliberately the client's fault. For instance,
151 * a timeout or connection reset is not counted as an error. However
152 * a bad request is.
153 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200154 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
155 /*
156 * First, let's catch bad requests.
157 */
158 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
159 stream_inc_http_req_ctr(s);
160 stream_inc_http_err_ctr(s);
161 proxy_inc_fe_req_ctr(sess->fe);
162 goto return_bad_req;
163 }
164
165 /* 1: Since we are in header mode, if there's no space
166 * left for headers, we won't be able to free more
167 * later, so the stream will never terminate. We
168 * must terminate it now.
169 */
170 if (unlikely(channel_full(req, global.tune.maxrewrite))) {
171 /* FIXME: check if URI is set and return Status
172 * 414 Request URI too long instead.
173 */
174 stream_inc_http_req_ctr(s);
175 stream_inc_http_err_ctr(s);
176 proxy_inc_fe_req_ctr(sess->fe);
177 if (msg->err_pos < 0)
178 msg->err_pos = ci_data(req);
179 goto return_bad_req;
180 }
181
182 /* 2: have we encountered a read error ? */
183 else if (req->flags & CF_READ_ERROR) {
184 if (!(s->flags & SF_ERR_MASK))
185 s->flags |= SF_ERR_CLICL;
186
187 if (txn->flags & TX_WAIT_NEXT_RQ)
188 goto failed_keep_alive;
189
190 if (sess->fe->options & PR_O_IGNORE_PRB)
191 goto failed_keep_alive;
192
193 /* we cannot return any message on error */
194 if (msg->err_pos >= 0) {
195 http_capture_bad_message(sess->fe, s, msg, msg->err_state, sess->fe);
196 stream_inc_http_err_ctr(s);
197 }
198
199 txn->status = 400;
200 msg->err_state = msg->msg_state;
201 msg->msg_state = HTTP_MSG_ERROR;
202 http_reply_and_close(s, txn->status, NULL);
203 req->analysers &= AN_REQ_FLT_END;
204 stream_inc_http_req_ctr(s);
205 proxy_inc_fe_req_ctr(sess->fe);
206 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
207 if (sess->listener->counters)
208 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
209
210 if (!(s->flags & SF_FINST_MASK))
211 s->flags |= SF_FINST_R;
212 return 0;
213 }
214
215 /* 3: has the read timeout expired ? */
216 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
217 if (!(s->flags & SF_ERR_MASK))
218 s->flags |= SF_ERR_CLITO;
219
220 if (txn->flags & TX_WAIT_NEXT_RQ)
221 goto failed_keep_alive;
222
223 if (sess->fe->options & PR_O_IGNORE_PRB)
224 goto failed_keep_alive;
225
226 /* read timeout : give up with an error message. */
227 if (msg->err_pos >= 0) {
228 http_capture_bad_message(sess->fe, s, msg, msg->err_state, sess->fe);
229 stream_inc_http_err_ctr(s);
230 }
231 txn->status = 408;
232 msg->err_state = msg->msg_state;
233 msg->msg_state = HTTP_MSG_ERROR;
234 http_reply_and_close(s, txn->status, http_error_message(s));
235 req->analysers &= AN_REQ_FLT_END;
236
237 stream_inc_http_req_ctr(s);
238 proxy_inc_fe_req_ctr(sess->fe);
239 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
240 if (sess->listener->counters)
241 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
242
243 if (!(s->flags & SF_FINST_MASK))
244 s->flags |= SF_FINST_R;
245 return 0;
246 }
247
248 /* 4: have we encountered a close ? */
249 else if (req->flags & CF_SHUTR) {
250 if (!(s->flags & SF_ERR_MASK))
251 s->flags |= SF_ERR_CLICL;
252
253 if (txn->flags & TX_WAIT_NEXT_RQ)
254 goto failed_keep_alive;
255
256 if (sess->fe->options & PR_O_IGNORE_PRB)
257 goto failed_keep_alive;
258
259 if (msg->err_pos >= 0)
260 http_capture_bad_message(sess->fe, s, msg, msg->err_state, sess->fe);
261 txn->status = 400;
262 msg->err_state = msg->msg_state;
263 msg->msg_state = HTTP_MSG_ERROR;
264 http_reply_and_close(s, txn->status, http_error_message(s));
265 req->analysers &= AN_REQ_FLT_END;
266 stream_inc_http_err_ctr(s);
267 stream_inc_http_req_ctr(s);
268 proxy_inc_fe_req_ctr(sess->fe);
269 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
270 if (sess->listener->counters)
271 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
272
273 if (!(s->flags & SF_FINST_MASK))
274 s->flags |= SF_FINST_R;
275 return 0;
276 }
277
278 channel_dont_connect(req);
279 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
280 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
281#ifdef TCP_QUICKACK
282 if (sess->listener->options & LI_O_NOQUICKACK && ci_data(req) &&
283 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
284 /* We need more data, we have to re-enable quick-ack in case we
285 * previously disabled it, otherwise we might cause the client
286 * to delay next data.
287 */
288 setsockopt(__objt_conn(sess->origin)->handle.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
289 }
290#endif
291
292 if ((msg->msg_state != HTTP_MSG_RQBEFORE) && (txn->flags & TX_WAIT_NEXT_RQ)) {
293 /* If the client starts to talk, let's fall back to
294 * request timeout processing.
295 */
296 txn->flags &= ~TX_WAIT_NEXT_RQ;
297 req->analyse_exp = TICK_ETERNITY;
298 }
299
300 /* just set the request timeout once at the beginning of the request */
301 if (!tick_isset(req->analyse_exp)) {
302 if ((msg->msg_state == HTTP_MSG_RQBEFORE) &&
303 (txn->flags & TX_WAIT_NEXT_RQ) &&
304 tick_isset(s->be->timeout.httpka))
305 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
306 else
307 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
308 }
309
310 /* we're not ready yet */
311 return 0;
312
313 failed_keep_alive:
314 /* Here we process low-level errors for keep-alive requests. In
315 * short, if the request is not the first one and it experiences
316 * a timeout, read error or shutdown, we just silently close so
317 * that the client can try again.
318 */
319 txn->status = 0;
320 msg->msg_state = HTTP_MSG_RQBEFORE;
321 req->analysers &= AN_REQ_FLT_END;
322 s->logs.logwait = 0;
323 s->logs.level = 0;
324 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
325 http_reply_and_close(s, txn->status, NULL);
326 return 0;
327 }
328
329 /* OK now we have a complete HTTP request with indexed headers. Let's
330 * complete the request parsing by setting a few fields we will need
331 * later. At this point, we have the last CRLF at req->buf.data + msg->eoh.
332 * If the request is in HTTP/0.9 form, the rule is still true, and eoh
333 * points to the CRLF of the request line. msg->next points to the first
334 * byte after the last LF. msg->sov points to the first byte of data.
335 * msg->eol cannot be trusted because it may have been left uninitialized
336 * (for instance in the absence of headers).
337 */
338
339 stream_inc_http_req_ctr(s);
340 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
341
342 if (txn->flags & TX_WAIT_NEXT_RQ) {
343 /* kill the pending keep-alive timeout */
344 txn->flags &= ~TX_WAIT_NEXT_RQ;
345 req->analyse_exp = TICK_ETERNITY;
346 }
347
348
349 /* Maybe we found in invalid header name while we were configured not
350 * to block on that, so we have to capture it now.
351 */
352 if (unlikely(msg->err_pos >= 0))
353 http_capture_bad_message(sess->fe, s, msg, msg->err_state, sess->fe);
354
355 /*
356 * 1: identify the method
357 */
358 txn->meth = find_http_meth(ci_head(req), msg->sl.rq.m_l);
359
360 /* we can make use of server redirect on GET and HEAD */
361 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
362 s->flags |= SF_REDIRECTABLE;
363 else if (txn->meth == HTTP_METH_OTHER &&
364 msg->sl.rq.m_l == 3 && memcmp(ci_head(req), "PRI", 3) == 0) {
365 /* PRI is reserved for the HTTP/2 preface */
366 msg->err_pos = 0;
367 goto return_bad_req;
368 }
369
370 /*
371 * 2: check if the URI matches the monitor_uri.
372 * We have to do this for every request which gets in, because
373 * the monitor-uri is defined by the frontend.
374 */
375 if (unlikely((sess->fe->monitor_uri_len != 0) &&
376 (sess->fe->monitor_uri_len == msg->sl.rq.u_l) &&
377 !memcmp(ci_head(req) + msg->sl.rq.u,
378 sess->fe->monitor_uri,
379 sess->fe->monitor_uri_len))) {
380 /*
381 * We have found the monitor URI
382 */
383 struct acl_cond *cond;
384
385 s->flags |= SF_MONITOR;
386 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
387
388 /* Check if we want to fail this monitor request or not */
389 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
390 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
391
392 ret = acl_pass(ret);
393 if (cond->pol == ACL_COND_UNLESS)
394 ret = !ret;
395
396 if (ret) {
397 /* we fail this request, let's return 503 service unavail */
398 txn->status = 503;
399 http_reply_and_close(s, txn->status, http_error_message(s));
400 if (!(s->flags & SF_ERR_MASK))
401 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
402 goto return_prx_cond;
403 }
404 }
405
406 /* nothing to fail, let's reply normaly */
407 txn->status = 200;
408 http_reply_and_close(s, txn->status, http_error_message(s));
409 if (!(s->flags & SF_ERR_MASK))
410 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
411 goto return_prx_cond;
412 }
413
414 /*
415 * 3: Maybe we have to copy the original REQURI for the logs ?
416 * Note: we cannot log anymore if the request has been
417 * classified as invalid.
418 */
419 if (unlikely(s->logs.logwait & LW_REQ)) {
420 /* we have a complete HTTP request that we must log */
421 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
422 int urilen = msg->sl.rq.l;
423
424 if (urilen >= global.tune.requri_len )
425 urilen = global.tune.requri_len - 1;
426 memcpy(txn->uri, ci_head(req), urilen);
427 txn->uri[urilen] = 0;
428
429 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
430 s->do_log(s);
431 } else {
432 ha_alert("HTTP logging : out of memory.\n");
433 }
434 }
435
436 /* RFC7230#2.6 has enforced the format of the HTTP version string to be
437 * exactly one digit "." one digit. This check may be disabled using
438 * option accept-invalid-http-request.
439 */
440 if (!(sess->fe->options2 & PR_O2_REQBUG_OK)) {
441 if (msg->sl.rq.v_l != 8) {
442 msg->err_pos = msg->sl.rq.v;
443 goto return_bad_req;
444 }
445
446 if (ci_head(req)[msg->sl.rq.v + 4] != '/' ||
447 !isdigit((unsigned char)ci_head(req)[msg->sl.rq.v + 5]) ||
448 ci_head(req)[msg->sl.rq.v + 6] != '.' ||
449 !isdigit((unsigned char)ci_head(req)[msg->sl.rq.v + 7])) {
450 msg->err_pos = msg->sl.rq.v + 4;
451 goto return_bad_req;
452 }
453 }
454 else {
455 /* 4. We may have to convert HTTP/0.9 requests to HTTP/1.0 */
456 if (unlikely(msg->sl.rq.v_l == 0) && !http_upgrade_v09_to_v10(txn))
457 goto return_bad_req;
458 }
459
460 /* ... and check if the request is HTTP/1.1 or above */
461 if ((msg->sl.rq.v_l == 8) &&
462 ((ci_head(req)[msg->sl.rq.v + 5] > '1') ||
463 ((ci_head(req)[msg->sl.rq.v + 5] == '1') &&
464 (ci_head(req)[msg->sl.rq.v + 7] >= '1'))))
465 msg->flags |= HTTP_MSGF_VER_11;
466
Christopher Faulete0768eb2018-10-03 16:38:02 +0200467 /* if the frontend has "option http-use-proxy-header", we'll check if
468 * we have what looks like a proxied connection instead of a connection,
469 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
470 * Note that this is *not* RFC-compliant, however browsers and proxies
471 * happen to do that despite being non-standard :-(
472 * We consider that a request not beginning with either '/' or '*' is
473 * a proxied connection, which covers both "scheme://location" and
474 * CONNECT ip:port.
475 */
476 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
477 ci_head(req)[msg->sl.rq.u] != '/' && ci_head(req)[msg->sl.rq.u] != '*')
478 txn->flags |= TX_USE_PX_CONN;
479
480 /* transfer length unknown*/
481 msg->flags &= ~HTTP_MSGF_XFER_LEN;
482
483 /* 5: we may need to capture headers */
484 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
485 http_capture_headers(ci_head(req), &txn->hdr_idx,
486 s->req_cap, sess->fe->req_cap);
487
488 /* 6: determine the transfer-length according to RFC2616 #4.4, updated
489 * by RFC7230#3.3.3 :
490 *
491 * The length of a message body is determined by one of the following
492 * (in order of precedence):
493 *
494 * 1. Any response to a HEAD request and any response with a 1xx
495 * (Informational), 204 (No Content), or 304 (Not Modified) status
496 * code is always terminated by the first empty line after the
497 * header fields, regardless of the header fields present in the
498 * message, and thus cannot contain a message body.
499 *
500 * 2. Any 2xx (Successful) response to a CONNECT request implies that
501 * the connection will become a tunnel immediately after the empty
502 * line that concludes the header fields. A client MUST ignore any
503 * Content-Length or Transfer-Encoding header fields received in
504 * such a message.
505 *
506 * 3. If a Transfer-Encoding header field is present and the chunked
507 * transfer coding (Section 4.1) is the final encoding, the message
508 * body length is determined by reading and decoding the chunked
509 * data until the transfer coding indicates the data is complete.
510 *
511 * If a Transfer-Encoding header field is present in a response and
512 * the chunked transfer coding is not the final encoding, the
513 * message body length is determined by reading the connection until
514 * it is closed by the server. If a Transfer-Encoding header field
515 * is present in a request and the chunked transfer coding is not
516 * the final encoding, the message body length cannot be determined
517 * reliably; the server MUST respond with the 400 (Bad Request)
518 * status code and then close the connection.
519 *
520 * If a message is received with both a Transfer-Encoding and a
521 * Content-Length header field, the Transfer-Encoding overrides the
522 * Content-Length. Such a message might indicate an attempt to
523 * perform request smuggling (Section 9.5) or response splitting
524 * (Section 9.4) and ought to be handled as an error. A sender MUST
525 * remove the received Content-Length field prior to forwarding such
526 * a message downstream.
527 *
528 * 4. If a message is received without Transfer-Encoding and with
529 * either multiple Content-Length header fields having differing
530 * field-values or a single Content-Length header field having an
531 * invalid value, then the message framing is invalid and the
532 * recipient MUST treat it as an unrecoverable error. If this is a
533 * request message, the server MUST respond with a 400 (Bad Request)
534 * status code and then close the connection. If this is a response
535 * message received by a proxy, the proxy MUST close the connection
536 * to the server, discard the received response, and send a 502 (Bad
537 * Gateway) response to the client. If this is a response message
538 * received by a user agent, the user agent MUST close the
539 * connection to the server and discard the received response.
540 *
541 * 5. If a valid Content-Length header field is present without
542 * Transfer-Encoding, its decimal value defines the expected message
543 * body length in octets. If the sender closes the connection or
544 * the recipient times out before the indicated number of octets are
545 * received, the recipient MUST consider the message to be
546 * incomplete and close the connection.
547 *
548 * 6. If this is a request message and none of the above are true, then
549 * the message body length is zero (no message body is present).
550 *
551 * 7. Otherwise, this is a response message without a declared message
552 * body length, so the message body length is determined by the
553 * number of octets received prior to the server closing the
554 * connection.
555 */
556
557 ctx.idx = 0;
558 /* set TE_CHNK and XFER_LEN only if "chunked" is seen last */
559 while (http_find_header2("Transfer-Encoding", 17, ci_head(req), &txn->hdr_idx, &ctx)) {
560 if (ctx.vlen == 7 && strncasecmp(ctx.line + ctx.val, "chunked", 7) == 0)
561 msg->flags |= HTTP_MSGF_TE_CHNK;
562 else if (msg->flags & HTTP_MSGF_TE_CHNK) {
563 /* chunked not last, return badreq */
564 goto return_bad_req;
565 }
566 }
567
568 /* Chunked requests must have their content-length removed */
569 ctx.idx = 0;
570 if (msg->flags & HTTP_MSGF_TE_CHNK) {
571 while (http_find_header2("Content-Length", 14, ci_head(req), &txn->hdr_idx, &ctx))
572 http_remove_header2(msg, &txn->hdr_idx, &ctx);
573 }
574 else while (http_find_header2("Content-Length", 14, ci_head(req), &txn->hdr_idx, &ctx)) {
575 signed long long cl;
576
577 if (!ctx.vlen) {
578 msg->err_pos = ctx.line + ctx.val - ci_head(req);
579 goto return_bad_req;
580 }
581
582 if (strl2llrc(ctx.line + ctx.val, ctx.vlen, &cl)) {
583 msg->err_pos = ctx.line + ctx.val - ci_head(req);
584 goto return_bad_req; /* parse failure */
585 }
586
587 if (cl < 0) {
588 msg->err_pos = ctx.line + ctx.val - ci_head(req);
589 goto return_bad_req;
590 }
591
592 if ((msg->flags & HTTP_MSGF_CNT_LEN) && (msg->chunk_len != cl)) {
593 msg->err_pos = ctx.line + ctx.val - ci_head(req);
594 goto return_bad_req; /* already specified, was different */
595 }
596
597 msg->flags |= HTTP_MSGF_CNT_LEN;
598 msg->body_len = msg->chunk_len = cl;
599 }
600
601 /* even bodyless requests have a known length */
602 msg->flags |= HTTP_MSGF_XFER_LEN;
603
604 /* Until set to anything else, the connection mode is set as Keep-Alive. It will
605 * only change if both the request and the config reference something else.
606 * Option httpclose by itself sets tunnel mode where headers are mangled.
607 * However, if another mode is set, it will affect it (eg: server-close/
608 * keep-alive + httpclose = close). Note that we avoid to redo the same work
609 * if FE and BE have the same settings (common). The method consists in
610 * checking if options changed between the two calls (implying that either
611 * one is non-null, or one of them is non-null and we are there for the first
612 * time.
613 */
Christopher Fauletf2824e62018-10-01 12:12:37 +0200614 if ((sess->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE))
615 htx_adjust_conn_mode(s, txn, msg);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200616
617 /* we may have to wait for the request's body */
618 if ((s->be->options & PR_O_WREQ_BODY) &&
619 (msg->body_len || (msg->flags & HTTP_MSGF_TE_CHNK)))
620 req->analysers |= AN_REQ_HTTP_BODY;
621
622 /*
623 * RFC7234#4:
624 * A cache MUST write through requests with methods
625 * that are unsafe (Section 4.2.1 of [RFC7231]) to
626 * the origin server; i.e., a cache is not allowed
627 * to generate a reply to such a request before
628 * having forwarded the request and having received
629 * a corresponding response.
630 *
631 * RFC7231#4.2.1:
632 * Of the request methods defined by this
633 * specification, the GET, HEAD, OPTIONS, and TRACE
634 * methods are defined to be safe.
635 */
636 if (likely(txn->meth == HTTP_METH_GET ||
637 txn->meth == HTTP_METH_HEAD ||
638 txn->meth == HTTP_METH_OPTIONS ||
639 txn->meth == HTTP_METH_TRACE))
640 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
641
642 /* end of job, return OK */
643 req->analysers &= ~an_bit;
644 req->analyse_exp = TICK_ETERNITY;
645 return 1;
646
647 return_bad_req:
648 /* We centralize bad requests processing here */
649 if (unlikely(msg->msg_state == HTTP_MSG_ERROR) || msg->err_pos >= 0) {
650 /* we detected a parsing error. We want to archive this request
651 * in the dedicated proxy area for later troubleshooting.
652 */
653 http_capture_bad_message(sess->fe, s, msg, msg->err_state, sess->fe);
654 }
655
656 txn->req.err_state = txn->req.msg_state;
657 txn->req.msg_state = HTTP_MSG_ERROR;
658 txn->status = 400;
659 http_reply_and_close(s, txn->status, http_error_message(s));
660
661 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
662 if (sess->listener->counters)
663 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
664
665 return_prx_cond:
666 if (!(s->flags & SF_ERR_MASK))
667 s->flags |= SF_ERR_PRXCOND;
668 if (!(s->flags & SF_FINST_MASK))
669 s->flags |= SF_FINST_R;
670
671 req->analysers &= AN_REQ_FLT_END;
672 req->analyse_exp = TICK_ETERNITY;
673 return 0;
674}
675
676
677/* This stream analyser runs all HTTP request processing which is common to
678 * frontends and backends, which means blocking ACLs, filters, connection-close,
679 * reqadd, stats and redirects. This is performed for the designated proxy.
680 * It returns 1 if the processing can continue on next analysers, or zero if it
681 * either needs more data or wants to immediately abort the request (eg: deny,
682 * error, ...).
683 */
684int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
685{
686 struct session *sess = s->sess;
687 struct http_txn *txn = s->txn;
688 struct http_msg *msg = &txn->req;
689 struct redirect_rule *rule;
690 struct cond_wordlist *wl;
691 enum rule_result verdict;
692 int deny_status = HTTP_ERR_403;
693 struct connection *conn = objt_conn(sess->origin);
694
695 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
696 /* we need more data */
697 goto return_prx_yield;
698 }
699
700 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
701 now_ms, __FUNCTION__,
702 s,
703 req,
704 req->rex, req->wex,
705 req->flags,
706 ci_data(req),
707 req->analysers);
708
709 /* just in case we have some per-backend tracking */
710 stream_inc_be_http_req_ctr(s);
711
712 /* evaluate http-request rules */
713 if (!LIST_ISEMPTY(&px->http_req_rules)) {
714 verdict = http_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
715
716 switch (verdict) {
717 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
718 goto return_prx_yield;
719
720 case HTTP_RULE_RES_CONT:
721 case HTTP_RULE_RES_STOP: /* nothing to do */
722 break;
723
724 case HTTP_RULE_RES_DENY: /* deny or tarpit */
725 if (txn->flags & TX_CLTARPIT)
726 goto tarpit;
727 goto deny;
728
729 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
730 goto return_prx_cond;
731
732 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
733 goto done;
734
735 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
736 goto return_bad_req;
737 }
738 }
739
740 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
741 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
742 struct hdr_ctx ctx;
743
744 ctx.idx = 0;
745 if (!http_find_header2("Early-Data", strlen("Early-Data"),
746 ci_head(&s->req), &txn->hdr_idx, &ctx)) {
747 if (unlikely(http_header_add_tail2(&txn->req,
748 &txn->hdr_idx, "Early-Data: 1",
749 strlen("Early-Data: 1")) < 0)) {
750 goto return_bad_req;
751 }
752 }
753
754 }
755
756 /* OK at this stage, we know that the request was accepted according to
757 * the http-request rules, we can check for the stats. Note that the
758 * URI is detected *before* the req* rules in order not to be affected
759 * by a possible reqrep, while they are processed *after* so that a
760 * reqdeny can still block them. This clearly needs to change in 1.6!
761 */
762 if (stats_check_uri(&s->si[1], txn, px)) {
763 s->target = &http_stats_applet.obj_type;
764 if (unlikely(!stream_int_register_handler(&s->si[1], objt_applet(s->target)))) {
765 txn->status = 500;
766 s->logs.tv_request = now;
767 http_reply_and_close(s, txn->status, http_error_message(s));
768
769 if (!(s->flags & SF_ERR_MASK))
770 s->flags |= SF_ERR_RESOURCE;
771 goto return_prx_cond;
772 }
773
774 /* parse the whole stats request and extract the relevant information */
775 http_handle_stats(s, req);
776 verdict = http_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
777 /* not all actions implemented: deny, allow, auth */
778
779 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
780 goto deny;
781
782 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
783 goto return_prx_cond;
784 }
785
786 /* evaluate the req* rules except reqadd */
787 if (px->req_exp != NULL) {
788 if (apply_filters_to_request(s, req, px) < 0)
789 goto return_bad_req;
790
791 if (txn->flags & TX_CLDENY)
792 goto deny;
793
794 if (txn->flags & TX_CLTARPIT) {
795 deny_status = HTTP_ERR_500;
796 goto tarpit;
797 }
798 }
799
800 /* add request headers from the rule sets in the same order */
801 list_for_each_entry(wl, &px->req_add, list) {
802 if (wl->cond) {
803 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
804 ret = acl_pass(ret);
805 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
806 ret = !ret;
807 if (!ret)
808 continue;
809 }
810
811 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, wl->s, strlen(wl->s)) < 0))
812 goto return_bad_req;
813 }
814
815
816 /* Proceed with the stats now. */
817 if (unlikely(objt_applet(s->target) == &http_stats_applet) ||
818 unlikely(objt_applet(s->target) == &http_cache_applet)) {
819 /* process the stats request now */
820 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
821 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
822
823 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
824 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
825 if (!(s->flags & SF_FINST_MASK))
826 s->flags |= SF_FINST_R;
827
828 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
829 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
830 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
831 req->analysers |= AN_REQ_HTTP_XFER_BODY;
832 goto done;
833 }
834
835 /* check whether we have some ACLs set to redirect this request */
836 list_for_each_entry(rule, &px->redirect_rules, list) {
837 if (rule->cond) {
838 int ret;
839
840 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
841 ret = acl_pass(ret);
842 if (rule->cond->pol == ACL_COND_UNLESS)
843 ret = !ret;
844 if (!ret)
845 continue;
846 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200847 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200848 goto return_bad_req;
849 goto done;
850 }
851
852 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
853 * If this happens, then the data will not come immediately, so we must
854 * send all what we have without waiting. Note that due to the small gain
855 * in waiting for the body of the request, it's easier to simply put the
856 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
857 * itself once used.
858 */
859 req->flags |= CF_SEND_DONTWAIT;
860
861 done: /* done with this analyser, continue with next ones that the calling
862 * points will have set, if any.
863 */
864 req->analyse_exp = TICK_ETERNITY;
865 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
866 req->analysers &= ~an_bit;
867 return 1;
868
869 tarpit:
870 /* Allow cookie logging
871 */
872 if (s->be->cookie_name || sess->fe->capture_name)
873 manage_client_side_cookies(s, req);
874
875 /* When a connection is tarpitted, we use the tarpit timeout,
876 * which may be the same as the connect timeout if unspecified.
877 * If unset, then set it to zero because we really want it to
878 * eventually expire. We build the tarpit as an analyser.
879 */
880 channel_erase(&s->req);
881
882 /* wipe the request out so that we can drop the connection early
883 * if the client closes first.
884 */
885 channel_dont_connect(req);
886
887 txn->status = http_err_codes[deny_status];
888
889 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
890 req->analysers |= AN_REQ_HTTP_TARPIT;
891 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
892 if (!req->analyse_exp)
893 req->analyse_exp = tick_add(now_ms, 0);
894 stream_inc_http_err_ctr(s);
895 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
896 if (sess->fe != s->be)
897 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
898 if (sess->listener->counters)
899 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
900 goto done_without_exp;
901
902 deny: /* this request was blocked (denied) */
903
904 /* Allow cookie logging
905 */
906 if (s->be->cookie_name || sess->fe->capture_name)
907 manage_client_side_cookies(s, req);
908
909 txn->flags |= TX_CLDENY;
910 txn->status = http_err_codes[deny_status];
911 s->logs.tv_request = now;
912 http_reply_and_close(s, txn->status, http_error_message(s));
913 stream_inc_http_err_ctr(s);
914 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
915 if (sess->fe != s->be)
916 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
917 if (sess->listener->counters)
918 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
919 goto return_prx_cond;
920
921 return_bad_req:
922 /* We centralize bad requests processing here */
923 if (unlikely(msg->msg_state == HTTP_MSG_ERROR) || msg->err_pos >= 0) {
924 /* we detected a parsing error. We want to archive this request
925 * in the dedicated proxy area for later troubleshooting.
926 */
927 http_capture_bad_message(sess->fe, s, msg, msg->err_state, sess->fe);
928 }
929
930 txn->req.err_state = txn->req.msg_state;
931 txn->req.msg_state = HTTP_MSG_ERROR;
932 txn->status = 400;
933 http_reply_and_close(s, txn->status, http_error_message(s));
934
935 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
936 if (sess->listener->counters)
937 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
938
939 return_prx_cond:
940 if (!(s->flags & SF_ERR_MASK))
941 s->flags |= SF_ERR_PRXCOND;
942 if (!(s->flags & SF_FINST_MASK))
943 s->flags |= SF_FINST_R;
944
945 req->analysers &= AN_REQ_FLT_END;
946 req->analyse_exp = TICK_ETERNITY;
947 return 0;
948
949 return_prx_yield:
950 channel_dont_connect(req);
951 return 0;
952}
953
954/* This function performs all the processing enabled for the current request.
955 * It returns 1 if the processing can continue on next analysers, or zero if it
956 * needs more data, encounters an error, or wants to immediately abort the
957 * request. It relies on buffers flags, and updates s->req.analysers.
958 */
959int htx_process_request(struct stream *s, struct channel *req, int an_bit)
960{
961 struct session *sess = s->sess;
962 struct http_txn *txn = s->txn;
963 struct http_msg *msg = &txn->req;
964 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
965
966 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
967 /* we need more data */
968 channel_dont_connect(req);
969 return 0;
970 }
971
972 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
973 now_ms, __FUNCTION__,
974 s,
975 req,
976 req->rex, req->wex,
977 req->flags,
978 ci_data(req),
979 req->analysers);
980
981 /*
982 * Right now, we know that we have processed the entire headers
983 * and that unwanted requests have been filtered out. We can do
984 * whatever we want with the remaining request. Also, now we
985 * may have separate values for ->fe, ->be.
986 */
987
988 /*
989 * If HTTP PROXY is set we simply get remote server address parsing
990 * incoming request. Note that this requires that a connection is
991 * allocated on the server side.
992 */
993 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
994 struct connection *conn;
995 char *path;
996
997 /* Note that for now we don't reuse existing proxy connections */
998 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
999 txn->req.err_state = txn->req.msg_state;
1000 txn->req.msg_state = HTTP_MSG_ERROR;
1001 txn->status = 500;
1002 req->analysers &= AN_REQ_FLT_END;
1003 http_reply_and_close(s, txn->status, http_error_message(s));
1004
1005 if (!(s->flags & SF_ERR_MASK))
1006 s->flags |= SF_ERR_RESOURCE;
1007 if (!(s->flags & SF_FINST_MASK))
1008 s->flags |= SF_FINST_R;
1009
1010 return 0;
1011 }
1012
1013 path = http_txn_get_path(txn);
1014 if (url2sa(ci_head(req) + msg->sl.rq.u,
1015 path ? path - (ci_head(req) + msg->sl.rq.u) : msg->sl.rq.u_l,
1016 &conn->addr.to, NULL) == -1)
1017 goto return_bad_req;
1018
1019 /* if the path was found, we have to remove everything between
1020 * ci_head(req) + msg->sl.rq.u and path (excluded). If it was not
1021 * found, we need to replace from ci_head(req) + msg->sl.rq.u for
1022 * u_l characters by a single "/".
1023 */
1024 if (path) {
1025 char *cur_ptr = ci_head(req);
1026 char *cur_end = cur_ptr + txn->req.sl.rq.l;
1027 int delta;
1028
1029 delta = b_rep_blk(&req->buf, cur_ptr + msg->sl.rq.u, path, NULL, 0);
1030 http_msg_move_end(&txn->req, delta);
1031 cur_end += delta;
1032 if (http_parse_reqline(&txn->req, HTTP_MSG_RQMETH, cur_ptr, cur_end + 1, NULL, NULL) == NULL)
1033 goto return_bad_req;
1034 }
1035 else {
1036 char *cur_ptr = ci_head(req);
1037 char *cur_end = cur_ptr + txn->req.sl.rq.l;
1038 int delta;
1039
1040 delta = b_rep_blk(&req->buf, cur_ptr + msg->sl.rq.u,
1041 cur_ptr + msg->sl.rq.u + msg->sl.rq.u_l, "/", 1);
1042 http_msg_move_end(&txn->req, delta);
1043 cur_end += delta;
1044 if (http_parse_reqline(&txn->req, HTTP_MSG_RQMETH, cur_ptr, cur_end + 1, NULL, NULL) == NULL)
1045 goto return_bad_req;
1046 }
1047 }
1048
1049 /*
1050 * 7: Now we can work with the cookies.
1051 * Note that doing so might move headers in the request, but
1052 * the fields will stay coherent and the URI will not move.
1053 * This should only be performed in the backend.
1054 */
1055 if (s->be->cookie_name || sess->fe->capture_name)
1056 manage_client_side_cookies(s, req);
1057
1058 /* add unique-id if "header-unique-id" is specified */
1059
1060 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
1061 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
1062 goto return_bad_req;
1063 s->unique_id[0] = '\0';
1064 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
1065 }
1066
1067 if (sess->fe->header_unique_id && s->unique_id) {
1068 if (chunk_printf(&trash, "%s: %s", sess->fe->header_unique_id, s->unique_id) < 0)
1069 goto return_bad_req;
1070 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.area, trash.data) < 0))
1071 goto return_bad_req;
1072 }
1073
1074 /*
1075 * 9: add X-Forwarded-For if either the frontend or the backend
1076 * asks for it.
1077 */
1078 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
1079 struct hdr_ctx ctx = { .idx = 0 };
1080 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
1081 http_find_header2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
1082 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len,
1083 ci_head(req), &txn->hdr_idx, &ctx)) {
1084 /* The header is set to be added only if none is present
1085 * and we found it, so don't do anything.
1086 */
1087 }
1088 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
1089 /* Add an X-Forwarded-For header unless the source IP is
1090 * in the 'except' network range.
1091 */
1092 if ((!sess->fe->except_mask.s_addr ||
1093 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
1094 != sess->fe->except_net.s_addr) &&
1095 (!s->be->except_mask.s_addr ||
1096 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
1097 != s->be->except_net.s_addr)) {
1098 int len;
1099 unsigned char *pn;
1100 pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
1101
1102 /* Note: we rely on the backend to get the header name to be used for
1103 * x-forwarded-for, because the header is really meant for the backends.
1104 * However, if the backend did not specify any option, we have to rely
1105 * on the frontend's header name.
1106 */
1107 if (s->be->fwdfor_hdr_len) {
1108 len = s->be->fwdfor_hdr_len;
1109 memcpy(trash.area,
1110 s->be->fwdfor_hdr_name, len);
1111 } else {
1112 len = sess->fe->fwdfor_hdr_len;
1113 memcpy(trash.area,
1114 sess->fe->fwdfor_hdr_name, len);
1115 }
1116 len += snprintf(trash.area + len,
1117 trash.size - len,
1118 ": %d.%d.%d.%d", pn[0], pn[1],
1119 pn[2], pn[3]);
1120
1121 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.area, len) < 0))
1122 goto return_bad_req;
1123 }
1124 }
1125 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
1126 /* FIXME: for the sake of completeness, we should also support
1127 * 'except' here, although it is mostly useless in this case.
1128 */
1129 int len;
1130 char pn[INET6_ADDRSTRLEN];
1131 inet_ntop(AF_INET6,
1132 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
1133 pn, sizeof(pn));
1134
1135 /* Note: we rely on the backend to get the header name to be used for
1136 * x-forwarded-for, because the header is really meant for the backends.
1137 * However, if the backend did not specify any option, we have to rely
1138 * on the frontend's header name.
1139 */
1140 if (s->be->fwdfor_hdr_len) {
1141 len = s->be->fwdfor_hdr_len;
1142 memcpy(trash.area, s->be->fwdfor_hdr_name,
1143 len);
1144 } else {
1145 len = sess->fe->fwdfor_hdr_len;
1146 memcpy(trash.area, sess->fe->fwdfor_hdr_name,
1147 len);
1148 }
1149 len += snprintf(trash.area + len, trash.size - len,
1150 ": %s", pn);
1151
1152 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.area, len) < 0))
1153 goto return_bad_req;
1154 }
1155 }
1156
1157 /*
1158 * 10: add X-Original-To if either the frontend or the backend
1159 * asks for it.
1160 */
1161 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
1162
1163 /* FIXME: don't know if IPv6 can handle that case too. */
1164 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
1165 /* Add an X-Original-To header unless the destination IP is
1166 * in the 'except' network range.
1167 */
1168 conn_get_to_addr(cli_conn);
1169
1170 if (cli_conn->addr.to.ss_family == AF_INET &&
1171 ((!sess->fe->except_mask_to.s_addr ||
1172 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
1173 != sess->fe->except_to.s_addr) &&
1174 (!s->be->except_mask_to.s_addr ||
1175 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
1176 != s->be->except_to.s_addr))) {
1177 int len;
1178 unsigned char *pn;
1179 pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
1180
1181 /* Note: we rely on the backend to get the header name to be used for
1182 * x-original-to, because the header is really meant for the backends.
1183 * However, if the backend did not specify any option, we have to rely
1184 * on the frontend's header name.
1185 */
1186 if (s->be->orgto_hdr_len) {
1187 len = s->be->orgto_hdr_len;
1188 memcpy(trash.area,
1189 s->be->orgto_hdr_name, len);
1190 } else {
1191 len = sess->fe->orgto_hdr_len;
1192 memcpy(trash.area,
1193 sess->fe->orgto_hdr_name, len);
1194 }
1195 len += snprintf(trash.area + len,
1196 trash.size - len,
1197 ": %d.%d.%d.%d", pn[0], pn[1],
1198 pn[2], pn[3]);
1199
1200 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.area, len) < 0))
1201 goto return_bad_req;
1202 }
1203 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001204 }
1205
Christopher Faulete0768eb2018-10-03 16:38:02 +02001206 /* If we have no server assigned yet and we're balancing on url_param
1207 * with a POST request, we may be interested in checking the body for
1208 * that parameter. This will be done in another analyser.
1209 */
1210 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
1211 s->txn->meth == HTTP_METH_POST && s->be->url_param_name != NULL &&
1212 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
1213 channel_dont_connect(req);
1214 req->analysers |= AN_REQ_HTTP_BODY;
1215 }
1216
1217 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
1218 req->analysers |= AN_REQ_HTTP_XFER_BODY;
1219#ifdef TCP_QUICKACK
1220 /* We expect some data from the client. Unless we know for sure
1221 * we already have a full request, we have to re-enable quick-ack
1222 * in case we previously disabled it, otherwise we might cause
1223 * the client to delay further data.
1224 */
1225 if ((sess->listener->options & LI_O_NOQUICKACK) &&
1226 cli_conn && conn_ctrl_ready(cli_conn) &&
1227 ((msg->flags & HTTP_MSGF_TE_CHNK) ||
1228 (msg->body_len > ci_data(req) - txn->req.eoh - 2)))
1229 setsockopt(cli_conn->handle.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
1230#endif
1231
1232 /*************************************************************
1233 * OK, that's finished for the headers. We have done what we *
1234 * could. Let's switch to the DATA state. *
1235 ************************************************************/
1236 req->analyse_exp = TICK_ETERNITY;
1237 req->analysers &= ~an_bit;
1238
1239 s->logs.tv_request = now;
1240 /* OK let's go on with the BODY now */
1241 return 1;
1242
1243 return_bad_req: /* let's centralize all bad requests */
1244 if (unlikely(msg->msg_state == HTTP_MSG_ERROR) || msg->err_pos >= 0) {
1245 /* we detected a parsing error. We want to archive this request
1246 * in the dedicated proxy area for later troubleshooting.
1247 */
1248 http_capture_bad_message(sess->fe, s, msg, msg->err_state, sess->fe);
1249 }
1250
1251 txn->req.err_state = txn->req.msg_state;
1252 txn->req.msg_state = HTTP_MSG_ERROR;
1253 txn->status = 400;
1254 req->analysers &= AN_REQ_FLT_END;
1255 http_reply_and_close(s, txn->status, http_error_message(s));
1256
1257 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1258 if (sess->listener->counters)
1259 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1260
1261 if (!(s->flags & SF_ERR_MASK))
1262 s->flags |= SF_ERR_PRXCOND;
1263 if (!(s->flags & SF_FINST_MASK))
1264 s->flags |= SF_FINST_R;
1265 return 0;
1266}
1267
1268/* This function is an analyser which processes the HTTP tarpit. It always
1269 * returns zero, at the beginning because it prevents any other processing
1270 * from occurring, and at the end because it terminates the request.
1271 */
1272int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
1273{
1274 struct http_txn *txn = s->txn;
1275
1276 /* This connection is being tarpitted. The CLIENT side has
1277 * already set the connect expiration date to the right
1278 * timeout. We just have to check that the client is still
1279 * there and that the timeout has not expired.
1280 */
1281 channel_dont_connect(req);
1282 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1283 !tick_is_expired(req->analyse_exp, now_ms))
1284 return 0;
1285
1286 /* We will set the queue timer to the time spent, just for
1287 * logging purposes. We fake a 500 server error, so that the
1288 * attacker will not suspect his connection has been tarpitted.
1289 * It will not cause trouble to the logs because we can exclude
1290 * the tarpitted connections by filtering on the 'PT' status flags.
1291 */
1292 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1293
1294 if (!(req->flags & CF_READ_ERROR))
1295 http_reply_and_close(s, txn->status, http_error_message(s));
1296
1297 req->analysers &= AN_REQ_FLT_END;
1298 req->analyse_exp = TICK_ETERNITY;
1299
1300 if (!(s->flags & SF_ERR_MASK))
1301 s->flags |= SF_ERR_PRXCOND;
1302 if (!(s->flags & SF_FINST_MASK))
1303 s->flags |= SF_FINST_T;
1304 return 0;
1305}
1306
1307/* This function is an analyser which waits for the HTTP request body. It waits
1308 * for either the buffer to be full, or the full advertised contents to have
1309 * reached the buffer. It must only be called after the standard HTTP request
1310 * processing has occurred, because it expects the request to be parsed and will
1311 * look for the Expect header. It may send a 100-Continue interim response. It
1312 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1313 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1314 * needs to read more data, or 1 once it has completed its analysis.
1315 */
1316int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1317{
1318 struct session *sess = s->sess;
1319 struct http_txn *txn = s->txn;
1320 struct http_msg *msg = &s->txn->req;
1321
1322 /* We have to parse the HTTP request body to find any required data.
1323 * "balance url_param check_post" should have been the only way to get
1324 * into this. We were brought here after HTTP header analysis, so all
1325 * related structures are ready.
1326 */
1327
1328 if (msg->msg_state < HTTP_MSG_CHUNK_SIZE) {
1329 /* This is the first call */
1330 if (msg->msg_state < HTTP_MSG_BODY)
1331 goto missing_data;
1332
1333 if (msg->msg_state < HTTP_MSG_100_SENT) {
1334 /* If we have HTTP/1.1 and Expect: 100-continue, then we must
1335 * send an HTTP/1.1 100 Continue intermediate response.
1336 */
1337 if (msg->flags & HTTP_MSGF_VER_11) {
1338 struct hdr_ctx ctx;
1339 ctx.idx = 0;
1340 /* Expect is allowed in 1.1, look for it */
1341 if (http_find_header2("Expect", 6, ci_head(req), &txn->hdr_idx, &ctx) &&
1342 unlikely(ctx.vlen == 12 && strncasecmp(ctx.line+ctx.val, "100-continue", 12) == 0)) {
1343 co_inject(&s->res, HTTP_100.ptr, HTTP_100.len);
1344 http_remove_header2(&txn->req, &txn->hdr_idx, &ctx);
1345 }
1346 }
1347 msg->msg_state = HTTP_MSG_100_SENT;
1348 }
1349
1350 /* we have msg->sov which points to the first byte of message body.
1351 * ci_head(req) still points to the beginning of the message. We
1352 * must save the body in msg->next because it survives buffer
1353 * re-alignments.
1354 */
1355 msg->next = msg->sov;
1356
1357 if (msg->flags & HTTP_MSGF_TE_CHNK)
1358 msg->msg_state = HTTP_MSG_CHUNK_SIZE;
1359 else
1360 msg->msg_state = HTTP_MSG_DATA;
1361 }
1362
1363 if (!(msg->flags & HTTP_MSGF_TE_CHNK)) {
1364 /* We're in content-length mode, we just have to wait for enough data. */
1365 if (http_body_bytes(msg) < msg->body_len)
1366 goto missing_data;
1367
1368 /* OK we have everything we need now */
1369 goto http_end;
1370 }
1371
1372 /* OK here we're parsing a chunked-encoded message */
1373
1374 if (msg->msg_state == HTTP_MSG_CHUNK_SIZE) {
1375 /* read the chunk size and assign it to ->chunk_len, then
1376 * set ->sov and ->next to point to the body and switch to DATA or
1377 * TRAILERS state.
1378 */
1379 unsigned int chunk;
1380 int ret = h1_parse_chunk_size(&req->buf, co_data(req) + msg->next, c_data(req), &chunk);
1381
1382 if (!ret)
1383 goto missing_data;
1384 else if (ret < 0) {
1385 msg->err_pos = ci_data(req) + ret;
1386 if (msg->err_pos < 0)
1387 msg->err_pos += req->buf.size;
1388 stream_inc_http_err_ctr(s);
1389 goto return_bad_req;
1390 }
1391
1392 msg->chunk_len = chunk;
1393 msg->body_len += chunk;
1394
1395 msg->sol = ret;
1396 msg->next += ret;
1397 msg->msg_state = msg->chunk_len ? HTTP_MSG_DATA : HTTP_MSG_TRAILERS;
1398 }
1399
1400 /* Now we're in HTTP_MSG_DATA or HTTP_MSG_TRAILERS state.
1401 * We have the first data byte is in msg->sov + msg->sol. We're waiting
1402 * for at least a whole chunk or the whole content length bytes after
1403 * msg->sov + msg->sol.
1404 */
1405 if (msg->msg_state == HTTP_MSG_TRAILERS)
1406 goto http_end;
1407
1408 if (http_body_bytes(msg) >= msg->body_len) /* we have enough bytes now */
1409 goto http_end;
1410
1411 missing_data:
1412 /* we get here if we need to wait for more data. If the buffer is full,
1413 * we have the maximum we can expect.
1414 */
1415 if (channel_full(req, global.tune.maxrewrite))
1416 goto http_end;
1417
1418 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1419 txn->status = 408;
1420 http_reply_and_close(s, txn->status, http_error_message(s));
1421
1422 if (!(s->flags & SF_ERR_MASK))
1423 s->flags |= SF_ERR_CLITO;
1424 if (!(s->flags & SF_FINST_MASK))
1425 s->flags |= SF_FINST_D;
1426 goto return_err_msg;
1427 }
1428
1429 /* we get here if we need to wait for more data */
1430 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1431 /* Not enough data. We'll re-use the http-request
1432 * timeout here. Ideally, we should set the timeout
1433 * relative to the accept() date. We just set the
1434 * request timeout once at the beginning of the
1435 * request.
1436 */
1437 channel_dont_connect(req);
1438 if (!tick_isset(req->analyse_exp))
1439 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1440 return 0;
1441 }
1442
1443 http_end:
1444 /* The situation will not evolve, so let's give up on the analysis. */
1445 s->logs.tv_request = now; /* update the request timer to reflect full request */
1446 req->analysers &= ~an_bit;
1447 req->analyse_exp = TICK_ETERNITY;
1448 return 1;
1449
1450 return_bad_req: /* let's centralize all bad requests */
1451 txn->req.err_state = txn->req.msg_state;
1452 txn->req.msg_state = HTTP_MSG_ERROR;
1453 txn->status = 400;
1454 http_reply_and_close(s, txn->status, http_error_message(s));
1455
1456 if (!(s->flags & SF_ERR_MASK))
1457 s->flags |= SF_ERR_PRXCOND;
1458 if (!(s->flags & SF_FINST_MASK))
1459 s->flags |= SF_FINST_R;
1460
1461 return_err_msg:
1462 req->analysers &= AN_REQ_FLT_END;
1463 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1464 if (sess->listener->counters)
1465 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1466 return 0;
1467}
1468
1469/* This function is an analyser which forwards request body (including chunk
1470 * sizes if any). It is called as soon as we must forward, even if we forward
1471 * zero byte. The only situation where it must not be called is when we're in
1472 * tunnel mode and we want to forward till the close. It's used both to forward
1473 * remaining data and to resync after end of body. It expects the msg_state to
1474 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1475 * read more data, or 1 once we can go on with next request or end the stream.
1476 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1477 * bytes of pending data + the headers if not already done.
1478 */
1479int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1480{
1481 struct session *sess = s->sess;
1482 struct http_txn *txn = s->txn;
1483 struct http_msg *msg = &s->txn->req;
1484 int ret;
1485
1486 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1487 now_ms, __FUNCTION__,
1488 s,
1489 req,
1490 req->rex, req->wex,
1491 req->flags,
1492 ci_data(req),
1493 req->analysers);
1494
1495 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
1496 return 0;
1497
1498 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1499 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1500 /* Output closed while we were sending data. We must abort and
1501 * wake the other side up.
1502 */
1503 msg->err_state = msg->msg_state;
1504 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001505 htx_end_request(s);
1506 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001507 return 1;
1508 }
1509
1510 /* Note that we don't have to send 100-continue back because we don't
1511 * need the data to complete our job, and it's up to the server to
1512 * decide whether to return 100, 417 or anything else in return of
1513 * an "Expect: 100-continue" header.
1514 */
1515 if (msg->msg_state == HTTP_MSG_BODY) {
1516 msg->msg_state = ((msg->flags & HTTP_MSGF_TE_CHNK)
1517 ? HTTP_MSG_CHUNK_SIZE
1518 : HTTP_MSG_DATA);
1519
1520 /* TODO/filters: when http-buffer-request option is set or if a
1521 * rule on url_param exists, the first chunk size could be
1522 * already parsed. In that case, msg->next is after the chunk
1523 * size (including the CRLF after the size). So this case should
1524 * be handled to */
1525 }
1526
1527 /* Some post-connect processing might want us to refrain from starting to
1528 * forward data. Currently, the only reason for this is "balance url_param"
1529 * whichs need to parse/process the request after we've enabled forwarding.
1530 */
1531 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1532 if (!(s->res.flags & CF_READ_ATTACHED)) {
1533 channel_auto_connect(req);
1534 req->flags |= CF_WAKE_CONNECT;
1535 channel_dont_close(req); /* don't fail on early shutr */
1536 goto waiting;
1537 }
1538 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1539 }
1540
1541 /* in most states, we should abort in case of early close */
1542 channel_auto_close(req);
1543
1544 if (req->to_forward) {
1545 /* We can't process the buffer's contents yet */
1546 req->flags |= CF_WAKE_WRITE;
1547 goto missing_data_or_waiting;
1548 }
1549
1550 if (msg->msg_state < HTTP_MSG_DONE) {
1551 ret = ((msg->flags & HTTP_MSGF_TE_CHNK)
1552 ? http_msg_forward_chunked_body(s, msg)
1553 : http_msg_forward_body(s, msg));
1554 if (!ret)
1555 goto missing_data_or_waiting;
1556 if (ret < 0)
1557 goto return_bad_req;
1558 }
1559
1560 /* other states, DONE...TUNNEL */
1561 /* we don't want to forward closes on DONE except in tunnel mode. */
1562 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1563 channel_dont_close(req);
1564
Christopher Fauletf2824e62018-10-01 12:12:37 +02001565 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001566 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001567 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001568 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1569 if (req->flags & CF_SHUTW) {
1570 /* request errors are most likely due to the
1571 * server aborting the transfer. */
1572 goto aborted_xfer;
1573 }
1574 if (msg->err_pos >= 0)
1575 http_capture_bad_message(sess->fe, s, msg, msg->err_state, s->be);
1576 goto return_bad_req;
1577 }
1578 return 1;
1579 }
1580
1581 /* If "option abortonclose" is set on the backend, we want to monitor
1582 * the client's connection and forward any shutdown notification to the
1583 * server, which will decide whether to close or to go on processing the
1584 * request. We only do that in tunnel mode, and not in other modes since
1585 * it can be abused to exhaust source ports. */
1586 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1587 channel_auto_read(req);
1588 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1589 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1590 s->si[1].flags |= SI_FL_NOLINGER;
1591 channel_auto_close(req);
1592 }
1593 else if (s->txn->meth == HTTP_METH_POST) {
1594 /* POST requests may require to read extra CRLF sent by broken
1595 * browsers and which could cause an RST to be sent upon close
1596 * on some systems (eg: Linux). */
1597 channel_auto_read(req);
1598 }
1599 return 0;
1600
1601 missing_data_or_waiting:
1602 /* stop waiting for data if the input is closed before the end */
1603 if (msg->msg_state < HTTP_MSG_ENDING && req->flags & CF_SHUTR) {
1604 if (!(s->flags & SF_ERR_MASK))
1605 s->flags |= SF_ERR_CLICL;
1606 if (!(s->flags & SF_FINST_MASK)) {
1607 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1608 s->flags |= SF_FINST_H;
1609 else
1610 s->flags |= SF_FINST_D;
1611 }
1612
1613 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1614 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1615 if (objt_server(s->target))
1616 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1617
1618 goto return_bad_req_stats_ok;
1619 }
1620
1621 waiting:
1622 /* waiting for the last bits to leave the buffer */
1623 if (req->flags & CF_SHUTW)
1624 goto aborted_xfer;
1625
1626 /* When TE: chunked is used, we need to get there again to parse remaining
1627 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1628 * And when content-length is used, we never want to let the possible
1629 * shutdown be forwarded to the other side, as the state machine will
1630 * take care of it once the client responds. It's also important to
1631 * prevent TIME_WAITs from accumulating on the backend side, and for
1632 * HTTP/2 where the last frame comes with a shutdown.
1633 */
1634 if (msg->flags & (HTTP_MSGF_TE_CHNK|HTTP_MSGF_CNT_LEN))
1635 channel_dont_close(req);
1636
1637 /* We know that more data are expected, but we couldn't send more that
1638 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1639 * system knows it must not set a PUSH on this first part. Interactive
1640 * modes are already handled by the stream sock layer. We must not do
1641 * this in content-length mode because it could present the MSG_MORE
1642 * flag with the last block of forwarded data, which would cause an
1643 * additional delay to be observed by the receiver.
1644 */
1645 if (msg->flags & HTTP_MSGF_TE_CHNK)
1646 req->flags |= CF_EXPECT_MORE;
1647
1648 return 0;
1649
1650 return_bad_req: /* let's centralize all bad requests */
1651 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1652 if (sess->listener->counters)
1653 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1654
1655 return_bad_req_stats_ok:
1656 txn->req.err_state = txn->req.msg_state;
1657 txn->req.msg_state = HTTP_MSG_ERROR;
1658 if (txn->status) {
1659 /* Note: we don't send any error if some data were already sent */
1660 http_reply_and_close(s, txn->status, NULL);
1661 } else {
1662 txn->status = 400;
1663 http_reply_and_close(s, txn->status, http_error_message(s));
1664 }
1665 req->analysers &= AN_REQ_FLT_END;
1666 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1667
1668 if (!(s->flags & SF_ERR_MASK))
1669 s->flags |= SF_ERR_PRXCOND;
1670 if (!(s->flags & SF_FINST_MASK)) {
1671 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1672 s->flags |= SF_FINST_H;
1673 else
1674 s->flags |= SF_FINST_D;
1675 }
1676 return 0;
1677
1678 aborted_xfer:
1679 txn->req.err_state = txn->req.msg_state;
1680 txn->req.msg_state = HTTP_MSG_ERROR;
1681 if (txn->status) {
1682 /* Note: we don't send any error if some data were already sent */
1683 http_reply_and_close(s, txn->status, NULL);
1684 } else {
1685 txn->status = 502;
1686 http_reply_and_close(s, txn->status, http_error_message(s));
1687 }
1688 req->analysers &= AN_REQ_FLT_END;
1689 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1690
1691 HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1692 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1693 if (objt_server(s->target))
1694 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1695
1696 if (!(s->flags & SF_ERR_MASK))
1697 s->flags |= SF_ERR_SRVCL;
1698 if (!(s->flags & SF_FINST_MASK)) {
1699 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1700 s->flags |= SF_FINST_H;
1701 else
1702 s->flags |= SF_FINST_D;
1703 }
1704 return 0;
1705}
1706
1707/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1708 * processing can continue on next analysers, or zero if it either needs more
1709 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1710 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1711 * when it has nothing left to do, and may remove any analyser when it wants to
1712 * abort.
1713 */
1714int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1715{
1716 struct session *sess = s->sess;
1717 struct http_txn *txn = s->txn;
1718 struct http_msg *msg = &txn->rsp;
1719 struct hdr_ctx ctx;
1720 int use_close_only;
1721 int cur_idx;
1722 int n;
1723
1724 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1725 now_ms, __FUNCTION__,
1726 s,
1727 rep,
1728 rep->rex, rep->wex,
1729 rep->flags,
1730 ci_data(rep),
1731 rep->analysers);
1732
1733 /*
1734 * Now parse the partial (or complete) lines.
1735 * We will check the response syntax, and also join multi-line
1736 * headers. An index of all the lines will be elaborated while
1737 * parsing.
1738 *
1739 * For the parsing, we use a 28 states FSM.
1740 *
1741 * Here is the information we currently have :
1742 * ci_head(rep) = beginning of response
1743 * ci_head(rep) + msg->eoh = end of processed headers / start of current one
1744 * ci_tail(rep) = end of input data
1745 * msg->eol = end of current header or line (LF or CRLF)
1746 * msg->next = first non-visited byte
1747 */
1748
1749 next_one:
1750 /* There's a protected area at the end of the buffer for rewriting
1751 * purposes. We don't want to start to parse the request if the
1752 * protected area is affected, because we may have to move processed
1753 * data later, which is much more complicated.
1754 */
1755 if (c_data(rep) && msg->msg_state < HTTP_MSG_ERROR) {
1756 if (unlikely(!channel_is_rewritable(rep))) {
1757 /* some data has still not left the buffer, wake us once that's done */
1758 if (rep->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_WRITE_ERROR|CF_WRITE_TIMEOUT))
1759 goto abort_response;
1760 channel_dont_close(rep);
1761 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1762 rep->flags |= CF_WAKE_WRITE;
1763 return 0;
1764 }
1765
1766 if (unlikely(ci_tail(rep) < c_ptr(rep, msg->next) ||
1767 ci_tail(rep) > b_wrap(&rep->buf) - global.tune.maxrewrite))
1768 channel_slow_realign(rep, trash.area);
1769
1770 if (likely(msg->next < ci_data(rep)))
1771 http_msg_analyzer(msg, &txn->hdr_idx);
1772 }
1773
1774 /* 1: we might have to print this header in debug mode */
1775 if (unlikely((global.mode & MODE_DEBUG) &&
1776 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) &&
1777 msg->msg_state >= HTTP_MSG_BODY)) {
1778 char *eol, *sol;
1779
1780 sol = ci_head(rep);
1781 eol = sol + (msg->sl.st.l ? msg->sl.st.l : ci_data(rep));
1782 debug_hdr("srvrep", s, sol, eol);
1783
1784 sol += hdr_idx_first_pos(&txn->hdr_idx);
1785 cur_idx = hdr_idx_first_idx(&txn->hdr_idx);
1786
1787 while (cur_idx) {
1788 eol = sol + txn->hdr_idx.v[cur_idx].len;
1789 debug_hdr("srvhdr", s, sol, eol);
1790 sol = eol + txn->hdr_idx.v[cur_idx].cr + 1;
1791 cur_idx = txn->hdr_idx.v[cur_idx].next;
1792 }
1793 }
1794
1795 /*
1796 * Now we quickly check if we have found a full valid response.
1797 * If not so, we check the FD and buffer states before leaving.
1798 * A full response is indicated by the fact that we have seen
1799 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1800 * responses are checked first.
1801 *
1802 * Depending on whether the client is still there or not, we
1803 * may send an error response back or not. Note that normally
1804 * we should only check for HTTP status there, and check I/O
1805 * errors somewhere else.
1806 */
1807
1808 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
1809 /* Invalid response */
1810 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1811 /* we detected a parsing error. We want to archive this response
1812 * in the dedicated proxy area for later troubleshooting.
1813 */
1814 hdr_response_bad:
1815 if (msg->msg_state == HTTP_MSG_ERROR || msg->err_pos >= 0)
1816 http_capture_bad_message(s->be, s, msg, msg->err_state, sess->fe);
1817
1818 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1819 if (objt_server(s->target)) {
1820 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1821 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
1822 }
1823 abort_response:
1824 channel_auto_close(rep);
1825 rep->analysers &= AN_RES_FLT_END;
1826 txn->status = 502;
1827 s->si[1].flags |= SI_FL_NOLINGER;
1828 channel_truncate(rep);
1829 http_reply_and_close(s, txn->status, http_error_message(s));
1830
1831 if (!(s->flags & SF_ERR_MASK))
1832 s->flags |= SF_ERR_PRXCOND;
1833 if (!(s->flags & SF_FINST_MASK))
1834 s->flags |= SF_FINST_H;
1835
1836 return 0;
1837 }
1838
1839 /* too large response does not fit in buffer. */
1840 else if (channel_full(rep, global.tune.maxrewrite)) {
1841 if (msg->err_pos < 0)
1842 msg->err_pos = ci_data(rep);
1843 goto hdr_response_bad;
1844 }
1845
1846 /* read error */
1847 else if (rep->flags & CF_READ_ERROR) {
1848 if (msg->err_pos >= 0)
1849 http_capture_bad_message(s->be, s, msg, msg->err_state, sess->fe);
1850 else if (txn->flags & TX_NOT_FIRST)
1851 goto abort_keep_alive;
1852
1853 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1854 if (objt_server(s->target)) {
1855 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1856 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
1857 }
1858
1859 channel_auto_close(rep);
1860 rep->analysers &= AN_RES_FLT_END;
1861 txn->status = 502;
1862
1863 /* Check to see if the server refused the early data.
1864 * If so, just send a 425
1865 */
1866 if (objt_cs(s->si[1].end)) {
1867 struct connection *conn = objt_cs(s->si[1].end)->conn;
1868
1869 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1870 txn->status = 425;
1871 }
1872
1873 s->si[1].flags |= SI_FL_NOLINGER;
1874 channel_truncate(rep);
1875 http_reply_and_close(s, txn->status, http_error_message(s));
1876
1877 if (!(s->flags & SF_ERR_MASK))
1878 s->flags |= SF_ERR_SRVCL;
1879 if (!(s->flags & SF_FINST_MASK))
1880 s->flags |= SF_FINST_H;
1881 return 0;
1882 }
1883
1884 /* read timeout : return a 504 to the client. */
1885 else if (rep->flags & CF_READ_TIMEOUT) {
1886 if (msg->err_pos >= 0)
1887 http_capture_bad_message(s->be, s, msg, msg->err_state, sess->fe);
1888
1889 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1890 if (objt_server(s->target)) {
1891 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1892 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
1893 }
1894
1895 channel_auto_close(rep);
1896 rep->analysers &= AN_RES_FLT_END;
1897 txn->status = 504;
1898 s->si[1].flags |= SI_FL_NOLINGER;
1899 channel_truncate(rep);
1900 http_reply_and_close(s, txn->status, http_error_message(s));
1901
1902 if (!(s->flags & SF_ERR_MASK))
1903 s->flags |= SF_ERR_SRVTO;
1904 if (!(s->flags & SF_FINST_MASK))
1905 s->flags |= SF_FINST_H;
1906 return 0;
1907 }
1908
1909 /* client abort with an abortonclose */
1910 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
1911 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1912 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1913 if (objt_server(s->target))
1914 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1915
1916 rep->analysers &= AN_RES_FLT_END;
1917 channel_auto_close(rep);
1918
1919 txn->status = 400;
1920 channel_truncate(rep);
1921 http_reply_and_close(s, txn->status, http_error_message(s));
1922
1923 if (!(s->flags & SF_ERR_MASK))
1924 s->flags |= SF_ERR_CLICL;
1925 if (!(s->flags & SF_FINST_MASK))
1926 s->flags |= SF_FINST_H;
1927
1928 /* process_stream() will take care of the error */
1929 return 0;
1930 }
1931
1932 /* close from server, capture the response if the server has started to respond */
1933 else if (rep->flags & CF_SHUTR) {
1934 if (msg->msg_state >= HTTP_MSG_RPVER || msg->err_pos >= 0)
1935 http_capture_bad_message(s->be, s, msg, msg->err_state, sess->fe);
1936 else if (txn->flags & TX_NOT_FIRST)
1937 goto abort_keep_alive;
1938
1939 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1940 if (objt_server(s->target)) {
1941 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1942 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
1943 }
1944
1945 channel_auto_close(rep);
1946 rep->analysers &= AN_RES_FLT_END;
1947 txn->status = 502;
1948 s->si[1].flags |= SI_FL_NOLINGER;
1949 channel_truncate(rep);
1950 http_reply_and_close(s, txn->status, http_error_message(s));
1951
1952 if (!(s->flags & SF_ERR_MASK))
1953 s->flags |= SF_ERR_SRVCL;
1954 if (!(s->flags & SF_FINST_MASK))
1955 s->flags |= SF_FINST_H;
1956 return 0;
1957 }
1958
1959 /* write error to client (we don't send any message then) */
1960 else if (rep->flags & CF_WRITE_ERROR) {
1961 if (msg->err_pos >= 0)
1962 http_capture_bad_message(s->be, s, msg, msg->err_state, sess->fe);
1963 else if (txn->flags & TX_NOT_FIRST)
1964 goto abort_keep_alive;
1965
1966 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1967 rep->analysers &= AN_RES_FLT_END;
1968 channel_auto_close(rep);
1969
1970 if (!(s->flags & SF_ERR_MASK))
1971 s->flags |= SF_ERR_CLICL;
1972 if (!(s->flags & SF_FINST_MASK))
1973 s->flags |= SF_FINST_H;
1974
1975 /* process_stream() will take care of the error */
1976 return 0;
1977 }
1978
1979 channel_dont_close(rep);
1980 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1981 return 0;
1982 }
1983
1984 /* More interesting part now : we know that we have a complete
1985 * response which at least looks like HTTP. We have an indicator
1986 * of each header's length, so we can parse them quickly.
1987 */
1988
1989 if (unlikely(msg->err_pos >= 0))
1990 http_capture_bad_message(s->be, s, msg, msg->err_state, sess->fe);
1991
1992 /*
1993 * 1: get the status code
1994 */
1995 n = ci_head(rep)[msg->sl.st.c] - '0';
1996 if (n < 1 || n > 5)
1997 n = 0;
1998 /* when the client triggers a 4xx from the server, it's most often due
1999 * to a missing object or permission. These events should be tracked
2000 * because if they happen often, it may indicate a brute force or a
2001 * vulnerability scan.
2002 */
2003 if (n == 4)
2004 stream_inc_http_err_ctr(s);
2005
2006 if (objt_server(s->target))
2007 HA_ATOMIC_ADD(&objt_server(s->target)->counters.p.http.rsp[n], 1);
2008
2009 /* RFC7230#2.6 has enforced the format of the HTTP version string to be
2010 * exactly one digit "." one digit. This check may be disabled using
2011 * option accept-invalid-http-response.
2012 */
2013 if (!(s->be->options2 & PR_O2_RSPBUG_OK)) {
2014 if (msg->sl.st.v_l != 8) {
2015 msg->err_pos = 0;
2016 goto hdr_response_bad;
2017 }
2018
2019 if (ci_head(rep)[4] != '/' ||
2020 !isdigit((unsigned char)ci_head(rep)[5]) ||
2021 ci_head(rep)[6] != '.' ||
2022 !isdigit((unsigned char)ci_head(rep)[7])) {
2023 msg->err_pos = 4;
2024 goto hdr_response_bad;
2025 }
2026 }
2027
2028 /* check if the response is HTTP/1.1 or above */
2029 if ((msg->sl.st.v_l == 8) &&
2030 ((ci_head(rep)[5] > '1') ||
2031 ((ci_head(rep)[5] == '1') && (ci_head(rep)[7] >= '1'))))
2032 msg->flags |= HTTP_MSGF_VER_11;
2033
Christopher Faulete0768eb2018-10-03 16:38:02 +02002034 /* transfer length unknown*/
2035 msg->flags &= ~HTTP_MSGF_XFER_LEN;
2036
2037 txn->status = strl2ui(ci_head(rep) + msg->sl.st.c, msg->sl.st.c_l);
2038
2039 /* Adjust server's health based on status code. Note: status codes 501
2040 * and 505 are triggered on demand by client request, so we must not
2041 * count them as server failures.
2042 */
2043 if (objt_server(s->target)) {
2044 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
2045 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_OK);
2046 else
2047 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_STS);
2048 }
2049
2050 /*
2051 * We may be facing a 100-continue response, or any other informational
2052 * 1xx response which is non-final, in which case this is not the right
2053 * response, and we're waiting for the next one. Let's allow this response
2054 * to go to the client and wait for the next one. There's an exception for
2055 * 101 which is used later in the code to switch protocols.
2056 */
2057 if (txn->status < 200 &&
2058 (txn->status == 100 || txn->status >= 102)) {
2059 hdr_idx_init(&txn->hdr_idx);
2060 msg->next -= channel_forward(rep, msg->next);
2061 msg->msg_state = HTTP_MSG_RPBEFORE;
2062 txn->status = 0;
2063 s->logs.t_data = -1; /* was not a response yet */
2064 FLT_STRM_CB(s, flt_http_reset(s, msg));
2065 goto next_one;
2066 }
2067
2068 /*
2069 * 2: check for cacheability.
2070 */
2071
2072 switch (txn->status) {
2073 case 200:
2074 case 203:
2075 case 204:
2076 case 206:
2077 case 300:
2078 case 301:
2079 case 404:
2080 case 405:
2081 case 410:
2082 case 414:
2083 case 501:
2084 break;
2085 default:
2086 /* RFC7231#6.1:
2087 * Responses with status codes that are defined as
2088 * cacheable by default (e.g., 200, 203, 204, 206,
2089 * 300, 301, 404, 405, 410, 414, and 501 in this
2090 * specification) can be reused by a cache with
2091 * heuristic expiration unless otherwise indicated
2092 * by the method definition or explicit cache
2093 * controls [RFC7234]; all other status codes are
2094 * not cacheable by default.
2095 */
2096 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
2097 break;
2098 }
2099
2100 /*
2101 * 3: we may need to capture headers
2102 */
2103 s->logs.logwait &= ~LW_RESP;
2104 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
2105 http_capture_headers(ci_head(rep), &txn->hdr_idx,
2106 s->res_cap, sess->fe->rsp_cap);
2107
2108 /* 4: determine the transfer-length according to RFC2616 #4.4, updated
2109 * by RFC7230#3.3.3 :
2110 *
2111 * The length of a message body is determined by one of the following
2112 * (in order of precedence):
2113 *
2114 * 1. Any 2xx (Successful) response to a CONNECT request implies that
2115 * the connection will become a tunnel immediately after the empty
2116 * line that concludes the header fields. A client MUST ignore
2117 * any Content-Length or Transfer-Encoding header fields received
2118 * in such a message. Any 101 response (Switching Protocols) is
2119 * managed in the same manner.
2120 *
2121 * 2. Any response to a HEAD request and any response with a 1xx
2122 * (Informational), 204 (No Content), or 304 (Not Modified) status
2123 * code is always terminated by the first empty line after the
2124 * header fields, regardless of the header fields present in the
2125 * message, and thus cannot contain a message body.
2126 *
2127 * 3. If a Transfer-Encoding header field is present and the chunked
2128 * transfer coding (Section 4.1) is the final encoding, the message
2129 * body length is determined by reading and decoding the chunked
2130 * data until the transfer coding indicates the data is complete.
2131 *
2132 * If a Transfer-Encoding header field is present in a response and
2133 * the chunked transfer coding is not the final encoding, the
2134 * message body length is determined by reading the connection until
2135 * it is closed by the server. If a Transfer-Encoding header field
2136 * is present in a request and the chunked transfer coding is not
2137 * the final encoding, the message body length cannot be determined
2138 * reliably; the server MUST respond with the 400 (Bad Request)
2139 * status code and then close the connection.
2140 *
2141 * If a message is received with both a Transfer-Encoding and a
2142 * Content-Length header field, the Transfer-Encoding overrides the
2143 * Content-Length. Such a message might indicate an attempt to
2144 * perform request smuggling (Section 9.5) or response splitting
2145 * (Section 9.4) and ought to be handled as an error. A sender MUST
2146 * remove the received Content-Length field prior to forwarding such
2147 * a message downstream.
2148 *
2149 * 4. If a message is received without Transfer-Encoding and with
2150 * either multiple Content-Length header fields having differing
2151 * field-values or a single Content-Length header field having an
2152 * invalid value, then the message framing is invalid and the
2153 * recipient MUST treat it as an unrecoverable error. If this is a
2154 * request message, the server MUST respond with a 400 (Bad Request)
2155 * status code and then close the connection. If this is a response
2156 * message received by a proxy, the proxy MUST close the connection
2157 * to the server, discard the received response, and send a 502 (Bad
2158 * Gateway) response to the client. If this is a response message
2159 * received by a user agent, the user agent MUST close the
2160 * connection to the server and discard the received response.
2161 *
2162 * 5. If a valid Content-Length header field is present without
2163 * Transfer-Encoding, its decimal value defines the expected message
2164 * body length in octets. If the sender closes the connection or
2165 * the recipient times out before the indicated number of octets are
2166 * received, the recipient MUST consider the message to be
2167 * incomplete and close the connection.
2168 *
2169 * 6. If this is a request message and none of the above are true, then
2170 * the message body length is zero (no message body is present).
2171 *
2172 * 7. Otherwise, this is a response message without a declared message
2173 * body length, so the message body length is determined by the
2174 * number of octets received prior to the server closing the
2175 * connection.
2176 */
2177
2178 /* Skip parsing if no content length is possible. The response flags
2179 * remain 0 as well as the chunk_len, which may or may not mirror
2180 * the real header value, and we note that we know the response's length.
2181 * FIXME: should we parse anyway and return an error on chunked encoding ?
2182 */
2183 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
2184 txn->status == 101)) {
2185 /* Either we've established an explicit tunnel, or we're
2186 * switching the protocol. In both cases, we're very unlikely
2187 * to understand the next protocols. We have to switch to tunnel
2188 * mode, so that we transfer the request and responses then let
2189 * this protocol pass unmodified. When we later implement specific
2190 * parsers for such protocols, we'll want to check the Upgrade
2191 * header which contains information about that protocol for
2192 * responses with status 101 (eg: see RFC2817 about TLS).
2193 */
2194 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
2195 msg->flags |= HTTP_MSGF_XFER_LEN;
2196 goto end;
2197 }
2198
2199 if (txn->meth == HTTP_METH_HEAD ||
2200 (txn->status >= 100 && txn->status < 200) ||
2201 txn->status == 204 || txn->status == 304) {
2202 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002203 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002204 }
2205
2206 use_close_only = 0;
2207 ctx.idx = 0;
2208 while (http_find_header2("Transfer-Encoding", 17, ci_head(rep), &txn->hdr_idx, &ctx)) {
2209 if (ctx.vlen == 7 && strncasecmp(ctx.line + ctx.val, "chunked", 7) == 0)
2210 msg->flags |= (HTTP_MSGF_TE_CHNK | HTTP_MSGF_XFER_LEN);
2211 else if (msg->flags & HTTP_MSGF_TE_CHNK) {
2212 /* bad transfer-encoding (chunked followed by something else) */
2213 use_close_only = 1;
2214 msg->flags &= ~(HTTP_MSGF_TE_CHNK | HTTP_MSGF_XFER_LEN);
2215 break;
2216 }
2217 }
2218
2219 /* Chunked responses must have their content-length removed */
2220 ctx.idx = 0;
2221 if (use_close_only || (msg->flags & HTTP_MSGF_TE_CHNK)) {
2222 while (http_find_header2("Content-Length", 14, ci_head(rep), &txn->hdr_idx, &ctx))
2223 http_remove_header2(msg, &txn->hdr_idx, &ctx);
2224 }
2225 else while (http_find_header2("Content-Length", 14, ci_head(rep), &txn->hdr_idx, &ctx)) {
2226 signed long long cl;
2227
2228 if (!ctx.vlen) {
2229 msg->err_pos = ctx.line + ctx.val - ci_head(rep);
2230 goto hdr_response_bad;
2231 }
2232
2233 if (strl2llrc(ctx.line + ctx.val, ctx.vlen, &cl)) {
2234 msg->err_pos = ctx.line + ctx.val - ci_head(rep);
2235 goto hdr_response_bad; /* parse failure */
2236 }
2237
2238 if (cl < 0) {
2239 msg->err_pos = ctx.line + ctx.val - ci_head(rep);
2240 goto hdr_response_bad;
2241 }
2242
2243 if ((msg->flags & HTTP_MSGF_CNT_LEN) && (msg->chunk_len != cl)) {
2244 msg->err_pos = ctx.line + ctx.val - ci_head(rep);
2245 goto hdr_response_bad; /* already specified, was different */
2246 }
2247
2248 msg->flags |= HTTP_MSGF_CNT_LEN | HTTP_MSGF_XFER_LEN;
2249 msg->body_len = msg->chunk_len = cl;
2250 }
2251
Christopher Faulete0768eb2018-10-03 16:38:02 +02002252 end:
2253 /* we want to have the response time before we start processing it */
2254 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
2255
2256 /* end of job, return OK */
2257 rep->analysers &= ~an_bit;
2258 rep->analyse_exp = TICK_ETERNITY;
2259 channel_auto_close(rep);
2260 return 1;
2261
2262 abort_keep_alive:
2263 /* A keep-alive request to the server failed on a network error.
2264 * The client is required to retry. We need to close without returning
2265 * any other information so that the client retries.
2266 */
2267 txn->status = 0;
2268 rep->analysers &= AN_RES_FLT_END;
2269 s->req.analysers &= AN_REQ_FLT_END;
2270 channel_auto_close(rep);
2271 s->logs.logwait = 0;
2272 s->logs.level = 0;
2273 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
2274 channel_truncate(rep);
2275 http_reply_and_close(s, txn->status, NULL);
2276 return 0;
2277}
2278
2279/* This function performs all the processing enabled for the current response.
2280 * It normally returns 1 unless it wants to break. It relies on buffers flags,
2281 * and updates s->res.analysers. It might make sense to explode it into several
2282 * other functions. It works like process_request (see indications above).
2283 */
2284int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
2285{
2286 struct session *sess = s->sess;
2287 struct http_txn *txn = s->txn;
2288 struct http_msg *msg = &txn->rsp;
2289 struct proxy *cur_proxy;
2290 struct cond_wordlist *wl;
2291 enum rule_result ret = HTTP_RULE_RES_CONT;
2292
2293 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2294 now_ms, __FUNCTION__,
2295 s,
2296 rep,
2297 rep->rex, rep->wex,
2298 rep->flags,
2299 ci_data(rep),
2300 rep->analysers);
2301
2302 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
2303 return 0;
2304
2305 /* The stats applet needs to adjust the Connection header but we don't
2306 * apply any filter there.
2307 */
2308 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
2309 rep->analysers &= ~an_bit;
2310 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002311 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002312 }
2313
2314 /*
2315 * We will have to evaluate the filters.
2316 * As opposed to version 1.2, now they will be evaluated in the
2317 * filters order and not in the header order. This means that
2318 * each filter has to be validated among all headers.
2319 *
2320 * Filters are tried with ->be first, then with ->fe if it is
2321 * different from ->be.
2322 *
2323 * Maybe we are in resume condiion. In this case I choose the
2324 * "struct proxy" which contains the rule list matching the resume
2325 * pointer. If none of theses "struct proxy" match, I initialise
2326 * the process with the first one.
2327 *
2328 * In fact, I check only correspondance betwwen the current list
2329 * pointer and the ->fe rule list. If it doesn't match, I initialize
2330 * the loop with the ->be.
2331 */
2332 if (s->current_rule_list == &sess->fe->http_res_rules)
2333 cur_proxy = sess->fe;
2334 else
2335 cur_proxy = s->be;
2336 while (1) {
2337 struct proxy *rule_set = cur_proxy;
2338
2339 /* evaluate http-response rules */
2340 if (ret == HTTP_RULE_RES_CONT) {
2341 ret = http_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
2342
2343 if (ret == HTTP_RULE_RES_BADREQ)
2344 goto return_srv_prx_502;
2345
2346 if (ret == HTTP_RULE_RES_DONE) {
2347 rep->analysers &= ~an_bit;
2348 rep->analyse_exp = TICK_ETERNITY;
2349 return 1;
2350 }
2351 }
2352
2353 /* we need to be called again. */
2354 if (ret == HTTP_RULE_RES_YIELD) {
2355 channel_dont_close(rep);
2356 return 0;
2357 }
2358
2359 /* try headers filters */
2360 if (rule_set->rsp_exp != NULL) {
2361 if (apply_filters_to_response(s, rep, rule_set) < 0) {
2362 return_bad_resp:
2363 if (objt_server(s->target)) {
2364 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2365 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_RSP);
2366 }
2367 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2368 return_srv_prx_502:
2369 rep->analysers &= AN_RES_FLT_END;
2370 txn->status = 502;
2371 s->logs.t_data = -1; /* was not a valid response */
2372 s->si[1].flags |= SI_FL_NOLINGER;
2373 channel_truncate(rep);
2374 http_reply_and_close(s, txn->status, http_error_message(s));
2375 if (!(s->flags & SF_ERR_MASK))
2376 s->flags |= SF_ERR_PRXCOND;
2377 if (!(s->flags & SF_FINST_MASK))
2378 s->flags |= SF_FINST_H;
2379 return 0;
2380 }
2381 }
2382
2383 /* has the response been denied ? */
2384 if (txn->flags & TX_SVDENY) {
2385 if (objt_server(s->target))
2386 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
2387
2388 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2389 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
2390 if (sess->listener->counters)
2391 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
2392
2393 goto return_srv_prx_502;
2394 }
2395
2396 /* add response headers from the rule sets in the same order */
2397 list_for_each_entry(wl, &rule_set->rsp_add, list) {
2398 if (txn->status < 200 && txn->status != 101)
2399 break;
2400 if (wl->cond) {
2401 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
2402 ret = acl_pass(ret);
2403 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
2404 ret = !ret;
2405 if (!ret)
2406 continue;
2407 }
2408 if (unlikely(http_header_add_tail2(&txn->rsp, &txn->hdr_idx, wl->s, strlen(wl->s)) < 0))
2409 goto return_bad_resp;
2410 }
2411
2412 /* check whether we're already working on the frontend */
2413 if (cur_proxy == sess->fe)
2414 break;
2415 cur_proxy = sess->fe;
2416 }
2417
2418 /* After this point, this anayzer can't return yield, so we can
2419 * remove the bit corresponding to this analyzer from the list.
2420 *
2421 * Note that the intermediate returns and goto found previously
2422 * reset the analyzers.
2423 */
2424 rep->analysers &= ~an_bit;
2425 rep->analyse_exp = TICK_ETERNITY;
2426
2427 /* OK that's all we can do for 1xx responses */
2428 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02002429 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002430
2431 /*
2432 * Now check for a server cookie.
2433 */
2434 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
2435 manage_server_side_cookies(s, rep);
2436
2437 /*
2438 * Check for cache-control or pragma headers if required.
2439 */
2440 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
2441 check_response_for_cacheability(s, rep);
2442
2443 /*
2444 * Add server cookie in the response if needed
2445 */
2446 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
2447 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
2448 (!(s->flags & SF_DIRECT) ||
2449 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
2450 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
2451 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2452 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2453 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2454 !(s->flags & SF_IGNORE_PRST)) {
2455 /* the server is known, it's not the one the client requested, or the
2456 * cookie's last seen date needs to be refreshed. We have to
2457 * insert a set-cookie here, except if we want to insert only on POST
2458 * requests and this one isn't. Note that servers which don't have cookies
2459 * (eg: some backup servers) will return a full cookie removal request.
2460 */
2461 if (!objt_server(s->target)->cookie) {
2462 chunk_printf(&trash,
2463 "Set-Cookie: %s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
2464 s->be->cookie_name);
2465 }
2466 else {
2467 chunk_printf(&trash, "Set-Cookie: %s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
2468
2469 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2470 /* emit last_date, which is mandatory */
2471 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2472 s30tob64((date.tv_sec+3) >> 2,
2473 trash.area + trash.data);
2474 trash.data += 5;
2475
2476 if (s->be->cookie_maxlife) {
2477 /* emit first_date, which is either the original one or
2478 * the current date.
2479 */
2480 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2481 s30tob64(txn->cookie_first_date ?
2482 txn->cookie_first_date >> 2 :
2483 (date.tv_sec+3) >> 2,
2484 trash.area + trash.data);
2485 trash.data += 5;
2486 }
2487 }
2488 chunk_appendf(&trash, "; path=/");
2489 }
2490
2491 if (s->be->cookie_domain)
2492 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2493
2494 if (s->be->ck_opts & PR_CK_HTTPONLY)
2495 chunk_appendf(&trash, "; HttpOnly");
2496
2497 if (s->be->ck_opts & PR_CK_SECURE)
2498 chunk_appendf(&trash, "; Secure");
2499
2500 if (unlikely(http_header_add_tail2(&txn->rsp, &txn->hdr_idx, trash.area, trash.data) < 0))
2501 goto return_bad_resp;
2502
2503 txn->flags &= ~TX_SCK_MASK;
2504 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2505 /* the server did not change, only the date was updated */
2506 txn->flags |= TX_SCK_UPDATED;
2507 else
2508 txn->flags |= TX_SCK_INSERTED;
2509
2510 /* Here, we will tell an eventual cache on the client side that we don't
2511 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2512 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2513 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2514 */
2515 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2516
2517 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2518
2519 if (unlikely(http_header_add_tail2(&txn->rsp, &txn->hdr_idx,
2520 "Cache-control: private", 22) < 0))
2521 goto return_bad_resp;
2522 }
2523 }
2524
2525 /*
2526 * Check if result will be cacheable with a cookie.
2527 * We'll block the response if security checks have caught
2528 * nasty things such as a cacheable cookie.
2529 */
2530 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2531 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2532 (s->be->options & PR_O_CHK_CACHE)) {
2533 /* we're in presence of a cacheable response containing
2534 * a set-cookie header. We'll block it as requested by
2535 * the 'checkcache' option, and send an alert.
2536 */
2537 if (objt_server(s->target))
2538 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
2539
2540 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2541 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
2542 if (sess->listener->counters)
2543 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
2544
2545 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2546 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2547 send_log(s->be, LOG_ALERT,
2548 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2549 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2550 goto return_srv_prx_502;
2551 }
2552
Christopher Fauletf2824e62018-10-01 12:12:37 +02002553 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002554 /* Always enter in the body analyzer */
2555 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2556 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2557
2558 /* if the user wants to log as soon as possible, without counting
2559 * bytes from the server, then this is the right moment. We have
2560 * to temporarily assign bytes_out to log what we currently have.
2561 */
2562 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2563 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
2564 s->logs.bytes_out = txn->rsp.eoh;
2565 s->do_log(s);
2566 s->logs.bytes_out = 0;
2567 }
2568 return 1;
2569}
2570
2571/* This function is an analyser which forwards response body (including chunk
2572 * sizes if any). It is called as soon as we must forward, even if we forward
2573 * zero byte. The only situation where it must not be called is when we're in
2574 * tunnel mode and we want to forward till the close. It's used both to forward
2575 * remaining data and to resync after end of body. It expects the msg_state to
2576 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2577 * read more data, or 1 once we can go on with next request or end the stream.
2578 *
2579 * It is capable of compressing response data both in content-length mode and
2580 * in chunked mode. The state machines follows different flows depending on
2581 * whether content-length and chunked modes are used, since there are no
2582 * trailers in content-length :
2583 *
2584 * chk-mode cl-mode
2585 * ,----- BODY -----.
2586 * / \
2587 * V size > 0 V chk-mode
2588 * .--> SIZE -------------> DATA -------------> CRLF
2589 * | | size == 0 | last byte |
2590 * | v final crlf v inspected |
2591 * | TRAILERS -----------> DONE |
2592 * | |
2593 * `----------------------------------------------'
2594 *
2595 * Compression only happens in the DATA state, and must be flushed in final
2596 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2597 * is performed at once on final states for all bytes parsed, or when leaving
2598 * on missing data.
2599 */
2600int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2601{
2602 struct session *sess = s->sess;
2603 struct http_txn *txn = s->txn;
2604 struct http_msg *msg = &s->txn->rsp;
2605 int ret;
2606
2607 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2608 now_ms, __FUNCTION__,
2609 s,
2610 res,
2611 res->rex, res->wex,
2612 res->flags,
2613 ci_data(res),
2614 res->analysers);
2615
2616 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
2617 return 0;
2618
2619 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002620 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002621 /* Output closed while we were sending data. We must abort and
2622 * wake the other side up.
2623 */
2624 msg->err_state = msg->msg_state;
2625 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002626 htx_end_response(s);
2627 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002628 return 1;
2629 }
2630
2631 /* in most states, we should abort in case of early close */
2632 channel_auto_close(res);
2633
2634 if (msg->msg_state == HTTP_MSG_BODY) {
2635 msg->msg_state = ((msg->flags & HTTP_MSGF_TE_CHNK)
2636 ? HTTP_MSG_CHUNK_SIZE
2637 : HTTP_MSG_DATA);
2638 }
2639
2640 if (res->to_forward) {
2641 /* We can't process the buffer's contents yet */
2642 res->flags |= CF_WAKE_WRITE;
2643 goto missing_data_or_waiting;
2644 }
2645
2646 if (msg->msg_state < HTTP_MSG_DONE) {
2647 ret = ((msg->flags & HTTP_MSGF_TE_CHNK)
2648 ? http_msg_forward_chunked_body(s, msg)
2649 : http_msg_forward_body(s, msg));
2650 if (!ret)
2651 goto missing_data_or_waiting;
2652 if (ret < 0)
2653 goto return_bad_res;
2654 }
2655
2656 /* other states, DONE...TUNNEL */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002657 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002658 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002659 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002660 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2661 if (res->flags & CF_SHUTW) {
2662 /* response errors are most likely due to the
2663 * client aborting the transfer. */
2664 goto aborted_xfer;
2665 }
2666 if (msg->err_pos >= 0)
2667 http_capture_bad_message(s->be, s, msg, msg->err_state, strm_fe(s));
2668 goto return_bad_res;
2669 }
2670 return 1;
2671 }
2672 return 0;
2673
2674 missing_data_or_waiting:
2675 if (res->flags & CF_SHUTW)
2676 goto aborted_xfer;
2677
2678 /* stop waiting for data if the input is closed before the end. If the
2679 * client side was already closed, it means that the client has aborted,
2680 * so we don't want to count this as a server abort. Otherwise it's a
2681 * server abort.
2682 */
2683 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
2684 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
2685 goto aborted_xfer;
2686 /* If we have some pending data, we continue the processing */
2687 if (!ci_data(res)) {
2688 if (!(s->flags & SF_ERR_MASK))
2689 s->flags |= SF_ERR_SRVCL;
2690 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
2691 if (objt_server(s->target))
2692 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2693 goto return_bad_res_stats_ok;
2694 }
2695 }
2696
Christopher Faulete0768eb2018-10-03 16:38:02 +02002697 /* When TE: chunked is used, we need to get there again to parse
2698 * remaining chunks even if the server has closed, so we don't want to
Christopher Fauletf2824e62018-10-01 12:12:37 +02002699 * set CF_DONTCLOSE. Similarly, if there are filters registered on the
2700 * stream, we don't want to forward a close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002701 */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002702 if ((msg->flags & HTTP_MSGF_TE_CHNK) || HAS_DATA_FILTERS(s, res))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002703 channel_dont_close(res);
2704
2705 /* We know that more data are expected, but we couldn't send more that
2706 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2707 * system knows it must not set a PUSH on this first part. Interactive
2708 * modes are already handled by the stream sock layer. We must not do
2709 * this in content-length mode because it could present the MSG_MORE
2710 * flag with the last block of forwarded data, which would cause an
2711 * additional delay to be observed by the receiver.
2712 */
2713 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2714 res->flags |= CF_EXPECT_MORE;
2715
2716 /* the stream handler will take care of timeouts and errors */
2717 return 0;
2718
2719 return_bad_res: /* let's centralize all bad responses */
2720 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2721 if (objt_server(s->target))
2722 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2723
2724 return_bad_res_stats_ok:
2725 txn->rsp.err_state = txn->rsp.msg_state;
2726 txn->rsp.msg_state = HTTP_MSG_ERROR;
2727 /* don't send any error message as we're in the body */
2728 http_reply_and_close(s, txn->status, NULL);
2729 res->analysers &= AN_RES_FLT_END;
2730 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2731 if (objt_server(s->target))
2732 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
2733
2734 if (!(s->flags & SF_ERR_MASK))
2735 s->flags |= SF_ERR_PRXCOND;
2736 if (!(s->flags & SF_FINST_MASK))
2737 s->flags |= SF_FINST_D;
2738 return 0;
2739
2740 aborted_xfer:
2741 txn->rsp.err_state = txn->rsp.msg_state;
2742 txn->rsp.msg_state = HTTP_MSG_ERROR;
2743 /* don't send any error message as we're in the body */
2744 http_reply_and_close(s, txn->status, NULL);
2745 res->analysers &= AN_RES_FLT_END;
2746 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2747
2748 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2749 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
2750 if (objt_server(s->target))
2751 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2752
2753 if (!(s->flags & SF_ERR_MASK))
2754 s->flags |= SF_ERR_CLICL;
2755 if (!(s->flags & SF_FINST_MASK))
2756 s->flags |= SF_FINST_D;
2757 return 0;
2758}
2759
Christopher Fauletf2824e62018-10-01 12:12:37 +02002760void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn, struct http_msg *msg)
2761{
2762 struct proxy *fe = strm_fe(s);
2763 int tmp = TX_CON_WANT_CLO;
2764
2765 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2766 tmp = TX_CON_WANT_TUN;
2767
2768 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
2769 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
2770}
2771
2772/* Perform an HTTP redirect based on the information in <rule>. The function
2773 * returns non-zero on success, or zero in case of a, irrecoverable error such
2774 * as too large a request to build a valid response.
2775 */
2776int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2777{
2778 struct http_msg *req = &txn->req;
2779 struct http_msg *res = &txn->rsp;
2780 const char *msg_fmt;
2781 struct buffer *chunk;
2782 int ret = 0;
2783
2784 chunk = alloc_trash_chunk();
2785 if (!chunk)
2786 goto leave;
2787
2788 /* build redirect message */
2789 switch(rule->code) {
2790 case 308:
2791 msg_fmt = HTTP_308;
2792 break;
2793 case 307:
2794 msg_fmt = HTTP_307;
2795 break;
2796 case 303:
2797 msg_fmt = HTTP_303;
2798 break;
2799 case 301:
2800 msg_fmt = HTTP_301;
2801 break;
2802 case 302:
2803 default:
2804 msg_fmt = HTTP_302;
2805 break;
2806 }
2807
2808 if (unlikely(!chunk_strcpy(chunk, msg_fmt)))
2809 goto leave;
2810
2811 switch(rule->type) {
2812 case REDIRECT_TYPE_SCHEME: {
2813 const char *path;
2814 const char *host;
2815 struct hdr_ctx ctx;
2816 int pathlen;
2817 int hostlen;
2818
2819 host = "";
2820 hostlen = 0;
2821 ctx.idx = 0;
2822 if (http_find_header2("Host", 4, ci_head(req->chn), &txn->hdr_idx, &ctx)) {
2823 host = ctx.line + ctx.val;
2824 hostlen = ctx.vlen;
2825 }
2826
2827 path = http_txn_get_path(txn);
2828 /* build message using path */
2829 if (path) {
2830 pathlen = req->sl.rq.u_l + (ci_head(req->chn) + req->sl.rq.u) - path;
2831 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2832 int qs = 0;
2833 while (qs < pathlen) {
2834 if (path[qs] == '?') {
2835 pathlen = qs;
2836 break;
2837 }
2838 qs++;
2839 }
2840 }
2841 } else {
2842 path = "/";
2843 pathlen = 1;
2844 }
2845
2846 if (rule->rdr_str) { /* this is an old "redirect" rule */
2847 /* check if we can add scheme + "://" + host + path */
2848 if (chunk->data + rule->rdr_len + 3 + hostlen + pathlen > chunk->size - 4)
2849 goto leave;
2850
2851 /* add scheme */
2852 memcpy(chunk->area + chunk->data, rule->rdr_str,
2853 rule->rdr_len);
2854 chunk->data += rule->rdr_len;
2855 }
2856 else {
2857 /* add scheme with executing log format */
2858 chunk->data += build_logline(s,
2859 chunk->area + chunk->data,
2860 chunk->size - chunk->data,
2861 &rule->rdr_fmt);
2862
2863 /* check if we can add scheme + "://" + host + path */
2864 if (chunk->data + 3 + hostlen + pathlen > chunk->size - 4)
2865 goto leave;
2866 }
2867 /* add "://" */
2868 memcpy(chunk->area + chunk->data, "://", 3);
2869 chunk->data += 3;
2870
2871 /* add host */
2872 memcpy(chunk->area + chunk->data, host, hostlen);
2873 chunk->data += hostlen;
2874
2875 /* add path */
2876 memcpy(chunk->area + chunk->data, path, pathlen);
2877 chunk->data += pathlen;
2878
2879 /* append a slash at the end of the location if needed and missing */
2880 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2881 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2882 if (chunk->data > chunk->size - 5)
2883 goto leave;
2884 chunk->area[chunk->data] = '/';
2885 chunk->data++;
2886 }
2887
2888 break;
2889 }
2890 case REDIRECT_TYPE_PREFIX: {
2891 const char *path;
2892 int pathlen;
2893
2894 path = http_txn_get_path(txn);
2895 /* build message using path */
2896 if (path) {
2897 pathlen = req->sl.rq.u_l + (ci_head(req->chn) + req->sl.rq.u) - path;
2898 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2899 int qs = 0;
2900 while (qs < pathlen) {
2901 if (path[qs] == '?') {
2902 pathlen = qs;
2903 break;
2904 }
2905 qs++;
2906 }
2907 }
2908 } else {
2909 path = "/";
2910 pathlen = 1;
2911 }
2912
2913 if (rule->rdr_str) { /* this is an old "redirect" rule */
2914 if (chunk->data + rule->rdr_len + pathlen > chunk->size - 4)
2915 goto leave;
2916
2917 /* add prefix. Note that if prefix == "/", we don't want to
2918 * add anything, otherwise it makes it hard for the user to
2919 * configure a self-redirection.
2920 */
2921 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2922 memcpy(chunk->area + chunk->data,
2923 rule->rdr_str, rule->rdr_len);
2924 chunk->data += rule->rdr_len;
2925 }
2926 }
2927 else {
2928 /* add prefix with executing log format */
2929 chunk->data += build_logline(s,
2930 chunk->area + chunk->data,
2931 chunk->size - chunk->data,
2932 &rule->rdr_fmt);
2933
2934 /* Check length */
2935 if (chunk->data + pathlen > chunk->size - 4)
2936 goto leave;
2937 }
2938
2939 /* add path */
2940 memcpy(chunk->area + chunk->data, path, pathlen);
2941 chunk->data += pathlen;
2942
2943 /* append a slash at the end of the location if needed and missing */
2944 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2945 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2946 if (chunk->data > chunk->size - 5)
2947 goto leave;
2948 chunk->area[chunk->data] = '/';
2949 chunk->data++;
2950 }
2951
2952 break;
2953 }
2954 case REDIRECT_TYPE_LOCATION:
2955 default:
2956 if (rule->rdr_str) { /* this is an old "redirect" rule */
2957 if (chunk->data + rule->rdr_len > chunk->size - 4)
2958 goto leave;
2959
2960 /* add location */
2961 memcpy(chunk->area + chunk->data, rule->rdr_str,
2962 rule->rdr_len);
2963 chunk->data += rule->rdr_len;
2964 }
2965 else {
2966 /* add location with executing log format */
2967 chunk->data += build_logline(s,
2968 chunk->area + chunk->data,
2969 chunk->size - chunk->data,
2970 &rule->rdr_fmt);
2971
2972 /* Check left length */
2973 if (chunk->data > chunk->size - 4)
2974 goto leave;
2975 }
2976 break;
2977 }
2978
2979 if (rule->cookie_len) {
2980 memcpy(chunk->area + chunk->data, "\r\nSet-Cookie: ", 14);
2981 chunk->data += 14;
2982 memcpy(chunk->area + chunk->data, rule->cookie_str,
2983 rule->cookie_len);
2984 chunk->data += rule->cookie_len;
2985 }
2986
2987 /* add end of headers and the keep-alive/close status. */
2988 txn->status = rule->code;
2989 /* let's log the request time */
2990 s->logs.tv_request = now;
2991
2992 if (((!(req->flags & HTTP_MSGF_TE_CHNK) && !req->body_len) || (req->msg_state == HTTP_MSG_DONE))) {
2993 /* keep-alive possible */
2994 if (!(req->flags & HTTP_MSGF_VER_11)) {
2995 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
2996 memcpy(chunk->area + chunk->data,
2997 "\r\nProxy-Connection: keep-alive", 30);
2998 chunk->data += 30;
2999 } else {
3000 memcpy(chunk->area + chunk->data,
3001 "\r\nConnection: keep-alive", 24);
3002 chunk->data += 24;
3003 }
3004 }
3005 memcpy(chunk->area + chunk->data, "\r\n\r\n", 4);
3006 chunk->data += 4;
3007 FLT_STRM_CB(s, flt_http_reply(s, txn->status, chunk));
3008 co_inject(res->chn, chunk->area, chunk->data);
3009 /* "eat" the request */
3010 b_del(&req->chn->buf, req->sov);
3011 req->next -= req->sov;
3012 req->sov = 0;
3013 s->req.analysers = AN_REQ_HTTP_XFER_BODY | (s->req.analysers & AN_REQ_FLT_END);
3014 s->res.analysers = AN_RES_HTTP_XFER_BODY | (s->res.analysers & AN_RES_FLT_END);
3015 req->msg_state = HTTP_MSG_CLOSED;
3016 res->msg_state = HTTP_MSG_DONE;
3017 /* Trim any possible response */
3018 b_set_data(&res->chn->buf, co_data(res->chn));
3019 res->next = res->sov = 0;
3020 /* let the server side turn to SI_ST_CLO */
3021 channel_shutw_now(req->chn);
3022 } else {
3023 /* keep-alive not possible */
3024 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
3025 memcpy(chunk->area + chunk->data,
3026 "\r\nProxy-Connection: close\r\n\r\n", 29);
3027 chunk->data += 29;
3028 } else {
3029 memcpy(chunk->area + chunk->data,
3030 "\r\nConnection: close\r\n\r\n", 23);
3031 chunk->data += 23;
3032 }
3033 http_reply_and_close(s, txn->status, chunk);
3034 req->chn->analysers &= AN_REQ_FLT_END;
3035 }
3036
3037 if (!(s->flags & SF_ERR_MASK))
3038 s->flags |= SF_ERR_LOCAL;
3039 if (!(s->flags & SF_FINST_MASK))
3040 s->flags |= SF_FINST_R;
3041
3042 ret = 1;
3043 leave:
3044 free_trash_chunk(chunk);
3045 return ret;
3046}
3047
3048/* This function terminates the request because it was completly analyzed or
3049 * because an error was triggered during the body forwarding.
3050 */
3051static void htx_end_request(struct stream *s)
3052{
3053 struct channel *chn = &s->req;
3054 struct http_txn *txn = s->txn;
3055
3056 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
3057 now_ms, __FUNCTION__, s,
3058 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
3059 s->req.analysers, s->res.analysers);
3060
3061 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR)) {
3062 channel_abort(chn);
3063 channel_truncate(chn);
3064 goto end;
3065 }
3066
3067 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
3068 return;
3069
3070 if (txn->req.msg_state == HTTP_MSG_DONE) {
3071 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
3072 /* The server has not finished to respond, so we
3073 * don't want to move in order not to upset it.
3074 */
3075 return;
3076 }
3077
3078 /* No need to read anymore, the request was completely parsed.
3079 * We can shut the read side unless we want to abort_on_close,
3080 * or we have a POST request. The issue with POST requests is
3081 * that some browsers still send a CRLF after the request, and
3082 * this CRLF must be read so that it does not remain in the kernel
3083 * buffers, otherwise a close could cause an RST on some systems
3084 * (eg: Linux).
3085 */
3086 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
3087 txn->meth != HTTP_METH_POST)
3088 channel_dont_read(chn);
3089
3090 /* if the server closes the connection, we want to immediately react
3091 * and close the socket to save packets and syscalls.
3092 */
3093 s->si[1].flags |= SI_FL_NOHALF;
3094
3095 /* In any case we've finished parsing the request so we must
3096 * disable Nagle when sending data because 1) we're not going
3097 * to shut this side, and 2) the server is waiting for us to
3098 * send pending data.
3099 */
3100 chn->flags |= CF_NEVER_WAIT;
3101
3102 /* When we get here, it means that both the request and the
3103 * response have finished receiving. Depending on the connection
3104 * mode, we'll have to wait for the last bytes to leave in either
3105 * direction, and sometimes for a close to be effective.
3106 */
3107 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
3108 /* Tunnel mode will not have any analyser so it needs to
3109 * poll for reads.
3110 */
3111 channel_auto_read(chn);
3112 txn->req.msg_state = HTTP_MSG_TUNNEL;
3113 }
3114 else {
3115 /* we're not expecting any new data to come for this
3116 * transaction, so we can close it.
3117 * However, there is an exception if the response length
3118 * is undefined. In this case, we need to wait the close
3119 * from the server. The response will be switched in
3120 * TUNNEL mode until the end.
3121 */
3122 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
3123 txn->rsp.msg_state != HTTP_MSG_CLOSED)
3124 return;
3125
3126 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
3127 channel_shutr_now(chn);
3128 channel_shutw_now(chn);
3129 }
3130 }
3131
3132 goto check_channel_flags;
3133 }
3134
3135 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
3136 http_msg_closing:
3137 /* nothing else to forward, just waiting for the output buffer
3138 * to be empty and for the shutw_now to take effect.
3139 */
3140 if (channel_is_empty(chn)) {
3141 txn->req.msg_state = HTTP_MSG_CLOSED;
3142 goto http_msg_closed;
3143 }
3144 else if (chn->flags & CF_SHUTW) {
3145 txn->req.err_state = txn->req.msg_state;
3146 txn->req.msg_state = HTTP_MSG_ERROR;
3147 goto end;
3148 }
3149 return;
3150 }
3151
3152 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
3153 http_msg_closed:
3154
3155 /* if we don't know whether the server will close, we need to hard close */
3156 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
3157 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
3158
3159 /* see above in MSG_DONE why we only do this in these states */
3160 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
3161 channel_dont_read(chn);
3162 goto end;
3163 }
3164
3165 check_channel_flags:
3166 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
3167 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
3168 /* if we've just closed an output, let's switch */
3169 txn->req.msg_state = HTTP_MSG_CLOSING;
3170 goto http_msg_closing;
3171 }
3172
3173 end:
3174 chn->analysers &= AN_REQ_FLT_END;
3175 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
3176 chn->analysers |= AN_REQ_FLT_XFER_DATA;
3177 channel_auto_close(chn);
3178 channel_auto_read(chn);
3179}
3180
3181
3182/* This function terminates the response because it was completly analyzed or
3183 * because an error was triggered during the body forwarding.
3184 */
3185static void htx_end_response(struct stream *s)
3186{
3187 struct channel *chn = &s->res;
3188 struct http_txn *txn = s->txn;
3189
3190 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
3191 now_ms, __FUNCTION__, s,
3192 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
3193 s->req.analysers, s->res.analysers);
3194
3195 if (unlikely(txn->rsp.msg_state == HTTP_MSG_ERROR)) {
3196 channel_abort(chn);
3197 channel_truncate(chn);
3198 goto end;
3199 }
3200
3201 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
3202 return;
3203
3204 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
3205 /* In theory, we don't need to read anymore, but we must
3206 * still monitor the server connection for a possible close
3207 * while the request is being uploaded, so we don't disable
3208 * reading.
3209 */
3210 /* channel_dont_read(chn); */
3211
3212 if (txn->req.msg_state < HTTP_MSG_DONE) {
3213 /* The client seems to still be sending data, probably
3214 * because we got an error response during an upload.
3215 * We have the choice of either breaking the connection
3216 * or letting it pass through. Let's do the later.
3217 */
3218 return;
3219 }
3220
3221 /* When we get here, it means that both the request and the
3222 * response have finished receiving. Depending on the connection
3223 * mode, we'll have to wait for the last bytes to leave in either
3224 * direction, and sometimes for a close to be effective.
3225 */
3226 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
3227 channel_auto_read(chn);
3228 chn->flags |= CF_NEVER_WAIT;
3229 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
3230 }
3231 else {
3232 /* we're not expecting any new data to come for this
3233 * transaction, so we can close it.
3234 */
3235 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
3236 channel_shutr_now(chn);
3237 channel_shutw_now(chn);
3238 }
3239 }
3240 goto check_channel_flags;
3241 }
3242
3243 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
3244 http_msg_closing:
3245 /* nothing else to forward, just waiting for the output buffer
3246 * to be empty and for the shutw_now to take effect.
3247 */
3248 if (channel_is_empty(chn)) {
3249 txn->rsp.msg_state = HTTP_MSG_CLOSED;
3250 goto http_msg_closed;
3251 }
3252 else if (chn->flags & CF_SHUTW) {
3253 txn->rsp.err_state = txn->rsp.msg_state;
3254 txn->rsp.msg_state = HTTP_MSG_ERROR;
3255 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
3256 if (objt_server(s->target))
3257 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
3258 goto end;
3259 }
3260 return;
3261 }
3262
3263 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
3264 http_msg_closed:
3265 /* drop any pending data */
3266 channel_truncate(chn);
3267 channel_auto_close(chn);
3268 channel_auto_read(chn);
3269 goto end;
3270 }
3271
3272 check_channel_flags:
3273 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
3274 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
3275 /* if we've just closed an output, let's switch */
3276 txn->rsp.msg_state = HTTP_MSG_CLOSING;
3277 goto http_msg_closing;
3278 }
3279
3280 end:
3281 chn->analysers &= AN_RES_FLT_END;
3282 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
3283 chn->analysers |= AN_RES_FLT_XFER_DATA;
3284 channel_auto_close(chn);
3285 channel_auto_read(chn);
3286}
3287
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02003288__attribute__((constructor))
3289static void __htx_protocol_init(void)
3290{
3291}
3292
3293
3294/*
3295 * Local variables:
3296 * c-indent-level: 8
3297 * c-basic-offset: 8
3298 * End:
3299 */