1 /*
2 * HTTP protocol analyzer
3 *
4 * Copyright 2000-2011 Willy Tarreau <w@1wt.eu>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
13 #include <ctype.h>
14 #include <errno.h>
15 #include <fcntl.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <syslog.h>
20 #include <time.h>
21
22 #include <sys/socket.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25
26 #include <netinet/tcp.h>
27
28 #include <common/base64.h>
29 #include <common/chunk.h>
30 #include <common/compat.h>
31 #include <common/config.h>
32 #include <common/debug.h>
33 #include <common/memory.h>
34 #include <common/mini-clist.h>
35 #include <common/standard.h>
36 #include <common/ticks.h>
37 #include <common/time.h>
38 #include <common/uri_auth.h>
39 #include <common/version.h>
40
41 #include <types/capture.h>
42 #include <types/cli.h>
43 #include <types/filters.h>
44 #include <types/global.h>
45 #include <types/cache.h>
46 #include <types/stats.h>
47
48 #include <proto/acl.h>
49 #include <proto/action.h>
50 #include <proto/arg.h>
51 #include <proto/auth.h>
52 #include <proto/backend.h>
53 #include <proto/channel.h>
54 #include <proto/checks.h>
55 #include <proto/cli.h>
56 #include <proto/compression.h>
57 #include <proto/stats.h>
58 #include <proto/fd.h>
59 #include <proto/filters.h>
60 #include <proto/frontend.h>
61 #include <proto/h1.h>
62 #include <proto/log.h>
63 #include <proto/hdr_idx.h>
64 #include <proto/hlua.h>
65 #include <proto/pattern.h>
66 #include <proto/proto_tcp.h>
67 #include <proto/proto_http.h>
68 #include <proto/proxy.h>
69 #include <proto/queue.h>
70 #include <proto/sample.h>
71 #include <proto/server.h>
72 #include <proto/stream.h>
73 #include <proto/stream_interface.h>
74 #include <proto/task.h>
75 #include <proto/pattern.h>
76 #include <proto/vars.h>
77
78 const char HTTP_100[] =
79 "HTTP/1.1 100 Continue\r\n\r\n";
80
81 const struct chunk http_100_chunk = {
82 .str = (char *)&HTTP_100,
83 .len = sizeof(HTTP_100)-1
84 };
85
86 /* Warning: no "connection" header is provided with the 3xx messages below */
87 const char *HTTP_301 =
88 "HTTP/1.1 301 Moved Permanently\r\n"
89 "Content-length: 0\r\n"
90 "Location: "; /* not terminated since it will be concatenated with the URL */
91
92 const char *HTTP_302 =
93 "HTTP/1.1 302 Found\r\n"
94 "Cache-Control: no-cache\r\n"
95 "Content-length: 0\r\n"
96 "Location: "; /* not terminated since it will be concatenated with the URL */
97
98 /* same as 302 except that the browser MUST retry with the GET method */
99 const char *HTTP_303 =
100 "HTTP/1.1 303 See Other\r\n"
101 "Cache-Control: no-cache\r\n"
102 "Content-length: 0\r\n"
103 "Location: "; /* not terminated since it will be concatenated with the URL */
104
105
106 /* same as 302 except that the browser MUST retry with the same method */
107 const char *HTTP_307 =
108 "HTTP/1.1 307 Temporary Redirect\r\n"
109 "Cache-Control: no-cache\r\n"
110 "Content-length: 0\r\n"
111 "Location: "; /* not terminated since it will be concatenated with the URL */
112
113 /* same as 301 except that the browser MUST retry with the same method */
114 const char *HTTP_308 =
115 "HTTP/1.1 308 Permanent Redirect\r\n"
116 "Content-length: 0\r\n"
117 "Location: "; /* not terminated since it will be concatenated with the URL */
118
119 /* Warning: this one is an sprintf() fmt string, with <realm> as its only argument */
120 const char *HTTP_401_fmt =
121 "HTTP/1.0 401 Unauthorized\r\n"
122 "Cache-Control: no-cache\r\n"
123 "Connection: close\r\n"
124 "Content-Type: text/html\r\n"
125 "WWW-Authenticate: Basic realm=\"%s\"\r\n"
126 "\r\n"
127 "<html><body><h1>401 Unauthorized</h1>\nYou need a valid user and password to access this content.\n</body></html>\n";
128
129 const char *HTTP_407_fmt =
130 "HTTP/1.0 407 Unauthorized\r\n"
131 "Cache-Control: no-cache\r\n"
132 "Connection: close\r\n"
133 "Content-Type: text/html\r\n"
134 "Proxy-Authenticate: Basic realm=\"%s\"\r\n"
135 "\r\n"
136 "<html><body><h1>407 Unauthorized</h1>\nYou need a valid user and password to access this content.\n</body></html>\n";
137
138
139 const int http_err_codes[HTTP_ERR_SIZE] = {
140 [HTTP_ERR_200] = 200, /* used by "monitor-uri" */
141 [HTTP_ERR_400] = 400,
142 [HTTP_ERR_403] = 403,
143 [HTTP_ERR_405] = 405,
144 [HTTP_ERR_408] = 408,
145 [HTTP_ERR_425] = 425,
146 [HTTP_ERR_429] = 429,
147 [HTTP_ERR_500] = 500,
148 [HTTP_ERR_502] = 502,
149 [HTTP_ERR_503] = 503,
150 [HTTP_ERR_504] = 504,
151 };
152
153 static const char *http_err_msgs[HTTP_ERR_SIZE] = {
154 [HTTP_ERR_200] =
155 "HTTP/1.0 200 OK\r\n"
156 "Cache-Control: no-cache\r\n"
157 "Connection: close\r\n"
158 "Content-Type: text/html\r\n"
159 "\r\n"
160 "<html><body><h1>200 OK</h1>\nService ready.\n</body></html>\n",
161
162 [HTTP_ERR_400] =
163 "HTTP/1.0 400 Bad request\r\n"
164 "Cache-Control: no-cache\r\n"
165 "Connection: close\r\n"
166 "Content-Type: text/html\r\n"
167 "\r\n"
168 "<html><body><h1>400 Bad request</h1>\nYour browser sent an invalid request.\n</body></html>\n",
169
170 [HTTP_ERR_403] =
171 "HTTP/1.0 403 Forbidden\r\n"
172 "Cache-Control: no-cache\r\n"
173 "Connection: close\r\n"
174 "Content-Type: text/html\r\n"
175 "\r\n"
176 "<html><body><h1>403 Forbidden</h1>\nRequest forbidden by administrative rules.\n</body></html>\n",
177
178 [HTTP_ERR_405] =
179 "HTTP/1.0 405 Method Not Allowed\r\n"
180 "Cache-Control: no-cache\r\n"
181 "Connection: close\r\n"
182 "Content-Type: text/html\r\n"
183 "\r\n"
184 "<html><body><h1>405 Method Not Allowed</h1>\nA request was made of a resource using a request method not supported by that resource\n</body></html>\n",
185
186 [HTTP_ERR_408] =
187 "HTTP/1.0 408 Request Time-out\r\n"
188 "Cache-Control: no-cache\r\n"
189 "Connection: close\r\n"
190 "Content-Type: text/html\r\n"
191 "\r\n"
192 "<html><body><h1>408 Request Time-out</h1>\nYour browser didn't send a complete request in time.\n</body></html>\n",
193
194 [HTTP_ERR_425] =
195 "HTTP/1.0 425 Too Early\r\n"
196 "Cache-Control: no-cache\r\n"
197 "Connection: close\r\n"
198 "Content-Type: text/html\r\n"
199 "\r\n"
200 "<html><body><h1>425 Too Early</h1>\nYour browser sent early data.\n</body></html>\n",
201
202 [HTTP_ERR_429] =
203 "HTTP/1.0 429 Too Many Requests\r\n"
204 "Cache-Control: no-cache\r\n"
205 "Connection: close\r\n"
206 "Content-Type: text/html\r\n"
207 "\r\n"
208 "<html><body><h1>429 Too Many Requests</h1>\nYou have sent too many requests in a given amount of time.\n</body></html>\n",
209
210 [HTTP_ERR_500] =
211 "HTTP/1.0 500 Internal Server Error\r\n"
212 "Cache-Control: no-cache\r\n"
213 "Connection: close\r\n"
214 "Content-Type: text/html\r\n"
215 "\r\n"
216 "<html><body><h1>500 Internal Server Error</h1>\nAn internal server error occured.\n</body></html>\n",
217
218 [HTTP_ERR_502] =
219 "HTTP/1.0 502 Bad Gateway\r\n"
220 "Cache-Control: no-cache\r\n"
221 "Connection: close\r\n"
222 "Content-Type: text/html\r\n"
223 "\r\n"
224 "<html><body><h1>502 Bad Gateway</h1>\nThe server returned an invalid or incomplete response.\n</body></html>\n",
225
226 [HTTP_ERR_503] =
227 "HTTP/1.0 503 Service Unavailable\r\n"
228 "Cache-Control: no-cache\r\n"
229 "Connection: close\r\n"
230 "Content-Type: text/html\r\n"
231 "\r\n"
232 "<html><body><h1>503 Service Unavailable</h1>\nNo server is available to handle this request.\n</body></html>\n",
233
234 [HTTP_ERR_504] =
235 "HTTP/1.0 504 Gateway Time-out\r\n"
236 "Cache-Control: no-cache\r\n"
237 "Connection: close\r\n"
238 "Content-Type: text/html\r\n"
239 "\r\n"
240 "<html><body><h1>504 Gateway Time-out</h1>\nThe server didn't respond in time.\n</body></html>\n",
241
242 };
243
244 /* status codes available for the stats admin page (strictly 4 chars length) */
245 const char *stat_status_codes[STAT_STATUS_SIZE] = {
246 [STAT_STATUS_DENY] = "DENY",
247 [STAT_STATUS_DONE] = "DONE",
248 [STAT_STATUS_ERRP] = "ERRP",
249 [STAT_STATUS_EXCD] = "EXCD",
250 [STAT_STATUS_NONE] = "NONE",
251 [STAT_STATUS_PART] = "PART",
252 [STAT_STATUS_UNKN] = "UNKN",
253 };
254
255
256 /* List head of all known action keywords for "http-request" */
257 struct action_kw_list http_req_keywords = {
258 .list = LIST_HEAD_INIT(http_req_keywords.list)
259 };
260
261 /* List head of all known action keywords for "http-response" */
262 struct action_kw_list http_res_keywords = {
263 .list = LIST_HEAD_INIT(http_res_keywords.list)
264 };
265
266 /* We must put the messages here since GCC cannot initialize consts depending
267 * on strlen().
268 */
269 struct chunk http_err_chunks[HTTP_ERR_SIZE];
270
271 /* this struct is used between calls to smp_fetch_hdr() or smp_fetch_cookie() */
272 static THREAD_LOCAL struct hdr_ctx static_hdr_ctx;
273
274 #define FD_SETS_ARE_BITFIELDS
275 #ifdef FD_SETS_ARE_BITFIELDS
276 /*
277 * This map is used with all the FD_* macros to check whether a particular bit
278 * is set or not. Each bit represents an ACSII code. FD_SET() sets those bytes
279 * which should be encoded. When FD_ISSET() returns non-zero, it means that the
280 * byte should be encoded. Be careful to always pass bytes from 0 to 255
281 * exclusively to the macros.
282 */
283 fd_set hdr_encode_map[(sizeof(fd_set) > (256/8)) ? 1 : ((256/8) / sizeof(fd_set))];
284 fd_set url_encode_map[(sizeof(fd_set) > (256/8)) ? 1 : ((256/8) / sizeof(fd_set))];
285 fd_set http_encode_map[(sizeof(fd_set) > (256/8)) ? 1 : ((256/8) / sizeof(fd_set))];
286
287 #else
288 #error "Check if your OS uses bitfields for fd_sets"
289 #endif
290
291 static int http_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn);
292
293 static inline int http_msg_forward_body(struct stream *s, struct http_msg *msg);
294 static inline int http_msg_forward_chunked_body(struct stream *s, struct http_msg *msg);
295
296 /* This function returns a reason associated with the HTTP status.
297 * This function never fails, a message is always returned.
298 */
get_reason(unsigned int status)299 const char *get_reason(unsigned int status)
300 {
301 switch (status) {
302 case 100: return "Continue";
303 case 101: return "Switching Protocols";
304 case 102: return "Processing";
305 case 200: return "OK";
306 case 201: return "Created";
307 case 202: return "Accepted";
308 case 203: return "Non-Authoritative Information";
309 case 204: return "No Content";
310 case 205: return "Reset Content";
311 case 206: return "Partial Content";
312 case 207: return "Multi-Status";
313 case 210: return "Content Different";
314 case 226: return "IM Used";
315 case 300: return "Multiple Choices";
316 case 301: return "Moved Permanently";
317 case 302: return "Moved Temporarily";
318 case 303: return "See Other";
319 case 304: return "Not Modified";
320 case 305: return "Use Proxy";
321 case 307: return "Temporary Redirect";
322 case 308: return "Permanent Redirect";
323 case 310: return "Too many Redirects";
324 case 400: return "Bad Request";
325 case 401: return "Unauthorized";
326 case 402: return "Payment Required";
327 case 403: return "Forbidden";
328 case 404: return "Not Found";
329 case 405: return "Method Not Allowed";
330 case 406: return "Not Acceptable";
331 case 407: return "Proxy Authentication Required";
332 case 408: return "Request Time-out";
333 case 409: return "Conflict";
334 case 410: return "Gone";
335 case 411: return "Length Required";
336 case 412: return "Precondition Failed";
337 case 413: return "Request Entity Too Large";
338 case 414: return "Request-URI Too Long";
339 case 415: return "Unsupported Media Type";
340 case 416: return "Requested range unsatisfiable";
341 case 417: return "Expectation failed";
342 case 418: return "I'm a teapot";
343 case 422: return "Unprocessable entity";
344 case 423: return "Locked";
345 case 424: return "Method failure";
346 case 425: return "Too Early";
347 case 426: return "Upgrade Required";
348 case 428: return "Precondition Required";
349 case 429: return "Too Many Requests";
350 case 431: return "Request Header Fields Too Large";
351 case 449: return "Retry With";
352 case 450: return "Blocked by Windows Parental Controls";
353 case 451: return "Unavailable For Legal Reasons";
354 case 456: return "Unrecoverable Error";
355 case 499: return "client has closed connection";
356 case 500: return "Internal Server Error";
357 case 501: return "Not Implemented";
358 case 502: return "Bad Gateway or Proxy Error";
359 case 503: return "Service Unavailable";
360 case 504: return "Gateway Time-out";
361 case 505: return "HTTP Version not supported";
362 case 506: return "Variant also negociate";
363 case 507: return "Insufficient storage";
364 case 508: return "Loop detected";
365 case 509: return "Bandwidth Limit Exceeded";
366 case 510: return "Not extended";
367 case 511: return "Network authentication required";
368 case 520: return "Web server is returning an unknown error";
369 default:
370 switch (status) {
371 case 100 ... 199: return "Informational";
372 case 200 ... 299: return "Success";
373 case 300 ... 399: return "Redirection";
374 case 400 ... 499: return "Client Error";
375 case 500 ... 599: return "Server Error";
376 default: return "Other";
377 }
378 }
379 }
380
381 /* This function returns HTTP_ERR_<num> (enum) matching http status code.
382 * Returned value should match codes from http_err_codes.
383 */
http_get_status_idx(unsigned int status)384 static const int http_get_status_idx(unsigned int status)
385 {
386 switch (status) {
387 case 200: return HTTP_ERR_200;
388 case 400: return HTTP_ERR_400;
389 case 403: return HTTP_ERR_403;
390 case 405: return HTTP_ERR_405;
391 case 408: return HTTP_ERR_408;
392 case 425: return HTTP_ERR_425;
393 case 429: return HTTP_ERR_429;
394 case 500: return HTTP_ERR_500;
395 case 502: return HTTP_ERR_502;
396 case 503: return HTTP_ERR_503;
397 case 504: return HTTP_ERR_504;
398 default: return HTTP_ERR_500;
399 }
400 }
401
init_proto_http()402 void init_proto_http()
403 {
404 int i;
405 char *tmp;
406 int msg;
407
408 for (msg = 0; msg < HTTP_ERR_SIZE; msg++) {
409 if (!http_err_msgs[msg]) {
410 ha_alert("Internal error: no message defined for HTTP return code %d. Aborting.\n", msg);
411 abort();
412 }
413
414 http_err_chunks[msg].str = (char *)http_err_msgs[msg];
415 http_err_chunks[msg].len = strlen(http_err_msgs[msg]);
416 }
417
418 /* initialize the log header encoding map : '{|}"#' should be encoded with
419 * '#' as prefix, as well as non-printable characters ( <32 or >= 127 ).
420 * URL encoding only requires '"', '#' to be encoded as well as non-
421 * printable characters above.
422 */
423 memset(hdr_encode_map, 0, sizeof(hdr_encode_map));
424 memset(url_encode_map, 0, sizeof(url_encode_map));
425 memset(http_encode_map, 0, sizeof(url_encode_map));
426 for (i = 0; i < 32; i++) {
427 FD_SET(i, hdr_encode_map);
428 FD_SET(i, url_encode_map);
429 }
430 for (i = 127; i < 256; i++) {
431 FD_SET(i, hdr_encode_map);
432 FD_SET(i, url_encode_map);
433 }
434
435 tmp = "\"#{|}";
436 while (*tmp) {
437 FD_SET(*tmp, hdr_encode_map);
438 tmp++;
439 }
440
441 tmp = "\"#";
442 while (*tmp) {
443 FD_SET(*tmp, url_encode_map);
444 tmp++;
445 }
446
447 /* initialize the http header encoding map. The draft httpbis define the
448 * header content as:
449 *
450 * HTTP-message = start-line
451 * *( header-field CRLF )
452 * CRLF
453 * [ message-body ]
454 * header-field = field-name ":" OWS field-value OWS
455 * field-value = *( field-content / obs-fold )
456 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
457 * obs-fold = CRLF 1*( SP / HTAB )
458 * field-vchar = VCHAR / obs-text
459 * VCHAR = %x21-7E
460 * obs-text = %x80-FF
461 *
462 * All the chars are encoded except "VCHAR", "obs-text", SP and HTAB.
463 * The encoded chars are form 0x00 to 0x08, 0x0a to 0x1f and 0x7f. The
464 * "obs-fold" is volontary forgotten because haproxy remove this.
465 */
466 memset(http_encode_map, 0, sizeof(http_encode_map));
467 for (i = 0x00; i <= 0x08; i++)
468 FD_SET(i, http_encode_map);
469 for (i = 0x0a; i <= 0x1f; i++)
470 FD_SET(i, http_encode_map);
471 FD_SET(0x7f, http_encode_map);
472
473 /* memory allocations */
474 pool_head_http_txn = create_pool("http_txn", sizeof(struct http_txn), MEM_F_SHARED);
475 pool_head_uniqueid = create_pool("uniqueid", UNIQUEID_LEN, MEM_F_SHARED);
476 }
477
478 /*
479 * We have 26 list of methods (1 per first letter), each of which can have
480 * up to 3 entries (2 valid, 1 null).
481 */
482 struct http_method_desc {
483 enum http_meth_t meth;
484 int len;
485 const char text[8];
486 };
487
488 const struct http_method_desc http_methods[26][3] = {
489 ['C' - 'A'] = {
490 [0] = { .meth = HTTP_METH_CONNECT , .len=7, .text="CONNECT" },
491 },
492 ['D' - 'A'] = {
493 [0] = { .meth = HTTP_METH_DELETE , .len=6, .text="DELETE" },
494 },
495 ['G' - 'A'] = {
496 [0] = { .meth = HTTP_METH_GET , .len=3, .text="GET" },
497 },
498 ['H' - 'A'] = {
499 [0] = { .meth = HTTP_METH_HEAD , .len=4, .text="HEAD" },
500 },
501 ['O' - 'A'] = {
502 [0] = { .meth = HTTP_METH_OPTIONS , .len=7, .text="OPTIONS" },
503 },
504 ['P' - 'A'] = {
505 [0] = { .meth = HTTP_METH_POST , .len=4, .text="POST" },
506 [1] = { .meth = HTTP_METH_PUT , .len=3, .text="PUT" },
507 },
508 ['T' - 'A'] = {
509 [0] = { .meth = HTTP_METH_TRACE , .len=5, .text="TRACE" },
510 },
511 /* rest is empty like this :
512 * [0] = { .meth = HTTP_METH_OTHER , .len=0, .text="" },
513 */
514 };
515
516 const struct http_method_name http_known_methods[HTTP_METH_OTHER] = {
517 [HTTP_METH_OPTIONS] = { "OPTIONS", 7 },
518 [HTTP_METH_GET] = { "GET", 3 },
519 [HTTP_METH_HEAD] = { "HEAD", 4 },
520 [HTTP_METH_POST] = { "POST", 4 },
521 [HTTP_METH_PUT] = { "PUT", 3 },
522 [HTTP_METH_DELETE] = { "DELETE", 6 },
523 [HTTP_METH_TRACE] = { "TRACE", 5 },
524 [HTTP_METH_CONNECT] = { "CONNECT", 7 },
525 };
526
527 /*
528 * Adds a header and its CRLF at the tail of the message's buffer, just before
529 * the last CRLF. Text length is measured first, so it cannot be NULL.
530 * The header is also automatically added to the index <hdr_idx>, and the end
531 * of headers is automatically adjusted. The number of bytes added is returned
532 * on success, otherwise <0 is returned indicating an error.
533 */
http_header_add_tail(struct http_msg * msg,struct hdr_idx * hdr_idx,const char * text)534 int http_header_add_tail(struct http_msg *msg, struct hdr_idx *hdr_idx, const char *text)
535 {
536 int bytes, len;
537
538 len = strlen(text);
539 bytes = buffer_insert_line2(msg->chn->buf, msg->chn->buf->p + msg->eoh, text, len);
540 if (!bytes)
541 return -1;
542 http_msg_move_end(msg, bytes);
543 return hdr_idx_add(len, 1, hdr_idx, hdr_idx->tail);
544 }
545
546 /*
547 * Adds a header and its CRLF at the tail of the message's buffer, just before
548 * the last CRLF. <len> bytes are copied, not counting the CRLF. If <text> is NULL, then
549 * the buffer is only opened and the space reserved, but nothing is copied.
550 * The header is also automatically added to the index <hdr_idx>, and the end
551 * of headers is automatically adjusted. The number of bytes added is returned
552 * on success, otherwise <0 is returned indicating an error.
553 */
http_header_add_tail2(struct http_msg * msg,struct hdr_idx * hdr_idx,const char * text,int len)554 int http_header_add_tail2(struct http_msg *msg,
555 struct hdr_idx *hdr_idx, const char *text, int len)
556 {
557 int bytes;
558
559 bytes = buffer_insert_line2(msg->chn->buf, msg->chn->buf->p + msg->eoh, text, len);
560 if (!bytes)
561 return -1;
562 http_msg_move_end(msg, bytes);
563 return hdr_idx_add(len, 1, hdr_idx, hdr_idx->tail);
564 }
565
566 /*
567 * Checks if <hdr> is exactly <name> for <len> chars, and ends with a colon.
568 * If so, returns the position of the first non-space character relative to
569 * <hdr>, or <end>-<hdr> if not found before. If no value is found, it tries
570 * to return a pointer to the place after the first space. Returns 0 if the
571 * header name does not match. Checks are case-insensitive.
572 */
http_header_match2(const char * hdr,const char * end,const char * name,int len)573 int http_header_match2(const char *hdr, const char *end,
574 const char *name, int len)
575 {
576 const char *val;
577
578 if (hdr + len >= end)
579 return 0;
580 if (hdr[len] != ':')
581 return 0;
582 if (strncasecmp(hdr, name, len) != 0)
583 return 0;
584 val = hdr + len + 1;
585 while (val < end && HTTP_IS_SPHT(*val))
586 val++;
587 if ((val >= end) && (len + 2 <= end - hdr))
588 return len + 2; /* we may replace starting from second space */
589 return val - hdr;
590 }
591
592 /* Find the first or next occurrence of header <name> in message buffer <sol>
593 * using headers index <idx>, and return it in the <ctx> structure. This
594 * structure holds everything necessary to use the header and find next
595 * occurrence. If its <idx> member is 0, the header is searched from the
596 * beginning. Otherwise, the next occurrence is returned. The function returns
597 * 1 when it finds a value, and 0 when there is no more. It is very similar to
598 * http_find_header2() except that it is designed to work with full-line headers
599 * whose comma is not a delimiter but is part of the syntax. As a special case,
600 * if ctx->val is NULL when searching for a new values of a header, the current
601 * header is rescanned. This allows rescanning after a header deletion.
602 */
http_find_full_header2(const char * name,int len,char * sol,struct hdr_idx * idx,struct hdr_ctx * ctx)603 int http_find_full_header2(const char *name, int len,
604 char *sol, struct hdr_idx *idx,
605 struct hdr_ctx *ctx)
606 {
607 char *eol, *sov;
608 int cur_idx, old_idx;
609
610 cur_idx = ctx->idx;
611 if (cur_idx) {
612 /* We have previously returned a header, let's search another one */
613 sol = ctx->line;
614 eol = sol + idx->v[cur_idx].len;
615 goto next_hdr;
616 }
617
618 /* first request for this header */
619 sol += hdr_idx_first_pos(idx);
620 old_idx = 0;
621 cur_idx = hdr_idx_first_idx(idx);
622 while (cur_idx) {
623 eol = sol + idx->v[cur_idx].len;
624
625 if (len == 0) {
626 /* No argument was passed, we want any header.
627 * To achieve this, we simply build a fake request. */
628 while (sol + len < eol && sol[len] != ':')
629 len++;
630 name = sol;
631 }
632
633 if ((len < eol - sol) &&
634 (sol[len] == ':') &&
635 (strncasecmp(sol, name, len) == 0)) {
636 ctx->del = len;
637 sov = sol + len + 1;
638 while (sov < eol && HTTP_IS_LWS(*sov))
639 sov++;
640
641 ctx->line = sol;
642 ctx->prev = old_idx;
643 ctx->idx = cur_idx;
644 ctx->val = sov - sol;
645 ctx->tws = 0;
646 while (eol > sov && HTTP_IS_LWS(*(eol - 1))) {
647 eol--;
648 ctx->tws++;
649 }
650 ctx->vlen = eol - sov;
651 return 1;
652 }
653 next_hdr:
654 sol = eol + idx->v[cur_idx].cr + 1;
655 old_idx = cur_idx;
656 cur_idx = idx->v[cur_idx].next;
657 }
658 return 0;
659 }
660
661 /* Find the first or next header field in message buffer <sol> using headers
662 * index <idx>, and return it in the <ctx> structure. This structure holds
663 * everything necessary to use the header and find next occurrence. If its
664 * <idx> member is 0, the first header is retrieved. Otherwise, the next
665 * occurrence is returned. The function returns 1 when it finds a value, and
666 * 0 when there is no more. It is equivalent to http_find_full_header2() with
667 * no header name.
668 */
http_find_next_header(char * sol,struct hdr_idx * idx,struct hdr_ctx * ctx)669 int http_find_next_header(char *sol, struct hdr_idx *idx, struct hdr_ctx *ctx)
670 {
671 char *eol, *sov;
672 int cur_idx, old_idx;
673 int len;
674
675 cur_idx = ctx->idx;
676 if (cur_idx) {
677 /* We have previously returned a header, let's search another one */
678 sol = ctx->line;
679 eol = sol + idx->v[cur_idx].len;
680 goto next_hdr;
681 }
682
683 /* first request for this header */
684 sol += hdr_idx_first_pos(idx);
685 old_idx = 0;
686 cur_idx = hdr_idx_first_idx(idx);
687 while (cur_idx) {
688 eol = sol + idx->v[cur_idx].len;
689
690 len = 0;
691 while (1) {
692 if (len >= eol - sol)
693 goto next_hdr;
694 if (sol[len] == ':')
695 break;
696 len++;
697 }
698
699 ctx->del = len;
700 sov = sol + len + 1;
701 while (sov < eol && HTTP_IS_LWS(*sov))
702 sov++;
703
704 ctx->line = sol;
705 ctx->prev = old_idx;
706 ctx->idx = cur_idx;
707 ctx->val = sov - sol;
708 ctx->tws = 0;
709
710 while (eol > sov && HTTP_IS_LWS(*(eol - 1))) {
711 eol--;
712 ctx->tws++;
713 }
714 ctx->vlen = eol - sov;
715 return 1;
716
717 next_hdr:
718 sol = eol + idx->v[cur_idx].cr + 1;
719 old_idx = cur_idx;
720 cur_idx = idx->v[cur_idx].next;
721 }
722 return 0;
723 }
724
725 /* Find the end of the header value contained between <s> and <e>. See RFC7230,
726 * par 3.2 for more information. Note that it requires a valid header to return
727 * a valid result. This works for headers defined as comma-separated lists.
728 */
find_hdr_value_end(char * s,const char * e)729 char *find_hdr_value_end(char *s, const char *e)
730 {
731 int quoted, qdpair;
732
733 quoted = qdpair = 0;
734
735 #if defined(__x86_64__) || \
736 defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) || \
737 defined(__ARM_ARCH_7A__)
738 /* speedup: skip everything not a comma nor a double quote */
739 for (; s <= e - sizeof(int); s += sizeof(int)) {
740 unsigned int c = *(int *)s; // comma
741 unsigned int q = c; // quote
742
743 c ^= 0x2c2c2c2c; // contains one zero on a comma
744 q ^= 0x22222222; // contains one zero on a quote
745
746 c = (c - 0x01010101) & ~c; // contains 0x80 below a comma
747 q = (q - 0x01010101) & ~q; // contains 0x80 below a quote
748
749 if ((c | q) & 0x80808080)
750 break; // found a comma or a quote
751 }
752 #endif
753 for (; s < e; s++) {
754 if (qdpair) qdpair = 0;
755 else if (quoted) {
756 if (*s == '\\') qdpair = 1;
757 else if (*s == '"') quoted = 0;
758 }
759 else if (*s == '"') quoted = 1;
760 else if (*s == ',') return s;
761 }
762 return s;
763 }
764
765 /* Find the first or next occurrence of header <name> in message buffer <sol>
766 * using headers index <idx>, and return it in the <ctx> structure. This
767 * structure holds everything necessary to use the header and find next
768 * occurrence. If its <idx> member is 0, the header is searched from the
769 * beginning. Otherwise, the next occurrence is returned. The function returns
770 * 1 when it finds a value, and 0 when there is no more. It is designed to work
771 * with headers defined as comma-separated lists. As a special case, if ctx->val
772 * is NULL when searching for a new values of a header, the current header is
773 * rescanned. This allows rescanning after a header deletion.
774 */
http_find_header2(const char * name,int len,char * sol,struct hdr_idx * idx,struct hdr_ctx * ctx)775 int http_find_header2(const char *name, int len,
776 char *sol, struct hdr_idx *idx,
777 struct hdr_ctx *ctx)
778 {
779 char *eol, *sov;
780 int cur_idx, old_idx;
781
782 cur_idx = ctx->idx;
783 if (cur_idx) {
784 /* We have previously returned a value, let's search
785 * another one on the same line.
786 */
787 sol = ctx->line;
788 ctx->del = ctx->val + ctx->vlen + ctx->tws;
789 sov = sol + ctx->del;
790 eol = sol + idx->v[cur_idx].len;
791
792 if (sov >= eol)
793 /* no more values in this header */
794 goto next_hdr;
795
796 /* values remaining for this header, skip the comma but save it
797 * for later use (eg: for header deletion).
798 */
799 sov++;
800 while (sov < eol && HTTP_IS_LWS((*sov)))
801 sov++;
802
803 goto return_hdr;
804 }
805
806 /* first request for this header */
807 sol += hdr_idx_first_pos(idx);
808 old_idx = 0;
809 cur_idx = hdr_idx_first_idx(idx);
810 while (cur_idx) {
811 eol = sol + idx->v[cur_idx].len;
812
813 if (len == 0) {
814 /* No argument was passed, we want any header.
815 * To achieve this, we simply build a fake request. */
816 while (sol + len < eol && sol[len] != ':')
817 len++;
818 name = sol;
819 }
820
821 if ((len < eol - sol) &&
822 (sol[len] == ':') &&
823 (strncasecmp(sol, name, len) == 0)) {
824 ctx->del = len;
825 sov = sol + len + 1;
826 while (sov < eol && HTTP_IS_LWS(*sov))
827 sov++;
828
829 ctx->line = sol;
830 ctx->prev = old_idx;
831 return_hdr:
832 ctx->idx = cur_idx;
833 ctx->val = sov - sol;
834
835 eol = find_hdr_value_end(sov, eol);
836 ctx->tws = 0;
837 while (eol > sov && HTTP_IS_LWS(*(eol - 1))) {
838 eol--;
839 ctx->tws++;
840 }
841 ctx->vlen = eol - sov;
842 return 1;
843 }
844 next_hdr:
845 sol = eol + idx->v[cur_idx].cr + 1;
846 old_idx = cur_idx;
847 cur_idx = idx->v[cur_idx].next;
848 }
849 return 0;
850 }
851
http_find_header(const char * name,char * sol,struct hdr_idx * idx,struct hdr_ctx * ctx)852 int http_find_header(const char *name,
853 char *sol, struct hdr_idx *idx,
854 struct hdr_ctx *ctx)
855 {
856 return http_find_header2(name, strlen(name), sol, idx, ctx);
857 }
858
859 /* Remove one value of a header. This only works on a <ctx> returned by one of
860 * the http_find_header functions. The value is removed, as well as surrounding
861 * commas if any. If the removed value was alone, the whole header is removed.
862 * The ctx is always updated accordingly, as well as the buffer and HTTP
863 * message <msg>. The new index is returned. If it is zero, it means there is
864 * no more header, so any processing may stop. The ctx is always left in a form
865 * that can be handled by http_find_header2() to find next occurrence.
866 */
http_remove_header2(struct http_msg * msg,struct hdr_idx * idx,struct hdr_ctx * ctx)867 int http_remove_header2(struct http_msg *msg, struct hdr_idx *idx, struct hdr_ctx *ctx)
868 {
869 int cur_idx = ctx->idx;
870 char *sol = ctx->line;
871 struct hdr_idx_elem *hdr;
872 int delta, skip_comma;
873
874 if (!cur_idx)
875 return 0;
876
877 hdr = &idx->v[cur_idx];
878 if (sol[ctx->del] == ':' && ctx->val + ctx->vlen + ctx->tws == hdr->len) {
879 /* This was the only value of the header, we must now remove it entirely. */
880 delta = buffer_replace2(msg->chn->buf, sol, sol + hdr->len + hdr->cr + 1, NULL, 0);
881 http_msg_move_end(msg, delta);
882 idx->used--;
883 hdr->len = 0; /* unused entry */
884 idx->v[ctx->prev].next = idx->v[ctx->idx].next;
885 if (idx->tail == ctx->idx)
886 idx->tail = ctx->prev;
887 ctx->idx = ctx->prev; /* walk back to the end of previous header */
888 ctx->line -= idx->v[ctx->idx].len + idx->v[ctx->idx].cr + 1;
889 ctx->val = idx->v[ctx->idx].len; /* point to end of previous header */
890 ctx->tws = ctx->vlen = 0;
891 return ctx->idx;
892 }
893
894 /* This was not the only value of this header. We have to remove between
895 * ctx->del+1 and ctx->val+ctx->vlen+ctx->tws+1 included. If it is the
896 * last entry of the list, we remove the last separator.
897 */
898
899 skip_comma = (ctx->val + ctx->vlen + ctx->tws == hdr->len) ? 0 : 1;
900 delta = buffer_replace2(msg->chn->buf, sol + ctx->del + skip_comma,
901 sol + ctx->val + ctx->vlen + ctx->tws + skip_comma,
902 NULL, 0);
903 hdr->len += delta;
904 http_msg_move_end(msg, delta);
905 ctx->val = ctx->del;
906 ctx->tws = ctx->vlen = 0;
907 return ctx->idx;
908 }
909
910 /* This function handles a server error at the stream interface level. The
911 * stream interface is assumed to be already in a closed state. An optional
912 * message is copied into the input buffer.
913 * The error flags are set to the values in arguments. Any pending request
914 * in this buffer will be lost.
915 */
http_server_error(struct stream * s,struct stream_interface * si,int err,int finst,const struct chunk * msg)916 static void http_server_error(struct stream *s, struct stream_interface *si,
917 int err, int finst, const struct chunk *msg)
918 {
919 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
920 channel_auto_read(si_oc(si));
921 channel_abort(si_oc(si));
922 channel_auto_close(si_oc(si));
923 channel_erase(si_oc(si));
924 channel_auto_close(si_ic(si));
925 channel_auto_read(si_ic(si));
926 if (msg)
927 co_inject(si_ic(si), msg->str, msg->len);
928 if (!(s->flags & SF_ERR_MASK))
929 s->flags |= err;
930 if (!(s->flags & SF_FINST_MASK))
931 s->flags |= finst;
932 }
933
934 /* This function returns the appropriate error location for the given stream
935 * and message.
936 */
937
http_error_message(struct stream * s)938 struct chunk *http_error_message(struct stream *s)
939 {
940 const int msgnum = http_get_status_idx(s->txn->status);
941
942 if (s->be->errmsg[msgnum].str)
943 return &s->be->errmsg[msgnum];
944 else if (strm_fe(s)->errmsg[msgnum].str)
945 return &strm_fe(s)->errmsg[msgnum];
946 else
947 return &http_err_chunks[msgnum];
948 }
949
950 void
http_reply_and_close(struct stream * s,short status,struct chunk * msg)951 http_reply_and_close(struct stream *s, short status, struct chunk *msg)
952 {
953 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
954 FLT_STRM_CB(s, flt_http_reply(s, status, msg));
955 stream_int_retnclose(&s->si[0], msg);
956 }
957
958 /*
959 * returns a known method among HTTP_METH_* or HTTP_METH_OTHER for all unknown
960 * ones.
961 */
find_http_meth(const char * str,const int len)962 enum http_meth_t find_http_meth(const char *str, const int len)
963 {
964 unsigned char m;
965 const struct http_method_desc *h;
966
967 m = ((unsigned)*str - 'A');
968
969 if (m < 26) {
970 for (h = http_methods[m]; h->len > 0; h++) {
971 if (unlikely(h->len != len))
972 continue;
973 if (likely(memcmp(str, h->text, h->len) == 0))
974 return h->meth;
975 };
976 }
977 return HTTP_METH_OTHER;
978 }
979
980 /* Parse the URI from the given transaction (which is assumed to be in request
981 * phase) and look for the "/" beginning the PATH. If not found, return NULL.
982 * It is returned otherwise.
983 */
http_get_path(struct http_txn * txn)984 char *http_get_path(struct http_txn *txn)
985 {
986 char *ptr, *end;
987
988 if (!txn->req.chn->buf->size)
989 return NULL;
990
991 ptr = txn->req.chn->buf->p + txn->req.sl.rq.u;
992 end = ptr + txn->req.sl.rq.u_l;
993
994 if (ptr >= end)
995 return NULL;
996
997 /* RFC7230, par. 2.7 :
998 * Request-URI = "*" | absuri | abspath | authority
999 */
1000
1001 if (*ptr == '*')
1002 return NULL;
1003
1004 if (isalpha((unsigned char)*ptr)) {
1005 /* this is a scheme as described by RFC3986, par. 3.1 */
1006 ptr++;
1007 while (ptr < end &&
1008 (isalnum((unsigned char)*ptr) || *ptr == '+' || *ptr == '-' || *ptr == '.'))
1009 ptr++;
1010 /* skip '://' */
1011 if (ptr == end || *ptr++ != ':')
1012 return NULL;
1013 if (ptr == end || *ptr++ != '/')
1014 return NULL;
1015 if (ptr == end || *ptr++ != '/')
1016 return NULL;
1017 }
1018 /* skip [user[:passwd]@]host[:[port]] */
1019
1020 while (ptr < end && *ptr != '/')
1021 ptr++;
1022
1023 if (ptr == end)
1024 return NULL;
1025
1026 /* OK, we got the '/' ! */
1027 return ptr;
1028 }
1029
1030 /* Parse the URI from the given string and look for the "/" beginning the PATH.
1031 * If not found, return NULL. It is returned otherwise.
1032 */
1033 static char *
http_get_path_from_string(char * str)1034 http_get_path_from_string(char *str)
1035 {
1036 char *ptr = str;
1037
1038 /* RFC2616, par. 5.1.2 :
1039 * Request-URI = "*" | absuri | abspath | authority
1040 */
1041
1042 if (*ptr == '*')
1043 return NULL;
1044
1045 if (isalpha((unsigned char)*ptr)) {
1046 /* this is a scheme as described by RFC3986, par. 3.1 */
1047 ptr++;
1048 while (isalnum((unsigned char)*ptr) || *ptr == '+' || *ptr == '-' || *ptr == '.')
1049 ptr++;
1050 /* skip '://' */
1051 if (*ptr == '\0' || *ptr++ != ':')
1052 return NULL;
1053 if (*ptr == '\0' || *ptr++ != '/')
1054 return NULL;
1055 if (*ptr == '\0' || *ptr++ != '/')
1056 return NULL;
1057 }
1058 /* skip [user[:passwd]@]host[:[port]] */
1059
1060 while (*ptr != '\0' && *ptr != ' ' && *ptr != '/')
1061 ptr++;
1062
1063 if (*ptr == '\0' || *ptr == ' ')
1064 return NULL;
1065
1066 /* OK, we got the '/' ! */
1067 return ptr;
1068 }
1069
1070 /* Returns a 302 for a redirectable request that reaches a server working in
1071 * in redirect mode. This may only be called just after the stream interface
1072 * has moved to SI_ST_ASS. Unprocessable requests are left unchanged and will
1073 * follow normal proxy processing. NOTE: this function is designed to support
1074 * being called once data are scheduled for forwarding.
1075 */
http_perform_server_redirect(struct stream * s,struct stream_interface * si)1076 void http_perform_server_redirect(struct stream *s, struct stream_interface *si)
1077 {
1078 struct http_txn *txn;
1079 struct server *srv;
1080 char *path;
1081 int len, rewind;
1082
1083 /* 1: create the response header */
1084 trash.len = strlen(HTTP_302);
1085 memcpy(trash.str, HTTP_302, trash.len);
1086
1087 srv = objt_server(s->target);
1088
1089 /* 2: add the server's prefix */
1090 if (trash.len + srv->rdr_len > trash.size)
1091 return;
1092
1093 /* special prefix "/" means don't change URL */
1094 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
1095 memcpy(trash.str + trash.len, srv->rdr_pfx, srv->rdr_len);
1096 trash.len += srv->rdr_len;
1097 }
1098
1099 /* 3: add the request URI. Since it was already forwarded, we need
1100 * to temporarily rewind the buffer.
1101 */
1102 txn = s->txn;
1103 b_rew(s->req.buf, rewind = http_hdr_rewind(&txn->req));
1104
1105 path = http_get_path(txn);
1106 len = buffer_count(s->req.buf, path, b_ptr(s->req.buf, txn->req.sl.rq.u + txn->req.sl.rq.u_l));
1107
1108 b_adv(s->req.buf, rewind);
1109
1110 if (!path)
1111 return;
1112
1113 if (trash.len + len > trash.size - 4) /* 4 for CRLF-CRLF */
1114 return;
1115
1116 memcpy(trash.str + trash.len, path, len);
1117 trash.len += len;
1118
1119 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
1120 memcpy(trash.str + trash.len, "\r\nProxy-Connection: close\r\n\r\n", 29);
1121 trash.len += 29;
1122 } else {
1123 memcpy(trash.str + trash.len, "\r\nConnection: close\r\n\r\n", 23);
1124 trash.len += 23;
1125 }
1126
1127 /* prepare to return without error. */
1128 si_shutr(si);
1129 si_shutw(si);
1130 si->err_type = SI_ET_NONE;
1131 si->state = SI_ST_CLO;
1132
1133 /* send the message */
1134 txn->status = 302;
1135 http_server_error(s, si, SF_ERR_LOCAL, SF_FINST_C, &trash);
1136
1137 /* FIXME: we should increase a counter of redirects per server and per backend. */
1138 srv_inc_sess_ctr(srv);
1139 srv_set_sess_last(srv);
1140 }
1141
1142 /* Return the error message corresponding to si->err_type. It is assumed
1143 * that the server side is closed. Note that err_type is actually a
1144 * bitmask, where almost only aborts may be cumulated with other
1145 * values. We consider that aborted operations are more important
1146 * than timeouts or errors due to the fact that nobody else in the
1147 * logs might explain incomplete retries. All others should avoid
1148 * being cumulated. It should normally not be possible to have multiple
1149 * aborts at once, but just in case, the first one in sequence is reported.
1150 * Note that connection errors appearing on the second request of a keep-alive
1151 * connection are not reported since this allows the client to retry.
1152 */
http_return_srv_error(struct stream * s,struct stream_interface * si)1153 void http_return_srv_error(struct stream *s, struct stream_interface *si)
1154 {
1155 int err_type = si->err_type;
1156
1157 /* set s->txn->status for http_error_message(s) */
1158 s->txn->status = 503;
1159
1160 if (err_type & SI_ET_QUEUE_ABRT)
1161 http_server_error(s, si, SF_ERR_CLICL, SF_FINST_Q,
1162 http_error_message(s));
1163 else if (err_type & SI_ET_CONN_ABRT)
1164 http_server_error(s, si, SF_ERR_CLICL, SF_FINST_C,
1165 (s->txn->flags & TX_NOT_FIRST) ? NULL :
1166 http_error_message(s));
1167 else if (err_type & SI_ET_QUEUE_TO)
1168 http_server_error(s, si, SF_ERR_SRVTO, SF_FINST_Q,
1169 http_error_message(s));
1170 else if (err_type & SI_ET_QUEUE_ERR)
1171 http_server_error(s, si, SF_ERR_SRVCL, SF_FINST_Q,
1172 http_error_message(s));
1173 else if (err_type & SI_ET_CONN_TO)
1174 http_server_error(s, si, SF_ERR_SRVTO, SF_FINST_C,
1175 (s->txn->flags & TX_NOT_FIRST) ? NULL :
1176 http_error_message(s));
1177 else if (err_type & SI_ET_CONN_ERR)
1178 http_server_error(s, si, SF_ERR_SRVCL, SF_FINST_C,
1179 (s->flags & SF_SRV_REUSED) ? NULL :
1180 http_error_message(s));
1181 else if (err_type & SI_ET_CONN_RES)
1182 http_server_error(s, si, SF_ERR_RESOURCE, SF_FINST_C,
1183 (s->txn->flags & TX_NOT_FIRST) ? NULL :
1184 http_error_message(s));
1185 else { /* SI_ET_CONN_OTHER and others */
1186 s->txn->status = 500;
1187 http_server_error(s, si, SF_ERR_INTERNAL, SF_FINST_C,
1188 http_error_message(s));
1189 }
1190 }
1191
1192 extern const char sess_term_cond[8];
1193 extern const char sess_fin_state[8];
1194 extern const char *monthname[12];
1195 struct pool_head *pool_head_http_txn;
1196 struct pool_head *pool_head_requri;
1197 struct pool_head *pool_head_capture = NULL;
1198 struct pool_head *pool_head_uniqueid;
1199
1200 /*
1201 * Capture headers from message starting at <som> according to header list
1202 * <cap_hdr>, and fill the <cap> pointers appropriately.
1203 */
capture_headers(char * som,struct hdr_idx * idx,char ** cap,struct cap_hdr * cap_hdr)1204 void capture_headers(char *som, struct hdr_idx *idx,
1205 char **cap, struct cap_hdr *cap_hdr)
1206 {
1207 char *eol, *sol, *col, *sov;
1208 int cur_idx;
1209 struct cap_hdr *h;
1210 int len;
1211
1212 sol = som + hdr_idx_first_pos(idx);
1213 cur_idx = hdr_idx_first_idx(idx);
1214
1215 while (cur_idx) {
1216 eol = sol + idx->v[cur_idx].len;
1217
1218 col = sol;
1219 while (col < eol && *col != ':')
1220 col++;
1221
1222 sov = col + 1;
1223 while (sov < eol && HTTP_IS_LWS(*sov))
1224 sov++;
1225
1226 for (h = cap_hdr; h; h = h->next) {
1227 if (h->namelen && (h->namelen == col - sol) &&
1228 (strncasecmp(sol, h->name, h->namelen) == 0)) {
1229 if (cap[h->index] == NULL)
1230 cap[h->index] =
1231 pool_alloc(h->pool);
1232
1233 if (cap[h->index] == NULL) {
1234 ha_alert("HTTP capture : out of memory.\n");
1235 continue;
1236 }
1237
1238 len = eol - sov;
1239 if (len > h->len)
1240 len = h->len;
1241
1242 memcpy(cap[h->index], sov, len);
1243 cap[h->index][len]=0;
1244 }
1245 }
1246 sol = eol + idx->v[cur_idx].cr + 1;
1247 cur_idx = idx->v[cur_idx].next;
1248 }
1249 }
1250
1251 /*
1252 * Returns the data from Authorization header. Function may be called more
1253 * than once so data is stored in txn->auth_data. When no header is found
1254 * or auth method is unknown auth_method is set to HTTP_AUTH_WRONG to avoid
1255 * searching again for something we are unable to find anyway. However, if
1256 * the result if valid, the cache is not reused because we would risk to
1257 * have the credentials overwritten by another stream in parallel.
1258 */
1259
1260 int
get_http_auth(struct stream * s)1261 get_http_auth(struct stream *s)
1262 {
1263
1264 struct http_txn *txn = s->txn;
1265 struct chunk auth_method;
1266 struct hdr_ctx ctx;
1267 char *h, *p;
1268 int len;
1269
1270 #ifdef DEBUG_AUTH
1271 printf("Auth for stream %p: %d\n", s, txn->auth.method);
1272 #endif
1273
1274 if (txn->auth.method == HTTP_AUTH_WRONG)
1275 return 0;
1276
1277 txn->auth.method = HTTP_AUTH_WRONG;
1278
1279 ctx.idx = 0;
1280
1281 if (txn->flags & TX_USE_PX_CONN) {
1282 h = "Proxy-Authorization";
1283 len = strlen(h);
1284 } else {
1285 h = "Authorization";
1286 len = strlen(h);
1287 }
1288
1289 if (!http_find_header2(h, len, s->req.buf->p, &txn->hdr_idx, &ctx))
1290 return 0;
1291
1292 h = ctx.line + ctx.val;
1293
1294 p = memchr(h, ' ', ctx.vlen);
1295 len = p - h;
1296 if (!p || len <= 0)
1297 return 0;
1298
1299 if (chunk_initlen(&auth_method, h, 0, len) != 1)
1300 return 0;
1301
1302 chunk_initlen(&txn->auth.method_data, p + 1, 0, ctx.vlen - len - 1);
1303
1304 if (!strncasecmp("Basic", auth_method.str, auth_method.len)) {
1305 struct chunk *http_auth = get_trash_chunk();
1306
1307 len = base64dec(txn->auth.method_data.str, txn->auth.method_data.len,
1308 http_auth->str, global.tune.bufsize - 1);
1309
1310 if (len < 0)
1311 return 0;
1312
1313
1314 http_auth->str[len] = '\0';
1315
1316 p = strchr(http_auth->str, ':');
1317
1318 if (!p)
1319 return 0;
1320
1321 txn->auth.user = http_auth->str;
1322 *p = '\0';
1323 txn->auth.pass = p+1;
1324
1325 txn->auth.method = HTTP_AUTH_BASIC;
1326 return 1;
1327 }
1328
1329 return 0;
1330 }
1331
1332
1333 /* convert an HTTP/0.9 request into an HTTP/1.0 request. Returns 1 if the
1334 * conversion succeeded, 0 in case of error. If the request was already 1.X,
1335 * nothing is done and 1 is returned.
1336 */
http_upgrade_v09_to_v10(struct http_txn * txn)1337 static int http_upgrade_v09_to_v10(struct http_txn *txn)
1338 {
1339 int delta;
1340 char *cur_end;
1341 struct http_msg *msg = &txn->req;
1342
1343 if (msg->sl.rq.v_l != 0)
1344 return 1;
1345
1346 /* RFC 1945 allows only GET for HTTP/0.9 requests */
1347 if (txn->meth != HTTP_METH_GET)
1348 return 0;
1349
1350 cur_end = msg->chn->buf->p + msg->sl.rq.l;
1351
1352 if (msg->sl.rq.u_l == 0) {
1353 /* HTTP/0.9 requests *must* have a request URI, per RFC 1945 */
1354 return 0;
1355 }
1356 /* add HTTP version */
1357 delta = buffer_replace2(msg->chn->buf, cur_end, cur_end, " HTTP/1.0\r\n", 11);
1358 http_msg_move_end(msg, delta);
1359 cur_end += delta;
1360 cur_end = (char *)http_parse_reqline(msg,
1361 HTTP_MSG_RQMETH,
1362 msg->chn->buf->p, cur_end + 1,
1363 NULL, NULL);
1364 if (unlikely(!cur_end))
1365 return 0;
1366
1367 /* we have a full HTTP/1.0 request now and we know that
1368 * we have either a CR or an LF at <ptr>.
1369 */
1370 hdr_idx_set_start(&txn->hdr_idx, msg->sl.rq.l, *cur_end == '\r');
1371 return 1;
1372 }
1373
1374 /* Parse the Connection: header of an HTTP request, looking for both "close"
1375 * and "keep-alive" values. If we already know that some headers may safely
1376 * be removed, we remove them now. The <to_del> flags are used for that :
1377 * - bit 0 means remove "close" headers (in HTTP/1.0 requests/responses)
1378 * - bit 1 means remove "keep-alive" headers (in HTTP/1.1 reqs/resp to 1.1).
1379 * Presence of the "Upgrade" token is also checked and reported.
1380 * The TX_HDR_CONN_* flags are adjusted in txn->flags depending on what was
1381 * found, and TX_CON_*_SET is adjusted depending on what is left so only
1382 * harmless combinations may be removed. Do not call that after changes have
1383 * been processed.
1384 */
http_parse_connection_header(struct http_txn * txn,struct http_msg * msg,int to_del)1385 void http_parse_connection_header(struct http_txn *txn, struct http_msg *msg, int to_del)
1386 {
1387 struct hdr_ctx ctx;
1388 const char *hdr_val = "Connection";
1389 int hdr_len = 10;
1390
1391 if (txn->flags & TX_HDR_CONN_PRS)
1392 return;
1393
1394 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
1395 hdr_val = "Proxy-Connection";
1396 hdr_len = 16;
1397 }
1398
1399 ctx.idx = 0;
1400 txn->flags &= ~(TX_CON_KAL_SET|TX_CON_CLO_SET);
1401 while (http_find_header2(hdr_val, hdr_len, msg->chn->buf->p, &txn->hdr_idx, &ctx)) {
1402 if (ctx.vlen >= 10 && word_match(ctx.line + ctx.val, ctx.vlen, "keep-alive", 10)) {
1403 txn->flags |= TX_HDR_CONN_KAL;
1404 if (to_del & 2)
1405 http_remove_header2(msg, &txn->hdr_idx, &ctx);
1406 else
1407 txn->flags |= TX_CON_KAL_SET;
1408 }
1409 else if (ctx.vlen >= 5 && word_match(ctx.line + ctx.val, ctx.vlen, "close", 5)) {
1410 txn->flags |= TX_HDR_CONN_CLO;
1411 if (to_del & 1)
1412 http_remove_header2(msg, &txn->hdr_idx, &ctx);
1413 else
1414 txn->flags |= TX_CON_CLO_SET;
1415 }
1416 else if (ctx.vlen >= 7 && word_match(ctx.line + ctx.val, ctx.vlen, "upgrade", 7)) {
1417 txn->flags |= TX_HDR_CONN_UPG;
1418 }
1419 }
1420
1421 txn->flags |= TX_HDR_CONN_PRS;
1422 return;
1423 }
1424
1425 /* Apply desired changes on the Connection: header. Values may be removed and/or
1426 * added depending on the <wanted> flags, which are exclusively composed of
1427 * TX_CON_CLO_SET and TX_CON_KAL_SET, depending on what flags are desired. The
1428 * TX_CON_*_SET flags are adjusted in txn->flags depending on what is left.
1429 */
http_change_connection_header(struct http_txn * txn,struct http_msg * msg,int wanted)1430 void http_change_connection_header(struct http_txn *txn, struct http_msg *msg, int wanted)
1431 {
1432 struct hdr_ctx ctx;
1433 const char *hdr_val = "Connection";
1434 int hdr_len = 10;
1435
1436 ctx.idx = 0;
1437
1438
1439 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
1440 hdr_val = "Proxy-Connection";
1441 hdr_len = 16;
1442 }
1443
1444 txn->flags &= ~(TX_CON_CLO_SET | TX_CON_KAL_SET);
1445 while (http_find_header2(hdr_val, hdr_len, msg->chn->buf->p, &txn->hdr_idx, &ctx)) {
1446 if (ctx.vlen >= 10 && word_match(ctx.line + ctx.val, ctx.vlen, "keep-alive", 10)) {
1447 if (wanted & TX_CON_KAL_SET)
1448 txn->flags |= TX_CON_KAL_SET;
1449 else
1450 http_remove_header2(msg, &txn->hdr_idx, &ctx);
1451 }
1452 else if (ctx.vlen >= 5 && word_match(ctx.line + ctx.val, ctx.vlen, "close", 5)) {
1453 if (wanted & TX_CON_CLO_SET)
1454 txn->flags |= TX_CON_CLO_SET;
1455 else
1456 http_remove_header2(msg, &txn->hdr_idx, &ctx);
1457 }
1458 }
1459
1460 if (wanted == (txn->flags & (TX_CON_CLO_SET|TX_CON_KAL_SET)))
1461 return;
1462
1463 if ((wanted & TX_CON_CLO_SET) && !(txn->flags & TX_CON_CLO_SET)) {
1464 txn->flags |= TX_CON_CLO_SET;
1465 hdr_val = "Connection: close";
1466 hdr_len = 17;
1467 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
1468 hdr_val = "Proxy-Connection: close";
1469 hdr_len = 23;
1470 }
1471 http_header_add_tail2(msg, &txn->hdr_idx, hdr_val, hdr_len);
1472 }
1473
1474 if ((wanted & TX_CON_KAL_SET) && !(txn->flags & TX_CON_KAL_SET)) {
1475 txn->flags |= TX_CON_KAL_SET;
1476 hdr_val = "Connection: keep-alive";
1477 hdr_len = 22;
1478 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
1479 hdr_val = "Proxy-Connection: keep-alive";
1480 hdr_len = 28;
1481 }
1482 http_header_add_tail2(msg, &txn->hdr_idx, hdr_val, hdr_len);
1483 }
1484 return;
1485 }
1486
1487 /* Parses a qvalue and returns it multipled by 1000, from 0 to 1000. If the
1488 * value is larger than 1000, it is bound to 1000. The parser consumes up to
1489 * 1 digit, one dot and 3 digits and stops on the first invalid character.
1490 * Unparsable qvalues return 1000 as "q=1.000".
1491 */
parse_qvalue(const char * qvalue,const char ** end)1492 int parse_qvalue(const char *qvalue, const char **end)
1493 {
1494 int q = 1000;
1495
1496 if (!isdigit((unsigned char)*qvalue))
1497 goto out;
1498 q = (*qvalue++ - '0') * 1000;
1499
1500 if (*qvalue++ != '.')
1501 goto out;
1502
1503 if (!isdigit((unsigned char)*qvalue))
1504 goto out;
1505 q += (*qvalue++ - '0') * 100;
1506
1507 if (!isdigit((unsigned char)*qvalue))
1508 goto out;
1509 q += (*qvalue++ - '0') * 10;
1510
1511 if (!isdigit((unsigned char)*qvalue))
1512 goto out;
1513 q += (*qvalue++ - '0') * 1;
1514 out:
1515 if (q > 1000)
1516 q = 1000;
1517 if (end)
1518 *end = qvalue;
1519 return q;
1520 }
1521
http_adjust_conn_mode(struct stream * s,struct http_txn * txn,struct http_msg * msg)1522 void http_adjust_conn_mode(struct stream *s, struct http_txn *txn, struct http_msg *msg)
1523 {
1524 struct proxy *fe = strm_fe(s);
1525 int tmp = TX_CON_WANT_KAL;
1526
1527 if (!((fe->options2|s->be->options2) & PR_O2_FAKE_KA)) {
1528 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN ||
1529 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
1530 tmp = TX_CON_WANT_TUN;
1531
1532 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||
1533 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL)
1534 tmp = TX_CON_WANT_TUN;
1535 }
1536
1537 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_SCL ||
1538 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_SCL) {
1539 /* option httpclose + server_close => forceclose */
1540 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||
1541 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL)
1542 tmp = TX_CON_WANT_CLO;
1543 else
1544 tmp = TX_CON_WANT_SCL;
1545 }
1546
1547 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_FCL ||
1548 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_FCL)
1549 tmp = TX_CON_WANT_CLO;
1550
1551 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
1552 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
1553
1554 if (!(txn->flags & TX_HDR_CONN_PRS) &&
1555 (txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN) {
1556 /* parse the Connection header and possibly clean it */
1557 int to_del = 0;
1558 if ((msg->flags & HTTP_MSGF_VER_11) ||
1559 ((txn->flags & TX_CON_WANT_MSK) >= TX_CON_WANT_SCL &&
1560 !((fe->options2|s->be->options2) & PR_O2_FAKE_KA)))
1561 to_del |= 2; /* remove "keep-alive" */
1562 if (!(msg->flags & HTTP_MSGF_VER_11))
1563 to_del |= 1; /* remove "close" */
1564 http_parse_connection_header(txn, msg, to_del);
1565 }
1566
1567 /* check if client or config asks for explicit close in KAL/SCL */
1568 if (((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL ||
1569 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) &&
1570 ((txn->flags & TX_HDR_CONN_CLO) || /* "connection: close" */
1571 (!(msg->flags & HTTP_MSGF_VER_11) && !(txn->flags & TX_HDR_CONN_KAL)) || /* no "connection: k-a" in 1.0 */
1572 !(msg->flags & HTTP_MSGF_XFER_LEN) || /* no length known => close */
1573 fe->state == PR_STSTOPPED)) /* frontend is stopping */
1574 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
1575 }
1576
1577 /* This stream analyser waits for a complete HTTP request. It returns 1 if the
1578 * processing can continue on next analysers, or zero if it either needs more
1579 * data or wants to immediately abort the request (eg: timeout, error, ...). It
1580 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
1581 * when it has nothing left to do, and may remove any analyser when it wants to
1582 * abort.
1583 */
http_wait_for_request(struct stream * s,struct channel * req,int an_bit)1584 int http_wait_for_request(struct stream *s, struct channel *req, int an_bit)
1585 {
1586 /*
1587 * We will parse the partial (or complete) lines.
1588 * We will check the request syntax, and also join multi-line
1589 * headers. An index of all the lines will be elaborated while
1590 * parsing.
1591 *
1592 * For the parsing, we use a 28 states FSM.
1593 *
1594 * Here is the information we currently have :
1595 * req->buf->p = beginning of request
1596 * req->buf->p + msg->eoh = end of processed headers / start of current one
1597 * req->buf->p + req->buf->i = end of input data
1598 * msg->eol = end of current header or line (LF or CRLF)
1599 * msg->next = first non-visited byte
1600 *
1601 * At end of parsing, we may perform a capture of the error (if any), and
1602 * we will set a few fields (txn->meth, sn->flags/SF_REDIRECTABLE).
1603 * We also check for monitor-uri, logging, HTTP/0.9 to 1.0 conversion, and
1604 * finally headers capture.
1605 */
1606
1607 int cur_idx;
1608 struct session *sess = s->sess;
1609 struct http_txn *txn = s->txn;
1610 struct http_msg *msg = &txn->req;
1611 struct hdr_ctx ctx;
1612
1613 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n",
1614 now_ms, __FUNCTION__,
1615 s,
1616 req,
1617 req->rex, req->wex,
1618 req->flags,
1619 req->buf->i,
1620 req->analysers);
1621
1622 /* we're speaking HTTP here, so let's speak HTTP to the client */
1623 s->srv_error = http_return_srv_error;
1624
1625 /* If there is data available for analysis, log the end of the idle time. */
1626 if (buffer_not_empty(req->buf) && s->logs.t_idle == -1)
1627 s->logs.t_idle = tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake;
1628
1629 /* There's a protected area at the end of the buffer for rewriting
1630 * purposes. We don't want to start to parse the request if the
1631 * protected area is affected, because we may have to move processed
1632 * data later, which is much more complicated.
1633 */
1634 if (buffer_not_empty(req->buf) && msg->msg_state < HTTP_MSG_ERROR) {
1635 if (txn->flags & TX_NOT_FIRST) {
1636 if (unlikely(!channel_is_rewritable(req) && req->buf->o)) {
1637 if (req->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_WRITE_ERROR|CF_WRITE_TIMEOUT))
1638 goto failed_keep_alive;
1639 /* some data has still not left the buffer, wake us once that's done */
1640 channel_dont_connect(req);
1641 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1642 req->flags |= CF_WAKE_WRITE;
1643 return 0;
1644 }
1645 if (unlikely(bi_end(req->buf) < b_ptr(req->buf, msg->next) ||
1646 bi_end(req->buf) > req->buf->data + req->buf->size - global.tune.maxrewrite))
1647 buffer_slow_realign(req->buf);
1648 }
1649
1650 if (likely(msg->next < req->buf->i)) /* some unparsed data are available */
1651 http_msg_analyzer(msg, &txn->hdr_idx);
1652 }
1653
1654 /* 1: we might have to print this header in debug mode */
1655 if (unlikely((global.mode & MODE_DEBUG) &&
1656 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) &&
1657 msg->msg_state >= HTTP_MSG_BODY)) {
1658 char *eol, *sol;
1659
1660 sol = req->buf->p;
1661 /* this is a bit complex : in case of error on the request line,
1662 * we know that rq.l is still zero, so we display only the part
1663 * up to the end of the line (truncated by debug_hdr).
1664 */
1665 eol = sol + (msg->sl.rq.l ? msg->sl.rq.l : req->buf->i);
1666 debug_hdr("clireq", s, sol, eol);
1667
1668 sol += hdr_idx_first_pos(&txn->hdr_idx);
1669 cur_idx = hdr_idx_first_idx(&txn->hdr_idx);
1670
1671 while (cur_idx) {
1672 eol = sol + txn->hdr_idx.v[cur_idx].len;
1673 debug_hdr("clihdr", s, sol, eol);
1674 sol = eol + txn->hdr_idx.v[cur_idx].cr + 1;
1675 cur_idx = txn->hdr_idx.v[cur_idx].next;
1676 }
1677 }
1678
1679
1680 /*
1681 * Now we quickly check if we have found a full valid request.
1682 * If not so, we check the FD and buffer states before leaving.
1683 * A full request is indicated by the fact that we have seen
1684 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1685 * requests are checked first. When waiting for a second request
1686 * on a keep-alive stream, if we encounter and error, close, t/o,
1687 * we note the error in the stream flags but don't set any state.
1688 * Since the error will be noted there, it will not be counted by
1689 * process_stream() as a frontend error.
1690 * Last, we may increase some tracked counters' http request errors on
1691 * the cases that are deliberately the client's fault. For instance,
1692 * a timeout or connection reset is not counted as an error. However
1693 * a bad request is.
1694 */
1695
1696 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
1697 /*
1698 * First, let's catch bad requests.
1699 */
1700 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1701 stream_inc_http_req_ctr(s);
1702 stream_inc_http_err_ctr(s);
1703 proxy_inc_fe_req_ctr(sess->fe);
1704 goto return_bad_req;
1705 }
1706
1707 /* 1: Since we are in header mode, if there's no space
1708 * left for headers, we won't be able to free more
1709 * later, so the stream will never terminate. We
1710 * must terminate it now.
1711 */
1712 if (unlikely(buffer_full(req->buf, global.tune.maxrewrite))) {
1713 /* FIXME: check if URI is set and return Status
1714 * 414 Request URI too long instead.
1715 */
1716 stream_inc_http_req_ctr(s);
1717 stream_inc_http_err_ctr(s);
1718 proxy_inc_fe_req_ctr(sess->fe);
1719 if (msg->err_pos < 0)
1720 msg->err_pos = req->buf->i;
1721 goto return_bad_req;
1722 }
1723
1724 /* 2: have we encountered a read error ? */
1725 else if (req->flags & CF_READ_ERROR) {
1726 if (!(s->flags & SF_ERR_MASK))
1727 s->flags |= SF_ERR_CLICL;
1728
1729 if (txn->flags & TX_WAIT_NEXT_RQ)
1730 goto failed_keep_alive;
1731
1732 if (sess->fe->options & PR_O_IGNORE_PRB)
1733 goto failed_keep_alive;
1734
1735 /* we cannot return any message on error */
1736 if (msg->err_pos >= 0) {
1737 http_capture_bad_message(sess->fe, &sess->fe->invalid_req, s, msg, msg->err_state, sess->fe);
1738 stream_inc_http_err_ctr(s);
1739 }
1740
1741 txn->status = 400;
1742 msg->err_state = msg->msg_state;
1743 msg->msg_state = HTTP_MSG_ERROR;
1744 http_reply_and_close(s, txn->status, NULL);
1745 req->analysers &= AN_REQ_FLT_END;
1746 stream_inc_http_req_ctr(s);
1747 proxy_inc_fe_req_ctr(sess->fe);
1748 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1749 if (sess->listener && sess->listener->counters)
1750 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1751
1752 if (!(s->flags & SF_FINST_MASK))
1753 s->flags |= SF_FINST_R;
1754 return 0;
1755 }
1756
1757 /* 3: has the read timeout expired ? */
1758 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
1759 if (!(s->flags & SF_ERR_MASK))
1760 s->flags |= SF_ERR_CLITO;
1761
1762 if (txn->flags & TX_WAIT_NEXT_RQ)
1763 goto failed_keep_alive;
1764
1765 if (sess->fe->options & PR_O_IGNORE_PRB)
1766 goto failed_keep_alive;
1767
1768 /* read timeout : give up with an error message. */
1769 if (msg->err_pos >= 0) {
1770 http_capture_bad_message(sess->fe, &sess->fe->invalid_req, s, msg, msg->err_state, sess->fe);
1771 stream_inc_http_err_ctr(s);
1772 }
1773 txn->status = 408;
1774 msg->err_state = msg->msg_state;
1775 msg->msg_state = HTTP_MSG_ERROR;
1776 http_reply_and_close(s, txn->status, http_error_message(s));
1777 req->analysers &= AN_REQ_FLT_END;
1778
1779 stream_inc_http_req_ctr(s);
1780 proxy_inc_fe_req_ctr(sess->fe);
1781 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1782 if (sess->listener && sess->listener->counters)
1783 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1784
1785 if (!(s->flags & SF_FINST_MASK))
1786 s->flags |= SF_FINST_R;
1787 return 0;
1788 }
1789
1790 /* 4: have we encountered a close ? */
1791 else if (req->flags & CF_SHUTR) {
1792 if (!(s->flags & SF_ERR_MASK))
1793 s->flags |= SF_ERR_CLICL;
1794
1795 if (txn->flags & TX_WAIT_NEXT_RQ)
1796 goto failed_keep_alive;
1797
1798 if (sess->fe->options & PR_O_IGNORE_PRB)
1799 goto failed_keep_alive;
1800
1801 if (msg->err_pos >= 0)
1802 http_capture_bad_message(sess->fe, &sess->fe->invalid_req, s, msg, msg->err_state, sess->fe);
1803 txn->status = 400;
1804 msg->err_state = msg->msg_state;
1805 msg->msg_state = HTTP_MSG_ERROR;
1806 http_reply_and_close(s, txn->status, http_error_message(s));
1807 req->analysers &= AN_REQ_FLT_END;
1808 stream_inc_http_err_ctr(s);
1809 stream_inc_http_req_ctr(s);
1810 proxy_inc_fe_req_ctr(sess->fe);
1811 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1812 if (sess->listener && sess->listener->counters)
1813 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1814
1815 if (!(s->flags & SF_FINST_MASK))
1816 s->flags |= SF_FINST_R;
1817 return 0;
1818 }
1819
1820 channel_dont_connect(req);
1821 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1822 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
1823 #ifdef TCP_QUICKACK
1824 if (sess->listener->options & LI_O_NOQUICKACK && req->buf->i &&
1825 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
1826 /* We need more data, we have to re-enable quick-ack in case we
1827 * previously disabled it, otherwise we might cause the client
1828 * to delay next data.
1829 */
1830 setsockopt(__objt_conn(sess->origin)->handle.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
1831 }
1832 #endif
1833
1834 if ((msg->msg_state != HTTP_MSG_RQBEFORE) && (txn->flags & TX_WAIT_NEXT_RQ)) {
1835 /* If the client starts to talk, let's fall back to
1836 * request timeout processing.
1837 */
1838 txn->flags &= ~TX_WAIT_NEXT_RQ;
1839 req->analyse_exp = TICK_ETERNITY;
1840 }
1841
1842 /* just set the request timeout once at the beginning of the request */
1843 if (!tick_isset(req->analyse_exp)) {
1844 if ((msg->msg_state == HTTP_MSG_RQBEFORE) &&
1845 (txn->flags & TX_WAIT_NEXT_RQ) &&
1846 tick_isset(s->be->timeout.httpka))
1847 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
1848 else
1849 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1850 }
1851
1852 /* we're not ready yet */
1853 return 0;
1854
1855 failed_keep_alive:
1856 /* Here we process low-level errors for keep-alive requests. In
1857 * short, if the request is not the first one and it experiences
1858 * a timeout, read error or shutdown, we just silently close so
1859 * that the client can try again.
1860 */
1861 txn->status = 0;
1862 msg->msg_state = HTTP_MSG_RQBEFORE;
1863 req->analysers &= AN_REQ_FLT_END;
1864 s->logs.logwait = 0;
1865 s->logs.level = 0;
1866 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
1867 http_reply_and_close(s, txn->status, NULL);
1868 return 0;
1869 }
1870
1871 /* OK now we have a complete HTTP request with indexed headers. Let's
1872 * complete the request parsing by setting a few fields we will need
1873 * later. At this point, we have the last CRLF at req->buf->data + msg->eoh.
1874 * If the request is in HTTP/0.9 form, the rule is still true, and eoh
1875 * points to the CRLF of the request line. msg->next points to the first
1876 * byte after the last LF. msg->sov points to the first byte of data.
1877 * msg->eol cannot be trusted because it may have been left uninitialized
1878 * (for instance in the absence of headers).
1879 */
1880
1881 stream_inc_http_req_ctr(s);
1882 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
1883
1884 if (txn->flags & TX_WAIT_NEXT_RQ) {
1885 /* kill the pending keep-alive timeout */
1886 txn->flags &= ~TX_WAIT_NEXT_RQ;
1887 req->analyse_exp = TICK_ETERNITY;
1888 }
1889
1890
1891 /* Maybe we found in invalid header name while we were configured not
1892 * to block on that, so we have to capture it now.
1893 */
1894 if (unlikely(msg->err_pos >= 0))
1895 http_capture_bad_message(sess->fe, &sess->fe->invalid_req, s, msg, msg->err_state, sess->fe);
1896
1897 /*
1898 * 1: identify the method
1899 */
1900 txn->meth = find_http_meth(req->buf->p, msg->sl.rq.m_l);
1901
1902 /* we can make use of server redirect on GET and HEAD */
1903 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
1904 s->flags |= SF_REDIRECTABLE;
1905 else if (txn->meth == HTTP_METH_OTHER &&
1906 msg->sl.rq.m_l == 3 && memcmp(req->buf->p, "PRI", 3) == 0) {
1907 /* PRI is reserved for the HTTP/2 preface */
1908 msg->err_pos = 0;
1909 goto return_bad_req;
1910 }
1911
1912 /*
1913 * 2: check if the URI matches the monitor_uri.
1914 * We have to do this for every request which gets in, because
1915 * the monitor-uri is defined by the frontend.
1916 */
1917 if (unlikely((sess->fe->monitor_uri_len != 0) &&
1918 (sess->fe->monitor_uri_len == msg->sl.rq.u_l) &&
1919 !memcmp(req->buf->p + msg->sl.rq.u,
1920 sess->fe->monitor_uri,
1921 sess->fe->monitor_uri_len))) {
1922 /*
1923 * We have found the monitor URI
1924 */
1925 struct acl_cond *cond;
1926
1927 s->flags |= SF_MONITOR;
1928 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
1929
1930 /* Check if we want to fail this monitor request or not */
1931 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
1932 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
1933
1934 ret = acl_pass(ret);
1935 if (cond->pol == ACL_COND_UNLESS)
1936 ret = !ret;
1937
1938 if (ret) {
1939 /* we fail this request, let's return 503 service unavail */
1940 txn->status = 503;
1941 http_reply_and_close(s, txn->status, http_error_message(s));
1942 if (!(s->flags & SF_ERR_MASK))
1943 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
1944 goto return_prx_cond;
1945 }
1946 }
1947
1948 /* nothing to fail, let's reply normaly */
1949 txn->status = 200;
1950 http_reply_and_close(s, txn->status, http_error_message(s));
1951 if (!(s->flags & SF_ERR_MASK))
1952 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
1953 goto return_prx_cond;
1954 }
1955
1956 /*
1957 * 3: Maybe we have to copy the original REQURI for the logs ?
1958 * Note: we cannot log anymore if the request has been
1959 * classified as invalid.
1960 */
1961 if (unlikely(s->logs.logwait & LW_REQ)) {
1962 /* we have a complete HTTP request that we must log */
1963 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
1964 int urilen = msg->sl.rq.l;
1965
1966 if (urilen >= global.tune.requri_len )
1967 urilen = global.tune.requri_len - 1;
1968 memcpy(txn->uri, req->buf->p, urilen);
1969 txn->uri[urilen] = 0;
1970
1971 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
1972 s->do_log(s);
1973 } else {
1974 ha_alert("HTTP logging : out of memory.\n");
1975 }
1976 }
1977
1978 /* RFC7230#2.6 has enforced the format of the HTTP version string to be
1979 * exactly one digit "." one digit. This check may be disabled using
1980 * option accept-invalid-http-request.
1981 */
1982 if (!(sess->fe->options2 & PR_O2_REQBUG_OK)) {
1983 if (msg->sl.rq.v_l != 8) {
1984 msg->err_pos = msg->sl.rq.v;
1985 goto return_bad_req;
1986 }
1987
1988 if (req->buf->p[msg->sl.rq.v + 4] != '/' ||
1989 !isdigit((unsigned char)req->buf->p[msg->sl.rq.v + 5]) ||
1990 req->buf->p[msg->sl.rq.v + 6] != '.' ||
1991 !isdigit((unsigned char)req->buf->p[msg->sl.rq.v + 7])) {
1992 msg->err_pos = msg->sl.rq.v + 4;
1993 goto return_bad_req;
1994 }
1995 }
1996 else {
1997 /* 4. We may have to convert HTTP/0.9 requests to HTTP/1.0 */
1998 if (unlikely(msg->sl.rq.v_l == 0) && !http_upgrade_v09_to_v10(txn))
1999 goto return_bad_req;
2000 }
2001
2002 /* ... and check if the request is HTTP/1.1 or above */
2003 if ((msg->sl.rq.v_l == 8) &&
2004 ((req->buf->p[msg->sl.rq.v + 5] > '1') ||
2005 ((req->buf->p[msg->sl.rq.v + 5] == '1') &&
2006 (req->buf->p[msg->sl.rq.v + 7] >= '1'))))
2007 msg->flags |= HTTP_MSGF_VER_11;
2008
2009 /* "connection" has not been parsed yet */
2010 txn->flags &= ~(TX_HDR_CONN_PRS | TX_HDR_CONN_CLO | TX_HDR_CONN_KAL | TX_HDR_CONN_UPG);
2011
2012 /* if the frontend has "option http-use-proxy-header", we'll check if
2013 * we have what looks like a proxied connection instead of a connection,
2014 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
2015 * Note that this is *not* RFC-compliant, however browsers and proxies
2016 * happen to do that despite being non-standard :-(
2017 * We consider that a request not beginning with either '/' or '*' is
2018 * a proxied connection, which covers both "scheme://location" and
2019 * CONNECT ip:port.
2020 */
2021 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
2022 req->buf->p[msg->sl.rq.u] != '/' && req->buf->p[msg->sl.rq.u] != '*')
2023 txn->flags |= TX_USE_PX_CONN;
2024
2025 /* transfer length unknown*/
2026 msg->flags &= ~HTTP_MSGF_XFER_LEN;
2027
2028 /* 5: we may need to capture headers */
2029 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
2030 capture_headers(req->buf->p, &txn->hdr_idx,
2031 s->req_cap, sess->fe->req_cap);
2032
2033 /* 6: determine the transfer-length according to RFC2616 #4.4, updated
2034 * by RFC7230#3.3.3 :
2035 *
2036 * The length of a message body is determined by one of the following
2037 * (in order of precedence):
2038 *
2039 * 1. Any response to a HEAD request and any response with a 1xx
2040 * (Informational), 204 (No Content), or 304 (Not Modified) status
2041 * code is always terminated by the first empty line after the
2042 * header fields, regardless of the header fields present in the
2043 * message, and thus cannot contain a message body.
2044 *
2045 * 2. Any 2xx (Successful) response to a CONNECT request implies that
2046 * the connection will become a tunnel immediately after the empty
2047 * line that concludes the header fields. A client MUST ignore any
2048 * Content-Length or Transfer-Encoding header fields received in
2049 * such a message.
2050 *
2051 * 3. If a Transfer-Encoding header field is present and the chunked
2052 * transfer coding (Section 4.1) is the final encoding, the message
2053 * body length is determined by reading and decoding the chunked
2054 * data until the transfer coding indicates the data is complete.
2055 *
2056 * If a Transfer-Encoding header field is present in a response and
2057 * the chunked transfer coding is not the final encoding, the
2058 * message body length is determined by reading the connection until
2059 * it is closed by the server. If a Transfer-Encoding header field
2060 * is present in a request and the chunked transfer coding is not
2061 * the final encoding, the message body length cannot be determined
2062 * reliably; the server MUST respond with the 400 (Bad Request)
2063 * status code and then close the connection.
2064 *
2065 * If a message is received with both a Transfer-Encoding and a
2066 * Content-Length header field, the Transfer-Encoding overrides the
2067 * Content-Length. Such a message might indicate an attempt to
2068 * perform request smuggling (Section 9.5) or response splitting
2069 * (Section 9.4) and ought to be handled as an error. A sender MUST
2070 * remove the received Content-Length field prior to forwarding such
2071 * a message downstream.
2072 *
2073 * 4. If a message is received without Transfer-Encoding and with
2074 * either multiple Content-Length header fields having differing
2075 * field-values or a single Content-Length header field having an
2076 * invalid value, then the message framing is invalid and the
2077 * recipient MUST treat it as an unrecoverable error. If this is a
2078 * request message, the server MUST respond with a 400 (Bad Request)
2079 * status code and then close the connection. If this is a response
2080 * message received by a proxy, the proxy MUST close the connection
2081 * to the server, discard the received response, and send a 502 (Bad
2082 * Gateway) response to the client. If this is a response message
2083 * received by a user agent, the user agent MUST close the
2084 * connection to the server and discard the received response.
2085 *
2086 * 5. If a valid Content-Length header field is present without
2087 * Transfer-Encoding, its decimal value defines the expected message
2088 * body length in octets. If the sender closes the connection or
2089 * the recipient times out before the indicated number of octets are
2090 * received, the recipient MUST consider the message to be
2091 * incomplete and close the connection.
2092 *
2093 * 6. If this is a request message and none of the above are true, then
2094 * the message body length is zero (no message body is present).
2095 *
2096 * 7. Otherwise, this is a response message without a declared message
2097 * body length, so the message body length is determined by the
2098 * number of octets received prior to the server closing the
2099 * connection.
2100 */
2101
2102 ctx.idx = 0;
2103 /* set TE_CHNK and XFER_LEN only if "chunked" is seen last */
2104 while (http_find_header2("Transfer-Encoding", 17, req->buf->p, &txn->hdr_idx, &ctx)) {
2105 if (ctx.vlen == 7 && strncasecmp(ctx.line + ctx.val, "chunked", 7) == 0)
2106 msg->flags |= HTTP_MSGF_TE_CHNK;
2107 else if (msg->flags & HTTP_MSGF_TE_CHNK) {
2108 /* chunked not last, return badreq */
2109 goto return_bad_req;
2110 }
2111 }
2112
2113 /* "chunked" mandatory if transfer-encoding is used */
2114 if (ctx.idx && !(msg->flags & HTTP_MSGF_TE_CHNK))
2115 goto return_bad_req;
2116
2117 /* Chunked requests must have their content-length removed */
2118 ctx.idx = 0;
2119 if (msg->flags & HTTP_MSGF_TE_CHNK) {
2120 while (http_find_header2("Content-Length", 14, req->buf->p, &txn->hdr_idx, &ctx))
2121 http_remove_header2(msg, &txn->hdr_idx, &ctx);
2122 }
2123 else while (http_find_header2("Content-Length", 14, req->buf->p, &txn->hdr_idx, &ctx)) {
2124 signed long long cl;
2125
2126 if (!ctx.vlen) {
2127 msg->err_pos = ctx.line + ctx.val - req->buf->p;
2128 goto return_bad_req;
2129 }
2130
2131 if (strl2llrc(ctx.line + ctx.val, ctx.vlen, &cl)) {
2132 msg->err_pos = ctx.line + ctx.val - req->buf->p;
2133 goto return_bad_req; /* parse failure */
2134 }
2135
2136 if (cl < 0) {
2137 msg->err_pos = ctx.line + ctx.val - req->buf->p;
2138 goto return_bad_req;
2139 }
2140
2141 if ((msg->flags & HTTP_MSGF_CNT_LEN) && (msg->chunk_len != cl)) {
2142 msg->err_pos = ctx.line + ctx.val - req->buf->p;
2143 goto return_bad_req; /* already specified, was different */
2144 }
2145
2146 msg->flags |= HTTP_MSGF_CNT_LEN;
2147 msg->body_len = msg->chunk_len = cl;
2148 }
2149
2150 /* even bodyless requests have a known length */
2151 msg->flags |= HTTP_MSGF_XFER_LEN;
2152
2153 /* Until set to anything else, the connection mode is set as Keep-Alive. It will
2154 * only change if both the request and the config reference something else.
2155 * Option httpclose by itself sets tunnel mode where headers are mangled.
2156 * However, if another mode is set, it will affect it (eg: server-close/
2157 * keep-alive + httpclose = close). Note that we avoid to redo the same work
2158 * if FE and BE have the same settings (common). The method consists in
2159 * checking if options changed between the two calls (implying that either
2160 * one is non-null, or one of them is non-null and we are there for the first
2161 * time.
2162 */
2163 if (!(txn->flags & TX_HDR_CONN_PRS) ||
2164 ((sess->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE)))
2165 http_adjust_conn_mode(s, txn, msg);
2166
2167 /* we may have to wait for the request's body */
2168 if ((s->be->options & PR_O_WREQ_BODY) &&
2169 (msg->body_len || (msg->flags & HTTP_MSGF_TE_CHNK)))
2170 req->analysers |= AN_REQ_HTTP_BODY;
2171
2172 /*
2173 * RFC7234#4:
2174 * A cache MUST write through requests with methods
2175 * that are unsafe (Section 4.2.1 of [RFC7231]) to
2176 * the origin server; i.e., a cache is not allowed
2177 * to generate a reply to such a request before
2178 * having forwarded the request and having received
2179 * a corresponding response.
2180 *
2181 * RFC7231#4.2.1:
2182 * Of the request methods defined by this
2183 * specification, the GET, HEAD, OPTIONS, and TRACE
2184 * methods are defined to be safe.
2185 */
2186 if (likely(txn->meth == HTTP_METH_GET ||
2187 txn->meth == HTTP_METH_HEAD ||
2188 txn->meth == HTTP_METH_OPTIONS ||
2189 txn->meth == HTTP_METH_TRACE))
2190 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
2191
2192 /* end of job, return OK */
2193 req->analysers &= ~an_bit;
2194 req->analyse_exp = TICK_ETERNITY;
2195 return 1;
2196
2197 return_bad_req:
2198 /* We centralize bad requests processing here */
2199 if (unlikely(msg->msg_state == HTTP_MSG_ERROR) || msg->err_pos >= 0) {
2200 /* we detected a parsing error. We want to archive this request
2201 * in the dedicated proxy area for later troubleshooting.
2202 */
2203 http_capture_bad_message(sess->fe, &sess->fe->invalid_req, s, msg, msg->err_state, sess->fe);
2204 }
2205
2206 txn->req.err_state = txn->req.msg_state;
2207 txn->req.msg_state = HTTP_MSG_ERROR;
2208 txn->status = 400;
2209 http_reply_and_close(s, txn->status, http_error_message(s));
2210
2211 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
2212 if (sess->listener && sess->listener->counters)
2213 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
2214
2215 return_prx_cond:
2216 if (!(s->flags & SF_ERR_MASK))
2217 s->flags |= SF_ERR_PRXCOND;
2218 if (!(s->flags & SF_FINST_MASK))
2219 s->flags |= SF_FINST_R;
2220
2221 req->analysers &= AN_REQ_FLT_END;
2222 req->analyse_exp = TICK_ETERNITY;
2223 return 0;
2224 }
2225
2226
2227 /* This function prepares an applet to handle the stats. It can deal with the
2228 * "100-continue" expectation, check that admin rules are met for POST requests,
2229 * and program a response message if something was unexpected. It cannot fail
2230 * and always relies on the stats applet to complete the job. It does not touch
2231 * analysers nor counters, which are left to the caller. It does not touch
2232 * s->target which is supposed to already point to the stats applet. The caller
2233 * is expected to have already assigned an appctx to the stream.
2234 */
http_handle_stats(struct stream * s,struct channel * req)2235 int http_handle_stats(struct stream *s, struct channel *req)
2236 {
2237 struct stats_admin_rule *stats_admin_rule;
2238 struct stream_interface *si = &s->si[1];
2239 struct session *sess = s->sess;
2240 struct http_txn *txn = s->txn;
2241 struct http_msg *msg = &txn->req;
2242 struct uri_auth *uri_auth = s->be->uri_auth;
2243 const char *uri, *h, *lookup;
2244 struct appctx *appctx;
2245
2246 appctx = si_appctx(si);
2247 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
2248 appctx->st1 = appctx->st2 = 0;
2249 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
2250 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
2251 if ((msg->flags & HTTP_MSGF_VER_11) && (s->txn->meth != HTTP_METH_HEAD))
2252 appctx->ctx.stats.flags |= STAT_CHUNKED;
2253
2254 uri = msg->chn->buf->p + msg->sl.rq.u;
2255 lookup = uri + uri_auth->uri_len;
2256
2257 for (h = lookup; h <= uri + msg->sl.rq.u_l - 3; h++) {
2258 if (memcmp(h, ";up", 3) == 0) {
2259 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
2260 break;
2261 }
2262 }
2263
2264 if (uri_auth->refresh) {
2265 for (h = lookup; h <= uri + msg->sl.rq.u_l - 10; h++) {
2266 if (memcmp(h, ";norefresh", 10) == 0) {
2267 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
2268 break;
2269 }
2270 }
2271 }
2272
2273 for (h = lookup; h <= uri + msg->sl.rq.u_l - 4; h++) {
2274 if (memcmp(h, ";csv", 4) == 0) {
2275 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
2276 break;
2277 }
2278 }
2279
2280 for (h = lookup; h <= uri + msg->sl.rq.u_l - 6; h++) {
2281 if (memcmp(h, ";typed", 6) == 0) {
2282 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
2283 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
2284 break;
2285 }
2286 }
2287
2288 for (h = lookup; h <= uri + msg->sl.rq.u_l - 8; h++) {
2289 if (memcmp(h, ";st=", 4) == 0) {
2290 int i;
2291 h += 4;
2292 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
2293 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
2294 if (strncmp(stat_status_codes[i], h, 4) == 0) {
2295 appctx->ctx.stats.st_code = i;
2296 break;
2297 }
2298 }
2299 break;
2300 }
2301 }
2302
2303 appctx->ctx.stats.scope_str = 0;
2304 appctx->ctx.stats.scope_len = 0;
2305 for (h = lookup; h <= uri + msg->sl.rq.u_l - 8; h++) {
2306 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
2307 int itx = 0;
2308 const char *h2;
2309 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
2310 const char *err;
2311
2312 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
2313 h2 = h;
2314 appctx->ctx.stats.scope_str = h2 - msg->chn->buf->p;
2315 while (*h != ';' && *h != '\0' && *h != '&' && *h != ' ' && *h != '\n') {
2316 itx++;
2317 h++;
2318 }
2319
2320 if (itx > STAT_SCOPE_TXT_MAXLEN)
2321 itx = STAT_SCOPE_TXT_MAXLEN;
2322 appctx->ctx.stats.scope_len = itx;
2323
2324 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
2325 memcpy(scope_txt, h2, itx);
2326 scope_txt[itx] = '\0';
2327 err = invalid_char(scope_txt);
2328 if (err) {
2329 /* bad char in search text => clear scope */
2330 appctx->ctx.stats.scope_str = 0;
2331 appctx->ctx.stats.scope_len = 0;
2332 }
2333 break;
2334 }
2335 }
2336
2337 /* now check whether we have some admin rules for this request */
2338 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
2339 int ret = 1;
2340
2341 if (stats_admin_rule->cond) {
2342 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2343 ret = acl_pass(ret);
2344 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
2345 ret = !ret;
2346 }
2347
2348 if (ret) {
2349 /* no rule, or the rule matches */
2350 appctx->ctx.stats.flags |= STAT_ADMIN;
2351 break;
2352 }
2353 }
2354
2355 /* Was the status page requested with a POST ? */
2356 if (unlikely(txn->meth == HTTP_METH_POST && txn->req.body_len > 0)) {
2357 if (appctx->ctx.stats.flags & STAT_ADMIN) {
2358 /* we'll need the request body, possibly after sending 100-continue */
2359 if (msg->msg_state < HTTP_MSG_CHUNK_SIZE)
2360 req->analysers |= AN_REQ_HTTP_BODY;
2361 appctx->st0 = STAT_HTTP_POST;
2362 }
2363 else {
2364 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
2365 appctx->st0 = STAT_HTTP_LAST;
2366 }
2367 }
2368 else {
2369 /* So it was another method (GET/HEAD) */
2370 appctx->st0 = STAT_HTTP_HEAD;
2371 }
2372
2373 s->task->nice = -32; /* small boost for HTTP statistics */
2374 return 1;
2375 }
2376
2377 /* Sets the TOS header in IPv4 and the traffic class header in IPv6 packets
2378 * (as per RFC3260 #4 and BCP37 #4.2 and #5.2).
2379 */
inet_set_tos(int fd,const struct sockaddr_storage * from,int tos)2380 void inet_set_tos(int fd, const struct sockaddr_storage *from, int tos)
2381 {
2382 #ifdef IP_TOS
2383 if (from->ss_family == AF_INET)
2384 setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
2385 #endif
2386 #ifdef IPV6_TCLASS
2387 if (from->ss_family == AF_INET6) {
2388 if (IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)from)->sin6_addr))
2389 /* v4-mapped addresses need IP_TOS */
2390 setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
2391 else
2392 setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos));
2393 }
2394 #endif
2395 }
2396
http_transform_header_str(struct stream * s,struct http_msg * msg,const char * name,unsigned int name_len,const char * str,struct my_regex * re,int action)2397 int http_transform_header_str(struct stream* s, struct http_msg *msg,
2398 const char* name, unsigned int name_len,
2399 const char *str, struct my_regex *re,
2400 int action)
2401 {
2402 struct hdr_ctx ctx;
2403 char *buf = msg->chn->buf->p;
2404 struct hdr_idx *idx = &s->txn->hdr_idx;
2405 int (*http_find_hdr_func)(const char *name, int len, char *sol,
2406 struct hdr_idx *idx, struct hdr_ctx *ctx);
2407 struct chunk *output = get_trash_chunk();
2408
2409 ctx.idx = 0;
2410
2411 /* Choose the header browsing function. */
2412 switch (action) {
2413 case ACT_HTTP_REPLACE_VAL:
2414 http_find_hdr_func = http_find_header2;
2415 break;
2416 case ACT_HTTP_REPLACE_HDR:
2417 http_find_hdr_func = http_find_full_header2;
2418 break;
2419 default: /* impossible */
2420 return -1;
2421 }
2422
2423 while (http_find_hdr_func(name, name_len, buf, idx, &ctx)) {
2424 struct hdr_idx_elem *hdr = idx->v + ctx.idx;
2425 int delta;
2426 char *val = ctx.line + ctx.val;
2427 char* val_end = val + ctx.vlen;
2428
2429 if (!regex_exec_match2(re, val, val_end-val, MAX_MATCH, pmatch, 0))
2430 continue;
2431
2432 output->len = exp_replace(output->str, output->size, val, str, pmatch);
2433 if (output->len == -1)
2434 return -1;
2435
2436 delta = buffer_replace2(msg->chn->buf, val, val_end, output->str, output->len);
2437
2438 hdr->len += delta;
2439 http_msg_move_end(msg, delta);
2440
2441 /* Adjust the length of the current value of the index. */
2442 ctx.vlen += delta;
2443 }
2444
2445 return 0;
2446 }
2447
http_transform_header(struct stream * s,struct http_msg * msg,const char * name,unsigned int name_len,struct list * fmt,struct my_regex * re,int action)2448 static int http_transform_header(struct stream* s, struct http_msg *msg,
2449 const char* name, unsigned int name_len,
2450 struct list *fmt, struct my_regex *re,
2451 int action)
2452 {
2453 struct chunk *replace;
2454 int ret = -1;
2455
2456 replace = alloc_trash_chunk();
2457 if (!replace)
2458 goto leave;
2459
2460 replace->len = build_logline(s, replace->str, replace->size, fmt);
2461 if (replace->len >= replace->size - 1)
2462 goto leave;
2463
2464 ret = http_transform_header_str(s, msg, name, name_len, replace->str, re, action);
2465
2466 leave:
2467 free_trash_chunk(replace);
2468 return ret;
2469 }
2470
2471 /* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2472 * transaction <txn>. Returns the verdict of the first rule that prevents
2473 * further processing of the request (auth, deny, ...), and defaults to
2474 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2475 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2476 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2477 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2478 * status.
2479 */
2480 enum rule_result
http_req_get_intercept_rule(struct proxy * px,struct list * rules,struct stream * s,int * deny_status)2481 http_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s, int *deny_status)
2482 {
2483 struct session *sess = strm_sess(s);
2484 struct http_txn *txn = s->txn;
2485 struct connection *cli_conn;
2486 struct act_rule *rule;
2487 struct hdr_ctx ctx;
2488 const char *auth_realm;
2489 int act_flags = 0;
2490 int len;
2491
2492 /* If "the current_rule_list" match the executed rule list, we are in
2493 * resume condition. If a resume is needed it is always in the action
2494 * and never in the ACL or converters. In this case, we initialise the
2495 * current rule, and go to the action execution point.
2496 */
2497 if (s->current_rule) {
2498 rule = s->current_rule;
2499 s->current_rule = NULL;
2500 if (s->current_rule_list == rules)
2501 goto resume_execution;
2502 }
2503 s->current_rule_list = rules;
2504
2505 list_for_each_entry(rule, rules, list) {
2506
2507 /* check optional condition */
2508 if (rule->cond) {
2509 int ret;
2510
2511 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2512 ret = acl_pass(ret);
2513
2514 if (rule->cond->pol == ACL_COND_UNLESS)
2515 ret = !ret;
2516
2517 if (!ret) /* condition not matched */
2518 continue;
2519 }
2520
2521 act_flags |= ACT_FLAG_FIRST;
2522 resume_execution:
2523 switch (rule->action) {
2524 case ACT_ACTION_ALLOW:
2525 return HTTP_RULE_RES_STOP;
2526
2527 case ACT_ACTION_DENY:
2528 if (deny_status)
2529 *deny_status = rule->deny_status;
2530 return HTTP_RULE_RES_DENY;
2531
2532 case ACT_HTTP_REQ_TARPIT:
2533 txn->flags |= TX_CLTARPIT;
2534 if (deny_status)
2535 *deny_status = rule->deny_status;
2536 return HTTP_RULE_RES_DENY;
2537
2538 case ACT_HTTP_REQ_AUTH:
2539 /* Auth might be performed on regular http-req rules as well as on stats */
2540 auth_realm = rule->arg.auth.realm;
2541 if (!auth_realm) {
2542 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2543 auth_realm = STATS_DEFAULT_REALM;
2544 else
2545 auth_realm = px->id;
2546 }
2547 /* send 401/407 depending on whether we use a proxy or not. We still
2548 * count one error, because normal browsing won't significantly
2549 * increase the counter but brute force attempts will.
2550 */
2551 chunk_printf(&trash, (txn->flags & TX_USE_PX_CONN) ? HTTP_407_fmt : HTTP_401_fmt, auth_realm);
2552 txn->status = (txn->flags & TX_USE_PX_CONN) ? 407 : 401;
2553 http_reply_and_close(s, txn->status, &trash);
2554 stream_inc_http_err_ctr(s);
2555 return HTTP_RULE_RES_ABRT;
2556
2557 case ACT_HTTP_REDIR:
2558 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
2559 return HTTP_RULE_RES_BADREQ;
2560 return HTTP_RULE_RES_DONE;
2561
2562 case ACT_HTTP_SET_NICE:
2563 s->task->nice = rule->arg.nice;
2564 break;
2565
2566 case ACT_HTTP_SET_TOS:
2567 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2568 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
2569 break;
2570
2571 case ACT_HTTP_SET_MARK:
2572 #ifdef SO_MARK
2573 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2574 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
2575 #endif
2576 break;
2577
2578 case ACT_HTTP_SET_LOGL:
2579 s->logs.level = rule->arg.loglevel;
2580 break;
2581
2582 case ACT_HTTP_REPLACE_HDR:
2583 case ACT_HTTP_REPLACE_VAL:
2584 if (http_transform_header(s, &txn->req, rule->arg.hdr_add.name,
2585 rule->arg.hdr_add.name_len,
2586 &rule->arg.hdr_add.fmt,
2587 &rule->arg.hdr_add.re, rule->action))
2588 return HTTP_RULE_RES_BADREQ;
2589 break;
2590
2591 case ACT_HTTP_DEL_HDR:
2592 ctx.idx = 0;
2593 /* remove all occurrences of the header */
2594 while (http_find_header2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len,
2595 txn->req.chn->buf->p, &txn->hdr_idx, &ctx)) {
2596 http_remove_header2(&txn->req, &txn->hdr_idx, &ctx);
2597 }
2598 break;
2599
2600 case ACT_HTTP_SET_HDR:
2601 case ACT_HTTP_ADD_HDR: {
2602 /* The scope of the trash buffer must be limited to this function. The
2603 * build_logline() function can execute a lot of other function which
2604 * can use the trash buffer. So for limiting the scope of this global
2605 * buffer, we build first the header value using build_logline, and
2606 * after we store the header name.
2607 */
2608 struct chunk *replace;
2609
2610 replace = alloc_trash_chunk();
2611 if (!replace)
2612 return HTTP_RULE_RES_BADREQ;
2613
2614 len = rule->arg.hdr_add.name_len + 2,
2615 len += build_logline(s, replace->str + len, replace->size - len, &rule->arg.hdr_add.fmt);
2616 memcpy(replace->str, rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2617 replace->str[rule->arg.hdr_add.name_len] = ':';
2618 replace->str[rule->arg.hdr_add.name_len + 1] = ' ';
2619 replace->len = len;
2620
2621 if (rule->action == ACT_HTTP_SET_HDR) {
2622 /* remove all occurrences of the header */
2623 ctx.idx = 0;
2624 while (http_find_header2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len,
2625 txn->req.chn->buf->p, &txn->hdr_idx, &ctx)) {
2626 http_remove_header2(&txn->req, &txn->hdr_idx, &ctx);
2627 }
2628 }
2629
2630 http_header_add_tail2(&txn->req, &txn->hdr_idx, replace->str, replace->len);
2631
2632 free_trash_chunk(replace);
2633 break;
2634 }
2635
2636 case ACT_HTTP_DEL_ACL:
2637 case ACT_HTTP_DEL_MAP: {
2638 struct pat_ref *ref;
2639 struct chunk *key;
2640
2641 /* collect reference */
2642 ref = pat_ref_lookup(rule->arg.map.ref);
2643 if (!ref)
2644 continue;
2645
2646 /* allocate key */
2647 key = alloc_trash_chunk();
2648 if (!key)
2649 return HTTP_RULE_RES_BADREQ;
2650
2651 /* collect key */
2652 key->len = build_logline(s, key->str, key->size, &rule->arg.map.key);
2653 key->str[key->len] = '\0';
2654
2655 /* perform update */
2656 /* returned code: 1=ok, 0=ko */
2657 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2658 pat_ref_delete(ref, key->str);
2659 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2660
2661 free_trash_chunk(key);
2662 break;
2663 }
2664
2665 case ACT_HTTP_ADD_ACL: {
2666 struct pat_ref *ref;
2667 struct chunk *key;
2668
2669 /* collect reference */
2670 ref = pat_ref_lookup(rule->arg.map.ref);
2671 if (!ref)
2672 continue;
2673
2674 /* allocate key */
2675 key = alloc_trash_chunk();
2676 if (!key)
2677 return HTTP_RULE_RES_BADREQ;
2678
2679 /* collect key */
2680 key->len = build_logline(s, key->str, key->size, &rule->arg.map.key);
2681 key->str[key->len] = '\0';
2682
2683 /* perform update */
2684 /* add entry only if it does not already exist */
2685 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2686 if (pat_ref_find_elt(ref, key->str) == NULL)
2687 pat_ref_add(ref, key->str, NULL, NULL);
2688 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2689
2690 free_trash_chunk(key);
2691 break;
2692 }
2693
2694 case ACT_HTTP_SET_MAP: {
2695 struct pat_ref *ref;
2696 struct chunk *key, *value;
2697
2698 /* collect reference */
2699 ref = pat_ref_lookup(rule->arg.map.ref);
2700 if (!ref)
2701 continue;
2702
2703 /* allocate key */
2704 key = alloc_trash_chunk();
2705 if (!key)
2706 return HTTP_RULE_RES_BADREQ;
2707
2708 /* allocate value */
2709 value = alloc_trash_chunk();
2710 if (!value) {
2711 free_trash_chunk(key);
2712 return HTTP_RULE_RES_BADREQ;
2713 }
2714
2715 /* collect key */
2716 key->len = build_logline(s, key->str, key->size, &rule->arg.map.key);
2717 key->str[key->len] = '\0';
2718
2719 /* collect value */
2720 value->len = build_logline(s, value->str, value->size, &rule->arg.map.value);
2721 value->str[value->len] = '\0';
2722
2723 /* perform update */
2724 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2725 if (pat_ref_find_elt(ref, key->str) != NULL)
2726 /* update entry if it exists */
2727 pat_ref_set(ref, key->str, value->str, NULL);
2728 else
2729 /* insert a new entry */
2730 pat_ref_add(ref, key->str, value->str, NULL);
2731 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2732
2733 free_trash_chunk(key);
2734 free_trash_chunk(value);
2735 break;
2736 }
2737
2738 case ACT_CUSTOM:
2739 if ((s->req.flags & CF_READ_ERROR) ||
2740 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
2741 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
2742 (px->options & PR_O_ABRT_CLOSE)))
2743 act_flags |= ACT_FLAG_FINAL;
2744
2745 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
2746 case ACT_RET_ERR:
2747 case ACT_RET_CONT:
2748 break;
2749 case ACT_RET_STOP:
2750 return HTTP_RULE_RES_DONE;
2751 case ACT_RET_YIELD:
2752 s->current_rule = rule;
2753 return HTTP_RULE_RES_YIELD;
2754 }
2755 break;
2756
2757 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
2758 /* Note: only the first valid tracking parameter of each
2759 * applies.
2760 */
2761
2762 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
2763 struct stktable *t;
2764 struct stksess *ts;
2765 struct stktable_key *key;
2766 void *ptr1, *ptr2;
2767
2768 t = rule->arg.trk_ctr.table.t;
2769 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL, rule->arg.trk_ctr.expr, NULL);
2770
2771 if (key && (ts = stktable_get_entry(t, key))) {
2772 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
2773
2774 /* let's count a new HTTP request as it's the first time we do it */
2775 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
2776 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
2777 if (ptr1 || ptr2) {
2778 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
2779
2780 if (ptr1)
2781 stktable_data_cast(ptr1, http_req_cnt)++;
2782
2783 if (ptr2)
2784 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
2785 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
2786
2787 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
2788
2789 /* If data was modified, we need to touch to re-schedule sync */
2790 stktable_touch_local(t, ts, 0);
2791 }
2792
2793 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
2794 if (sess->fe != s->be)
2795 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
2796 }
2797 }
2798 break;
2799
2800 /* other flags exists, but normaly, they never be matched. */
2801 default:
2802 break;
2803 }
2804 }
2805
2806 /* we reached the end of the rules, nothing to report */
2807 return HTTP_RULE_RES_CONT;
2808 }
2809
2810
2811 /* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
2812 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
2813 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
2814 * is returned, the process can continue the evaluation of next rule list. If
2815 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
2816 * is returned, it means the operation could not be processed and a server error
2817 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
2818 * deny rule. If *YIELD is returned, the caller must call again the function
2819 * with the same context.
2820 */
2821 static enum rule_result
http_res_get_intercept_rule(struct proxy * px,struct list * rules,struct stream * s)2822 http_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s)
2823 {
2824 struct session *sess = strm_sess(s);
2825 struct http_txn *txn = s->txn;
2826 struct connection *cli_conn;
2827 struct act_rule *rule;
2828 struct hdr_ctx ctx;
2829 int act_flags = 0;
2830
2831 /* If "the current_rule_list" match the executed rule list, we are in
2832 * resume condition. If a resume is needed it is always in the action
2833 * and never in the ACL or converters. In this case, we initialise the
2834 * current rule, and go to the action execution point.
2835 */
2836 if (s->current_rule) {
2837 rule = s->current_rule;
2838 s->current_rule = NULL;
2839 if (s->current_rule_list == rules)
2840 goto resume_execution;
2841 }
2842 s->current_rule_list = rules;
2843
2844 list_for_each_entry(rule, rules, list) {
2845
2846 /* check optional condition */
2847 if (rule->cond) {
2848 int ret;
2849
2850 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
2851 ret = acl_pass(ret);
2852
2853 if (rule->cond->pol == ACL_COND_UNLESS)
2854 ret = !ret;
2855
2856 if (!ret) /* condition not matched */
2857 continue;
2858 }
2859
2860 act_flags |= ACT_FLAG_FIRST;
2861 resume_execution:
2862 switch (rule->action) {
2863 case ACT_ACTION_ALLOW:
2864 return HTTP_RULE_RES_STOP; /* "allow" rules are OK */
2865
2866 case ACT_ACTION_DENY:
2867 txn->flags |= TX_SVDENY;
2868 return HTTP_RULE_RES_STOP;
2869
2870 case ACT_HTTP_SET_NICE:
2871 s->task->nice = rule->arg.nice;
2872 break;
2873
2874 case ACT_HTTP_SET_TOS:
2875 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2876 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
2877 break;
2878
2879 case ACT_HTTP_SET_MARK:
2880 #ifdef SO_MARK
2881 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2882 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
2883 #endif
2884 break;
2885
2886 case ACT_HTTP_SET_LOGL:
2887 s->logs.level = rule->arg.loglevel;
2888 break;
2889
2890 case ACT_HTTP_REPLACE_HDR:
2891 case ACT_HTTP_REPLACE_VAL:
2892 if (http_transform_header(s, &txn->rsp, rule->arg.hdr_add.name,
2893 rule->arg.hdr_add.name_len,
2894 &rule->arg.hdr_add.fmt,
2895 &rule->arg.hdr_add.re, rule->action))
2896 return HTTP_RULE_RES_BADREQ;
2897 break;
2898
2899 case ACT_HTTP_DEL_HDR:
2900 ctx.idx = 0;
2901 /* remove all occurrences of the header */
2902 while (http_find_header2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len,
2903 txn->rsp.chn->buf->p, &txn->hdr_idx, &ctx)) {
2904 http_remove_header2(&txn->rsp, &txn->hdr_idx, &ctx);
2905 }
2906 break;
2907
2908 case ACT_HTTP_SET_HDR:
2909 case ACT_HTTP_ADD_HDR: {
2910 struct chunk *replace;
2911
2912 replace = alloc_trash_chunk();
2913 if (!replace)
2914 return HTTP_RULE_RES_BADREQ;
2915
2916 chunk_printf(replace, "%s: ", rule->arg.hdr_add.name);
2917 memcpy(replace->str, rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2918 replace->len = rule->arg.hdr_add.name_len;
2919 replace->str[replace->len++] = ':';
2920 replace->str[replace->len++] = ' ';
2921 replace->len += build_logline(s, replace->str + replace->len, replace->size - replace->len,
2922 &rule->arg.hdr_add.fmt);
2923
2924 if (rule->action == ACT_HTTP_SET_HDR) {
2925 /* remove all occurrences of the header */
2926 ctx.idx = 0;
2927 while (http_find_header2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len,
2928 txn->rsp.chn->buf->p, &txn->hdr_idx, &ctx)) {
2929 http_remove_header2(&txn->rsp, &txn->hdr_idx, &ctx);
2930 }
2931 }
2932 http_header_add_tail2(&txn->rsp, &txn->hdr_idx, replace->str, replace->len);
2933
2934 free_trash_chunk(replace);
2935 break;
2936 }
2937
2938 case ACT_HTTP_DEL_ACL:
2939 case ACT_HTTP_DEL_MAP: {
2940 struct pat_ref *ref;
2941 struct chunk *key;
2942
2943 /* collect reference */
2944 ref = pat_ref_lookup(rule->arg.map.ref);
2945 if (!ref)
2946 continue;
2947
2948 /* allocate key */
2949 key = alloc_trash_chunk();
2950 if (!key)
2951 return HTTP_RULE_RES_BADREQ;
2952
2953 /* collect key */
2954 key->len = build_logline(s, key->str, key->size, &rule->arg.map.key);
2955 key->str[key->len] = '\0';
2956
2957 /* perform update */
2958 /* returned code: 1=ok, 0=ko */
2959 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2960 pat_ref_delete(ref, key->str);
2961 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2962
2963 free_trash_chunk(key);
2964 break;
2965 }
2966
2967 case ACT_HTTP_ADD_ACL: {
2968 struct pat_ref *ref;
2969 struct chunk *key;
2970
2971 /* collect reference */
2972 ref = pat_ref_lookup(rule->arg.map.ref);
2973 if (!ref)
2974 continue;
2975
2976 /* allocate key */
2977 key = alloc_trash_chunk();
2978 if (!key)
2979 return HTTP_RULE_RES_BADREQ;
2980
2981 /* collect key */
2982 key->len = build_logline(s, key->str, key->size, &rule->arg.map.key);
2983 key->str[key->len] = '\0';
2984
2985 /* perform update */
2986 /* check if the entry already exists */
2987 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2988 if (pat_ref_find_elt(ref, key->str) == NULL)
2989 pat_ref_add(ref, key->str, NULL, NULL);
2990 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2991
2992 free_trash_chunk(key);
2993 break;
2994 }
2995
2996 case ACT_HTTP_SET_MAP: {
2997 struct pat_ref *ref;
2998 struct chunk *key, *value;
2999
3000 /* collect reference */
3001 ref = pat_ref_lookup(rule->arg.map.ref);
3002 if (!ref)
3003 continue;
3004
3005 /* allocate key */
3006 key = alloc_trash_chunk();
3007 if (!key)
3008 return HTTP_RULE_RES_BADREQ;
3009
3010 /* allocate value */
3011 value = alloc_trash_chunk();
3012 if (!value) {
3013 free_trash_chunk(key);
3014 return HTTP_RULE_RES_BADREQ;
3015 }
3016
3017 /* collect key */
3018 key->len = build_logline(s, key->str, key->size, &rule->arg.map.key);
3019 key->str[key->len] = '\0';
3020
3021 /* collect value */
3022 value->len = build_logline(s, value->str, value->size, &rule->arg.map.value);
3023 value->str[value->len] = '\0';
3024
3025 /* perform update */
3026 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3027 if (pat_ref_find_elt(ref, key->str) != NULL)
3028 /* update entry if it exists */
3029 pat_ref_set(ref, key->str, value->str, NULL);
3030 else
3031 /* insert a new entry */
3032 pat_ref_add(ref, key->str, value->str, NULL);
3033 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3034 free_trash_chunk(key);
3035 free_trash_chunk(value);
3036 break;
3037 }
3038
3039 case ACT_HTTP_REDIR:
3040 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3041 return HTTP_RULE_RES_BADREQ;
3042 return HTTP_RULE_RES_DONE;
3043
3044 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3045 /* Note: only the first valid tracking parameter of each
3046 * applies.
3047 */
3048
3049 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3050 struct stktable *t;
3051 struct stksess *ts;
3052 struct stktable_key *key;
3053 void *ptr;
3054
3055 t = rule->arg.trk_ctr.table.t;
3056 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL, rule->arg.trk_ctr.expr, NULL);
3057
3058 if (key && (ts = stktable_get_entry(t, key))) {
3059 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3060
3061 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3062
3063 /* let's count a new HTTP request as it's the first time we do it */
3064 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3065 if (ptr)
3066 stktable_data_cast(ptr, http_req_cnt)++;
3067
3068 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3069 if (ptr)
3070 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3071 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3072
3073 /* When the client triggers a 4xx from the server, it's most often due
3074 * to a missing object or permission. These events should be tracked
3075 * because if they happen often, it may indicate a brute force or a
3076 * vulnerability scan. Normally this is done when receiving the response
3077 * but here we're tracking after this ought to have been done so we have
3078 * to do it on purpose.
3079 */
3080 if ((unsigned)(txn->status - 400) < 100) {
3081 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3082 if (ptr)
3083 stktable_data_cast(ptr, http_err_cnt)++;
3084
3085 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3086 if (ptr)
3087 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3088 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3089 }
3090
3091 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3092
3093 /* If data was modified, we need to touch to re-schedule sync */
3094 stktable_touch_local(t, ts, 0);
3095
3096 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3097 if (sess->fe != s->be)
3098 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3099
3100 }
3101 }
3102 break;
3103
3104 case ACT_CUSTOM:
3105 if ((s->req.flags & CF_READ_ERROR) ||
3106 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3107 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3108 (px->options & PR_O_ABRT_CLOSE)))
3109 act_flags |= ACT_FLAG_FINAL;
3110
3111 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3112 case ACT_RET_ERR:
3113 case ACT_RET_CONT:
3114 break;
3115 case ACT_RET_STOP:
3116 return HTTP_RULE_RES_STOP;
3117 case ACT_RET_YIELD:
3118 s->current_rule = rule;
3119 return HTTP_RULE_RES_YIELD;
3120 }
3121 break;
3122
3123 /* other flags exists, but normaly, they never be matched. */
3124 default:
3125 break;
3126 }
3127 }
3128
3129 /* we reached the end of the rules, nothing to report */
3130 return HTTP_RULE_RES_CONT;
3131 }
3132
3133
3134 /* Perform an HTTP redirect based on the information in <rule>. The function
3135 * returns non-zero on success, or zero in case of a, irrecoverable error such
3136 * as too large a request to build a valid response.
3137 */
http_apply_redirect_rule(struct redirect_rule * rule,struct stream * s,struct http_txn * txn)3138 static int http_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
3139 {
3140 struct http_msg *req = &txn->req;
3141 struct http_msg *res = &txn->rsp;
3142 const char *msg_fmt;
3143 struct chunk *chunk;
3144 int ret = 0;
3145
3146 chunk = alloc_trash_chunk();
3147 if (!chunk)
3148 goto leave;
3149
3150 /* build redirect message */
3151 switch(rule->code) {
3152 case 308:
3153 msg_fmt = HTTP_308;
3154 break;
3155 case 307:
3156 msg_fmt = HTTP_307;
3157 break;
3158 case 303:
3159 msg_fmt = HTTP_303;
3160 break;
3161 case 301:
3162 msg_fmt = HTTP_301;
3163 break;
3164 case 302:
3165 default:
3166 msg_fmt = HTTP_302;
3167 break;
3168 }
3169
3170 if (unlikely(!chunk_strcpy(chunk, msg_fmt)))
3171 goto leave;
3172
3173 switch(rule->type) {
3174 case REDIRECT_TYPE_SCHEME: {
3175 const char *path;
3176 const char *host;
3177 struct hdr_ctx ctx;
3178 int pathlen;
3179 int hostlen;
3180
3181 host = "";
3182 hostlen = 0;
3183 ctx.idx = 0;
3184 if (http_find_header2("Host", 4, req->chn->buf->p, &txn->hdr_idx, &ctx)) {
3185 host = ctx.line + ctx.val;
3186 hostlen = ctx.vlen;
3187 }
3188
3189 path = http_get_path(txn);
3190 /* build message using path */
3191 if (path) {
3192 pathlen = req->sl.rq.u_l + (req->chn->buf->p + req->sl.rq.u) - path;
3193 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
3194 int qs = 0;
3195 while (qs < pathlen) {
3196 if (path[qs] == '?') {
3197 pathlen = qs;
3198 break;
3199 }
3200 qs++;
3201 }
3202 }
3203 } else {
3204 path = "/";
3205 pathlen = 1;
3206 }
3207
3208 if (rule->rdr_str) { /* this is an old "redirect" rule */
3209 /* check if we can add scheme + "://" + host + path */
3210 if (chunk->len + rule->rdr_len + 3 + hostlen + pathlen > chunk->size - 4)
3211 goto leave;
3212
3213 /* add scheme */
3214 memcpy(chunk->str + chunk->len, rule->rdr_str, rule->rdr_len);
3215 chunk->len += rule->rdr_len;
3216 }
3217 else {
3218 /* add scheme with executing log format */
3219 chunk->len += build_logline(s, chunk->str + chunk->len, chunk->size - chunk->len, &rule->rdr_fmt);
3220
3221 /* check if we can add scheme + "://" + host + path */
3222 if (chunk->len + 3 + hostlen + pathlen > chunk->size - 4)
3223 goto leave;
3224 }
3225 /* add "://" */
3226 memcpy(chunk->str + chunk->len, "://", 3);
3227 chunk->len += 3;
3228
3229 /* add host */
3230 memcpy(chunk->str + chunk->len, host, hostlen);
3231 chunk->len += hostlen;
3232
3233 /* add path */
3234 memcpy(chunk->str + chunk->len, path, pathlen);
3235 chunk->len += pathlen;
3236
3237 /* append a slash at the end of the location if needed and missing */
3238 if (chunk->len && chunk->str[chunk->len - 1] != '/' &&
3239 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
3240 if (chunk->len > chunk->size - 5)
3241 goto leave;
3242 chunk->str[chunk->len] = '/';
3243 chunk->len++;
3244 }
3245
3246 break;
3247 }
3248 case REDIRECT_TYPE_PREFIX: {
3249 const char *path;
3250 int pathlen;
3251
3252 path = http_get_path(txn);
3253 /* build message using path */
3254 if (path) {
3255 pathlen = req->sl.rq.u_l + (req->chn->buf->p + req->sl.rq.u) - path;
3256 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
3257 int qs = 0;
3258 while (qs < pathlen) {
3259 if (path[qs] == '?') {
3260 pathlen = qs;
3261 break;
3262 }
3263 qs++;
3264 }
3265 }
3266 } else {
3267 path = "/";
3268 pathlen = 1;
3269 }
3270
3271 if (rule->rdr_str) { /* this is an old "redirect" rule */
3272 if (chunk->len + rule->rdr_len + pathlen > chunk->size - 4)
3273 goto leave;
3274
3275 /* add prefix. Note that if prefix == "/", we don't want to
3276 * add anything, otherwise it makes it hard for the user to
3277 * configure a self-redirection.
3278 */
3279 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
3280 memcpy(chunk->str + chunk->len, rule->rdr_str, rule->rdr_len);
3281 chunk->len += rule->rdr_len;
3282 }
3283 }
3284 else {
3285 /* add prefix with executing log format */
3286 chunk->len += build_logline(s, chunk->str + chunk->len, chunk->size - chunk->len, &rule->rdr_fmt);
3287
3288 /* Check length */
3289 if (chunk->len + pathlen > chunk->size - 4)
3290 goto leave;
3291 }
3292
3293 /* add path */
3294 memcpy(chunk->str + chunk->len, path, pathlen);
3295 chunk->len += pathlen;
3296
3297 /* append a slash at the end of the location if needed and missing */
3298 if (chunk->len && chunk->str[chunk->len - 1] != '/' &&
3299 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
3300 if (chunk->len > chunk->size - 5)
3301 goto leave;
3302 chunk->str[chunk->len] = '/';
3303 chunk->len++;
3304 }
3305
3306 break;
3307 }
3308 case REDIRECT_TYPE_LOCATION:
3309 default:
3310 if (rule->rdr_str) { /* this is an old "redirect" rule */
3311 if (chunk->len + rule->rdr_len > chunk->size - 4)
3312 goto leave;
3313
3314 /* add location */
3315 memcpy(chunk->str + chunk->len, rule->rdr_str, rule->rdr_len);
3316 chunk->len += rule->rdr_len;
3317 }
3318 else {
3319 /* add location with executing log format */
3320 chunk->len += build_logline(s, chunk->str + chunk->len, chunk->size - chunk->len, &rule->rdr_fmt);
3321
3322 /* Check left length */
3323 if (chunk->len > chunk->size - 4)
3324 goto leave;
3325 }
3326 break;
3327 }
3328
3329 if (rule->cookie_len) {
3330 memcpy(chunk->str + chunk->len, "\r\nSet-Cookie: ", 14);
3331 chunk->len += 14;
3332 memcpy(chunk->str + chunk->len, rule->cookie_str, rule->cookie_len);
3333 chunk->len += rule->cookie_len;
3334 }
3335
3336 /* add end of headers and the keep-alive/close status. */
3337 txn->status = rule->code;
3338
3339 if (((!(req->flags & HTTP_MSGF_TE_CHNK) && !req->body_len) || (req->msg_state == HTTP_MSG_DONE)) &&
3340 ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL ||
3341 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)) {
3342 /* keep-alive possible */
3343 if (!(req->flags & HTTP_MSGF_VER_11)) {
3344 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
3345 memcpy(chunk->str + chunk->len, "\r\nProxy-Connection: keep-alive", 30);
3346 chunk->len += 30;
3347 } else {
3348 memcpy(chunk->str + chunk->len, "\r\nConnection: keep-alive", 24);
3349 chunk->len += 24;
3350 }
3351 }
3352 memcpy(chunk->str + chunk->len, "\r\n\r\n", 4);
3353 chunk->len += 4;
3354 FLT_STRM_CB(s, flt_http_reply(s, txn->status, chunk));
3355 co_inject(res->chn, chunk->str, chunk->len);
3356 /* "eat" the request */
3357 bi_fast_delete(req->chn->buf, req->sov);
3358 req->next -= req->sov;
3359 req->sov = 0;
3360 s->req.analysers = AN_REQ_HTTP_XFER_BODY | (s->req.analysers & AN_REQ_FLT_END);
3361 s->res.analysers = AN_RES_HTTP_XFER_BODY | (s->res.analysers & AN_RES_FLT_END);
3362 req->msg_state = HTTP_MSG_CLOSED;
3363 res->msg_state = HTTP_MSG_DONE;
3364 /* Trim any possible response */
3365 res->chn->buf->i = 0;
3366 res->next = res->sov = 0;
3367 /* let the server side turn to SI_ST_CLO */
3368 channel_shutw_now(req->chn);
3369 channel_dont_connect(req->chn);
3370
3371 if (rule->flags & REDIRECT_FLAG_FROM_REQ) {
3372 /* let's log the request time */
3373 s->logs.tv_request = now;
3374 }
3375 } else {
3376 /* keep-alive not possible */
3377 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
3378 memcpy(chunk->str + chunk->len, "\r\nProxy-Connection: close\r\n\r\n", 29);
3379 chunk->len += 29;
3380 } else {
3381 memcpy(chunk->str + chunk->len, "\r\nConnection: close\r\n\r\n", 23);
3382 chunk->len += 23;
3383 }
3384 http_reply_and_close(s, txn->status, chunk);
3385
3386 if (rule->flags & REDIRECT_FLAG_FROM_REQ) {
3387 /* let's log the request time */
3388 s->logs.tv_request = now;
3389 req->chn->analysers &= AN_REQ_FLT_END;
3390 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
3391 HA_ATOMIC_ADD(&s->sess->fe->fe_counters.intercepted_req, 1);
3392
3393 }
3394 }
3395
3396 if (!(s->flags & SF_ERR_MASK))
3397 s->flags |= SF_ERR_LOCAL;
3398 if (!(s->flags & SF_FINST_MASK))
3399 s->flags |= ((rule->flags & REDIRECT_FLAG_FROM_REQ) ? SF_FINST_R : SF_FINST_H);
3400
3401 ret = 1;
3402 leave:
3403 free_trash_chunk(chunk);
3404 return ret;
3405 }
3406
3407 /* This stream analyser runs all HTTP request processing which is common to
3408 * frontends and backends, which means blocking ACLs, filters, connection-close,
3409 * reqadd, stats and redirects. This is performed for the designated proxy.
3410 * It returns 1 if the processing can continue on next analysers, or zero if it
3411 * either needs more data or wants to immediately abort the request (eg: deny,
3412 * error, ...).
3413 */
http_process_req_common(struct stream * s,struct channel * req,int an_bit,struct proxy * px)3414 int http_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
3415 {
3416 struct session *sess = s->sess;
3417 struct http_txn *txn = s->txn;
3418 struct http_msg *msg = &txn->req;
3419 struct redirect_rule *rule;
3420 struct cond_wordlist *wl;
3421 enum rule_result verdict;
3422 int deny_status = HTTP_ERR_403;
3423 struct connection *conn = objt_conn(sess->origin);
3424
3425 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
3426 /* we need more data */
3427 goto return_prx_yield;
3428 }
3429
3430 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n",
3431 now_ms, __FUNCTION__,
3432 s,
3433 req,
3434 req->rex, req->wex,
3435 req->flags,
3436 req->buf->i,
3437 req->analysers);
3438
3439 /* just in case we have some per-backend tracking. Only called the first
3440 * execution of the analyser. */
3441 if (!s->current_rule || s->current_rule_list != &px->http_req_rules)
3442 stream_inc_be_http_req_ctr(s);
3443
3444 /* evaluate http-request rules */
3445 if (!LIST_ISEMPTY(&px->http_req_rules)) {
3446 verdict = http_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
3447
3448 switch (verdict) {
3449 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
3450 goto return_prx_yield;
3451
3452 case HTTP_RULE_RES_CONT:
3453 case HTTP_RULE_RES_STOP: /* nothing to do */
3454 break;
3455
3456 case HTTP_RULE_RES_DENY: /* deny or tarpit */
3457 if (txn->flags & TX_CLTARPIT)
3458 goto tarpit;
3459 goto deny;
3460
3461 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
3462 goto return_prx_cond;
3463
3464 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
3465 goto done;
3466
3467 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
3468 goto return_bad_req;
3469 }
3470 }
3471
3472 if (conn && conn->flags & CO_FL_EARLY_DATA) {
3473 struct hdr_ctx ctx;
3474
3475 ctx.idx = 0;
3476 if (!http_find_header2("Early-Data", strlen("Early-Data"),
3477 s->req.buf->p, &txn->hdr_idx, &ctx)) {
3478 if (unlikely(http_header_add_tail2(&txn->req,
3479 &txn->hdr_idx, "Early-Data: 1",
3480 strlen("Early-Data: 1")) < 0)) {
3481 goto return_bad_req;
3482 }
3483 }
3484
3485 }
3486
3487 /* OK at this stage, we know that the request was accepted according to
3488 * the http-request rules, we can check for the stats. Note that the
3489 * URI is detected *before* the req* rules in order not to be affected
3490 * by a possible reqrep, while they are processed *after* so that a
3491 * reqdeny can still block them. This clearly needs to change in 1.6!
3492 */
3493 if (stats_check_uri(&s->si[1], txn, px)) {
3494 s->target = &http_stats_applet.obj_type;
3495 if (unlikely(!stream_int_register_handler(&s->si[1], objt_applet(s->target)))) {
3496 txn->status = 500;
3497 s->logs.tv_request = now;
3498 http_reply_and_close(s, txn->status, http_error_message(s));
3499
3500 if (!(s->flags & SF_ERR_MASK))
3501 s->flags |= SF_ERR_RESOURCE;
3502 goto return_prx_cond;
3503 }
3504
3505 /* parse the whole stats request and extract the relevant information */
3506 http_handle_stats(s, req);
3507 verdict = http_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
3508 /* not all actions implemented: deny, allow, auth */
3509
3510 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
3511 goto deny;
3512
3513 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
3514 goto return_prx_cond;
3515 }
3516
3517 /* evaluate the req* rules except reqadd */
3518 if (px->req_exp != NULL) {
3519 if (apply_filters_to_request(s, req, px) < 0)
3520 goto return_bad_req;
3521
3522 if (txn->flags & TX_CLDENY)
3523 goto deny;
3524
3525 if (txn->flags & TX_CLTARPIT) {
3526 deny_status = HTTP_ERR_500;
3527 goto tarpit;
3528 }
3529 }
3530
3531 /* add request headers from the rule sets in the same order */
3532 list_for_each_entry(wl, &px->req_add, list) {
3533 if (wl->cond) {
3534 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3535 ret = acl_pass(ret);
3536 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
3537 ret = !ret;
3538 if (!ret)
3539 continue;
3540 }
3541
3542 if (unlikely(http_header_add_tail(&txn->req, &txn->hdr_idx, wl->s) < 0))
3543 goto return_bad_req;
3544 }
3545
3546
3547 /* Proceed with the stats now. */
3548 if (unlikely(objt_applet(s->target) == &http_stats_applet) ||
3549 unlikely(objt_applet(s->target) == &http_cache_applet)) {
3550 /* process the stats request now */
3551 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
3552 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
3553
3554 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
3555 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
3556 if (!(s->flags & SF_FINST_MASK))
3557 s->flags |= SF_FINST_R;
3558
3559 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
3560 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
3561 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
3562 req->analysers |= AN_REQ_HTTP_XFER_BODY;
3563 goto done;
3564 }
3565
3566 /* check whether we have some ACLs set to redirect this request */
3567 list_for_each_entry(rule, &px->redirect_rules, list) {
3568 if (rule->cond) {
3569 int ret;
3570
3571 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3572 ret = acl_pass(ret);
3573 if (rule->cond->pol == ACL_COND_UNLESS)
3574 ret = !ret;
3575 if (!ret)
3576 continue;
3577 }
3578 if (!http_apply_redirect_rule(rule, s, txn))
3579 goto return_bad_req;
3580 goto done;
3581 }
3582
3583 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
3584 * If this happens, then the data will not come immediately, so we must
3585 * send all what we have without waiting. Note that due to the small gain
3586 * in waiting for the body of the request, it's easier to simply put the
3587 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
3588 * itself once used.
3589 */
3590 req->flags |= CF_SEND_DONTWAIT;
3591
3592 done: /* done with this analyser, continue with next ones that the calling
3593 * points will have set, if any.
3594 */
3595 req->analyse_exp = TICK_ETERNITY;
3596 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
3597 req->analysers &= ~an_bit;
3598 return 1;
3599
3600 tarpit:
3601 /* Allow cookie logging
3602 */
3603 if (s->be->cookie_name || sess->fe->capture_name)
3604 manage_client_side_cookies(s, req);
3605
3606 /* When a connection is tarpitted, we use the tarpit timeout,
3607 * which may be the same as the connect timeout if unspecified.
3608 * If unset, then set it to zero because we really want it to
3609 * eventually expire. We build the tarpit as an analyser.
3610 */
3611 channel_erase(&s->req);
3612
3613 /* wipe the request out so that we can drop the connection early
3614 * if the client closes first.
3615 */
3616 channel_dont_connect(req);
3617
3618 txn->status = http_err_codes[deny_status];
3619
3620 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
3621 req->analysers |= AN_REQ_HTTP_TARPIT;
3622 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
3623 if (!req->analyse_exp)
3624 req->analyse_exp = tick_add(now_ms, 0);
3625 stream_inc_http_err_ctr(s);
3626 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
3627 if (sess->fe != s->be)
3628 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
3629 if (sess->listener && sess->listener->counters)
3630 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
3631 goto done_without_exp;
3632
3633 deny: /* this request was blocked (denied) */
3634
3635 /* Allow cookie logging
3636 */
3637 if (s->be->cookie_name || sess->fe->capture_name)
3638 manage_client_side_cookies(s, req);
3639
3640 txn->flags |= TX_CLDENY;
3641 txn->status = http_err_codes[deny_status];
3642 s->logs.tv_request = now;
3643 http_reply_and_close(s, txn->status, http_error_message(s));
3644 stream_inc_http_err_ctr(s);
3645 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
3646 if (sess->fe != s->be)
3647 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
3648 if (sess->listener && sess->listener->counters)
3649 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
3650 goto return_prx_cond;
3651
3652 return_bad_req:
3653 /* We centralize bad requests processing here */
3654 if (unlikely(msg->msg_state == HTTP_MSG_ERROR) || msg->err_pos >= 0) {
3655 /* we detected a parsing error. We want to archive this request
3656 * in the dedicated proxy area for later troubleshooting.
3657 */
3658 http_capture_bad_message(sess->fe, &sess->fe->invalid_req, s, msg, msg->err_state, sess->fe);
3659 }
3660
3661 txn->req.err_state = txn->req.msg_state;
3662 txn->req.msg_state = HTTP_MSG_ERROR;
3663 txn->status = 400;
3664 http_reply_and_close(s, txn->status, http_error_message(s));
3665
3666 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
3667 if (sess->listener && sess->listener->counters)
3668 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
3669
3670 return_prx_cond:
3671 if (!(s->flags & SF_ERR_MASK))
3672 s->flags |= SF_ERR_PRXCOND;
3673 if (!(s->flags & SF_FINST_MASK))
3674 s->flags |= SF_FINST_R;
3675
3676 req->analysers &= AN_REQ_FLT_END;
3677 req->analyse_exp = TICK_ETERNITY;
3678 return 0;
3679
3680 return_prx_yield:
3681 channel_dont_connect(req);
3682 return 0;
3683 }
3684
3685 /* This function performs all the processing enabled for the current request.
3686 * It returns 1 if the processing can continue on next analysers, or zero if it
3687 * needs more data, encounters an error, or wants to immediately abort the
3688 * request. It relies on buffers flags, and updates s->req.analysers.
3689 */
http_process_request(struct stream * s,struct channel * req,int an_bit)3690 int http_process_request(struct stream *s, struct channel *req, int an_bit)
3691 {
3692 struct session *sess = s->sess;
3693 struct http_txn *txn = s->txn;
3694 struct http_msg *msg = &txn->req;
3695 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
3696
3697 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
3698 /* we need more data */
3699 channel_dont_connect(req);
3700 return 0;
3701 }
3702
3703 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n",
3704 now_ms, __FUNCTION__,
3705 s,
3706 req,
3707 req->rex, req->wex,
3708 req->flags,
3709 req->buf->i,
3710 req->analysers);
3711
3712 /*
3713 * Right now, we know that we have processed the entire headers
3714 * and that unwanted requests have been filtered out. We can do
3715 * whatever we want with the remaining request. Also, now we
3716 * may have separate values for ->fe, ->be.
3717 */
3718
3719 /*
3720 * If HTTP PROXY is set we simply get remote server address parsing
3721 * incoming request. Note that this requires that a connection is
3722 * allocated on the server side.
3723 */
3724 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
3725 struct connection *conn;
3726 char *path;
3727
3728 /* Note that for now we don't reuse existing proxy connections */
3729 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
3730 txn->req.err_state = txn->req.msg_state;
3731 txn->req.msg_state = HTTP_MSG_ERROR;
3732 txn->status = 500;
3733 req->analysers &= AN_REQ_FLT_END;
3734 http_reply_and_close(s, txn->status, http_error_message(s));
3735
3736 if (!(s->flags & SF_ERR_MASK))
3737 s->flags |= SF_ERR_RESOURCE;
3738 if (!(s->flags & SF_FINST_MASK))
3739 s->flags |= SF_FINST_R;
3740
3741 return 0;
3742 }
3743
3744 path = http_get_path(txn);
3745 if (url2sa(req->buf->p + msg->sl.rq.u,
3746 path ? path - (req->buf->p + msg->sl.rq.u) : msg->sl.rq.u_l,
3747 &conn->addr.to, NULL) == -1)
3748 goto return_bad_req;
3749
3750 /* if the path was found, we have to remove everything between
3751 * req->buf->p + msg->sl.rq.u and path (excluded). If it was not
3752 * found, we need to replace from req->buf->p + msg->sl.rq.u for
3753 * u_l characters by a single "/".
3754 */
3755 if (path) {
3756 char *cur_ptr = req->buf->p;
3757 char *cur_end = cur_ptr + txn->req.sl.rq.l;
3758 int delta;
3759
3760 delta = buffer_replace2(req->buf, req->buf->p + msg->sl.rq.u, path, NULL, 0);
3761 http_msg_move_end(&txn->req, delta);
3762 cur_end += delta;
3763 if (http_parse_reqline(&txn->req, HTTP_MSG_RQMETH, cur_ptr, cur_end + 1, NULL, NULL) == NULL)
3764 goto return_bad_req;
3765 }
3766 else {
3767 char *cur_ptr = req->buf->p;
3768 char *cur_end = cur_ptr + txn->req.sl.rq.l;
3769 int delta;
3770
3771 delta = buffer_replace2(req->buf, req->buf->p + msg->sl.rq.u,
3772 req->buf->p + msg->sl.rq.u + msg->sl.rq.u_l, "/", 1);
3773 http_msg_move_end(&txn->req, delta);
3774 cur_end += delta;
3775 if (http_parse_reqline(&txn->req, HTTP_MSG_RQMETH, cur_ptr, cur_end + 1, NULL, NULL) == NULL)
3776 goto return_bad_req;
3777 }
3778 conn->target = &s->be->obj_type;
3779 }
3780
3781 /*
3782 * 7: Now we can work with the cookies.
3783 * Note that doing so might move headers in the request, but
3784 * the fields will stay coherent and the URI will not move.
3785 * This should only be performed in the backend.
3786 */
3787 if (s->be->cookie_name || sess->fe->capture_name)
3788 manage_client_side_cookies(s, req);
3789
3790 /* add unique-id if "header-unique-id" is specified */
3791
3792 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
3793 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
3794 goto return_bad_req;
3795 s->unique_id[0] = '\0';
3796 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
3797 }
3798
3799 if (sess->fe->header_unique_id && s->unique_id) {
3800 chunk_printf(&trash, "%s: %s", sess->fe->header_unique_id, s->unique_id);
3801 if (trash.len < 0)
3802 goto return_bad_req;
3803 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, trash.len) < 0))
3804 goto return_bad_req;
3805 }
3806
3807 /*
3808 * 9: add X-Forwarded-For if either the frontend or the backend
3809 * asks for it.
3810 */
3811 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
3812 struct hdr_ctx ctx = { .idx = 0 };
3813 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
3814 http_find_header2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
3815 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len,
3816 req->buf->p, &txn->hdr_idx, &ctx)) {
3817 /* The header is set to be added only if none is present
3818 * and we found it, so don't do anything.
3819 */
3820 }
3821 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
3822 /* Add an X-Forwarded-For header unless the source IP is
3823 * in the 'except' network range.
3824 */
3825 if ((!sess->fe->except_mask.s_addr ||
3826 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
3827 != sess->fe->except_net.s_addr) &&
3828 (!s->be->except_mask.s_addr ||
3829 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
3830 != s->be->except_net.s_addr)) {
3831 int len;
3832 unsigned char *pn;
3833 pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
3834
3835 /* Note: we rely on the backend to get the header name to be used for
3836 * x-forwarded-for, because the header is really meant for the backends.
3837 * However, if the backend did not specify any option, we have to rely
3838 * on the frontend's header name.
3839 */
3840 if (s->be->fwdfor_hdr_len) {
3841 len = s->be->fwdfor_hdr_len;
3842 memcpy(trash.str, s->be->fwdfor_hdr_name, len);
3843 } else {
3844 len = sess->fe->fwdfor_hdr_len;
3845 memcpy(trash.str, sess->fe->fwdfor_hdr_name, len);
3846 }
3847 len += snprintf(trash.str + len, trash.size - len, ": %d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
3848
3849 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, len) < 0))
3850 goto return_bad_req;
3851 }
3852 }
3853 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
3854 /* FIXME: for the sake of completeness, we should also support
3855 * 'except' here, although it is mostly useless in this case.
3856 */
3857 int len;
3858 char pn[INET6_ADDRSTRLEN];
3859 inet_ntop(AF_INET6,
3860 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
3861 pn, sizeof(pn));
3862
3863 /* Note: we rely on the backend to get the header name to be used for
3864 * x-forwarded-for, because the header is really meant for the backends.
3865 * However, if the backend did not specify any option, we have to rely
3866 * on the frontend's header name.
3867 */
3868 if (s->be->fwdfor_hdr_len) {
3869 len = s->be->fwdfor_hdr_len;
3870 memcpy(trash.str, s->be->fwdfor_hdr_name, len);
3871 } else {
3872 len = sess->fe->fwdfor_hdr_len;
3873 memcpy(trash.str, sess->fe->fwdfor_hdr_name, len);
3874 }
3875 len += snprintf(trash.str + len, trash.size - len, ": %s", pn);
3876
3877 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, len) < 0))
3878 goto return_bad_req;
3879 }
3880 }
3881
3882 /*
3883 * 10: add X-Original-To if either the frontend or the backend
3884 * asks for it.
3885 */
3886 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
3887
3888 /* FIXME: don't know if IPv6 can handle that case too. */
3889 if (cli_conn && cli_conn->addr.to.ss_family == AF_INET) {
3890 /* Add an X-Original-To header unless the destination IP is
3891 * in the 'except' network range.
3892 */
3893 conn_get_to_addr(cli_conn);
3894
3895 if (cli_conn->addr.to.ss_family == AF_INET &&
3896 ((!sess->fe->except_mask_to.s_addr ||
3897 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
3898 != sess->fe->except_to.s_addr) &&
3899 (!s->be->except_mask_to.s_addr ||
3900 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
3901 != s->be->except_to.s_addr))) {
3902 int len;
3903 unsigned char *pn;
3904 pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
3905
3906 /* Note: we rely on the backend to get the header name to be used for
3907 * x-original-to, because the header is really meant for the backends.
3908 * However, if the backend did not specify any option, we have to rely
3909 * on the frontend's header name.
3910 */
3911 if (s->be->orgto_hdr_len) {
3912 len = s->be->orgto_hdr_len;
3913 memcpy(trash.str, s->be->orgto_hdr_name, len);
3914 } else {
3915 len = sess->fe->orgto_hdr_len;
3916 memcpy(trash.str, sess->fe->orgto_hdr_name, len);
3917 }
3918 len += snprintf(trash.str + len, trash.size - len, ": %d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
3919
3920 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, len) < 0))
3921 goto return_bad_req;
3922 }
3923 }
3924 }
3925
3926 /* 11: add "Connection: close" or "Connection: keep-alive" if needed and not yet set.
3927 * If an "Upgrade" token is found, the header is left untouched in order not to have
3928 * to deal with some servers bugs : some of them fail an Upgrade if anything but
3929 * "Upgrade" is present in the Connection header.
3930 */
3931 if (!(txn->flags & TX_HDR_CONN_UPG) &&
3932 (((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN) ||
3933 ((sess->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||
3934 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL))) {
3935 unsigned int want_flags = 0;
3936
3937 if (msg->flags & HTTP_MSGF_VER_11) {
3938 if (((txn->flags & TX_CON_WANT_MSK) >= TX_CON_WANT_SCL ||
3939 ((sess->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||
3940 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL)) &&
3941 !((sess->fe->options2|s->be->options2) & PR_O2_FAKE_KA))
3942 want_flags |= TX_CON_CLO_SET;
3943 } else {
3944 if (((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL &&
3945 ((sess->fe->options & PR_O_HTTP_MODE) != PR_O_HTTP_PCL &&
3946 (s->be->options & PR_O_HTTP_MODE) != PR_O_HTTP_PCL)) ||
3947 ((sess->fe->options2|s->be->options2) & PR_O2_FAKE_KA))
3948 want_flags |= TX_CON_KAL_SET;
3949 }
3950
3951 if (want_flags != (txn->flags & (TX_CON_CLO_SET|TX_CON_KAL_SET)))
3952 http_change_connection_header(txn, msg, want_flags);
3953 }
3954
3955
3956 /* If we have no server assigned yet and we're balancing on url_param
3957 * with a POST request, we may be interested in checking the body for
3958 * that parameter. This will be done in another analyser.
3959 */
3960 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
3961 s->txn->meth == HTTP_METH_POST &&
3962 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH &&
3963 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
3964 channel_dont_connect(req);
3965 req->analysers |= AN_REQ_HTTP_BODY;
3966 }
3967
3968 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
3969 req->analysers |= AN_REQ_HTTP_XFER_BODY;
3970 #ifdef TCP_QUICKACK
3971 /* We expect some data from the client. Unless we know for sure
3972 * we already have a full request, we have to re-enable quick-ack
3973 * in case we previously disabled it, otherwise we might cause
3974 * the client to delay further data.
3975 */
3976 if ((sess->listener->options & LI_O_NOQUICKACK) &&
3977 cli_conn && conn_ctrl_ready(cli_conn) &&
3978 ((msg->flags & HTTP_MSGF_TE_CHNK) ||
3979 (msg->body_len > req->buf->i - txn->req.eoh - 2)))
3980 setsockopt(cli_conn->handle.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
3981 #endif
3982
3983 /*************************************************************
3984 * OK, that's finished for the headers. We have done what we *
3985 * could. Let's switch to the DATA state. *
3986 ************************************************************/
3987 req->analyse_exp = TICK_ETERNITY;
3988 req->analysers &= ~an_bit;
3989
3990 s->logs.tv_request = now;
3991 /* OK let's go on with the BODY now */
3992 return 1;
3993
3994 return_bad_req: /* let's centralize all bad requests */
3995 if (unlikely(msg->msg_state == HTTP_MSG_ERROR) || msg->err_pos >= 0) {
3996 /* we detected a parsing error. We want to archive this request
3997 * in the dedicated proxy area for later troubleshooting.
3998 */
3999 http_capture_bad_message(sess->fe, &sess->fe->invalid_req, s, msg, msg->err_state, sess->fe);
4000 }
4001
4002 txn->req.err_state = txn->req.msg_state;
4003 txn->req.msg_state = HTTP_MSG_ERROR;
4004 txn->status = 400;
4005 req->analysers &= AN_REQ_FLT_END;
4006 http_reply_and_close(s, txn->status, http_error_message(s));
4007
4008 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
4009 if (sess->listener && sess->listener->counters)
4010 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
4011
4012 if (!(s->flags & SF_ERR_MASK))
4013 s->flags |= SF_ERR_PRXCOND;
4014 if (!(s->flags & SF_FINST_MASK))
4015 s->flags |= SF_FINST_R;
4016 return 0;
4017 }
4018
4019 /* This function is an analyser which processes the HTTP tarpit. It always
4020 * returns zero, at the beginning because it prevents any other processing
4021 * from occurring, and at the end because it terminates the request.
4022 */
http_process_tarpit(struct stream * s,struct channel * req,int an_bit)4023 int http_process_tarpit(struct stream *s, struct channel *req, int an_bit)
4024 {
4025 struct http_txn *txn = s->txn;
4026
4027 /* This connection is being tarpitted. The CLIENT side has
4028 * already set the connect expiration date to the right
4029 * timeout. We just have to check that the client is still
4030 * there and that the timeout has not expired.
4031 */
4032 channel_dont_connect(req);
4033 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
4034 !tick_is_expired(req->analyse_exp, now_ms))
4035 return 0;
4036
4037 /* We will set the queue timer to the time spent, just for
4038 * logging purposes. We fake a 500 server error, so that the
4039 * attacker will not suspect his connection has been tarpitted.
4040 * It will not cause trouble to the logs because we can exclude
4041 * the tarpitted connections by filtering on the 'PT' status flags.
4042 */
4043 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
4044
4045 if (!(req->flags & CF_READ_ERROR))
4046 http_reply_and_close(s, txn->status, http_error_message(s));
4047
4048 req->analysers &= AN_REQ_FLT_END;
4049 req->analyse_exp = TICK_ETERNITY;
4050
4051 if (!(s->flags & SF_ERR_MASK))
4052 s->flags |= SF_ERR_PRXCOND;
4053 if (!(s->flags & SF_FINST_MASK))
4054 s->flags |= SF_FINST_T;
4055 return 0;
4056 }
4057
4058 /* This function is an analyser which waits for the HTTP request body. It waits
4059 * for either the buffer to be full, or the full advertised contents to have
4060 * reached the buffer. It must only be called after the standard HTTP request
4061 * processing has occurred, because it expects the request to be parsed and will
4062 * look for the Expect header. It may send a 100-Continue interim response. It
4063 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
4064 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
4065 * needs to read more data, or 1 once it has completed its analysis.
4066 */
http_wait_for_request_body(struct stream * s,struct channel * req,int an_bit)4067 int http_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
4068 {
4069 struct session *sess = s->sess;
4070 struct http_txn *txn = s->txn;
4071 struct http_msg *msg = &s->txn->req;
4072
4073 /* We have to parse the HTTP request body to find any required data.
4074 * "balance url_param check_post" should have been the only way to get
4075 * into this. We were brought here after HTTP header analysis, so all
4076 * related structures are ready.
4077 */
4078
4079 if (msg->msg_state < HTTP_MSG_CHUNK_SIZE) {
4080 /* This is the first call */
4081 if (msg->msg_state < HTTP_MSG_BODY)
4082 goto missing_data;
4083
4084 if (msg->msg_state < HTTP_MSG_100_SENT) {
4085 /* If we have HTTP/1.1 and Expect: 100-continue, then we must
4086 * send an HTTP/1.1 100 Continue intermediate response.
4087 */
4088 if (msg->flags & HTTP_MSGF_VER_11) {
4089 struct hdr_ctx ctx;
4090 ctx.idx = 0;
4091 /* Expect is allowed in 1.1, look for it */
4092 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &ctx) &&
4093 unlikely(ctx.vlen == 12 && strncasecmp(ctx.line+ctx.val, "100-continue", 12) == 0)) {
4094 co_inject(&s->res, http_100_chunk.str, http_100_chunk.len);
4095 http_remove_header2(&txn->req, &txn->hdr_idx, &ctx);
4096 }
4097 }
4098 msg->msg_state = HTTP_MSG_100_SENT;
4099 }
4100
4101 /* we have msg->sov which points to the first byte of message body.
4102 * req->buf->p still points to the beginning of the message. We
4103 * must save the body in msg->next because it survives buffer
4104 * re-alignments.
4105 */
4106 msg->next = msg->sov;
4107
4108 if (msg->flags & HTTP_MSGF_TE_CHNK)
4109 msg->msg_state = HTTP_MSG_CHUNK_SIZE;
4110 else
4111 msg->msg_state = HTTP_MSG_DATA;
4112 }
4113
4114 if (!(msg->flags & HTTP_MSGF_TE_CHNK)) {
4115 /* We're in content-length mode, we just have to wait for enough data. */
4116 if (http_body_bytes(msg) < msg->body_len)
4117 goto missing_data;
4118
4119 /* OK we have everything we need now */
4120 goto http_end;
4121 }
4122
4123 /* OK here we're parsing a chunked-encoded message */
4124
4125 if (msg->msg_state == HTTP_MSG_CHUNK_SIZE) {
4126 /* read the chunk size and assign it to ->chunk_len, then
4127 * set ->sov and ->next to point to the body and switch to DATA or
4128 * TRAILERS state.
4129 */
4130 unsigned int chunk;
4131 int ret = h1_parse_chunk_size(req->buf, msg->next, req->buf->i, &chunk);
4132
4133 if (!ret)
4134 goto missing_data;
4135 else if (ret < 0) {
4136 msg->err_pos = req->buf->i + ret;
4137 if (msg->err_pos < 0)
4138 msg->err_pos += req->buf->size;
4139 stream_inc_http_err_ctr(s);
4140 goto return_bad_req;
4141 }
4142
4143 msg->chunk_len = chunk;
4144 msg->body_len += chunk;
4145
4146 msg->sol = ret;
4147 msg->next += ret;
4148 msg->msg_state = msg->chunk_len ? HTTP_MSG_DATA : HTTP_MSG_TRAILERS;
4149 }
4150
4151 /* Now we're in HTTP_MSG_DATA or HTTP_MSG_TRAILERS state.
4152 * We have the first data byte is in msg->sov + msg->sol. We're waiting
4153 * for at least a whole chunk or the whole content length bytes after
4154 * msg->sov + msg->sol.
4155 */
4156 if (msg->msg_state == HTTP_MSG_TRAILERS)
4157 goto http_end;
4158
4159 if (http_body_bytes(msg) >= msg->body_len) /* we have enough bytes now */
4160 goto http_end;
4161
4162 missing_data:
4163 /* we get here if we need to wait for more data. If the buffer is full,
4164 * we have the maximum we can expect.
4165 */
4166 if (buffer_full(req->buf, global.tune.maxrewrite))
4167 goto http_end;
4168
4169 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
4170 txn->status = 408;
4171 http_reply_and_close(s, txn->status, http_error_message(s));
4172
4173 if (!(s->flags & SF_ERR_MASK))
4174 s->flags |= SF_ERR_CLITO;
4175 if (!(s->flags & SF_FINST_MASK))
4176 s->flags |= SF_FINST_D;
4177 goto return_err_msg;
4178 }
4179
4180 /* we get here if we need to wait for more data */
4181 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
4182 /* Not enough data. We'll re-use the http-request
4183 * timeout here. Ideally, we should set the timeout
4184 * relative to the accept() date. We just set the
4185 * request timeout once at the beginning of the
4186 * request.
4187 */
4188 channel_dont_connect(req);
4189 if (!tick_isset(req->analyse_exp))
4190 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
4191 return 0;
4192 }
4193
4194 http_end:
4195 /* The situation will not evolve, so let's give up on the analysis. */
4196 s->logs.tv_request = now; /* update the request timer to reflect full request */
4197 req->analysers &= ~an_bit;
4198 req->analyse_exp = TICK_ETERNITY;
4199 return 1;
4200
4201 return_bad_req: /* let's centralize all bad requests */
4202 txn->req.err_state = txn->req.msg_state;
4203 txn->req.msg_state = HTTP_MSG_ERROR;
4204 txn->status = 400;
4205 http_reply_and_close(s, txn->status, http_error_message(s));
4206
4207 if (!(s->flags & SF_ERR_MASK))
4208 s->flags |= SF_ERR_PRXCOND;
4209 if (!(s->flags & SF_FINST_MASK))
4210 s->flags |= SF_FINST_R;
4211
4212 return_err_msg:
4213 req->analysers &= AN_REQ_FLT_END;
4214 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
4215 if (sess->listener && sess->listener->counters)
4216 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
4217 return 0;
4218 }
4219
4220 /* send a server's name with an outgoing request over an established connection.
4221 * Note: this function is designed to be called once the request has been scheduled
4222 * for being forwarded. This is the reason why it rewinds the buffer before
4223 * proceeding.
4224 */
http_send_name_header(struct http_txn * txn,struct proxy * be,const char * srv_name)4225 int http_send_name_header(struct http_txn *txn, struct proxy* be, const char* srv_name) {
4226
4227 struct hdr_ctx ctx;
4228
4229 char *hdr_name = be->server_id_hdr_name;
4230 int hdr_name_len = be->server_id_hdr_len;
4231 struct channel *chn = txn->req.chn;
4232 char *hdr_val;
4233 unsigned int old_o, old_i;
4234
4235 ctx.idx = 0;
4236
4237 old_o = http_hdr_rewind(&txn->req);
4238 if (old_o) {
4239 /* The request was already skipped, let's restore it */
4240 b_rew(chn->buf, old_o);
4241 txn->req.next += old_o;
4242 txn->req.sov += old_o;
4243 }
4244
4245 old_i = chn->buf->i;
4246 while (http_find_header2(hdr_name, hdr_name_len, txn->req.chn->buf->p, &txn->hdr_idx, &ctx)) {
4247 /* remove any existing values from the header */
4248 http_remove_header2(&txn->req, &txn->hdr_idx, &ctx);
4249 }
4250
4251 /* Add the new header requested with the server value */
4252 hdr_val = trash.str;
4253 memcpy(hdr_val, hdr_name, hdr_name_len);
4254 hdr_val += hdr_name_len;
4255 *hdr_val++ = ':';
4256 *hdr_val++ = ' ';
4257 hdr_val += strlcpy2(hdr_val, srv_name, trash.str + trash.size - hdr_val);
4258 http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, hdr_val - trash.str);
4259
4260 if (old_o) {
4261 /* If this was a forwarded request, we must readjust the amount of
4262 * data to be forwarded in order to take into account the size
4263 * variations. Note that the current state is >= HTTP_MSG_BODY,
4264 * so we don't have to adjust ->sol.
4265 */
4266 old_o += chn->buf->i - old_i;
4267 b_adv(chn->buf, old_o);
4268 txn->req.next -= old_o;
4269 txn->req.sov -= old_o;
4270 }
4271
4272 return 0;
4273 }
4274
4275 /* Terminate current transaction and prepare a new one. This is very tricky
4276 * right now but it works.
4277 */
http_end_txn_clean_session(struct stream * s)4278 void http_end_txn_clean_session(struct stream *s)
4279 {
4280 int prev_status = s->txn->status;
4281 struct proxy *fe = strm_fe(s);
4282 struct proxy *be = s->be;
4283 struct conn_stream *cs;
4284 struct connection *srv_conn;
4285 struct server *srv;
4286 unsigned int prev_flags = s->txn->flags;
4287
4288 /* FIXME: We need a more portable way of releasing a backend's and a
4289 * server's connections. We need a safer way to reinitialize buffer
4290 * flags. We also need a more accurate method for computing per-request
4291 * data.
4292 */
4293 /*
4294 * XXX cognet: This is probably wrong, this is killing a whole
4295 * connection, in the new world order, we probably want to just kill
4296 * the stream, this is to be revisited the day we handle multiple
4297 * streams in one server connection.
4298 */
4299 cs = objt_cs(s->si[1].end);
4300 srv_conn = cs_conn(cs);
4301
4302 /* unless we're doing keep-alive, we want to quickly close the connection
4303 * to the server.
4304 */
4305 if (((s->txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) ||
4306 !si_conn_ready(&s->si[1])) {
4307 s->si[1].flags |= SI_FL_NOLINGER | SI_FL_NOHALF;
4308 si_shutr(&s->si[1]);
4309 si_shutw(&s->si[1]);
4310 }
4311
4312 if (s->flags & SF_BE_ASSIGNED) {
4313 HA_ATOMIC_SUB(&be->beconn, 1);
4314 if (unlikely(s->srv_conn))
4315 sess_change_server(s, NULL);
4316 }
4317
4318 s->logs.t_close = tv_ms_elapsed(&s->logs.tv_accept, &now);
4319 stream_process_counters(s);
4320
4321 if (s->txn->status) {
4322 int n;
4323
4324 n = s->txn->status / 100;
4325 if (n < 1 || n > 5)
4326 n = 0;
4327
4328 if (fe->mode == PR_MODE_HTTP) {
4329 HA_ATOMIC_ADD(&fe->fe_counters.p.http.rsp[n], 1);
4330 }
4331 if ((s->flags & SF_BE_ASSIGNED) &&
4332 (be->mode == PR_MODE_HTTP)) {
4333 HA_ATOMIC_ADD(&be->be_counters.p.http.rsp[n], 1);
4334 HA_ATOMIC_ADD(&be->be_counters.p.http.cum_req, 1);
4335 }
4336 }
4337
4338 /* don't count other requests' data */
4339 s->logs.bytes_in -= s->req.buf->i;
4340 s->logs.bytes_out -= s->res.buf->i;
4341
4342 /* let's do a final log if we need it */
4343 if (!LIST_ISEMPTY(&fe->logformat) && s->logs.logwait &&
4344 !(s->flags & SF_MONITOR) &&
4345 (!(fe->options & PR_O_NULLNOLOG) || s->req.total)) {
4346 s->do_log(s);
4347 }
4348
4349 /* stop tracking content-based counters */
4350 stream_stop_content_counters(s);
4351 stream_update_time_stats(s);
4352
4353 s->logs.accept_date = date; /* user-visible date for logging */
4354 s->logs.tv_accept = now; /* corrected date for internal use */
4355 s->logs.t_handshake = 0; /* There are no handshake in keep alive connection. */
4356 s->logs.t_idle = -1;
4357 tv_zero(&s->logs.tv_request);
4358 s->logs.t_queue = -1;
4359 s->logs.t_connect = -1;
4360 s->logs.t_data = -1;
4361 s->logs.t_close = 0;
4362 s->logs.prx_queue_size = 0; /* we get the number of pending conns before us */
4363 s->logs.srv_queue_size = 0; /* we will get this number soon */
4364
4365 s->logs.bytes_in = s->req.total = s->req.buf->i;
4366 s->logs.bytes_out = s->res.total = s->res.buf->i;
4367
4368 if (s->pend_pos)
4369 pendconn_free(s->pend_pos);
4370
4371 if (objt_server(s->target)) {
4372 if (s->flags & SF_CURR_SESS) {
4373 s->flags &= ~SF_CURR_SESS;
4374 HA_ATOMIC_SUB(&__objt_server(s->target)->cur_sess, 1);
4375 }
4376 if (may_dequeue_tasks(objt_server(s->target), be))
4377 process_srv_queue(objt_server(s->target));
4378 }
4379
4380 s->target = NULL;
4381
4382 /* only release our endpoint if we don't intend to reuse the
4383 * connection.
4384 */
4385 if (((s->txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) ||
4386 !si_conn_ready(&s->si[1])) {
4387 si_release_endpoint(&s->si[1]);
4388 srv_conn = NULL;
4389 }
4390
4391 s->si[1].state = s->si[1].prev_state = SI_ST_INI;
4392 s->si[1].err_type = SI_ET_NONE;
4393 s->si[1].conn_retries = 0; /* used for logging too */
4394 s->si[1].exp = TICK_ETERNITY;
4395 s->si[1].flags &= SI_FL_ISBACK | SI_FL_DONT_WAKE; /* we're in the context of process_stream */
4396 s->req.flags &= ~(CF_SHUTW|CF_SHUTW_NOW|CF_AUTO_CONNECT|CF_WRITE_ERROR|CF_STREAMER|CF_STREAMER_FAST|CF_NEVER_WAIT|CF_WAKE_CONNECT|CF_WROTE_DATA);
4397 s->res.flags &= ~(CF_SHUTR|CF_SHUTR_NOW|CF_READ_ATTACHED|CF_READ_ERROR|CF_READ_NOEXP|CF_STREAMER|CF_STREAMER_FAST|CF_WRITE_PARTIAL|CF_NEVER_WAIT|CF_WROTE_DATA|CF_WRITE_EVENT);
4398 s->flags &= ~(SF_DIRECT|SF_ASSIGNED|SF_ADDR_SET|SF_BE_ASSIGNED|SF_FORCE_PRST|SF_IGNORE_PRST);
4399 s->flags &= ~(SF_CURR_SESS|SF_REDIRECTABLE|SF_SRV_REUSED);
4400 s->flags &= ~(SF_ERR_MASK|SF_FINST_MASK|SF_REDISP);
4401
4402 hlua_ctx_destroy(s->hlua);
4403 s->hlua = NULL;
4404
4405 /* cleanup and reinit capture arrays, if any */
4406 if (s->req_cap) {
4407 struct cap_hdr *h;
4408 for (h = fe->req_cap; h; h = h->next)
4409 pool_free(h->pool, s->req_cap[h->index]);
4410 memset(s->req_cap, 0, fe->nb_req_cap * sizeof(void *));
4411 }
4412
4413 if (s->res_cap) {
4414 struct cap_hdr *h;
4415 for (h = fe->rsp_cap; h; h = h->next)
4416 pool_free(h->pool, s->res_cap[h->index]);
4417 memset(s->res_cap, 0, fe->nb_rsp_cap * sizeof(void *));
4418 }
4419
4420 s->txn->meth = 0;
4421 http_reset_txn(s);
4422 s->txn->flags |= TX_NOT_FIRST | TX_WAIT_NEXT_RQ;
4423
4424 if (prev_status == 401 || prev_status == 407) {
4425 /* In HTTP keep-alive mode, if we receive a 401, we still have
4426 * a chance of being able to send the visitor again to the same
4427 * server over the same connection. This is required by some
4428 * broken protocols such as NTLM, and anyway whenever there is
4429 * an opportunity for sending the challenge to the proper place,
4430 * it's better to do it (at least it helps with debugging), at
4431 * least for non-deterministic load balancing algorithms.
4432 */
4433 s->txn->flags |= TX_PREFER_LAST;
4434 }
4435
4436 /* Never ever allow to reuse a connection from a non-reuse backend */
4437 if (srv_conn && (be->options & PR_O_REUSE_MASK) == PR_O_REUSE_NEVR)
4438 srv_conn->flags |= CO_FL_PRIVATE;
4439
4440 if (fe->options2 & PR_O2_INDEPSTR)
4441 s->si[1].flags |= SI_FL_INDEP_STR;
4442
4443 if (fe->options2 & PR_O2_NODELAY) {
4444 s->req.flags |= CF_NEVER_WAIT;
4445 s->res.flags |= CF_NEVER_WAIT;
4446 }
4447
4448 /* we're removing the analysers, we MUST re-enable events detection.
4449 * We don't enable close on the response channel since it's either
4450 * already closed, or in keep-alive with an idle connection handler.
4451 */
4452 channel_auto_read(&s->req);
4453 channel_auto_close(&s->req);
4454 channel_auto_read(&s->res);
4455
4456 /* we're in keep-alive with an idle connection, monitor it if not already done */
4457 if (srv_conn && LIST_ISEMPTY(&srv_conn->list)) {
4458 srv = objt_server(srv_conn->target);
4459 if (!srv)
4460 si_idle_cs(&s->si[1], NULL);
4461 else if (srv_conn->flags & CO_FL_PRIVATE)
4462 si_idle_cs(&s->si[1], (srv->priv_conns ? &srv->priv_conns[tid] : NULL));
4463 else if (prev_flags & TX_NOT_FIRST)
4464 /* note: we check the request, not the connection, but
4465 * this is valid for strategies SAFE and AGGR, and in
4466 * case of ALWS, we don't care anyway.
4467 */
4468 si_idle_cs(&s->si[1], (srv->safe_conns ? &srv->safe_conns[tid] : NULL));
4469 else
4470 si_idle_cs(&s->si[1], (srv->idle_conns ? &srv->idle_conns[tid] : NULL));
4471 }
4472 s->req.analysers = strm_li(s) ? strm_li(s)->analysers : 0;
4473 s->res.analysers = 0;
4474 }
4475
4476
4477 /* This function updates the request state machine according to the response
4478 * state machine and buffer flags. It returns 1 if it changes anything (flag
4479 * or state), otherwise zero. It ignores any state before HTTP_MSG_DONE, as
4480 * it is only used to find when a request/response couple is complete. Both
4481 * this function and its equivalent should loop until both return zero. It
4482 * can set its own state to DONE, CLOSING, CLOSED, TUNNEL, ERROR.
4483 */
http_sync_req_state(struct stream * s)4484 int http_sync_req_state(struct stream *s)
4485 {
4486 struct channel *chn = &s->req;
4487 struct http_txn *txn = s->txn;
4488 unsigned int old_flags = chn->flags;
4489 unsigned int old_state = txn->req.msg_state;
4490
4491 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
4492 return 0;
4493
4494 if (txn->req.msg_state == HTTP_MSG_DONE) {
4495 /* No need to read anymore, the request was completely parsed.
4496 * We can shut the read side unless we want to abort_on_close,
4497 * or we have a POST request. The issue with POST requests is
4498 * that some browsers still send a CRLF after the request, and
4499 * this CRLF must be read so that it does not remain in the kernel
4500 * buffers, otherwise a close could cause an RST on some systems
4501 * (eg: Linux).
4502 * Note that if we're using keep-alive on the client side, we'd
4503 * rather poll now and keep the polling enabled for the whole
4504 * stream's life than enabling/disabling it between each
4505 * response and next request.
4506 */
4507 if (((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_SCL) &&
4508 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) &&
4509 (!(s->be->options & PR_O_ABRT_CLOSE) ||
4510 (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
4511 txn->meth != HTTP_METH_POST)
4512 channel_dont_read(chn);
4513
4514 /* if the server closes the connection, we want to immediately react
4515 * and close the socket to save packets and syscalls.
4516 */
4517 s->si[1].flags |= SI_FL_NOHALF;
4518
4519 /* In any case we've finished parsing the request so we must
4520 * disable Nagle when sending data because 1) we're not going
4521 * to shut this side, and 2) the server is waiting for us to
4522 * send pending data.
4523 */
4524 chn->flags |= CF_NEVER_WAIT;
4525
4526 if (txn->rsp.msg_state == HTTP_MSG_ERROR)
4527 goto wait_other_side;
4528
4529 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
4530 /* The server has not finished to respond, so we
4531 * don't want to move in order not to upset it.
4532 */
4533 goto wait_other_side;
4534 }
4535
4536 /* When we get here, it means that both the request and the
4537 * response have finished receiving. Depending on the connection
4538 * mode, we'll have to wait for the last bytes to leave in either
4539 * direction, and sometimes for a close to be effective.
4540 */
4541
4542 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) {
4543 /* Server-close mode : queue a connection close to the server */
4544 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW)))
4545 channel_shutw_now(chn);
4546 }
4547 else if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_CLO) {
4548 /* Option forceclose is set, or either side wants to close,
4549 * let's enforce it now that we're not expecting any new
4550 * data to come. The caller knows the stream is complete
4551 * once both states are CLOSED.
4552 *
4553 * However, there is an exception if the response
4554 * length is undefined. In this case, we need to wait
4555 * the close from the server. The response will be
4556 * switched in TUNNEL mode until the end.
4557 */
4558 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
4559 txn->rsp.msg_state != HTTP_MSG_CLOSED)
4560 goto check_channel_flags;
4561
4562 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
4563 channel_shutr_now(chn);
4564 channel_shutw_now(chn);
4565 }
4566 }
4567 else {
4568 /* The last possible modes are keep-alive and tunnel. Tunnel mode
4569 * will not have any analyser so it needs to poll for reads.
4570 */
4571 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
4572 channel_auto_read(chn);
4573 txn->req.msg_state = HTTP_MSG_TUNNEL;
4574 }
4575 }
4576
4577 goto check_channel_flags;
4578 }
4579
4580 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
4581 http_msg_closing:
4582 /* nothing else to forward, just waiting for the output buffer
4583 * to be empty and for the shutw_now to take effect.
4584 */
4585 if (channel_is_empty(chn)) {
4586 txn->req.msg_state = HTTP_MSG_CLOSED;
4587 goto http_msg_closed;
4588 }
4589 else if (chn->flags & CF_SHUTW) {
4590 txn->req.err_state = txn->req.msg_state;
4591 txn->req.msg_state = HTTP_MSG_ERROR;
4592 }
4593 goto wait_other_side;
4594 }
4595
4596 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
4597 http_msg_closed:
4598 /* if we don't know whether the server will close, we need to hard close */
4599 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
4600 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
4601
4602 /* see above in MSG_DONE why we only do this in these states */
4603 if (((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_SCL) &&
4604 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) &&
4605 (!(s->be->options & PR_O_ABRT_CLOSE) ||
4606 (s->si[0].flags & SI_FL_CLEAN_ABRT)))
4607 channel_dont_read(chn);
4608 goto wait_other_side;
4609 }
4610
4611 check_channel_flags:
4612 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
4613 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
4614 /* if we've just closed an output, let's switch */
4615 txn->req.msg_state = HTTP_MSG_CLOSING;
4616 goto http_msg_closing;
4617 }
4618
4619
4620 wait_other_side:
4621 return txn->req.msg_state != old_state || chn->flags != old_flags;
4622 }
4623
4624
4625 /* This function updates the response state machine according to the request
4626 * state machine and buffer flags. It returns 1 if it changes anything (flag
4627 * or state), otherwise zero. It ignores any state before HTTP_MSG_DONE, as
4628 * it is only used to find when a request/response couple is complete. Both
4629 * this function and its equivalent should loop until both return zero. It
4630 * can set its own state to DONE, CLOSING, CLOSED, TUNNEL, ERROR.
4631 */
http_sync_res_state(struct stream * s)4632 int http_sync_res_state(struct stream *s)
4633 {
4634 struct channel *chn = &s->res;
4635 struct http_txn *txn = s->txn;
4636 unsigned int old_flags = chn->flags;
4637 unsigned int old_state = txn->rsp.msg_state;
4638
4639 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
4640 return 0;
4641
4642 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
4643 /* In theory, we don't need to read anymore, but we must
4644 * still monitor the server connection for a possible close
4645 * while the request is being uploaded, so we don't disable
4646 * reading.
4647 */
4648 /* channel_dont_read(chn); */
4649
4650 if (txn->req.msg_state == HTTP_MSG_ERROR)
4651 goto wait_other_side;
4652
4653 if (txn->req.msg_state < HTTP_MSG_DONE) {
4654 /* The client seems to still be sending data, probably
4655 * because we got an error response during an upload.
4656 * We have the choice of either breaking the connection
4657 * or letting it pass through. Let's do the later.
4658 */
4659 goto wait_other_side;
4660 }
4661
4662 /* When we get here, it means that both the request and the
4663 * response have finished receiving. Depending on the connection
4664 * mode, we'll have to wait for the last bytes to leave in either
4665 * direction, and sometimes for a close to be effective.
4666 */
4667
4668 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) {
4669 /* Server-close mode : shut read and wait for the request
4670 * side to close its output buffer. The caller will detect
4671 * when we're in DONE and the other is in CLOSED and will
4672 * catch that for the final cleanup.
4673 */
4674 if (!(chn->flags & (CF_SHUTR|CF_SHUTR_NOW)))
4675 channel_shutr_now(chn);
4676 }
4677 else if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_CLO) {
4678 /* Option forceclose is set, or either side wants to close,
4679 * let's enforce it now that we're not expecting any new
4680 * data to come. The caller knows the stream is complete
4681 * once both states are CLOSED.
4682 */
4683 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
4684 channel_shutr_now(chn);
4685 channel_shutw_now(chn);
4686 }
4687 }
4688 else {
4689 /* The last possible modes are keep-alive and tunnel. Tunnel will
4690 * need to forward remaining data. Keep-alive will need to monitor
4691 * for connection closing.
4692 */
4693 channel_auto_read(chn);
4694 chn->flags |= CF_NEVER_WAIT;
4695 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN)
4696 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
4697 }
4698
4699 goto check_channel_flags;
4700 }
4701
4702 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
4703 http_msg_closing:
4704 /* nothing else to forward, just waiting for the output buffer
4705 * to be empty and for the shutw_now to take effect.
4706 */
4707 if (channel_is_empty(chn)) {
4708 txn->rsp.msg_state = HTTP_MSG_CLOSED;
4709 goto http_msg_closed;
4710 }
4711 else if (chn->flags & CF_SHUTW) {
4712 txn->rsp.err_state = txn->rsp.msg_state;
4713 txn->rsp.msg_state = HTTP_MSG_ERROR;
4714 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
4715 if (objt_server(s->target))
4716 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
4717 }
4718 goto wait_other_side;
4719 }
4720
4721 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
4722 http_msg_closed:
4723 /* drop any pending data */
4724 channel_truncate(chn);
4725 channel_auto_close(chn);
4726 channel_auto_read(chn);
4727 goto wait_other_side;
4728 }
4729
4730 check_channel_flags:
4731 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
4732 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
4733 /* if we've just closed an output, let's switch */
4734 txn->rsp.msg_state = HTTP_MSG_CLOSING;
4735 goto http_msg_closing;
4736 }
4737
4738 wait_other_side:
4739 /* We force the response to leave immediately if we're waiting for the
4740 * other side, since there is no pending shutdown to push it out.
4741 */
4742 if (!channel_is_empty(chn))
4743 chn->flags |= CF_SEND_DONTWAIT;
4744 return txn->rsp.msg_state != old_state || chn->flags != old_flags;
4745 }
4746
4747
4748 /* Resync the request and response state machines. */
http_resync_states(struct stream * s)4749 void http_resync_states(struct stream *s)
4750 {
4751 struct http_txn *txn = s->txn;
4752 #ifdef DEBUG_FULL
4753 int old_req_state = txn->req.msg_state;
4754 int old_res_state = txn->rsp.msg_state;
4755 #endif
4756
4757 http_sync_req_state(s);
4758 while (1) {
4759 if (!http_sync_res_state(s))
4760 break;
4761 if (!http_sync_req_state(s))
4762 break;
4763 }
4764
4765 DPRINTF(stderr,"[%u] %s: stream=%p old=%s,%s cur=%s,%s "
4766 "req->analysers=0x%08x res->analysers=0x%08x\n",
4767 now_ms, __FUNCTION__, s,
4768 h1_msg_state_str(old_req_state), h1_msg_state_str(old_res_state),
4769 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
4770 s->req.analysers, s->res.analysers);
4771
4772
4773 /* OK, both state machines agree on a compatible state.
4774 * There are a few cases we're interested in :
4775 * - HTTP_MSG_CLOSED on both sides means we've reached the end in both
4776 * directions, so let's simply disable both analysers.
4777 * - HTTP_MSG_CLOSED on the response only or HTTP_MSG_ERROR on either
4778 * means we must abort the request.
4779 * - HTTP_MSG_TUNNEL on either means we have to disable analyser on
4780 * corresponding channel.
4781 * - HTTP_MSG_DONE or HTTP_MSG_CLOSED on the request and HTTP_MSG_DONE
4782 * on the response with server-close mode means we've completed one
4783 * request and we must re-initialize the server connection.
4784 */
4785 if (txn->req.msg_state == HTTP_MSG_CLOSED &&
4786 txn->rsp.msg_state == HTTP_MSG_CLOSED) {
4787 s->req.analysers &= AN_REQ_FLT_END;
4788 channel_auto_close(&s->req);
4789 channel_auto_read(&s->req);
4790 s->res.analysers &= AN_RES_FLT_END;
4791 channel_auto_close(&s->res);
4792 channel_auto_read(&s->res);
4793 }
4794 else if (txn->rsp.msg_state == HTTP_MSG_CLOSED ||
4795 txn->rsp.msg_state == HTTP_MSG_ERROR ||
4796 txn->req.msg_state == HTTP_MSG_ERROR) {
4797 s->res.analysers &= AN_RES_FLT_END;
4798 channel_auto_close(&s->res);
4799 channel_auto_read(&s->res);
4800 s->req.analysers &= AN_REQ_FLT_END;
4801 channel_abort(&s->req);
4802 channel_auto_close(&s->req);
4803 channel_auto_read(&s->req);
4804 channel_truncate(&s->req);
4805 }
4806 else if (txn->req.msg_state == HTTP_MSG_TUNNEL ||
4807 txn->rsp.msg_state == HTTP_MSG_TUNNEL) {
4808 if (txn->req.msg_state == HTTP_MSG_TUNNEL) {
4809 s->req.analysers &= AN_REQ_FLT_END;
4810 if (HAS_REQ_DATA_FILTERS(s))
4811 s->req.analysers |= AN_REQ_FLT_XFER_DATA;
4812 }
4813 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL) {
4814 s->res.analysers &= AN_RES_FLT_END;
4815 if (HAS_RSP_DATA_FILTERS(s))
4816 s->res.analysers |= AN_RES_FLT_XFER_DATA;
4817 }
4818 channel_auto_close(&s->req);
4819 channel_auto_read(&s->req);
4820 channel_auto_close(&s->res);
4821 channel_auto_read(&s->res);
4822 }
4823 else if ((txn->req.msg_state == HTTP_MSG_DONE ||
4824 txn->req.msg_state == HTTP_MSG_CLOSED) &&
4825 txn->rsp.msg_state == HTTP_MSG_DONE &&
4826 ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL ||
4827 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)) {
4828 /* server-close/keep-alive: terminate this transaction,
4829 * possibly killing the server connection and reinitialize
4830 * a fresh-new transaction, but only once we're sure there's
4831 * enough room in the request and response buffer to process
4832 * another request. They must not hold any pending output data
4833 * and the response buffer must realigned
4834 * (realign is done is http_end_txn_clean_session).
4835 */
4836 if (s->req.buf->o)
4837 s->req.flags |= CF_WAKE_WRITE;
4838 else if (s->res.buf->o)
4839 s->res.flags |= CF_WAKE_WRITE;
4840 else {
4841 s->req.analysers = AN_REQ_FLT_END;
4842 s->res.analysers = AN_RES_FLT_END;
4843 txn->flags |= TX_WAIT_CLEANUP;
4844 }
4845 }
4846 }
4847
4848 /* This function is an analyser which forwards request body (including chunk
4849 * sizes if any). It is called as soon as we must forward, even if we forward
4850 * zero byte. The only situation where it must not be called is when we're in
4851 * tunnel mode and we want to forward till the close. It's used both to forward
4852 * remaining data and to resync after end of body. It expects the msg_state to
4853 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
4854 * read more data, or 1 once we can go on with next request or end the stream.
4855 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
4856 * bytes of pending data + the headers if not already done.
4857 */
http_request_forward_body(struct stream * s,struct channel * req,int an_bit)4858 int http_request_forward_body(struct stream *s, struct channel *req, int an_bit)
4859 {
4860 struct session *sess = s->sess;
4861 struct http_txn *txn = s->txn;
4862 struct http_msg *msg = &s->txn->req;
4863 int ret;
4864
4865 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n",
4866 now_ms, __FUNCTION__,
4867 s,
4868 req,
4869 req->rex, req->wex,
4870 req->flags,
4871 req->buf->i,
4872 req->analysers);
4873
4874 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4875 return 0;
4876
4877 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
4878 ((req->flags & CF_SHUTW) && (req->to_forward || req->buf->o))) {
4879 /* Output closed while we were sending data. We must abort and
4880 * wake the other side up.
4881 */
4882 msg->err_state = msg->msg_state;
4883 msg->msg_state = HTTP_MSG_ERROR;
4884 http_resync_states(s);
4885 return 1;
4886 }
4887
4888 /* Note that we don't have to send 100-continue back because we don't
4889 * need the data to complete our job, and it's up to the server to
4890 * decide whether to return 100, 417 or anything else in return of
4891 * an "Expect: 100-continue" header.
4892 */
4893 if (msg->msg_state == HTTP_MSG_BODY) {
4894 msg->msg_state = ((msg->flags & HTTP_MSGF_TE_CHNK)
4895 ? HTTP_MSG_CHUNK_SIZE
4896 : HTTP_MSG_DATA);
4897
4898 /* TODO/filters: when http-buffer-request option is set or if a
4899 * rule on url_param exists, the first chunk size could be
4900 * already parsed. In that case, msg->next is after the chunk
4901 * size (including the CRLF after the size). So this case should
4902 * be handled to */
4903 }
4904
4905 /* Some post-connect processing might want us to refrain from starting to
4906 * forward data. Currently, the only reason for this is "balance url_param"
4907 * whichs need to parse/process the request after we've enabled forwarding.
4908 */
4909 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
4910 if (!(s->res.flags & CF_READ_ATTACHED)) {
4911 channel_auto_connect(req);
4912 req->flags |= CF_WAKE_CONNECT;
4913 channel_dont_close(req); /* don't fail on early shutr */
4914 goto waiting;
4915 }
4916 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
4917 }
4918
4919 /* in most states, we should abort in case of early close */
4920 channel_auto_close(req);
4921
4922 if (req->to_forward) {
4923 /* We can't process the buffer's contents yet */
4924 req->flags |= CF_WAKE_WRITE;
4925 goto missing_data_or_waiting;
4926 }
4927
4928 if (msg->msg_state < HTTP_MSG_DONE) {
4929 ret = ((msg->flags & HTTP_MSGF_TE_CHNK)
4930 ? http_msg_forward_chunked_body(s, msg)
4931 : http_msg_forward_body(s, msg));
4932 if (!ret)
4933 goto missing_data_or_waiting;
4934 if (ret < 0)
4935 goto return_bad_req;
4936 }
4937
4938 /* other states, DONE...TUNNEL */
4939 /* we don't want to forward closes on DONE except in tunnel mode. */
4940 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
4941 channel_dont_close(req);
4942
4943 http_resync_states(s);
4944 if (!(req->analysers & an_bit)) {
4945 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
4946 if (req->flags & CF_SHUTW) {
4947 /* request errors are most likely due to the
4948 * server aborting the transfer. */
4949 goto aborted_xfer;
4950 }
4951 if (msg->err_pos >= 0)
4952 http_capture_bad_message(sess->fe, &sess->fe->invalid_req, s, msg, msg->err_state, s->be);
4953 goto return_bad_req;
4954 }
4955 return 1;
4956 }
4957
4958 /* If "option abortonclose" is set on the backend, we want to monitor
4959 * the client's connection and forward any shutdown notification to the
4960 * server, which will decide whether to close or to go on processing the
4961 * request. We only do that in tunnel mode, and not in other modes since
4962 * it can be abused to exhaust source ports. */
4963 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
4964 channel_auto_read(req);
4965 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
4966 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
4967 s->si[1].flags |= SI_FL_NOLINGER;
4968 channel_auto_close(req);
4969 }
4970 else if (s->txn->meth == HTTP_METH_POST) {
4971 /* POST requests may require to read extra CRLF sent by broken
4972 * browsers and which could cause an RST to be sent upon close
4973 * on some systems (eg: Linux). */
4974 channel_auto_read(req);
4975 }
4976 return 0;
4977
4978 missing_data_or_waiting:
4979 /* stop waiting for data if the input is closed before the end */
4980 if (msg->msg_state < HTTP_MSG_ENDING && req->flags & CF_SHUTR) {
4981 if (!(s->flags & SF_ERR_MASK))
4982 s->flags |= SF_ERR_CLICL;
4983 if (!(s->flags & SF_FINST_MASK)) {
4984 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
4985 s->flags |= SF_FINST_H;
4986 else
4987 s->flags |= SF_FINST_D;
4988 }
4989
4990 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
4991 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
4992 if (objt_server(s->target))
4993 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
4994
4995 goto return_bad_req_stats_ok;
4996 }
4997
4998 waiting:
4999 /* waiting for the last bits to leave the buffer */
5000 if (req->flags & CF_SHUTW)
5001 goto aborted_xfer;
5002
5003 /* When TE: chunked is used, we need to get there again to parse remaining
5004 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
5005 * And when content-length is used, we never want to let the possible
5006 * shutdown be forwarded to the other side, as the state machine will
5007 * take care of it once the client responds. It's also important to
5008 * prevent TIME_WAITs from accumulating on the backend side, and for
5009 * HTTP/2 where the last frame comes with a shutdown.
5010 */
5011 if (msg->flags & (HTTP_MSGF_TE_CHNK|HTTP_MSGF_CNT_LEN))
5012 channel_dont_close(req);
5013
5014 /* We know that more data are expected, but we couldn't send more that
5015 * what we did. So we always set the CF_EXPECT_MORE flag so that the
5016 * system knows it must not set a PUSH on this first part. Interactive
5017 * modes are already handled by the stream sock layer. We must not do
5018 * this in content-length mode because it could present the MSG_MORE
5019 * flag with the last block of forwarded data, which would cause an
5020 * additional delay to be observed by the receiver.
5021 */
5022 if (msg->flags & HTTP_MSGF_TE_CHNK)
5023 req->flags |= CF_EXPECT_MORE;
5024
5025 return 0;
5026
5027 return_bad_req: /* let's centralize all bad requests */
5028 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
5029 if (sess->listener && sess->listener->counters)
5030 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
5031
5032 return_bad_req_stats_ok:
5033 txn->req.err_state = txn->req.msg_state;
5034 txn->req.msg_state = HTTP_MSG_ERROR;
5035 if (txn->status) {
5036 /* Note: we don't send any error if some data were already sent */
5037 http_reply_and_close(s, txn->status, NULL);
5038 } else {
5039 txn->status = 400;
5040 http_reply_and_close(s, txn->status, http_error_message(s));
5041 }
5042 req->analysers &= AN_REQ_FLT_END;
5043 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
5044
5045 if (!(s->flags & SF_ERR_MASK))
5046 s->flags |= SF_ERR_PRXCOND;
5047 if (!(s->flags & SF_FINST_MASK)) {
5048 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
5049 s->flags |= SF_FINST_H;
5050 else
5051 s->flags |= SF_FINST_D;
5052 }
5053 return 0;
5054
5055 aborted_xfer:
5056 txn->req.err_state = txn->req.msg_state;
5057 txn->req.msg_state = HTTP_MSG_ERROR;
5058 if (txn->status) {
5059 /* Note: we don't send any error if some data were already sent */
5060 http_reply_and_close(s, txn->status, NULL);
5061 } else {
5062 txn->status = 502;
5063 http_reply_and_close(s, txn->status, http_error_message(s));
5064 }
5065 req->analysers &= AN_REQ_FLT_END;
5066 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
5067
5068 HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
5069 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
5070 if (objt_server(s->target))
5071 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
5072
5073 if (!(s->flags & SF_ERR_MASK))
5074 s->flags |= SF_ERR_SRVCL;
5075 if (!(s->flags & SF_FINST_MASK)) {
5076 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
5077 s->flags |= SF_FINST_H;
5078 else
5079 s->flags |= SF_FINST_D;
5080 }
5081 return 0;
5082 }
5083
5084 /* This stream analyser waits for a complete HTTP response. It returns 1 if the
5085 * processing can continue on next analysers, or zero if it either needs more
5086 * data or wants to immediately abort the response (eg: timeout, error, ...). It
5087 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
5088 * when it has nothing left to do, and may remove any analyser when it wants to
5089 * abort.
5090 */
http_wait_for_response(struct stream * s,struct channel * rep,int an_bit)5091 int http_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
5092 {
5093 struct session *sess = s->sess;
5094 struct http_txn *txn = s->txn;
5095 struct http_msg *msg = &txn->rsp;
5096 struct hdr_ctx ctx;
5097 struct connection *srv_conn;
5098 int use_close_only;
5099 int cur_idx;
5100 int n;
5101
5102 srv_conn = cs_conn(objt_cs(s->si[1].end));
5103
5104 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n",
5105 now_ms, __FUNCTION__,
5106 s,
5107 rep,
5108 rep->rex, rep->wex,
5109 rep->flags,
5110 rep->buf->i,
5111 rep->analysers);
5112
5113 /*
5114 * Now parse the partial (or complete) lines.
5115 * We will check the response syntax, and also join multi-line
5116 * headers. An index of all the lines will be elaborated while
5117 * parsing.
5118 *
5119 * For the parsing, we use a 28 states FSM.
5120 *
5121 * Here is the information we currently have :
5122 * rep->buf->p = beginning of response
5123 * rep->buf->p + msg->eoh = end of processed headers / start of current one
5124 * rep->buf->p + rep->buf->i = end of input data
5125 * msg->eol = end of current header or line (LF or CRLF)
5126 * msg->next = first non-visited byte
5127 */
5128
5129 next_one:
5130 /* There's a protected area at the end of the buffer for rewriting
5131 * purposes. We don't want to start to parse the request if the
5132 * protected area is affected, because we may have to move processed
5133 * data later, which is much more complicated.
5134 */
5135 if (buffer_not_empty(rep->buf) && msg->msg_state < HTTP_MSG_ERROR) {
5136 if (unlikely(!channel_is_rewritable(rep) && rep->buf->o)) {
5137 /* some data has still not left the buffer, wake us once that's done */
5138 if (rep->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_WRITE_ERROR|CF_WRITE_TIMEOUT))
5139 goto abort_response;
5140 channel_dont_close(rep);
5141 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
5142 rep->flags |= CF_WAKE_WRITE;
5143 return 0;
5144 }
5145
5146 if (unlikely(bi_end(rep->buf) < b_ptr(rep->buf, msg->next) ||
5147 bi_end(rep->buf) > rep->buf->data + rep->buf->size - global.tune.maxrewrite))
5148 buffer_slow_realign(rep->buf);
5149
5150 if (likely(msg->next < rep->buf->i))
5151 http_msg_analyzer(msg, &txn->hdr_idx);
5152 }
5153
5154 /* 1: we might have to print this header in debug mode */
5155 if (unlikely((global.mode & MODE_DEBUG) &&
5156 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) &&
5157 msg->msg_state >= HTTP_MSG_BODY)) {
5158 char *eol, *sol;
5159
5160 sol = rep->buf->p;
5161 eol = sol + (msg->sl.st.l ? msg->sl.st.l : rep->buf->i);
5162 debug_hdr("srvrep", s, sol, eol);
5163
5164 sol += hdr_idx_first_pos(&txn->hdr_idx);
5165 cur_idx = hdr_idx_first_idx(&txn->hdr_idx);
5166
5167 while (cur_idx) {
5168 eol = sol + txn->hdr_idx.v[cur_idx].len;
5169 debug_hdr("srvhdr", s, sol, eol);
5170 sol = eol + txn->hdr_idx.v[cur_idx].cr + 1;
5171 cur_idx = txn->hdr_idx.v[cur_idx].next;
5172 }
5173 }
5174
5175 /*
5176 * Now we quickly check if we have found a full valid response.
5177 * If not so, we check the FD and buffer states before leaving.
5178 * A full response is indicated by the fact that we have seen
5179 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
5180 * responses are checked first.
5181 *
5182 * Depending on whether the client is still there or not, we
5183 * may send an error response back or not. Note that normally
5184 * we should only check for HTTP status there, and check I/O
5185 * errors somewhere else.
5186 */
5187
5188 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
5189 /* Invalid response */
5190 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
5191 /* we detected a parsing error. We want to archive this response
5192 * in the dedicated proxy area for later troubleshooting.
5193 */
5194 hdr_response_bad:
5195 if (msg->msg_state == HTTP_MSG_ERROR || msg->err_pos >= 0)
5196 http_capture_bad_message(s->be, &s->be->invalid_rep, s, msg, msg->err_state, sess->fe);
5197
5198 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
5199 if (objt_server(s->target)) {
5200 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
5201 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
5202 }
5203 abort_response:
5204 channel_auto_close(rep);
5205 rep->analysers &= AN_RES_FLT_END;
5206 s->req.analysers &= AN_REQ_FLT_END;
5207 rep->analyse_exp = TICK_ETERNITY;
5208 txn->status = 502;
5209 s->si[1].flags |= SI_FL_NOLINGER;
5210 channel_truncate(rep);
5211 http_reply_and_close(s, txn->status, http_error_message(s));
5212
5213 if (!(s->flags & SF_ERR_MASK))
5214 s->flags |= SF_ERR_PRXCOND;
5215 if (!(s->flags & SF_FINST_MASK))
5216 s->flags |= SF_FINST_H;
5217
5218 return 0;
5219 }
5220
5221 /* too large response does not fit in buffer. */
5222 else if (buffer_full(rep->buf, global.tune.maxrewrite)) {
5223 if (msg->err_pos < 0)
5224 msg->err_pos = rep->buf->i;
5225 goto hdr_response_bad;
5226 }
5227
5228 /* read error */
5229 else if (rep->flags & CF_READ_ERROR) {
5230 if (msg->err_pos >= 0)
5231 http_capture_bad_message(s->be, &s->be->invalid_rep, s, msg, msg->err_state, sess->fe);
5232 else if (txn->flags & TX_NOT_FIRST)
5233 goto abort_keep_alive;
5234
5235 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
5236 if (objt_server(s->target)) {
5237 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
5238 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
5239 }
5240
5241 channel_auto_close(rep);
5242 rep->analysers &= AN_RES_FLT_END;
5243 s->req.analysers &= AN_REQ_FLT_END;
5244 rep->analyse_exp = TICK_ETERNITY;
5245 txn->status = 502;
5246
5247 /* Check to see if the server refused the early data.
5248 * If so, just send a 425
5249 */
5250 if (objt_cs(s->si[1].end)) {
5251 struct connection *conn = objt_cs(s->si[1].end)->conn;
5252
5253 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
5254 txn->status = 425;
5255 }
5256
5257 s->si[1].flags |= SI_FL_NOLINGER;
5258 channel_truncate(rep);
5259 http_reply_and_close(s, txn->status, http_error_message(s));
5260
5261 if (!(s->flags & SF_ERR_MASK))
5262 s->flags |= SF_ERR_SRVCL;
5263 if (!(s->flags & SF_FINST_MASK))
5264 s->flags |= SF_FINST_H;
5265 return 0;
5266 }
5267
5268 /* read timeout : return a 504 to the client. */
5269 else if (rep->flags & CF_READ_TIMEOUT) {
5270 if (msg->err_pos >= 0)
5271 http_capture_bad_message(s->be, &s->be->invalid_rep, s, msg, msg->err_state, sess->fe);
5272
5273 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
5274 if (objt_server(s->target)) {
5275 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
5276 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
5277 }
5278
5279 channel_auto_close(rep);
5280 rep->analysers &= AN_RES_FLT_END;
5281 s->req.analysers &= AN_REQ_FLT_END;
5282 rep->analyse_exp = TICK_ETERNITY;
5283 txn->status = 504;
5284 s->si[1].flags |= SI_FL_NOLINGER;
5285 channel_truncate(rep);
5286 http_reply_and_close(s, txn->status, http_error_message(s));
5287
5288 if (!(s->flags & SF_ERR_MASK))
5289 s->flags |= SF_ERR_SRVTO;
5290 if (!(s->flags & SF_FINST_MASK))
5291 s->flags |= SF_FINST_H;
5292 return 0;
5293 }
5294
5295 /* client abort with an abortonclose */
5296 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
5297 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
5298 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
5299 if (objt_server(s->target))
5300 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
5301
5302 rep->analysers &= AN_RES_FLT_END;
5303 s->req.analysers &= AN_REQ_FLT_END;
5304 rep->analyse_exp = TICK_ETERNITY;
5305 channel_auto_close(rep);
5306
5307 txn->status = 400;
5308 channel_truncate(rep);
5309 http_reply_and_close(s, txn->status, http_error_message(s));
5310
5311 if (!(s->flags & SF_ERR_MASK))
5312 s->flags |= SF_ERR_CLICL;
5313 if (!(s->flags & SF_FINST_MASK))
5314 s->flags |= SF_FINST_H;
5315
5316 /* process_stream() will take care of the error */
5317 return 0;
5318 }
5319
5320 /* close from server, capture the response if the server has started to respond */
5321 else if (rep->flags & CF_SHUTR) {
5322 if (msg->msg_state >= HTTP_MSG_RPVER || msg->err_pos >= 0)
5323 http_capture_bad_message(s->be, &s->be->invalid_rep, s, msg, msg->err_state, sess->fe);
5324 else if (txn->flags & TX_NOT_FIRST)
5325 goto abort_keep_alive;
5326
5327 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
5328 if (objt_server(s->target)) {
5329 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
5330 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
5331 }
5332
5333 channel_auto_close(rep);
5334 rep->analysers &= AN_RES_FLT_END;
5335 s->req.analysers &= AN_REQ_FLT_END;
5336 rep->analyse_exp = TICK_ETERNITY;
5337 txn->status = 502;
5338 s->si[1].flags |= SI_FL_NOLINGER;
5339 channel_truncate(rep);
5340 http_reply_and_close(s, txn->status, http_error_message(s));
5341
5342 if (!(s->flags & SF_ERR_MASK))
5343 s->flags |= SF_ERR_SRVCL;
5344 if (!(s->flags & SF_FINST_MASK))
5345 s->flags |= SF_FINST_H;
5346 return 0;
5347 }
5348
5349 /* write error to client (we don't send any message then) */
5350 else if (rep->flags & CF_WRITE_ERROR) {
5351 if (msg->err_pos >= 0)
5352 http_capture_bad_message(s->be, &s->be->invalid_rep, s, msg, msg->err_state, sess->fe);
5353 else if (txn->flags & TX_NOT_FIRST)
5354 goto abort_keep_alive;
5355
5356 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
5357 rep->analysers &= AN_RES_FLT_END;
5358 s->req.analysers &= AN_REQ_FLT_END;
5359 rep->analyse_exp = TICK_ETERNITY;
5360 channel_auto_close(rep);
5361
5362 if (!(s->flags & SF_ERR_MASK))
5363 s->flags |= SF_ERR_CLICL;
5364 if (!(s->flags & SF_FINST_MASK))
5365 s->flags |= SF_FINST_H;
5366
5367 /* process_stream() will take care of the error */
5368 return 0;
5369 }
5370
5371 channel_dont_close(rep);
5372 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
5373 return 0;
5374 }
5375
5376 /* More interesting part now : we know that we have a complete
5377 * response which at least looks like HTTP. We have an indicator
5378 * of each header's length, so we can parse them quickly.
5379 */
5380
5381 if (unlikely(msg->err_pos >= 0))
5382 http_capture_bad_message(s->be, &s->be->invalid_rep, s, msg, msg->err_state, sess->fe);
5383
5384 /*
5385 * 1: get the status code
5386 */
5387 n = rep->buf->p[msg->sl.st.c] - '0';
5388 if (n < 1 || n > 5)
5389 n = 0;
5390 /* when the client triggers a 4xx from the server, it's most often due
5391 * to a missing object or permission. These events should be tracked
5392 * because if they happen often, it may indicate a brute force or a
5393 * vulnerability scan.
5394 */
5395 if (n == 4)
5396 stream_inc_http_err_ctr(s);
5397
5398 if (objt_server(s->target))
5399 HA_ATOMIC_ADD(&objt_server(s->target)->counters.p.http.rsp[n], 1);
5400
5401 /* RFC7230#2.6 has enforced the format of the HTTP version string to be
5402 * exactly one digit "." one digit. This check may be disabled using
5403 * option accept-invalid-http-response.
5404 */
5405 if (!(s->be->options2 & PR_O2_RSPBUG_OK)) {
5406 if (msg->sl.st.v_l != 8) {
5407 msg->err_pos = 0;
5408 goto hdr_response_bad;
5409 }
5410
5411 if (rep->buf->p[4] != '/' ||
5412 !isdigit((unsigned char)rep->buf->p[5]) ||
5413 rep->buf->p[6] != '.' ||
5414 !isdigit((unsigned char)rep->buf->p[7])) {
5415 msg->err_pos = 4;
5416 goto hdr_response_bad;
5417 }
5418 }
5419
5420 /* check if the response is HTTP/1.1 or above */
5421 if ((msg->sl.st.v_l == 8) &&
5422 ((rep->buf->p[5] > '1') ||
5423 ((rep->buf->p[5] == '1') && (rep->buf->p[7] >= '1'))))
5424 msg->flags |= HTTP_MSGF_VER_11;
5425
5426 /* "connection" has not been parsed yet */
5427 txn->flags &= ~(TX_HDR_CONN_PRS|TX_HDR_CONN_CLO|TX_HDR_CONN_KAL|TX_HDR_CONN_UPG|TX_CON_CLO_SET|TX_CON_KAL_SET);
5428
5429 /* transfer length unknown*/
5430 msg->flags &= ~HTTP_MSGF_XFER_LEN;
5431
5432 txn->status = strl2ui(rep->buf->p + msg->sl.st.c, msg->sl.st.c_l);
5433
5434 /* Adjust server's health based on status code. Note: status codes 501
5435 * and 505 are triggered on demand by client request, so we must not
5436 * count them as server failures.
5437 */
5438 if (objt_server(s->target)) {
5439 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
5440 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
5441 else
5442 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
5443 }
5444
5445 /*
5446 * We may be facing a 100-continue response, or any other informational
5447 * 1xx response which is non-final, in which case this is not the right
5448 * response, and we're waiting for the next one. Let's allow this response
5449 * to go to the client and wait for the next one. There's an exception for
5450 * 101 which is used later in the code to switch protocols.
5451 */
5452 if (txn->status < 200 &&
5453 (txn->status == 100 || txn->status >= 102)) {
5454 hdr_idx_init(&txn->hdr_idx);
5455 msg->next -= channel_forward(rep, msg->next);
5456 msg->msg_state = HTTP_MSG_RPBEFORE;
5457 txn->status = 0;
5458 s->logs.t_data = -1; /* was not a response yet */
5459 FLT_STRM_CB(s, flt_http_reset(s, msg));
5460 goto next_one;
5461 }
5462
5463 /*
5464 * 2: check for cacheability.
5465 */
5466
5467 switch (txn->status) {
5468 case 200:
5469 case 203:
5470 case 204:
5471 case 206:
5472 case 300:
5473 case 301:
5474 case 404:
5475 case 405:
5476 case 410:
5477 case 414:
5478 case 501:
5479 break;
5480 default:
5481 /* RFC7231#6.1:
5482 * Responses with status codes that are defined as
5483 * cacheable by default (e.g., 200, 203, 204, 206,
5484 * 300, 301, 404, 405, 410, 414, and 501 in this
5485 * specification) can be reused by a cache with
5486 * heuristic expiration unless otherwise indicated
5487 * by the method definition or explicit cache
5488 * controls [RFC7234]; all other status codes are
5489 * not cacheable by default.
5490 */
5491 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
5492 break;
5493 }
5494
5495 /*
5496 * 3: we may need to capture headers
5497 */
5498 s->logs.logwait &= ~LW_RESP;
5499 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
5500 capture_headers(rep->buf->p, &txn->hdr_idx,
5501 s->res_cap, sess->fe->rsp_cap);
5502
5503 /* 4: determine the transfer-length according to RFC2616 #4.4, updated
5504 * by RFC7230#3.3.3 :
5505 *
5506 * The length of a message body is determined by one of the following
5507 * (in order of precedence):
5508 *
5509 * 1. Any 2xx (Successful) response to a CONNECT request implies that
5510 * the connection will become a tunnel immediately after the empty
5511 * line that concludes the header fields. A client MUST ignore
5512 * any Content-Length or Transfer-Encoding header fields received
5513 * in such a message. Any 101 response (Switching Protocols) is
5514 * managed in the same manner.
5515 *
5516 * 2. Any response to a HEAD request and any response with a 1xx
5517 * (Informational), 204 (No Content), or 304 (Not Modified) status
5518 * code is always terminated by the first empty line after the
5519 * header fields, regardless of the header fields present in the
5520 * message, and thus cannot contain a message body.
5521 *
5522 * 3. If a Transfer-Encoding header field is present and the chunked
5523 * transfer coding (Section 4.1) is the final encoding, the message
5524 * body length is determined by reading and decoding the chunked
5525 * data until the transfer coding indicates the data is complete.
5526 *
5527 * If a Transfer-Encoding header field is present in a response and
5528 * the chunked transfer coding is not the final encoding, the
5529 * message body length is determined by reading the connection until
5530 * it is closed by the server. If a Transfer-Encoding header field
5531 * is present in a request and the chunked transfer coding is not
5532 * the final encoding, the message body length cannot be determined
5533 * reliably; the server MUST respond with the 400 (Bad Request)
5534 * status code and then close the connection.
5535 *
5536 * If a message is received with both a Transfer-Encoding and a
5537 * Content-Length header field, the Transfer-Encoding overrides the
5538 * Content-Length. Such a message might indicate an attempt to
5539 * perform request smuggling (Section 9.5) or response splitting
5540 * (Section 9.4) and ought to be handled as an error. A sender MUST
5541 * remove the received Content-Length field prior to forwarding such
5542 * a message downstream.
5543 *
5544 * 4. If a message is received without Transfer-Encoding and with
5545 * either multiple Content-Length header fields having differing
5546 * field-values or a single Content-Length header field having an
5547 * invalid value, then the message framing is invalid and the
5548 * recipient MUST treat it as an unrecoverable error. If this is a
5549 * request message, the server MUST respond with a 400 (Bad Request)
5550 * status code and then close the connection. If this is a response
5551 * message received by a proxy, the proxy MUST close the connection
5552 * to the server, discard the received response, and send a 502 (Bad
5553 * Gateway) response to the client. If this is a response message
5554 * received by a user agent, the user agent MUST close the
5555 * connection to the server and discard the received response.
5556 *
5557 * 5. If a valid Content-Length header field is present without
5558 * Transfer-Encoding, its decimal value defines the expected message
5559 * body length in octets. If the sender closes the connection or
5560 * the recipient times out before the indicated number of octets are
5561 * received, the recipient MUST consider the message to be
5562 * incomplete and close the connection.
5563 *
5564 * 6. If this is a request message and none of the above are true, then
5565 * the message body length is zero (no message body is present).
5566 *
5567 * 7. Otherwise, this is a response message without a declared message
5568 * body length, so the message body length is determined by the
5569 * number of octets received prior to the server closing the
5570 * connection.
5571 */
5572
5573 /* Skip parsing if no content length is possible. The response flags
5574 * remain 0 as well as the chunk_len, which may or may not mirror
5575 * the real header value, and we note that we know the response's length.
5576 * FIXME: should we parse anyway and return an error on chunked encoding ?
5577 */
5578 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
5579 txn->status == 101)) {
5580 /* Either we've established an explicit tunnel, or we're
5581 * switching the protocol. In both cases, we're very unlikely
5582 * to understand the next protocols. We have to switch to tunnel
5583 * mode, so that we transfer the request and responses then let
5584 * this protocol pass unmodified. When we later implement specific
5585 * parsers for such protocols, we'll want to check the Upgrade
5586 * header which contains information about that protocol for
5587 * responses with status 101 (eg: see RFC2817 about TLS).
5588 */
5589 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
5590 msg->flags |= HTTP_MSGF_XFER_LEN;
5591 goto end;
5592 }
5593
5594 if (txn->meth == HTTP_METH_HEAD ||
5595 (txn->status >= 100 && txn->status < 200) ||
5596 txn->status == 204 || txn->status == 304) {
5597 msg->flags |= HTTP_MSGF_XFER_LEN;
5598 goto skip_content_length;
5599 }
5600
5601 use_close_only = 0;
5602 ctx.idx = 0;
5603 while (http_find_header2("Transfer-Encoding", 17, rep->buf->p, &txn->hdr_idx, &ctx)) {
5604 if (ctx.vlen == 7 && strncasecmp(ctx.line + ctx.val, "chunked", 7) == 0)
5605 msg->flags |= (HTTP_MSGF_TE_CHNK | HTTP_MSGF_XFER_LEN);
5606 else if (msg->flags & HTTP_MSGF_TE_CHNK) {
5607 /* bad transfer-encoding (chunked followed by something else) */
5608 use_close_only = 1;
5609 msg->flags &= ~(HTTP_MSGF_TE_CHNK | HTTP_MSGF_XFER_LEN);
5610 break;
5611 }
5612 }
5613
5614 /* "chunked" mandatory if transfer-encoding is used */
5615 if (ctx.idx && !(msg->flags & HTTP_MSGF_TE_CHNK)) {
5616 use_close_only = 1;
5617 msg->flags &= ~(HTTP_MSGF_TE_CHNK | HTTP_MSGF_XFER_LEN);
5618 }
5619
5620 /* Chunked responses must have their content-length removed */
5621 ctx.idx = 0;
5622 if (use_close_only || (msg->flags & HTTP_MSGF_TE_CHNK)) {
5623 while (http_find_header2("Content-Length", 14, rep->buf->p, &txn->hdr_idx, &ctx))
5624 http_remove_header2(msg, &txn->hdr_idx, &ctx);
5625 }
5626 else while (http_find_header2("Content-Length", 14, rep->buf->p, &txn->hdr_idx, &ctx)) {
5627 signed long long cl;
5628
5629 if (!ctx.vlen) {
5630 msg->err_pos = ctx.line + ctx.val - rep->buf->p;
5631 goto hdr_response_bad;
5632 }
5633
5634 if (strl2llrc(ctx.line + ctx.val, ctx.vlen, &cl)) {
5635 msg->err_pos = ctx.line + ctx.val - rep->buf->p;
5636 goto hdr_response_bad; /* parse failure */
5637 }
5638
5639 if (cl < 0) {
5640 msg->err_pos = ctx.line + ctx.val - rep->buf->p;
5641 goto hdr_response_bad;
5642 }
5643
5644 if ((msg->flags & HTTP_MSGF_CNT_LEN) && (msg->chunk_len != cl)) {
5645 msg->err_pos = ctx.line + ctx.val - rep->buf->p;
5646 goto hdr_response_bad; /* already specified, was different */
5647 }
5648
5649 msg->flags |= HTTP_MSGF_CNT_LEN | HTTP_MSGF_XFER_LEN;
5650 msg->body_len = msg->chunk_len = cl;
5651 }
5652
5653 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
5654 * 407 (Proxy-Authenticate) responses and set the connection to private
5655 */
5656 if (srv_conn && txn->status == 401) {
5657 /* check for Negotiate/NTLM WWW-Authenticate headers */
5658 ctx.idx = 0;
5659 while (http_find_header2("WWW-Authenticate", 16, rep->buf->p, &txn->hdr_idx, &ctx)) {
5660 /* If www-authenticate contains "Negotiate", "Nego2", or "NTLM",
5661 * possibly followed by blanks and a base64 string, the connection
5662 * is private. Since it's a mess to deal with, we only check for
5663 * values starting with "NTLM" or "Nego". Note that often multiple
5664 * headers are sent by the server there.
5665 */
5666 if ((ctx.vlen >= 4 && strncasecmp(ctx.line + ctx.val, "Nego", 4)) ||
5667 (ctx.vlen >= 4 && strncasecmp(ctx.line + ctx.val, "NTLM", 4)))
5668 srv_conn->flags |= CO_FL_PRIVATE;
5669 }
5670 } else if (srv_conn && txn->status == 407) {
5671 /* check for Negotiate/NTLM Proxy-Authenticate headers */
5672 ctx.idx = 0;
5673 while (http_find_header2("Proxy-Authenticate", 18, rep->buf->p, &txn->hdr_idx, &ctx)) {
5674 if ((ctx.vlen >= 4 && strncasecmp(ctx.line + ctx.val, "Nego", 4)) ||
5675 (ctx.vlen >= 4 && strncasecmp(ctx.line + ctx.val, "NTLM", 4)))
5676 srv_conn->flags |= CO_FL_PRIVATE;
5677 }
5678 }
5679
5680 skip_content_length:
5681 /* Now we have to check if we need to modify the Connection header.
5682 * This is more difficult on the response than it is on the request,
5683 * because we can have two different HTTP versions and we don't know
5684 * how the client will interprete a response. For instance, let's say
5685 * that the client sends a keep-alive request in HTTP/1.0 and gets an
5686 * HTTP/1.1 response without any header. Maybe it will bound itself to
5687 * HTTP/1.0 because it only knows about it, and will consider the lack
5688 * of header as a close, or maybe it knows HTTP/1.1 and can consider
5689 * the lack of header as a keep-alive. Thus we will use two flags
5690 * indicating how a request MAY be understood by the client. In case
5691 * of multiple possibilities, we'll fix the header to be explicit. If
5692 * ambiguous cases such as both close and keepalive are seen, then we
5693 * will fall back to explicit close. Note that we won't take risks with
5694 * HTTP/1.0 clients which may not necessarily understand keep-alive.
5695 * See doc/internals/connection-header.txt for the complete matrix.
5696 */
5697 if ((txn->status >= 200) && !(txn->flags & TX_HDR_CONN_PRS) &&
5698 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN ||
5699 ((sess->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||
5700 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL))) {
5701 int to_del = 0;
5702
5703 /* this situation happens when combining pretend-keepalive with httpclose. */
5704 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL &&
5705 ((sess->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||
5706 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL))
5707 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
5708
5709 /* on unknown transfer length, we must close */
5710 if (!(msg->flags & HTTP_MSGF_XFER_LEN) &&
5711 (txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
5712 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
5713
5714 /* now adjust header transformations depending on current state */
5715 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN ||
5716 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_CLO) {
5717 to_del |= 2; /* remove "keep-alive" on any response */
5718 if (!(msg->flags & HTTP_MSGF_VER_11))
5719 to_del |= 1; /* remove "close" for HTTP/1.0 responses */
5720 }
5721 else { /* SCL / KAL */
5722 to_del |= 1; /* remove "close" on any response */
5723 if (txn->req.flags & msg->flags & HTTP_MSGF_VER_11)
5724 to_del |= 2; /* remove "keep-alive" on pure 1.1 responses */
5725 }
5726
5727 /* Parse and remove some headers from the connection header */
5728 http_parse_connection_header(txn, msg, to_del);
5729
5730 /* Some keep-alive responses are converted to Server-close if
5731 * the server wants to close.
5732 */
5733 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL) {
5734 if ((txn->flags & TX_HDR_CONN_CLO) ||
5735 (!(txn->flags & TX_HDR_CONN_KAL) && !(msg->flags & HTTP_MSGF_VER_11)))
5736 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
5737 }
5738 }
5739
5740 end:
5741 /* we want to have the response time before we start processing it */
5742 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
5743
5744 /* end of job, return OK */
5745 rep->analysers &= ~an_bit;
5746 rep->analyse_exp = TICK_ETERNITY;
5747 channel_auto_close(rep);
5748 return 1;
5749
5750 abort_keep_alive:
5751 /* A keep-alive request to the server failed on a network error.
5752 * The client is required to retry. We need to close without returning
5753 * any other information so that the client retries.
5754 */
5755 txn->status = 0;
5756 rep->analysers &= AN_RES_FLT_END;
5757 s->req.analysers &= AN_REQ_FLT_END;
5758 rep->analyse_exp = TICK_ETERNITY;
5759 channel_auto_close(rep);
5760 s->logs.logwait = 0;
5761 s->logs.level = 0;
5762 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
5763 channel_truncate(rep);
5764 http_reply_and_close(s, txn->status, NULL);
5765 return 0;
5766 }
5767
5768 /* This function performs all the processing enabled for the current response.
5769 * It normally returns 1 unless it wants to break. It relies on buffers flags,
5770 * and updates s->res.analysers. It might make sense to explode it into several
5771 * other functions. It works like process_request (see indications above).
5772 */
http_process_res_common(struct stream * s,struct channel * rep,int an_bit,struct proxy * px)5773 int http_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
5774 {
5775 struct session *sess = s->sess;
5776 struct http_txn *txn = s->txn;
5777 struct http_msg *msg = &txn->rsp;
5778 struct proxy *cur_proxy;
5779 struct cond_wordlist *wl;
5780 enum rule_result ret = HTTP_RULE_RES_CONT;
5781
5782 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n",
5783 now_ms, __FUNCTION__,
5784 s,
5785 rep,
5786 rep->rex, rep->wex,
5787 rep->flags,
5788 rep->buf->i,
5789 rep->analysers);
5790
5791 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
5792 return 0;
5793
5794 /* The stats applet needs to adjust the Connection header but we don't
5795 * apply any filter there.
5796 */
5797 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
5798 rep->analysers &= ~an_bit;
5799 rep->analyse_exp = TICK_ETERNITY;
5800 goto skip_filters;
5801 }
5802
5803 /*
5804 * We will have to evaluate the filters.
5805 * As opposed to version 1.2, now they will be evaluated in the
5806 * filters order and not in the header order. This means that
5807 * each filter has to be validated among all headers.
5808 *
5809 * Filters are tried with ->be first, then with ->fe if it is
5810 * different from ->be.
5811 *
5812 * Maybe we are in resume condiion. In this case I choose the
5813 * "struct proxy" which contains the rule list matching the resume
5814 * pointer. If none of theses "struct proxy" match, I initialise
5815 * the process with the first one.
5816 *
5817 * In fact, I check only correspondance betwwen the current list
5818 * pointer and the ->fe rule list. If it doesn't match, I initialize
5819 * the loop with the ->be.
5820 */
5821 if (s->current_rule_list == &sess->fe->http_res_rules)
5822 cur_proxy = sess->fe;
5823 else
5824 cur_proxy = s->be;
5825 while (1) {
5826 struct proxy *rule_set = cur_proxy;
5827
5828 /* evaluate http-response rules */
5829 if (ret == HTTP_RULE_RES_CONT) {
5830 ret = http_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
5831
5832 if (ret == HTTP_RULE_RES_BADREQ)
5833 goto return_srv_prx_502;
5834
5835 if (ret == HTTP_RULE_RES_DONE) {
5836 rep->analysers &= ~an_bit;
5837 rep->analyse_exp = TICK_ETERNITY;
5838 return 1;
5839 }
5840 }
5841
5842 /* we need to be called again. */
5843 if (ret == HTTP_RULE_RES_YIELD) {
5844 channel_dont_close(rep);
5845 return 0;
5846 }
5847
5848 /* try headers filters */
5849 if (rule_set->rsp_exp != NULL) {
5850 if (apply_filters_to_response(s, rep, rule_set) < 0) {
5851 return_bad_resp:
5852 if (objt_server(s->target)) {
5853 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
5854 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
5855 }
5856 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
5857 return_srv_prx_502:
5858 rep->analysers &= AN_RES_FLT_END;
5859 s->req.analysers &= AN_REQ_FLT_END;
5860 rep->analyse_exp = TICK_ETERNITY;
5861 txn->status = 502;
5862 s->logs.t_data = -1; /* was not a valid response */
5863 s->si[1].flags |= SI_FL_NOLINGER;
5864 channel_truncate(rep);
5865 http_reply_and_close(s, txn->status, http_error_message(s));
5866 if (!(s->flags & SF_ERR_MASK))
5867 s->flags |= SF_ERR_PRXCOND;
5868 if (!(s->flags & SF_FINST_MASK))
5869 s->flags |= SF_FINST_H;
5870 return 0;
5871 }
5872 }
5873
5874 /* has the response been denied ? */
5875 if (txn->flags & TX_SVDENY) {
5876 if (objt_server(s->target))
5877 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
5878
5879 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
5880 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
5881 if (sess->listener && sess->listener->counters)
5882 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
5883
5884 goto return_srv_prx_502;
5885 }
5886
5887 /* add response headers from the rule sets in the same order */
5888 list_for_each_entry(wl, &rule_set->rsp_add, list) {
5889 if (txn->status < 200 && txn->status != 101)
5890 break;
5891 if (wl->cond) {
5892 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
5893 ret = acl_pass(ret);
5894 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
5895 ret = !ret;
5896 if (!ret)
5897 continue;
5898 }
5899 if (unlikely(http_header_add_tail(&txn->rsp, &txn->hdr_idx, wl->s) < 0))
5900 goto return_bad_resp;
5901 }
5902
5903 /* check whether we're already working on the frontend */
5904 if (cur_proxy == sess->fe)
5905 break;
5906 cur_proxy = sess->fe;
5907 }
5908
5909 /* After this point, this anayzer can't return yield, so we can
5910 * remove the bit corresponding to this analyzer from the list.
5911 *
5912 * Note that the intermediate returns and goto found previously
5913 * reset the analyzers.
5914 */
5915 rep->analysers &= ~an_bit;
5916 rep->analyse_exp = TICK_ETERNITY;
5917
5918 /* OK that's all we can do for 1xx responses */
5919 if (unlikely(txn->status < 200 && txn->status != 101))
5920 goto skip_header_mangling;
5921
5922 /*
5923 * Now check for a server cookie.
5924 */
5925 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
5926 manage_server_side_cookies(s, rep);
5927
5928 /*
5929 * Check for cache-control or pragma headers if required.
5930 */
5931 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
5932 check_response_for_cacheability(s, rep);
5933
5934 /*
5935 * Add server cookie in the response if needed
5936 */
5937 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
5938 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
5939 (!(s->flags & SF_DIRECT) ||
5940 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
5941 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
5942 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
5943 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
5944 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
5945 !(s->flags & SF_IGNORE_PRST)) {
5946 /* the server is known, it's not the one the client requested, or the
5947 * cookie's last seen date needs to be refreshed. We have to
5948 * insert a set-cookie here, except if we want to insert only on POST
5949 * requests and this one isn't. Note that servers which don't have cookies
5950 * (eg: some backup servers) will return a full cookie removal request.
5951 */
5952 if (!objt_server(s->target)->cookie) {
5953 chunk_printf(&trash,
5954 "Set-Cookie: %s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
5955 s->be->cookie_name);
5956 }
5957 else {
5958 chunk_printf(&trash, "Set-Cookie: %s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
5959
5960 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
5961 /* emit last_date, which is mandatory */
5962 trash.str[trash.len++] = COOKIE_DELIM_DATE;
5963 s30tob64((date.tv_sec+3) >> 2, trash.str + trash.len);
5964 trash.len += 5;
5965
5966 if (s->be->cookie_maxlife) {
5967 /* emit first_date, which is either the original one or
5968 * the current date.
5969 */
5970 trash.str[trash.len++] = COOKIE_DELIM_DATE;
5971 s30tob64(txn->cookie_first_date ?
5972 txn->cookie_first_date >> 2 :
5973 (date.tv_sec+3) >> 2, trash.str + trash.len);
5974 trash.len += 5;
5975 }
5976 }
5977 chunk_appendf(&trash, "; path=/");
5978 }
5979
5980 if (s->be->cookie_domain)
5981 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
5982
5983 if (s->be->ck_opts & PR_CK_HTTPONLY)
5984 chunk_appendf(&trash, "; HttpOnly");
5985
5986 if (s->be->ck_opts & PR_CK_SECURE)
5987 chunk_appendf(&trash, "; Secure");
5988
5989 if (s->be->cookie_attrs)
5990 chunk_appendf(&trash, "; %s", s->be->cookie_attrs);
5991
5992 if (unlikely(http_header_add_tail2(&txn->rsp, &txn->hdr_idx, trash.str, trash.len) < 0))
5993 goto return_bad_resp;
5994
5995 txn->flags &= ~TX_SCK_MASK;
5996 if (objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
5997 /* the server did not change, only the date was updated */
5998 txn->flags |= TX_SCK_UPDATED;
5999 else
6000 txn->flags |= TX_SCK_INSERTED;
6001
6002 /* Here, we will tell an eventual cache on the client side that we don't
6003 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
6004 * Some caches understand the correct form: 'no-cache="set-cookie"', but
6005 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
6006 */
6007 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
6008
6009 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
6010
6011 if (unlikely(http_header_add_tail2(&txn->rsp, &txn->hdr_idx,
6012 "Cache-control: private", 22) < 0))
6013 goto return_bad_resp;
6014 }
6015 }
6016
6017 /*
6018 * Check if result will be cacheable with a cookie.
6019 * We'll block the response if security checks have caught
6020 * nasty things such as a cacheable cookie.
6021 */
6022 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
6023 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
6024 (s->be->options & PR_O_CHK_CACHE)) {
6025 /* we're in presence of a cacheable response containing
6026 * a set-cookie header. We'll block it as requested by
6027 * the 'checkcache' option, and send an alert.
6028 */
6029 if (objt_server(s->target))
6030 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
6031
6032 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
6033 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
6034 if (sess->listener && sess->listener->counters)
6035 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
6036
6037 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
6038 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
6039 send_log(s->be, LOG_ALERT,
6040 "Blocking cacheable cookie in response from instance %s, server %s.\n",
6041 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
6042 goto return_srv_prx_502;
6043 }
6044
6045 skip_filters:
6046 /*
6047 * Adjust "Connection: close" or "Connection: keep-alive" if needed.
6048 * If an "Upgrade" token is found, the header is left untouched in order
6049 * not to have to deal with some client bugs : some of them fail an upgrade
6050 * if anything but "Upgrade" is present in the Connection header. We don't
6051 * want to touch any 101 response either since it's switching to another
6052 * protocol.
6053 */
6054 if ((txn->status != 101) && !(txn->flags & TX_HDR_CONN_UPG) &&
6055 (((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN) ||
6056 ((sess->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||
6057 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL))) {
6058 unsigned int want_flags = 0;
6059
6060 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL ||
6061 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) {
6062 /* we want a keep-alive response here. Keep-alive header
6063 * required if either side is not 1.1.
6064 */
6065 if (!(txn->req.flags & msg->flags & HTTP_MSGF_VER_11))
6066 want_flags |= TX_CON_KAL_SET;
6067 }
6068 else {
6069 /* we want a close response here. Close header required if
6070 * the server is 1.1, regardless of the client.
6071 */
6072 if (msg->flags & HTTP_MSGF_VER_11)
6073 want_flags |= TX_CON_CLO_SET;
6074 }
6075
6076 if (want_flags != (txn->flags & (TX_CON_CLO_SET|TX_CON_KAL_SET)))
6077 http_change_connection_header(txn, msg, want_flags);
6078 }
6079
6080 skip_header_mangling:
6081 /* Always enter in the body analyzer */
6082 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
6083 rep->analysers |= AN_RES_HTTP_XFER_BODY;
6084
6085 /* if the user wants to log as soon as possible, without counting
6086 * bytes from the server, then this is the right moment. We have
6087 * to temporarily assign bytes_out to log what we currently have.
6088 */
6089 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
6090 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
6091 s->logs.bytes_out = txn->rsp.eoh;
6092 s->do_log(s);
6093 s->logs.bytes_out = 0;
6094 }
6095 return 1;
6096 }
6097
6098 /* This function is an analyser which forwards response body (including chunk
6099 * sizes if any). It is called as soon as we must forward, even if we forward
6100 * zero byte. The only situation where it must not be called is when we're in
6101 * tunnel mode and we want to forward till the close. It's used both to forward
6102 * remaining data and to resync after end of body. It expects the msg_state to
6103 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
6104 * read more data, or 1 once we can go on with next request or end the stream.
6105 *
6106 * It is capable of compressing response data both in content-length mode and
6107 * in chunked mode. The state machines follows different flows depending on
6108 * whether content-length and chunked modes are used, since there are no
6109 * trailers in content-length :
6110 *
6111 * chk-mode cl-mode
6112 * ,----- BODY -----.
6113 * / \
6114 * V size > 0 V chk-mode
6115 * .--> SIZE -------------> DATA -------------> CRLF
6116 * | | size == 0 | last byte |
6117 * | v final crlf v inspected |
6118 * | TRAILERS -----------> DONE |
6119 * | |
6120 * `----------------------------------------------'
6121 *
6122 * Compression only happens in the DATA state, and must be flushed in final
6123 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
6124 * is performed at once on final states for all bytes parsed, or when leaving
6125 * on missing data.
6126 */
http_response_forward_body(struct stream * s,struct channel * res,int an_bit)6127 int http_response_forward_body(struct stream *s, struct channel *res, int an_bit)
6128 {
6129 struct session *sess = s->sess;
6130 struct http_txn *txn = s->txn;
6131 struct http_msg *msg = &s->txn->rsp;
6132 int ret;
6133
6134 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n",
6135 now_ms, __FUNCTION__,
6136 s,
6137 res,
6138 res->rex, res->wex,
6139 res->flags,
6140 res->buf->i,
6141 res->analysers);
6142
6143 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
6144 return 0;
6145
6146 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
6147 ((res->flags & CF_SHUTW) && (res->to_forward || res->buf->o)) ||
6148 !s->req.analysers) {
6149 /* Output closed while we were sending data. We must abort and
6150 * wake the other side up.
6151 */
6152 msg->err_state = msg->msg_state;
6153 msg->msg_state = HTTP_MSG_ERROR;
6154 http_resync_states(s);
6155 return 1;
6156 }
6157
6158 /* in most states, we should abort in case of early close */
6159 channel_auto_close(res);
6160
6161 if (msg->msg_state == HTTP_MSG_BODY) {
6162 msg->msg_state = ((msg->flags & HTTP_MSGF_TE_CHNK)
6163 ? HTTP_MSG_CHUNK_SIZE
6164 : HTTP_MSG_DATA);
6165 }
6166
6167 if (res->to_forward) {
6168 /* We can't process the buffer's contents yet */
6169 res->flags |= CF_WAKE_WRITE;
6170 goto missing_data_or_waiting;
6171 }
6172
6173 if (msg->msg_state < HTTP_MSG_DONE) {
6174 ret = ((msg->flags & HTTP_MSGF_TE_CHNK)
6175 ? http_msg_forward_chunked_body(s, msg)
6176 : http_msg_forward_body(s, msg));
6177 if (!ret)
6178 goto missing_data_or_waiting;
6179 if (ret < 0)
6180 goto return_bad_res;
6181 }
6182
6183 /* other states, DONE...TUNNEL */
6184 /* for keep-alive we don't want to forward closes on DONE */
6185 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL ||
6186 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL)
6187 channel_dont_close(res);
6188
6189 http_resync_states(s);
6190 if (!(res->analysers & an_bit)) {
6191 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
6192 if (res->flags & CF_SHUTW) {
6193 /* response errors are most likely due to the
6194 * client aborting the transfer. */
6195 goto aborted_xfer;
6196 }
6197 if (msg->err_pos >= 0)
6198 http_capture_bad_message(s->be, &s->be->invalid_rep, s, msg, msg->err_state, strm_fe(s));
6199 goto return_bad_res;
6200 }
6201 return 1;
6202 }
6203 return 0;
6204
6205 missing_data_or_waiting:
6206 if (res->flags & CF_SHUTW)
6207 goto aborted_xfer;
6208
6209 /* stop waiting for data if the input is closed before the end. If the
6210 * client side was already closed, it means that the client has aborted,
6211 * so we don't want to count this as a server abort. Otherwise it's a
6212 * server abort.
6213 */
6214 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
6215 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
6216 goto aborted_xfer;
6217 /* If we have some pending data, we continue the processing */
6218 if (!buffer_pending(res->buf)) {
6219 if (!(s->flags & SF_ERR_MASK))
6220 s->flags |= SF_ERR_SRVCL;
6221 HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
6222 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
6223 if (objt_server(s->target))
6224 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
6225 goto return_bad_res_stats_ok;
6226 }
6227 }
6228
6229 /* we need to obey the req analyser, so if it leaves, we must too */
6230 if (!s->req.analysers)
6231 goto return_bad_res;
6232
6233 /* When TE: chunked is used, we need to get there again to parse
6234 * remaining chunks even if the server has closed, so we don't want to
6235 * set CF_DONTCLOSE. Similarly, if keep-alive is set on the client side
6236 * or if there are filters registered on the stream, we don't want to
6237 * forward a close
6238 */
6239 if ((msg->flags & HTTP_MSGF_TE_CHNK) ||
6240 HAS_DATA_FILTERS(s, res) ||
6241 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL ||
6242 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL)
6243 channel_dont_close(res);
6244
6245 /* We know that more data are expected, but we couldn't send more that
6246 * what we did. So we always set the CF_EXPECT_MORE flag so that the
6247 * system knows it must not set a PUSH on this first part. Interactive
6248 * modes are already handled by the stream sock layer. We must not do
6249 * this in content-length mode because it could present the MSG_MORE
6250 * flag with the last block of forwarded data, which would cause an
6251 * additional delay to be observed by the receiver.
6252 */
6253 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
6254 res->flags |= CF_EXPECT_MORE;
6255
6256 /* the stream handler will take care of timeouts and errors */
6257 return 0;
6258
6259 return_bad_res: /* let's centralize all bad responses */
6260 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
6261 if (objt_server(s->target))
6262 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
6263
6264 return_bad_res_stats_ok:
6265 txn->rsp.err_state = txn->rsp.msg_state;
6266 txn->rsp.msg_state = HTTP_MSG_ERROR;
6267 /* don't send any error message as we're in the body */
6268 http_reply_and_close(s, txn->status, NULL);
6269 res->analysers &= AN_RES_FLT_END;
6270 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
6271 if (objt_server(s->target))
6272 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
6273
6274 if (!(s->flags & SF_ERR_MASK))
6275 s->flags |= SF_ERR_PRXCOND;
6276 if (!(s->flags & SF_FINST_MASK))
6277 s->flags |= SF_FINST_D;
6278 return 0;
6279
6280 aborted_xfer:
6281 txn->rsp.err_state = txn->rsp.msg_state;
6282 txn->rsp.msg_state = HTTP_MSG_ERROR;
6283 /* don't send any error message as we're in the body */
6284 http_reply_and_close(s, txn->status, NULL);
6285 res->analysers &= AN_RES_FLT_END;
6286 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
6287
6288 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
6289 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
6290 if (objt_server(s->target))
6291 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
6292
6293 if (!(s->flags & SF_ERR_MASK))
6294 s->flags |= SF_ERR_CLICL;
6295 if (!(s->flags & SF_FINST_MASK))
6296 s->flags |= SF_FINST_D;
6297 return 0;
6298 }
6299
6300
6301 static inline int
http_msg_forward_body(struct stream * s,struct http_msg * msg)6302 http_msg_forward_body(struct stream *s, struct http_msg *msg)
6303 {
6304 struct channel *chn = msg->chn;
6305 int ret;
6306
6307 /* Here we have the guarantee to be in HTTP_MSG_DATA or HTTP_MSG_ENDING state */
6308
6309 if (msg->msg_state == HTTP_MSG_ENDING)
6310 goto ending;
6311
6312 /* Neither content-length, nor transfer-encoding was found, so we must
6313 * read the body until the server connection is closed. In that case, we
6314 * eat data as they come. Of course, this happens for response only. */
6315 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
6316 unsigned long long len = (chn->buf->i - msg->next);
6317 msg->chunk_len += len;
6318 msg->body_len += len;
6319 }
6320 ret = FLT_STRM_DATA_CB(s, chn, flt_http_data(s, msg),
6321 /* default_ret */ MIN(msg->chunk_len, chn->buf->i - msg->next),
6322 /* on_error */ goto error);
6323 msg->next += ret;
6324 msg->chunk_len -= ret;
6325 if (msg->chunk_len) {
6326 /* input empty or output full */
6327 if (chn->buf->i > msg->next)
6328 chn->flags |= CF_WAKE_WRITE;
6329 goto missing_data_or_waiting;
6330 }
6331
6332 /* This check can only be true for a response. HTTP_MSGF_XFER_LEN is
6333 * always set for a request. */
6334 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
6335 /* The server still sending data that should be filtered */
6336 if (!(chn->flags & CF_SHUTR) && HAS_DATA_FILTERS(s, chn))
6337 goto missing_data_or_waiting;
6338 msg->msg_state = HTTP_MSG_TUNNEL;
6339 goto ending;
6340 }
6341
6342 msg->msg_state = HTTP_MSG_ENDING;
6343
6344 ending:
6345 /* we may have some pending data starting at res->buf->p such as a last
6346 * chunk of data or trailers. */
6347 ret = FLT_STRM_DATA_CB(s, chn, flt_http_forward_data(s, msg, msg->next),
6348 /* default_ret */ msg->next,
6349 /* on_error */ goto error);
6350 b_adv(chn->buf, ret);
6351 msg->next -= ret;
6352 if (unlikely(!(chn->flags & CF_WROTE_DATA) || msg->sov > 0))
6353 msg->sov -= ret;
6354 if (msg->next)
6355 goto waiting;
6356
6357 FLT_STRM_DATA_CB(s, chn, flt_http_end(s, msg),
6358 /* default_ret */ 1,
6359 /* on_error */ goto error,
6360 /* on_wait */ goto waiting);
6361 if (msg->msg_state == HTTP_MSG_ENDING)
6362 msg->msg_state = HTTP_MSG_DONE;
6363 return 1;
6364
6365 missing_data_or_waiting:
6366 /* we may have some pending data starting at chn->buf->p */
6367 ret = FLT_STRM_DATA_CB(s, chn, flt_http_forward_data(s, msg, msg->next),
6368 /* default_ret */ msg->next,
6369 /* on_error */ goto error);
6370 b_adv(chn->buf, ret);
6371 msg->next -= ret;
6372 if (!(chn->flags & CF_WROTE_DATA) || msg->sov > 0)
6373 msg->sov -= ret;
6374 if (!HAS_DATA_FILTERS(s, chn))
6375 msg->chunk_len -= channel_forward(chn, msg->chunk_len);
6376 waiting:
6377 return 0;
6378 error:
6379 return -1;
6380 }
6381
6382 static inline int
http_msg_forward_chunked_body(struct stream * s,struct http_msg * msg)6383 http_msg_forward_chunked_body(struct stream *s, struct http_msg *msg)
6384 {
6385 struct channel *chn = msg->chn;
6386 unsigned int chunk;
6387 int ret;
6388
6389 /* Here we have the guarantee to be in one of the following state:
6390 * HTTP_MSG_DATA, HTTP_MSG_CHUNK_SIZE, HTTP_MSG_CHUNK_CRLF,
6391 * HTTP_MSG_TRAILERS or HTTP_MSG_ENDING. */
6392
6393 switch_states:
6394 switch (msg->msg_state) {
6395 case HTTP_MSG_DATA:
6396 ret = FLT_STRM_DATA_CB(s, chn, flt_http_data(s, msg),
6397 /* default_ret */ MIN(msg->chunk_len, chn->buf->i - msg->next),
6398 /* on_error */ goto error);
6399 msg->next += ret;
6400 msg->chunk_len -= ret;
6401 if (msg->chunk_len) {
6402 /* input empty or output full */
6403 if (chn->buf->i > msg->next)
6404 chn->flags |= CF_WAKE_WRITE;
6405 goto missing_data_or_waiting;
6406 }
6407
6408 /* nothing left to forward for this chunk*/
6409 msg->msg_state = HTTP_MSG_CHUNK_CRLF;
6410 /* fall through for HTTP_MSG_CHUNK_CRLF */
6411
6412 case HTTP_MSG_CHUNK_CRLF:
6413 /* we want the CRLF after the data */
6414 ret = h1_skip_chunk_crlf(chn->buf, msg->next, chn->buf->i);
6415 if (ret == 0)
6416 goto missing_data_or_waiting;
6417 if (ret < 0) {
6418 msg->err_pos = chn->buf->i + ret;
6419 if (msg->err_pos < 0)
6420 msg->err_pos += chn->buf->size;
6421 goto chunk_parsing_error;
6422 }
6423 msg->next += ret;
6424 msg->msg_state = HTTP_MSG_CHUNK_SIZE;
6425 /* fall through for HTTP_MSG_CHUNK_SIZE */
6426
6427 case HTTP_MSG_CHUNK_SIZE:
6428 /* read the chunk size and assign it to ->chunk_len,
6429 * then set ->next to point to the body and switch to
6430 * DATA or TRAILERS state.
6431 */
6432 ret = h1_parse_chunk_size(chn->buf, msg->next, chn->buf->i, &chunk);
6433 if (ret == 0)
6434 goto missing_data_or_waiting;
6435 if (ret < 0) {
6436 msg->err_pos = chn->buf->i + ret;
6437 if (msg->err_pos < 0)
6438 msg->err_pos += chn->buf->size;
6439 goto chunk_parsing_error;
6440 }
6441
6442 msg->sol = ret;
6443 msg->next += ret;
6444 msg->chunk_len = chunk;
6445 msg->body_len += chunk;
6446
6447 if (msg->chunk_len) {
6448 msg->msg_state = HTTP_MSG_DATA;
6449 goto switch_states;
6450 }
6451 msg->msg_state = HTTP_MSG_TRAILERS;
6452 /* fall through for HTTP_MSG_TRAILERS */
6453
6454 case HTTP_MSG_TRAILERS:
6455 ret = http_forward_trailers(msg);
6456 if (ret < 0)
6457 goto chunk_parsing_error;
6458 FLT_STRM_DATA_CB(s, chn, flt_http_chunk_trailers(s, msg),
6459 /* default_ret */ 1,
6460 /* on_error */ goto error);
6461 msg->next += msg->sol;
6462 if (!ret)
6463 goto missing_data_or_waiting;
6464 break;
6465
6466 case HTTP_MSG_ENDING:
6467 goto ending;
6468
6469 default:
6470 /* This should no happen in this function */
6471 goto error;
6472 }
6473
6474 msg->msg_state = HTTP_MSG_ENDING;
6475 ending:
6476 /* we may have some pending data starting at res->buf->p such as a last
6477 * chunk of data or trailers. */
6478 ret = FLT_STRM_DATA_CB(s, chn, flt_http_forward_data(s, msg, msg->next),
6479 /* default_ret */ msg->next,
6480 /* on_error */ goto error);
6481 b_adv(chn->buf, ret);
6482 msg->next -= ret;
6483 if (unlikely(!(chn->flags & CF_WROTE_DATA) || msg->sov > 0))
6484 msg->sov -= ret;
6485 if (msg->next)
6486 goto waiting;
6487
6488 FLT_STRM_DATA_CB(s, chn, flt_http_end(s, msg),
6489 /* default_ret */ 1,
6490 /* on_error */ goto error,
6491 /* on_wait */ goto waiting);
6492 msg->msg_state = HTTP_MSG_DONE;
6493 return 1;
6494
6495 missing_data_or_waiting:
6496 /* we may have some pending data starting at chn->buf->p */
6497 ret = FLT_STRM_DATA_CB(s, chn, flt_http_forward_data(s, msg, msg->next),
6498 /* default_ret */ msg->next,
6499 /* on_error */ goto error);
6500 b_adv(chn->buf, ret);
6501 msg->next -= ret;
6502 if (!(chn->flags & CF_WROTE_DATA) || msg->sov > 0)
6503 msg->sov -= ret;
6504 if (!HAS_DATA_FILTERS(s, chn))
6505 msg->chunk_len -= channel_forward(chn, msg->chunk_len);
6506 waiting:
6507 return 0;
6508
6509 chunk_parsing_error:
6510 if (msg->err_pos >= 0) {
6511 if (chn->flags & CF_ISRESP)
6512 http_capture_bad_message(s->be, &s->be->invalid_rep, s, msg,
6513 msg->msg_state, strm_fe(s));
6514 else
6515 http_capture_bad_message(strm_fe(s), &strm_fe(s)->invalid_req, s,
6516 msg, msg->msg_state, s->be);
6517 }
6518 error:
6519 return -1;
6520 }
6521
6522
6523 /* Iterate the same filter through all request headers.
6524 * Returns 1 if this filter can be stopped upon return, otherwise 0.
6525 * Since it can manage the switch to another backend, it updates the per-proxy
6526 * DENY stats.
6527 */
apply_filter_to_req_headers(struct stream * s,struct channel * req,struct hdr_exp * exp)6528 int apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
6529 {
6530 char *cur_ptr, *cur_end, *cur_next;
6531 int cur_idx, old_idx, last_hdr;
6532 struct http_txn *txn = s->txn;
6533 struct hdr_idx_elem *cur_hdr;
6534 int delta;
6535
6536 last_hdr = 0;
6537
6538 cur_next = req->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
6539 old_idx = 0;
6540
6541 while (!last_hdr) {
6542 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
6543 return 1;
6544 else if (unlikely(txn->flags & TX_CLALLOW) &&
6545 (exp->action == ACT_ALLOW ||
6546 exp->action == ACT_DENY ||
6547 exp->action == ACT_TARPIT))
6548 return 0;
6549
6550 cur_idx = txn->hdr_idx.v[old_idx].next;
6551 if (!cur_idx)
6552 break;
6553
6554 cur_hdr = &txn->hdr_idx.v[cur_idx];
6555 cur_ptr = cur_next;
6556 cur_end = cur_ptr + cur_hdr->len;
6557 cur_next = cur_end + cur_hdr->cr + 1;
6558
6559 /* Now we have one header between cur_ptr and cur_end,
6560 * and the next header starts at cur_next.
6561 */
6562
6563 if (regex_exec_match2(exp->preg, cur_ptr, cur_end-cur_ptr, MAX_MATCH, pmatch, 0)) {
6564 switch (exp->action) {
6565 case ACT_ALLOW:
6566 txn->flags |= TX_CLALLOW;
6567 last_hdr = 1;
6568 break;
6569
6570 case ACT_DENY:
6571 txn->flags |= TX_CLDENY;
6572 last_hdr = 1;
6573 break;
6574
6575 case ACT_TARPIT:
6576 txn->flags |= TX_CLTARPIT;
6577 last_hdr = 1;
6578 break;
6579
6580 case ACT_REPLACE:
6581 trash.len = exp_replace(trash.str, trash.size, cur_ptr, exp->replace, pmatch);
6582 if (trash.len < 0)
6583 return -1;
6584
6585 delta = buffer_replace2(req->buf, cur_ptr, cur_end, trash.str, trash.len);
6586 /* FIXME: if the user adds a newline in the replacement, the
6587 * index will not be recalculated for now, and the new line
6588 * will not be counted as a new header.
6589 */
6590
6591 cur_end += delta;
6592 cur_next += delta;
6593 cur_hdr->len += delta;
6594 http_msg_move_end(&txn->req, delta);
6595 break;
6596
6597 case ACT_REMOVE:
6598 delta = buffer_replace2(req->buf, cur_ptr, cur_next, NULL, 0);
6599 cur_next += delta;
6600
6601 http_msg_move_end(&txn->req, delta);
6602 txn->hdr_idx.v[old_idx].next = cur_hdr->next;
6603 txn->hdr_idx.used--;
6604 cur_hdr->len = 0;
6605 cur_end = NULL; /* null-term has been rewritten */
6606 cur_idx = old_idx;
6607 break;
6608
6609 }
6610 }
6611
6612 /* keep the link from this header to next one in case of later
6613 * removal of next header.
6614 */
6615 old_idx = cur_idx;
6616 }
6617 return 0;
6618 }
6619
6620
6621 /* Apply the filter to the request line.
6622 * Returns 0 if nothing has been done, 1 if the filter has been applied,
6623 * or -1 if a replacement resulted in an invalid request line.
6624 * Since it can manage the switch to another backend, it updates the per-proxy
6625 * DENY stats.
6626 */
apply_filter_to_req_line(struct stream * s,struct channel * req,struct hdr_exp * exp)6627 int apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
6628 {
6629 char *cur_ptr, *cur_end;
6630 int done;
6631 struct http_txn *txn = s->txn;
6632 int delta;
6633
6634 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
6635 return 1;
6636 else if (unlikely(txn->flags & TX_CLALLOW) &&
6637 (exp->action == ACT_ALLOW ||
6638 exp->action == ACT_DENY ||
6639 exp->action == ACT_TARPIT))
6640 return 0;
6641 else if (exp->action == ACT_REMOVE)
6642 return 0;
6643
6644 done = 0;
6645
6646 cur_ptr = req->buf->p;
6647 cur_end = cur_ptr + txn->req.sl.rq.l;
6648
6649 /* Now we have the request line between cur_ptr and cur_end */
6650
6651 if (regex_exec_match2(exp->preg, cur_ptr, cur_end-cur_ptr, MAX_MATCH, pmatch, 0)) {
6652 switch (exp->action) {
6653 case ACT_ALLOW:
6654 txn->flags |= TX_CLALLOW;
6655 done = 1;
6656 break;
6657
6658 case ACT_DENY:
6659 txn->flags |= TX_CLDENY;
6660 done = 1;
6661 break;
6662
6663 case ACT_TARPIT:
6664 txn->flags |= TX_CLTARPIT;
6665 done = 1;
6666 break;
6667
6668 case ACT_REPLACE:
6669 trash.len = exp_replace(trash.str, trash.size, cur_ptr, exp->replace, pmatch);
6670 if (trash.len < 0)
6671 return -1;
6672
6673 delta = buffer_replace2(req->buf, cur_ptr, cur_end, trash.str, trash.len);
6674 /* FIXME: if the user adds a newline in the replacement, the
6675 * index will not be recalculated for now, and the new line
6676 * will not be counted as a new header.
6677 */
6678
6679 http_msg_move_end(&txn->req, delta);
6680 cur_end += delta;
6681 cur_end = (char *)http_parse_reqline(&txn->req,
6682 HTTP_MSG_RQMETH,
6683 cur_ptr, cur_end + 1,
6684 NULL, NULL);
6685 if (unlikely(!cur_end))
6686 return -1;
6687
6688 /* we have a full request and we know that we have either a CR
6689 * or an LF at <ptr>.
6690 */
6691 txn->meth = find_http_meth(cur_ptr, txn->req.sl.rq.m_l);
6692 hdr_idx_set_start(&txn->hdr_idx, txn->req.sl.rq.l, *cur_end == '\r');
6693 /* there is no point trying this regex on headers */
6694 return 1;
6695 }
6696 }
6697 return done;
6698 }
6699
6700
6701
6702 /*
6703 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
6704 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
6705 * unparsable request. Since it can manage the switch to another backend, it
6706 * updates the per-proxy DENY stats.
6707 */
apply_filters_to_request(struct stream * s,struct channel * req,struct proxy * px)6708 int apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
6709 {
6710 struct session *sess = s->sess;
6711 struct http_txn *txn = s->txn;
6712 struct hdr_exp *exp;
6713
6714 for (exp = px->req_exp; exp; exp = exp->next) {
6715 int ret;
6716
6717 /*
6718 * The interleaving of transformations and verdicts
6719 * makes it difficult to decide to continue or stop
6720 * the evaluation.
6721 */
6722
6723 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
6724 break;
6725
6726 if ((txn->flags & TX_CLALLOW) &&
6727 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
6728 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
6729 continue;
6730
6731 /* if this filter had a condition, evaluate it now and skip to
6732 * next filter if the condition does not match.
6733 */
6734 if (exp->cond) {
6735 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
6736 ret = acl_pass(ret);
6737 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
6738 ret = !ret;
6739
6740 if (!ret)
6741 continue;
6742 }
6743
6744 /* Apply the filter to the request line. */
6745 ret = apply_filter_to_req_line(s, req, exp);
6746 if (unlikely(ret < 0))
6747 return -1;
6748
6749 if (likely(ret == 0)) {
6750 /* The filter did not match the request, it can be
6751 * iterated through all headers.
6752 */
6753 if (unlikely(apply_filter_to_req_headers(s, req, exp) < 0))
6754 return -1;
6755 }
6756 }
6757 return 0;
6758 }
6759
6760
6761 /* Find the end of a cookie value contained between <s> and <e>. It works the
6762 * same way as with headers above except that the semi-colon also ends a token.
6763 * See RFC2965 for more information. Note that it requires a valid header to
6764 * return a valid result.
6765 */
find_cookie_value_end(char * s,const char * e)6766 char *find_cookie_value_end(char *s, const char *e)
6767 {
6768 int quoted, qdpair;
6769
6770 quoted = qdpair = 0;
6771 for (; s < e; s++) {
6772 if (qdpair) qdpair = 0;
6773 else if (quoted) {
6774 if (*s == '\\') qdpair = 1;
6775 else if (*s == '"') quoted = 0;
6776 }
6777 else if (*s == '"') quoted = 1;
6778 else if (*s == ',' || *s == ';') return s;
6779 }
6780 return s;
6781 }
6782
6783 /* Delete a value in a header between delimiters <from> and <next> in buffer
6784 * <buf>. The number of characters displaced is returned, and the pointer to
6785 * the first delimiter is updated if required. The function tries as much as
6786 * possible to respect the following principles :
6787 * - replace <from> delimiter by the <next> one unless <from> points to a
6788 * colon, in which case <next> is simply removed
6789 * - set exactly one space character after the new first delimiter, unless
6790 * there are not enough characters in the block being moved to do so.
6791 * - remove unneeded spaces before the previous delimiter and after the new
6792 * one.
6793 *
6794 * It is the caller's responsibility to ensure that :
6795 * - <from> points to a valid delimiter or the colon ;
6796 * - <next> points to a valid delimiter or the final CR/LF ;
6797 * - there are non-space chars before <from> ;
6798 * - there is a CR/LF at or after <next>.
6799 */
del_hdr_value(struct buffer * buf,char ** from,char * next)6800 int del_hdr_value(struct buffer *buf, char **from, char *next)
6801 {
6802 char *prev = *from;
6803
6804 if (*prev == ':') {
6805 /* We're removing the first value, preserve the colon and add a
6806 * space if possible.
6807 */
6808 if (!HTTP_IS_CRLF(*next))
6809 next++;
6810 prev++;
6811 if (prev < next)
6812 *prev++ = ' ';
6813
6814 while (HTTP_IS_SPHT(*next))
6815 next++;
6816 } else {
6817 /* Remove useless spaces before the old delimiter. */
6818 while (HTTP_IS_SPHT(*(prev-1)))
6819 prev--;
6820 *from = prev;
6821
6822 /* copy the delimiter and if possible a space if we're
6823 * not at the end of the line.
6824 */
6825 if (!HTTP_IS_CRLF(*next)) {
6826 *prev++ = *next++;
6827 if (prev + 1 < next)
6828 *prev++ = ' ';
6829 while (HTTP_IS_SPHT(*next))
6830 next++;
6831 }
6832 }
6833 return buffer_replace2(buf, prev, next, NULL, 0);
6834 }
6835
6836 /*
6837 * Manage client-side cookie. It can impact performance by about 2% so it is
6838 * desirable to call it only when needed. This code is quite complex because
6839 * of the multiple very crappy and ambiguous syntaxes we have to support. it
6840 * highly recommended not to touch this part without a good reason !
6841 */
manage_client_side_cookies(struct stream * s,struct channel * req)6842 void manage_client_side_cookies(struct stream *s, struct channel *req)
6843 {
6844 struct http_txn *txn = s->txn;
6845 struct session *sess = s->sess;
6846 int preserve_hdr;
6847 int cur_idx, old_idx;
6848 char *hdr_beg, *hdr_end, *hdr_next, *del_from;
6849 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
6850
6851 /* Iterate through the headers, we start with the start line. */
6852 old_idx = 0;
6853 hdr_next = req->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
6854
6855 while ((cur_idx = txn->hdr_idx.v[old_idx].next)) {
6856 struct hdr_idx_elem *cur_hdr;
6857 int val;
6858
6859 cur_hdr = &txn->hdr_idx.v[cur_idx];
6860 hdr_beg = hdr_next;
6861 hdr_end = hdr_beg + cur_hdr->len;
6862 hdr_next = hdr_end + cur_hdr->cr + 1;
6863
6864 /* We have one full header between hdr_beg and hdr_end, and the
6865 * next header starts at hdr_next. We're only interested in
6866 * "Cookie:" headers.
6867 */
6868
6869 val = http_header_match2(hdr_beg, hdr_end, "Cookie", 6);
6870 if (!val) {
6871 old_idx = cur_idx;
6872 continue;
6873 }
6874
6875 del_from = NULL; /* nothing to be deleted */
6876 preserve_hdr = 0; /* assume we may kill the whole header */
6877
6878 /* Now look for cookies. Conforming to RFC2109, we have to support
6879 * attributes whose name begin with a '$', and associate them with
6880 * the right cookie, if we want to delete this cookie.
6881 * So there are 3 cases for each cookie read :
6882 * 1) it's a special attribute, beginning with a '$' : ignore it.
6883 * 2) it's a server id cookie that we *MAY* want to delete : save
6884 * some pointers on it (last semi-colon, beginning of cookie...)
6885 * 3) it's an application cookie : we *MAY* have to delete a previous
6886 * "special" cookie.
6887 * At the end of loop, if a "special" cookie remains, we may have to
6888 * remove it. If no application cookie persists in the header, we
6889 * *MUST* delete it.
6890 *
6891 * Note: RFC2965 is unclear about the processing of spaces around
6892 * the equal sign in the ATTR=VALUE form. A careful inspection of
6893 * the RFC explicitly allows spaces before it, and not within the
6894 * tokens (attrs or values). An inspection of RFC2109 allows that
6895 * too but section 10.1.3 lets one think that spaces may be allowed
6896 * after the equal sign too, resulting in some (rare) buggy
6897 * implementations trying to do that. So let's do what servers do.
6898 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
6899 * allowed quoted strings in values, with any possible character
6900 * after a backslash, including control chars and delimitors, which
6901 * causes parsing to become ambiguous. Browsers also allow spaces
6902 * within values even without quotes.
6903 *
6904 * We have to keep multiple pointers in order to support cookie
6905 * removal at the beginning, middle or end of header without
6906 * corrupting the header. All of these headers are valid :
6907 *
6908 * Cookie:NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3\r\n
6909 * Cookie:NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3\r\n
6910 * Cookie: NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3\r\n
6911 * | | | | | | | | |
6912 * | | | | | | | | hdr_end <--+
6913 * | | | | | | | +--> next
6914 * | | | | | | +----> val_end
6915 * | | | | | +-----------> val_beg
6916 * | | | | +--------------> equal
6917 * | | | +----------------> att_end
6918 * | | +---------------------> att_beg
6919 * | +--------------------------> prev
6920 * +--------------------------------> hdr_beg
6921 */
6922
6923 for (prev = hdr_beg + 6; prev < hdr_end; prev = next) {
6924 /* Iterate through all cookies on this line */
6925
6926 /* find att_beg */
6927 att_beg = prev + 1;
6928 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
6929 att_beg++;
6930
6931 /* find att_end : this is the first character after the last non
6932 * space before the equal. It may be equal to hdr_end.
6933 */
6934 equal = att_end = att_beg;
6935
6936 while (equal < hdr_end) {
6937 if (*equal == '=' || *equal == ',' || *equal == ';')
6938 break;
6939 if (HTTP_IS_SPHT(*equal++))
6940 continue;
6941 att_end = equal;
6942 }
6943
6944 /* here, <equal> points to '=', a delimitor or the end. <att_end>
6945 * is between <att_beg> and <equal>, both may be identical.
6946 */
6947
6948 /* look for end of cookie if there is an equal sign */
6949 if (equal < hdr_end && *equal == '=') {
6950 /* look for the beginning of the value */
6951 val_beg = equal + 1;
6952 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
6953 val_beg++;
6954
6955 /* find the end of the value, respecting quotes */
6956 next = find_cookie_value_end(val_beg, hdr_end);
6957
6958 /* make val_end point to the first white space or delimitor after the value */
6959 val_end = next;
6960 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
6961 val_end--;
6962 } else {
6963 val_beg = val_end = next = equal;
6964 }
6965
6966 /* We have nothing to do with attributes beginning with '$'. However,
6967 * they will automatically be removed if a header before them is removed,
6968 * since they're supposed to be linked together.
6969 */
6970 if (*att_beg == '$')
6971 continue;
6972
6973 /* Ignore cookies with no equal sign */
6974 if (equal == next) {
6975 /* This is not our cookie, so we must preserve it. But if we already
6976 * scheduled another cookie for removal, we cannot remove the
6977 * complete header, but we can remove the previous block itself.
6978 */
6979 preserve_hdr = 1;
6980 if (del_from != NULL) {
6981 int delta = del_hdr_value(req->buf, &del_from, prev);
6982 val_end += delta;
6983 next += delta;
6984 hdr_end += delta;
6985 hdr_next += delta;
6986 cur_hdr->len += delta;
6987 http_msg_move_end(&txn->req, delta);
6988 prev = del_from;
6989 del_from = NULL;
6990 }
6991 continue;
6992 }
6993
6994 /* if there are spaces around the equal sign, we need to
6995 * strip them otherwise we'll get trouble for cookie captures,
6996 * or even for rewrites. Since this happens extremely rarely,
6997 * it does not hurt performance.
6998 */
6999 if (unlikely(att_end != equal || val_beg > equal + 1)) {
7000 int stripped_before = 0;
7001 int stripped_after = 0;
7002
7003 if (att_end != equal) {
7004 stripped_before = buffer_replace2(req->buf, att_end, equal, NULL, 0);
7005 equal += stripped_before;
7006 val_beg += stripped_before;
7007 }
7008
7009 if (val_beg > equal + 1) {
7010 stripped_after = buffer_replace2(req->buf, equal + 1, val_beg, NULL, 0);
7011 val_beg += stripped_after;
7012 stripped_before += stripped_after;
7013 }
7014
7015 val_end += stripped_before;
7016 next += stripped_before;
7017 hdr_end += stripped_before;
7018 hdr_next += stripped_before;
7019 cur_hdr->len += stripped_before;
7020 http_msg_move_end(&txn->req, stripped_before);
7021 }
7022 /* now everything is as on the diagram above */
7023
7024 /* First, let's see if we want to capture this cookie. We check
7025 * that we don't already have a client side cookie, because we
7026 * can only capture one. Also as an optimisation, we ignore
7027 * cookies shorter than the declared name.
7028 */
7029 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
7030 (val_end - att_beg >= sess->fe->capture_namelen) &&
7031 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
7032 int log_len = val_end - att_beg;
7033
7034 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
7035 ha_alert("HTTP logging : out of memory.\n");
7036 } else {
7037 if (log_len > sess->fe->capture_len)
7038 log_len = sess->fe->capture_len;
7039 memcpy(txn->cli_cookie, att_beg, log_len);
7040 txn->cli_cookie[log_len] = 0;
7041 }
7042 }
7043
7044 /* Persistence cookies in passive, rewrite or insert mode have the
7045 * following form :
7046 *
7047 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
7048 *
7049 * For cookies in prefix mode, the form is :
7050 *
7051 * Cookie: NAME=SRV~VALUE
7052 */
7053 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
7054 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
7055 struct server *srv = s->be->srv;
7056 char *delim;
7057
7058 /* if we're in cookie prefix mode, we'll search the delimitor so that we
7059 * have the server ID between val_beg and delim, and the original cookie between
7060 * delim+1 and val_end. Otherwise, delim==val_end :
7061 *
7062 * Cookie: NAME=SRV; # in all but prefix modes
7063 * Cookie: NAME=SRV~OPAQUE ; # in prefix mode
7064 * | || || | |+-> next
7065 * | || || | +--> val_end
7066 * | || || +---------> delim
7067 * | || |+------------> val_beg
7068 * | || +-------------> att_end = equal
7069 * | |+-----------------> att_beg
7070 * | +------------------> prev
7071 * +-------------------------> hdr_beg
7072 */
7073
7074 if (s->be->ck_opts & PR_CK_PFX) {
7075 for (delim = val_beg; delim < val_end; delim++)
7076 if (*delim == COOKIE_DELIM)
7077 break;
7078 } else {
7079 char *vbar1;
7080 delim = val_end;
7081 /* Now check if the cookie contains a date field, which would
7082 * appear after a vertical bar ('|') just after the server name
7083 * and before the delimiter.
7084 */
7085 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
7086 if (vbar1) {
7087 /* OK, so left of the bar is the server's cookie and
7088 * right is the last seen date. It is a base64 encoded
7089 * 30-bit value representing the UNIX date since the
7090 * epoch in 4-second quantities.
7091 */
7092 int val;
7093 delim = vbar1++;
7094 if (val_end - vbar1 >= 5) {
7095 val = b64tos30(vbar1);
7096 if (val > 0)
7097 txn->cookie_last_date = val << 2;
7098 }
7099 /* look for a second vertical bar */
7100 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
7101 if (vbar1 && (val_end - vbar1 > 5)) {
7102 val = b64tos30(vbar1 + 1);
7103 if (val > 0)
7104 txn->cookie_first_date = val << 2;
7105 }
7106 }
7107 }
7108
7109 /* if the cookie has an expiration date and the proxy wants to check
7110 * it, then we do that now. We first check if the cookie is too old,
7111 * then only if it has expired. We detect strict overflow because the
7112 * time resolution here is not great (4 seconds). Cookies with dates
7113 * in the future are ignored if their offset is beyond one day. This
7114 * allows an admin to fix timezone issues without expiring everyone
7115 * and at the same time avoids keeping unwanted side effects for too
7116 * long.
7117 */
7118 if (txn->cookie_first_date && s->be->cookie_maxlife &&
7119 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
7120 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
7121 txn->flags &= ~TX_CK_MASK;
7122 txn->flags |= TX_CK_OLD;
7123 delim = val_beg; // let's pretend we have not found the cookie
7124 txn->cookie_first_date = 0;
7125 txn->cookie_last_date = 0;
7126 }
7127 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
7128 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
7129 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
7130 txn->flags &= ~TX_CK_MASK;
7131 txn->flags |= TX_CK_EXPIRED;
7132 delim = val_beg; // let's pretend we have not found the cookie
7133 txn->cookie_first_date = 0;
7134 txn->cookie_last_date = 0;
7135 }
7136
7137 /* Here, we'll look for the first running server which supports the cookie.
7138 * This allows to share a same cookie between several servers, for example
7139 * to dedicate backup servers to specific servers only.
7140 * However, to prevent clients from sticking to cookie-less backup server
7141 * when they have incidentely learned an empty cookie, we simply ignore
7142 * empty cookies and mark them as invalid.
7143 * The same behaviour is applied when persistence must be ignored.
7144 */
7145 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
7146 srv = NULL;
7147
7148 while (srv) {
7149 if (srv->cookie && (srv->cklen == delim - val_beg) &&
7150 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
7151 if ((srv->cur_state != SRV_ST_STOPPED) ||
7152 (s->be->options & PR_O_PERSIST) ||
7153 (s->flags & SF_FORCE_PRST)) {
7154 /* we found the server and we can use it */
7155 txn->flags &= ~TX_CK_MASK;
7156 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
7157 s->flags |= SF_DIRECT | SF_ASSIGNED;
7158 s->target = &srv->obj_type;
7159 break;
7160 } else {
7161 /* we found a server, but it's down,
7162 * mark it as such and go on in case
7163 * another one is available.
7164 */
7165 txn->flags &= ~TX_CK_MASK;
7166 txn->flags |= TX_CK_DOWN;
7167 }
7168 }
7169 srv = srv->next;
7170 }
7171
7172 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
7173 /* no server matched this cookie or we deliberately skipped it */
7174 txn->flags &= ~TX_CK_MASK;
7175 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
7176 txn->flags |= TX_CK_UNUSED;
7177 else
7178 txn->flags |= TX_CK_INVALID;
7179 }
7180
7181 /* depending on the cookie mode, we may have to either :
7182 * - delete the complete cookie if we're in insert+indirect mode, so that
7183 * the server never sees it ;
7184 * - remove the server id from the cookie value, and tag the cookie as an
7185 * application cookie so that it does not get accidentely removed later,
7186 * if we're in cookie prefix mode
7187 */
7188 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
7189 int delta; /* negative */
7190
7191 delta = buffer_replace2(req->buf, val_beg, delim + 1, NULL, 0);
7192 val_end += delta;
7193 next += delta;
7194 hdr_end += delta;
7195 hdr_next += delta;
7196 cur_hdr->len += delta;
7197 http_msg_move_end(&txn->req, delta);
7198
7199 del_from = NULL;
7200 preserve_hdr = 1; /* we want to keep this cookie */
7201 }
7202 else if (del_from == NULL &&
7203 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
7204 del_from = prev;
7205 }
7206 } else {
7207 /* This is not our cookie, so we must preserve it. But if we already
7208 * scheduled another cookie for removal, we cannot remove the
7209 * complete header, but we can remove the previous block itself.
7210 */
7211 preserve_hdr = 1;
7212
7213 if (del_from != NULL) {
7214 int delta = del_hdr_value(req->buf, &del_from, prev);
7215 if (att_beg >= del_from)
7216 att_beg += delta;
7217 if (att_end >= del_from)
7218 att_end += delta;
7219 val_beg += delta;
7220 val_end += delta;
7221 next += delta;
7222 hdr_end += delta;
7223 hdr_next += delta;
7224 cur_hdr->len += delta;
7225 http_msg_move_end(&txn->req, delta);
7226 prev = del_from;
7227 del_from = NULL;
7228 }
7229 }
7230
7231 /* continue with next cookie on this header line */
7232 att_beg = next;
7233 } /* for each cookie */
7234
7235 /* There are no more cookies on this line.
7236 * We may still have one (or several) marked for deletion at the
7237 * end of the line. We must do this now in two ways :
7238 * - if some cookies must be preserved, we only delete from the
7239 * mark to the end of line ;
7240 * - if nothing needs to be preserved, simply delete the whole header
7241 */
7242 if (del_from) {
7243 int delta;
7244 if (preserve_hdr) {
7245 delta = del_hdr_value(req->buf, &del_from, hdr_end);
7246 hdr_end = del_from;
7247 cur_hdr->len += delta;
7248 } else {
7249 delta = buffer_replace2(req->buf, hdr_beg, hdr_next, NULL, 0);
7250
7251 /* FIXME: this should be a separate function */
7252 txn->hdr_idx.v[old_idx].next = cur_hdr->next;
7253 txn->hdr_idx.used--;
7254 cur_hdr->len = 0;
7255 cur_idx = old_idx;
7256 }
7257 hdr_next += delta;
7258 http_msg_move_end(&txn->req, delta);
7259 }
7260
7261 /* check next header */
7262 old_idx = cur_idx;
7263 }
7264 }
7265
7266
7267 /* Iterate the same filter through all response headers contained in <rtr>.
7268 * Returns 1 if this filter can be stopped upon return, otherwise 0.
7269 */
apply_filter_to_resp_headers(struct stream * s,struct channel * rtr,struct hdr_exp * exp)7270 int apply_filter_to_resp_headers(struct stream *s, struct channel *rtr, struct hdr_exp *exp)
7271 {
7272 char *cur_ptr, *cur_end, *cur_next;
7273 int cur_idx, old_idx, last_hdr;
7274 struct http_txn *txn = s->txn;
7275 struct hdr_idx_elem *cur_hdr;
7276 int delta;
7277
7278 last_hdr = 0;
7279
7280 cur_next = rtr->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
7281 old_idx = 0;
7282
7283 while (!last_hdr) {
7284 if (unlikely(txn->flags & TX_SVDENY))
7285 return 1;
7286 else if (unlikely(txn->flags & TX_SVALLOW) &&
7287 (exp->action == ACT_ALLOW ||
7288 exp->action == ACT_DENY))
7289 return 0;
7290
7291 cur_idx = txn->hdr_idx.v[old_idx].next;
7292 if (!cur_idx)
7293 break;
7294
7295 cur_hdr = &txn->hdr_idx.v[cur_idx];
7296 cur_ptr = cur_next;
7297 cur_end = cur_ptr + cur_hdr->len;
7298 cur_next = cur_end + cur_hdr->cr + 1;
7299
7300 /* Now we have one header between cur_ptr and cur_end,
7301 * and the next header starts at cur_next.
7302 */
7303
7304 if (regex_exec_match2(exp->preg, cur_ptr, cur_end-cur_ptr, MAX_MATCH, pmatch, 0)) {
7305 switch (exp->action) {
7306 case ACT_ALLOW:
7307 txn->flags |= TX_SVALLOW;
7308 last_hdr = 1;
7309 break;
7310
7311 case ACT_DENY:
7312 txn->flags |= TX_SVDENY;
7313 last_hdr = 1;
7314 break;
7315
7316 case ACT_REPLACE:
7317 trash.len = exp_replace(trash.str, trash.size, cur_ptr, exp->replace, pmatch);
7318 if (trash.len < 0)
7319 return -1;
7320
7321 delta = buffer_replace2(rtr->buf, cur_ptr, cur_end, trash.str, trash.len);
7322 /* FIXME: if the user adds a newline in the replacement, the
7323 * index will not be recalculated for now, and the new line
7324 * will not be counted as a new header.
7325 */
7326
7327 cur_end += delta;
7328 cur_next += delta;
7329 cur_hdr->len += delta;
7330 http_msg_move_end(&txn->rsp, delta);
7331 break;
7332
7333 case ACT_REMOVE:
7334 delta = buffer_replace2(rtr->buf, cur_ptr, cur_next, NULL, 0);
7335 cur_next += delta;
7336
7337 http_msg_move_end(&txn->rsp, delta);
7338 txn->hdr_idx.v[old_idx].next = cur_hdr->next;
7339 txn->hdr_idx.used--;
7340 cur_hdr->len = 0;
7341 cur_end = NULL; /* null-term has been rewritten */
7342 cur_idx = old_idx;
7343 break;
7344
7345 }
7346 }
7347
7348 /* keep the link from this header to next one in case of later
7349 * removal of next header.
7350 */
7351 old_idx = cur_idx;
7352 }
7353 return 0;
7354 }
7355
7356
7357 /* Apply the filter to the status line in the response buffer <rtr>.
7358 * Returns 0 if nothing has been done, 1 if the filter has been applied,
7359 * or -1 if a replacement resulted in an invalid status line.
7360 */
apply_filter_to_sts_line(struct stream * s,struct channel * rtr,struct hdr_exp * exp)7361 int apply_filter_to_sts_line(struct stream *s, struct channel *rtr, struct hdr_exp *exp)
7362 {
7363 char *cur_ptr, *cur_end;
7364 int done;
7365 struct http_txn *txn = s->txn;
7366 int delta;
7367
7368
7369 if (unlikely(txn->flags & TX_SVDENY))
7370 return 1;
7371 else if (unlikely(txn->flags & TX_SVALLOW) &&
7372 (exp->action == ACT_ALLOW ||
7373 exp->action == ACT_DENY))
7374 return 0;
7375 else if (exp->action == ACT_REMOVE)
7376 return 0;
7377
7378 done = 0;
7379
7380 cur_ptr = rtr->buf->p;
7381 cur_end = cur_ptr + txn->rsp.sl.st.l;
7382
7383 /* Now we have the status line between cur_ptr and cur_end */
7384
7385 if (regex_exec_match2(exp->preg, cur_ptr, cur_end-cur_ptr, MAX_MATCH, pmatch, 0)) {
7386 switch (exp->action) {
7387 case ACT_ALLOW:
7388 txn->flags |= TX_SVALLOW;
7389 done = 1;
7390 break;
7391
7392 case ACT_DENY:
7393 txn->flags |= TX_SVDENY;
7394 done = 1;
7395 break;
7396
7397 case ACT_REPLACE:
7398 trash.len = exp_replace(trash.str, trash.size, cur_ptr, exp->replace, pmatch);
7399 if (trash.len < 0)
7400 return -1;
7401
7402 delta = buffer_replace2(rtr->buf, cur_ptr, cur_end, trash.str, trash.len);
7403 /* FIXME: if the user adds a newline in the replacement, the
7404 * index will not be recalculated for now, and the new line
7405 * will not be counted as a new header.
7406 */
7407
7408 http_msg_move_end(&txn->rsp, delta);
7409 cur_end += delta;
7410 cur_end = (char *)http_parse_stsline(&txn->rsp,
7411 HTTP_MSG_RPVER,
7412 cur_ptr, cur_end + 1,
7413 NULL, NULL);
7414 if (unlikely(!cur_end))
7415 return -1;
7416
7417 /* we have a full respnse and we know that we have either a CR
7418 * or an LF at <ptr>.
7419 */
7420 txn->status = strl2ui(rtr->buf->p + txn->rsp.sl.st.c, txn->rsp.sl.st.c_l);
7421 hdr_idx_set_start(&txn->hdr_idx, txn->rsp.sl.st.l, *cur_end == '\r');
7422 /* there is no point trying this regex on headers */
7423 return 1;
7424 }
7425 }
7426 return done;
7427 }
7428
7429
7430
7431 /*
7432 * Apply all the resp filters of proxy <px> to all headers in buffer <rtr> of stream <s>.
7433 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
7434 * unparsable response.
7435 */
apply_filters_to_response(struct stream * s,struct channel * rtr,struct proxy * px)7436 int apply_filters_to_response(struct stream *s, struct channel *rtr, struct proxy *px)
7437 {
7438 struct session *sess = s->sess;
7439 struct http_txn *txn = s->txn;
7440 struct hdr_exp *exp;
7441
7442 for (exp = px->rsp_exp; exp; exp = exp->next) {
7443 int ret;
7444
7445 /*
7446 * The interleaving of transformations and verdicts
7447 * makes it difficult to decide to continue or stop
7448 * the evaluation.
7449 */
7450
7451 if (txn->flags & TX_SVDENY)
7452 break;
7453
7454 if ((txn->flags & TX_SVALLOW) &&
7455 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
7456 exp->action == ACT_PASS)) {
7457 exp = exp->next;
7458 continue;
7459 }
7460
7461 /* if this filter had a condition, evaluate it now and skip to
7462 * next filter if the condition does not match.
7463 */
7464 if (exp->cond) {
7465 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
7466 ret = acl_pass(ret);
7467 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
7468 ret = !ret;
7469 if (!ret)
7470 continue;
7471 }
7472
7473 /* Apply the filter to the status line. */
7474 ret = apply_filter_to_sts_line(s, rtr, exp);
7475 if (unlikely(ret < 0))
7476 return -1;
7477
7478 if (likely(ret == 0)) {
7479 /* The filter did not match the response, it can be
7480 * iterated through all headers.
7481 */
7482 if (unlikely(apply_filter_to_resp_headers(s, rtr, exp) < 0))
7483 return -1;
7484 }
7485 }
7486 return 0;
7487 }
7488
7489
7490 /*
7491 * Manage server-side cookies. It can impact performance by about 2% so it is
7492 * desirable to call it only when needed. This function is also used when we
7493 * just need to know if there is a cookie (eg: for check-cache).
7494 */
manage_server_side_cookies(struct stream * s,struct channel * res)7495 void manage_server_side_cookies(struct stream *s, struct channel *res)
7496 {
7497 struct http_txn *txn = s->txn;
7498 struct session *sess = s->sess;
7499 struct server *srv;
7500 int is_cookie2;
7501 int cur_idx, old_idx, delta;
7502 char *hdr_beg, *hdr_end, *hdr_next;
7503 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
7504
7505 /* Iterate through the headers.
7506 * we start with the start line.
7507 */
7508 old_idx = 0;
7509 hdr_next = res->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
7510
7511 while ((cur_idx = txn->hdr_idx.v[old_idx].next)) {
7512 struct hdr_idx_elem *cur_hdr;
7513 int val;
7514
7515 cur_hdr = &txn->hdr_idx.v[cur_idx];
7516 hdr_beg = hdr_next;
7517 hdr_end = hdr_beg + cur_hdr->len;
7518 hdr_next = hdr_end + cur_hdr->cr + 1;
7519
7520 /* We have one full header between hdr_beg and hdr_end, and the
7521 * next header starts at hdr_next. We're only interested in
7522 * "Set-Cookie" and "Set-Cookie2" headers.
7523 */
7524
7525 is_cookie2 = 0;
7526 prev = hdr_beg + 10;
7527 val = http_header_match2(hdr_beg, hdr_end, "Set-Cookie", 10);
7528 if (!val) {
7529 val = http_header_match2(hdr_beg, hdr_end, "Set-Cookie2", 11);
7530 if (!val) {
7531 old_idx = cur_idx;
7532 continue;
7533 }
7534 is_cookie2 = 1;
7535 prev = hdr_beg + 11;
7536 }
7537
7538 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
7539 * <prev> points to the colon.
7540 */
7541 txn->flags |= TX_SCK_PRESENT;
7542
7543 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
7544 * check-cache is enabled) and we are not interested in checking
7545 * them. Warning, the cookie capture is declared in the frontend.
7546 */
7547 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
7548 return;
7549
7550 /* OK so now we know we have to process this response cookie.
7551 * The format of the Set-Cookie header is slightly different
7552 * from the format of the Cookie header in that it does not
7553 * support the comma as a cookie delimiter (thus the header
7554 * cannot be folded) because the Expires attribute described in
7555 * the original Netscape's spec may contain an unquoted date
7556 * with a comma inside. We have to live with this because
7557 * many browsers don't support Max-Age and some browsers don't
7558 * support quoted strings. However the Set-Cookie2 header is
7559 * clean.
7560 *
7561 * We have to keep multiple pointers in order to support cookie
7562 * removal at the beginning, middle or end of header without
7563 * corrupting the header (in case of set-cookie2). A special
7564 * pointer, <scav> points to the beginning of the set-cookie-av
7565 * fields after the first semi-colon. The <next> pointer points
7566 * either to the end of line (set-cookie) or next unquoted comma
7567 * (set-cookie2). All of these headers are valid :
7568 *
7569 * Set-Cookie: NAME1 = VALUE 1 ; Secure; Path="/"\r\n
7570 * Set-Cookie:NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT\r\n
7571 * Set-Cookie: NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT\r\n
7572 * Set-Cookie2: NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard\r\n
7573 * | | | | | | | | | |
7574 * | | | | | | | | +-> next hdr_end <--+
7575 * | | | | | | | +------------> scav
7576 * | | | | | | +--------------> val_end
7577 * | | | | | +--------------------> val_beg
7578 * | | | | +----------------------> equal
7579 * | | | +------------------------> att_end
7580 * | | +----------------------------> att_beg
7581 * | +------------------------------> prev
7582 * +-----------------------------------------> hdr_beg
7583 */
7584
7585 for (; prev < hdr_end; prev = next) {
7586 /* Iterate through all cookies on this line */
7587
7588 /* find att_beg */
7589 att_beg = prev + 1;
7590 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
7591 att_beg++;
7592
7593 /* find att_end : this is the first character after the last non
7594 * space before the equal. It may be equal to hdr_end.
7595 */
7596 equal = att_end = att_beg;
7597
7598 while (equal < hdr_end) {
7599 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
7600 break;
7601 if (HTTP_IS_SPHT(*equal++))
7602 continue;
7603 att_end = equal;
7604 }
7605
7606 /* here, <equal> points to '=', a delimitor or the end. <att_end>
7607 * is between <att_beg> and <equal>, both may be identical.
7608 */
7609
7610 /* look for end of cookie if there is an equal sign */
7611 if (equal < hdr_end && *equal == '=') {
7612 /* look for the beginning of the value */
7613 val_beg = equal + 1;
7614 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
7615 val_beg++;
7616
7617 /* find the end of the value, respecting quotes */
7618 next = find_cookie_value_end(val_beg, hdr_end);
7619
7620 /* make val_end point to the first white space or delimitor after the value */
7621 val_end = next;
7622 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
7623 val_end--;
7624 } else {
7625 /* <equal> points to next comma, semi-colon or EOL */
7626 val_beg = val_end = next = equal;
7627 }
7628
7629 if (next < hdr_end) {
7630 /* Set-Cookie2 supports multiple cookies, and <next> points to
7631 * a colon or semi-colon before the end. So skip all attr-value
7632 * pairs and look for the next comma. For Set-Cookie, since
7633 * commas are permitted in values, skip to the end.
7634 */
7635 if (is_cookie2)
7636 next = find_hdr_value_end(next, hdr_end);
7637 else
7638 next = hdr_end;
7639 }
7640
7641 /* Now everything is as on the diagram above */
7642
7643 /* Ignore cookies with no equal sign */
7644 if (equal == val_end)
7645 continue;
7646
7647 /* If there are spaces around the equal sign, we need to
7648 * strip them otherwise we'll get trouble for cookie captures,
7649 * or even for rewrites. Since this happens extremely rarely,
7650 * it does not hurt performance.
7651 */
7652 if (unlikely(att_end != equal || val_beg > equal + 1)) {
7653 int stripped_before = 0;
7654 int stripped_after = 0;
7655
7656 if (att_end != equal) {
7657 stripped_before = buffer_replace2(res->buf, att_end, equal, NULL, 0);
7658 equal += stripped_before;
7659 val_beg += stripped_before;
7660 }
7661
7662 if (val_beg > equal + 1) {
7663 stripped_after = buffer_replace2(res->buf, equal + 1, val_beg, NULL, 0);
7664 val_beg += stripped_after;
7665 stripped_before += stripped_after;
7666 }
7667
7668 val_end += stripped_before;
7669 next += stripped_before;
7670 hdr_end += stripped_before;
7671 hdr_next += stripped_before;
7672 cur_hdr->len += stripped_before;
7673 http_msg_move_end(&txn->rsp, stripped_before);
7674 }
7675
7676 /* First, let's see if we want to capture this cookie. We check
7677 * that we don't already have a server side cookie, because we
7678 * can only capture one. Also as an optimisation, we ignore
7679 * cookies shorter than the declared name.
7680 */
7681 if (sess->fe->capture_name != NULL &&
7682 txn->srv_cookie == NULL &&
7683 (val_end - att_beg >= sess->fe->capture_namelen) &&
7684 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
7685 int log_len = val_end - att_beg;
7686 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
7687 ha_alert("HTTP logging : out of memory.\n");
7688 }
7689 else {
7690 if (log_len > sess->fe->capture_len)
7691 log_len = sess->fe->capture_len;
7692 memcpy(txn->srv_cookie, att_beg, log_len);
7693 txn->srv_cookie[log_len] = 0;
7694 }
7695 }
7696
7697 srv = objt_server(s->target);
7698 /* now check if we need to process it for persistence */
7699 if (!(s->flags & SF_IGNORE_PRST) &&
7700 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
7701 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
7702 /* assume passive cookie by default */
7703 txn->flags &= ~TX_SCK_MASK;
7704 txn->flags |= TX_SCK_FOUND;
7705
7706 /* If the cookie is in insert mode on a known server, we'll delete
7707 * this occurrence because we'll insert another one later.
7708 * We'll delete it too if the "indirect" option is set and we're in
7709 * a direct access.
7710 */
7711 if (s->be->ck_opts & PR_CK_PSV) {
7712 /* The "preserve" flag was set, we don't want to touch the
7713 * server's cookie.
7714 */
7715 }
7716 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
7717 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
7718 /* this cookie must be deleted */
7719 if (*prev == ':' && next == hdr_end) {
7720 /* whole header */
7721 delta = buffer_replace2(res->buf, hdr_beg, hdr_next, NULL, 0);
7722 txn->hdr_idx.v[old_idx].next = cur_hdr->next;
7723 txn->hdr_idx.used--;
7724 cur_hdr->len = 0;
7725 cur_idx = old_idx;
7726 hdr_next += delta;
7727 http_msg_move_end(&txn->rsp, delta);
7728 /* note: while both invalid now, <next> and <hdr_end>
7729 * are still equal, so the for() will stop as expected.
7730 */
7731 } else {
7732 /* just remove the value */
7733 int delta = del_hdr_value(res->buf, &prev, next);
7734 next = prev;
7735 hdr_end += delta;
7736 hdr_next += delta;
7737 cur_hdr->len += delta;
7738 http_msg_move_end(&txn->rsp, delta);
7739 }
7740 txn->flags &= ~TX_SCK_MASK;
7741 txn->flags |= TX_SCK_DELETED;
7742 /* and go on with next cookie */
7743 }
7744 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
7745 /* replace bytes val_beg->val_end with the cookie name associated
7746 * with this server since we know it.
7747 */
7748 delta = buffer_replace2(res->buf, val_beg, val_end, srv->cookie, srv->cklen);
7749 next += delta;
7750 hdr_end += delta;
7751 hdr_next += delta;
7752 cur_hdr->len += delta;
7753 http_msg_move_end(&txn->rsp, delta);
7754
7755 txn->flags &= ~TX_SCK_MASK;
7756 txn->flags |= TX_SCK_REPLACED;
7757 }
7758 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
7759 /* insert the cookie name associated with this server
7760 * before existing cookie, and insert a delimiter between them..
7761 */
7762 delta = buffer_replace2(res->buf, val_beg, val_beg, srv->cookie, srv->cklen + 1);
7763 next += delta;
7764 hdr_end += delta;
7765 hdr_next += delta;
7766 cur_hdr->len += delta;
7767 http_msg_move_end(&txn->rsp, delta);
7768
7769 val_beg[srv->cklen] = COOKIE_DELIM;
7770 txn->flags &= ~TX_SCK_MASK;
7771 txn->flags |= TX_SCK_REPLACED;
7772 }
7773 }
7774 /* that's done for this cookie, check the next one on the same
7775 * line when next != hdr_end (only if is_cookie2).
7776 */
7777 }
7778 /* check next header */
7779 old_idx = cur_idx;
7780 }
7781 }
7782
7783
7784 /*
7785 * Parses the Cache-Control and Pragma request header fields to determine if
7786 * the request may be served from the cache and/or if it is cacheable. Updates
7787 * s->txn->flags.
7788 */
check_request_for_cacheability(struct stream * s,struct channel * chn)7789 void check_request_for_cacheability(struct stream *s, struct channel *chn)
7790 {
7791 struct http_txn *txn = s->txn;
7792 char *p1, *p2;
7793 char *cur_ptr, *cur_end, *cur_next;
7794 int pragma_found;
7795 int cc_found;
7796 int cur_idx;
7797
7798 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
7799 return; /* nothing more to do here */
7800
7801 cur_idx = 0;
7802 pragma_found = cc_found = 0;
7803 cur_next = chn->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
7804
7805 while ((cur_idx = txn->hdr_idx.v[cur_idx].next)) {
7806 struct hdr_idx_elem *cur_hdr;
7807 int val;
7808
7809 cur_hdr = &txn->hdr_idx.v[cur_idx];
7810 cur_ptr = cur_next;
7811 cur_end = cur_ptr + cur_hdr->len;
7812 cur_next = cur_end + cur_hdr->cr + 1;
7813
7814 /* We have one full header between cur_ptr and cur_end, and the
7815 * next header starts at cur_next.
7816 */
7817
7818 val = http_header_match2(cur_ptr, cur_end, "Pragma", 6);
7819 if (val) {
7820 if ((cur_end - (cur_ptr + val) >= 8) &&
7821 strncasecmp(cur_ptr + val, "no-cache", 8) == 0) {
7822 pragma_found = 1;
7823 continue;
7824 }
7825 }
7826
7827 /* Don't use the cache and don't try to store if we found the
7828 * Authorization header */
7829 val = http_header_match2(cur_ptr, cur_end, "Authorization", 13);
7830 if (val) {
7831 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
7832 txn->flags |= TX_CACHE_IGNORE;
7833 continue;
7834 }
7835
7836 val = http_header_match2(cur_ptr, cur_end, "Cache-control", 13);
7837 if (!val)
7838 continue;
7839
7840 /* OK, right now we know we have a cache-control header at cur_ptr */
7841 cc_found = 1;
7842 p1 = cur_ptr + val; /* first non-space char after 'cache-control:' */
7843
7844 if (p1 >= cur_end) /* no more info */
7845 continue;
7846
7847 /* p1 is at the beginning of the value */
7848 p2 = p1;
7849 while (p2 < cur_end && *p2 != '=' && *p2 != ',' && !isspace((unsigned char)*p2))
7850 p2++;
7851
7852 /* we have a complete value between p1 and p2. We don't check the
7853 * values after max-age, max-stale nor min-fresh, we simply don't
7854 * use the cache when they're specified.
7855 */
7856 if (((p2 - p1 == 7) && strncasecmp(p1, "max-age", 7) == 0) ||
7857 ((p2 - p1 == 8) && strncasecmp(p1, "no-cache", 8) == 0) ||
7858 ((p2 - p1 == 9) && strncasecmp(p1, "max-stale", 9) == 0) ||
7859 ((p2 - p1 == 9) && strncasecmp(p1, "min-fresh", 9) == 0)) {
7860 txn->flags |= TX_CACHE_IGNORE;
7861 continue;
7862 }
7863
7864 if ((p2 - p1 == 8) && strncasecmp(p1, "no-store", 8) == 0) {
7865 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
7866 continue;
7867 }
7868 }
7869
7870 /* RFC7234#5.4:
7871 * When the Cache-Control header field is also present and
7872 * understood in a request, Pragma is ignored.
7873 * When the Cache-Control header field is not present in a
7874 * request, caches MUST consider the no-cache request
7875 * pragma-directive as having the same effect as if
7876 * "Cache-Control: no-cache" were present.
7877 */
7878 if (!cc_found && pragma_found)
7879 txn->flags |= TX_CACHE_IGNORE;
7880 }
7881
7882 /*
7883 * Check if response is cacheable or not. Updates s->txn->flags.
7884 */
check_response_for_cacheability(struct stream * s,struct channel * rtr)7885 void check_response_for_cacheability(struct stream *s, struct channel *rtr)
7886 {
7887 struct http_txn *txn = s->txn;
7888 char *p1, *p2;
7889
7890 char *cur_ptr, *cur_end, *cur_next;
7891 int cur_idx;
7892
7893 if (txn->status < 200) {
7894 /* do not try to cache interim responses! */
7895 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
7896 return;
7897 }
7898
7899 /* Iterate through the headers.
7900 * we start with the start line.
7901 */
7902 cur_idx = 0;
7903 cur_next = rtr->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
7904
7905 while ((cur_idx = txn->hdr_idx.v[cur_idx].next)) {
7906 struct hdr_idx_elem *cur_hdr;
7907 int val;
7908
7909 cur_hdr = &txn->hdr_idx.v[cur_idx];
7910 cur_ptr = cur_next;
7911 cur_end = cur_ptr + cur_hdr->len;
7912 cur_next = cur_end + cur_hdr->cr + 1;
7913
7914 /* We have one full header between cur_ptr and cur_end, and the
7915 * next header starts at cur_next.
7916 */
7917
7918 val = http_header_match2(cur_ptr, cur_end, "Pragma", 6);
7919 if (val) {
7920 if ((cur_end - (cur_ptr + val) >= 8) &&
7921 strncasecmp(cur_ptr + val, "no-cache", 8) == 0) {
7922 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
7923 return;
7924 }
7925 }
7926
7927 val = http_header_match2(cur_ptr, cur_end, "Cache-control", 13);
7928 if (!val)
7929 continue;
7930
7931 /* OK, right now we know we have a cache-control header at cur_ptr */
7932
7933 p1 = cur_ptr + val; /* first non-space char after 'cache-control:' */
7934
7935 if (p1 >= cur_end) /* no more info */
7936 continue;
7937
7938 /* p1 is at the beginning of the value */
7939 p2 = p1;
7940
7941 while (p2 < cur_end && *p2 != '=' && *p2 != ',' && !isspace((unsigned char)*p2))
7942 p2++;
7943
7944 /* we have a complete value between p1 and p2 */
7945 if (p2 < cur_end && *p2 == '=') {
7946 if (((cur_end - p2) > 1 && (p2 - p1 == 7) && strncasecmp(p1, "max-age=0", 9) == 0) ||
7947 ((cur_end - p2) > 1 && (p2 - p1 == 8) && strncasecmp(p1, "s-maxage=0", 10) == 0)) {
7948 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
7949 continue;
7950 }
7951
7952 /* we have something of the form no-cache="set-cookie" */
7953 if ((cur_end - p1 >= 21) &&
7954 strncasecmp(p1, "no-cache=\"set-cookie", 20) == 0
7955 && (p1[20] == '"' || p1[20] == ','))
7956 txn->flags &= ~TX_CACHE_COOK;
7957 continue;
7958 }
7959
7960 /* OK, so we know that either p2 points to the end of string or to a comma */
7961 if (((p2 - p1 == 7) && strncasecmp(p1, "private", 7) == 0) ||
7962 ((p2 - p1 == 8) && strncasecmp(p1, "no-cache", 8) == 0) ||
7963 ((p2 - p1 == 8) && strncasecmp(p1, "no-store", 8) == 0)) {
7964 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
7965 return;
7966 }
7967
7968 if ((p2 - p1 == 6) && strncasecmp(p1, "public", 6) == 0) {
7969 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
7970 continue;
7971 }
7972 }
7973 }
7974
7975
7976 /*
7977 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
7978 * for the current backend.
7979 *
7980 * It is assumed that the request is either a HEAD, GET, or POST and that the
7981 * uri_auth field is valid.
7982 *
7983 * Returns 1 if stats should be provided, otherwise 0.
7984 */
stats_check_uri(struct stream_interface * si,struct http_txn * txn,struct proxy * backend)7985 int stats_check_uri(struct stream_interface *si, struct http_txn *txn, struct proxy *backend)
7986 {
7987 struct uri_auth *uri_auth = backend->uri_auth;
7988 struct http_msg *msg = &txn->req;
7989 const char *uri = msg->chn->buf->p+ msg->sl.rq.u;
7990
7991 if (!uri_auth)
7992 return 0;
7993
7994 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
7995 return 0;
7996
7997 /* check URI size */
7998 if (uri_auth->uri_len > msg->sl.rq.u_l)
7999 return 0;
8000
8001 if (memcmp(uri, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
8002 return 0;
8003
8004 return 1;
8005 }
8006
8007 /*
8008 * Capture a bad request or response and archive it in the proxy's structure.
8009 * By default it tries to report the error position as msg->err_pos. However if
8010 * this one is not set, it will then report msg->next, which is the last known
8011 * parsing point. The function is able to deal with wrapping buffers. It always
8012 * displays buffers as a contiguous area starting at buf->p.
8013 */
http_capture_bad_message(struct proxy * proxy,struct error_snapshot * es,struct stream * s,struct http_msg * msg,enum h1_state state,struct proxy * other_end)8014 void http_capture_bad_message(struct proxy *proxy, struct error_snapshot *es, struct stream *s,
8015 struct http_msg *msg,
8016 enum h1_state state, struct proxy *other_end)
8017 {
8018 struct session *sess = strm_sess(s);
8019 struct channel *chn = msg->chn;
8020 int len1, len2;
8021
8022 HA_SPIN_LOCK(PROXY_LOCK, &proxy->lock);
8023 es->len = MIN(chn->buf->i, global.tune.bufsize);
8024 len1 = chn->buf->data + chn->buf->size - chn->buf->p;
8025 len1 = MIN(len1, es->len);
8026 len2 = es->len - len1; /* remaining data if buffer wraps */
8027
8028 if (!es->buf)
8029 es->buf = malloc(global.tune.bufsize);
8030
8031 if (es->buf) {
8032 memcpy(es->buf, chn->buf->p, len1);
8033 if (len2)
8034 memcpy(es->buf + len1, chn->buf->data, len2);
8035 }
8036
8037 if (msg->err_pos >= 0)
8038 es->pos = msg->err_pos;
8039 else
8040 es->pos = msg->next;
8041
8042 es->when = date; // user-visible date
8043 es->sid = s->uniq_id;
8044 es->srv = objt_server(s->target);
8045 es->oe = other_end;
8046 if (objt_conn(sess->origin))
8047 es->src = __objt_conn(sess->origin)->addr.from;
8048 else
8049 memset(&es->src, 0, sizeof(es->src));
8050
8051 es->state = state;
8052 es->ev_id = HA_ATOMIC_XADD(&error_snapshot_id, 1);
8053 es->b_flags = chn->flags;
8054 es->s_flags = s->flags;
8055 es->t_flags = s->txn->flags;
8056 es->m_flags = msg->flags;
8057 es->b_out = chn->buf->o;
8058 es->b_wrap = chn->buf->data + chn->buf->size - chn->buf->p;
8059 es->b_tot = chn->total;
8060 es->m_clen = msg->chunk_len;
8061 es->m_blen = msg->body_len;
8062 HA_SPIN_UNLOCK(PROXY_LOCK, &proxy->lock);
8063 }
8064
8065 /* Return in <vptr> and <vlen> the pointer and length of occurrence <occ> of
8066 * header whose name is <hname> of length <hlen>. If <ctx> is null, lookup is
8067 * performed over the whole headers. Otherwise it must contain a valid header
8068 * context, initialised with ctx->idx=0 for the first lookup in a series. If
8069 * <occ> is positive or null, occurrence #occ from the beginning (or last ctx)
8070 * is returned. Occ #0 and #1 are equivalent. If <occ> is negative (and no less
8071 * than -MAX_HDR_HISTORY), the occurrence is counted from the last one which is
8072 * -1. The value fetch stops at commas, so this function is suited for use with
8073 * list headers.
8074 * The return value is 0 if nothing was found, or non-zero otherwise.
8075 */
http_get_hdr(const struct http_msg * msg,const char * hname,int hlen,struct hdr_idx * idx,int occ,struct hdr_ctx * ctx,char ** vptr,int * vlen)8076 unsigned int http_get_hdr(const struct http_msg *msg, const char *hname, int hlen,
8077 struct hdr_idx *idx, int occ,
8078 struct hdr_ctx *ctx, char **vptr, int *vlen)
8079 {
8080 struct hdr_ctx local_ctx;
8081 char *ptr_hist[MAX_HDR_HISTORY];
8082 int len_hist[MAX_HDR_HISTORY];
8083 unsigned int hist_ptr;
8084 int found;
8085
8086 if (!ctx) {
8087 local_ctx.idx = 0;
8088 ctx = &local_ctx;
8089 }
8090
8091 if (occ >= 0) {
8092 /* search from the beginning */
8093 while (http_find_header2(hname, hlen, msg->chn->buf->p, idx, ctx)) {
8094 occ--;
8095 if (occ <= 0) {
8096 *vptr = ctx->line + ctx->val;
8097 *vlen = ctx->vlen;
8098 return 1;
8099 }
8100 }
8101 return 0;
8102 }
8103
8104 /* negative occurrence, we scan all the list then walk back */
8105 if (-occ > MAX_HDR_HISTORY)
8106 return 0;
8107
8108 found = hist_ptr = 0;
8109 while (http_find_header2(hname, hlen, msg->chn->buf->p, idx, ctx)) {
8110 ptr_hist[hist_ptr] = ctx->line + ctx->val;
8111 len_hist[hist_ptr] = ctx->vlen;
8112 if (++hist_ptr >= MAX_HDR_HISTORY)
8113 hist_ptr = 0;
8114 found++;
8115 }
8116 if (-occ > found)
8117 return 0;
8118 /* OK now we have the last occurrence in [hist_ptr-1], and we need to
8119 * find occurrence -occ. 0 <= hist_ptr < MAX_HDR_HISTORY, and we have
8120 * -10 <= occ <= -1. So we have to check [hist_ptr%MAX_HDR_HISTORY+occ]
8121 * to remain in the 0..9 range.
8122 */
8123 hist_ptr += occ + MAX_HDR_HISTORY;
8124 if (hist_ptr >= MAX_HDR_HISTORY)
8125 hist_ptr -= MAX_HDR_HISTORY;
8126 *vptr = ptr_hist[hist_ptr];
8127 *vlen = len_hist[hist_ptr];
8128 return 1;
8129 }
8130
8131 /* Return in <vptr> and <vlen> the pointer and length of occurrence <occ> of
8132 * header whose name is <hname> of length <hlen>. If <ctx> is null, lookup is
8133 * performed over the whole headers. Otherwise it must contain a valid header
8134 * context, initialised with ctx->idx=0 for the first lookup in a series. If
8135 * <occ> is positive or null, occurrence #occ from the beginning (or last ctx)
8136 * is returned. Occ #0 and #1 are equivalent. If <occ> is negative (and no less
8137 * than -MAX_HDR_HISTORY), the occurrence is counted from the last one which is
8138 * -1. This function differs from http_get_hdr() in that it only returns full
8139 * line header values and does not stop at commas.
8140 * The return value is 0 if nothing was found, or non-zero otherwise.
8141 */
http_get_fhdr(const struct http_msg * msg,const char * hname,int hlen,struct hdr_idx * idx,int occ,struct hdr_ctx * ctx,char ** vptr,int * vlen)8142 unsigned int http_get_fhdr(const struct http_msg *msg, const char *hname, int hlen,
8143 struct hdr_idx *idx, int occ,
8144 struct hdr_ctx *ctx, char **vptr, int *vlen)
8145 {
8146 struct hdr_ctx local_ctx;
8147 char *ptr_hist[MAX_HDR_HISTORY];
8148 int len_hist[MAX_HDR_HISTORY];
8149 unsigned int hist_ptr;
8150 int found;
8151
8152 if (!ctx) {
8153 local_ctx.idx = 0;
8154 ctx = &local_ctx;
8155 }
8156
8157 if (occ >= 0) {
8158 /* search from the beginning */
8159 while (http_find_full_header2(hname, hlen, msg->chn->buf->p, idx, ctx)) {
8160 occ--;
8161 if (occ <= 0) {
8162 *vptr = ctx->line + ctx->val;
8163 *vlen = ctx->vlen;
8164 return 1;
8165 }
8166 }
8167 return 0;
8168 }
8169
8170 /* negative occurrence, we scan all the list then walk back */
8171 if (-occ > MAX_HDR_HISTORY)
8172 return 0;
8173
8174 found = hist_ptr = 0;
8175 while (http_find_full_header2(hname, hlen, msg->chn->buf->p, idx, ctx)) {
8176 ptr_hist[hist_ptr] = ctx->line + ctx->val;
8177 len_hist[hist_ptr] = ctx->vlen;
8178 if (++hist_ptr >= MAX_HDR_HISTORY)
8179 hist_ptr = 0;
8180 found++;
8181 }
8182 if (-occ > found)
8183 return 0;
8184
8185 /* OK now we have the last occurrence in [hist_ptr-1], and we need to
8186 * find occurrence -occ. 0 <= hist_ptr < MAX_HDR_HISTORY, and we have
8187 * -10 <= occ <= -1. So we have to check [hist_ptr%MAX_HDR_HISTORY+occ]
8188 * to remain in the 0..9 range.
8189 */
8190 hist_ptr += occ + MAX_HDR_HISTORY;
8191 if (hist_ptr >= MAX_HDR_HISTORY)
8192 hist_ptr -= MAX_HDR_HISTORY;
8193 *vptr = ptr_hist[hist_ptr];
8194 *vlen = len_hist[hist_ptr];
8195 return 1;
8196 }
8197
8198 /*
8199 * Print a debug line with a header. Always stop at the first CR or LF char,
8200 * so it is safe to pass it a full buffer if needed. If <err> is not NULL, an
8201 * arrow is printed after the line which contains the pointer.
8202 */
debug_hdr(const char * dir,struct stream * s,const char * start,const char * end)8203 void debug_hdr(const char *dir, struct stream *s, const char *start, const char *end)
8204 {
8205 struct session *sess = strm_sess(s);
8206 int max;
8207
8208 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
8209 dir,
8210 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
8211 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
8212
8213 for (max = 0; start + max < end; max++)
8214 if (start[max] == '\r' || start[max] == '\n')
8215 break;
8216
8217 UBOUND(max, trash.size - trash.len - 3);
8218 trash.len += strlcpy2(trash.str + trash.len, start, max + 1);
8219 trash.str[trash.len++] = '\n';
8220 shut_your_big_mouth_gcc(write(1, trash.str, trash.len));
8221 }
8222
8223
8224 /* Allocate a new HTTP transaction for stream <s> unless there is one already.
8225 * The hdr_idx is allocated as well. In case of allocation failure, everything
8226 * allocated is freed and NULL is returned. Otherwise the new transaction is
8227 * assigned to the stream and returned.
8228 */
http_alloc_txn(struct stream * s)8229 struct http_txn *http_alloc_txn(struct stream *s)
8230 {
8231 struct http_txn *txn = s->txn;
8232
8233 if (txn)
8234 return txn;
8235
8236 txn = pool_alloc(pool_head_http_txn);
8237 if (!txn)
8238 return txn;
8239
8240 txn->hdr_idx.size = global.tune.max_http_hdr;
8241 txn->hdr_idx.v = pool_alloc(pool_head_hdr_idx);
8242 if (!txn->hdr_idx.v) {
8243 pool_free(pool_head_http_txn, txn);
8244 return NULL;
8245 }
8246
8247 s->txn = txn;
8248 return txn;
8249 }
8250
http_txn_reset_req(struct http_txn * txn)8251 void http_txn_reset_req(struct http_txn *txn)
8252 {
8253 txn->req.flags = 0;
8254 txn->req.sol = txn->req.eol = txn->req.eoh = 0; /* relative to the buffer */
8255 txn->req.next = 0;
8256 txn->req.chunk_len = 0LL;
8257 txn->req.body_len = 0LL;
8258 txn->req.msg_state = HTTP_MSG_RQBEFORE; /* at the very beginning of the request */
8259 }
8260
http_txn_reset_res(struct http_txn * txn)8261 void http_txn_reset_res(struct http_txn *txn)
8262 {
8263 txn->rsp.flags = 0;
8264 txn->rsp.sol = txn->rsp.eol = txn->rsp.eoh = 0; /* relative to the buffer */
8265 txn->rsp.next = 0;
8266 txn->rsp.chunk_len = 0LL;
8267 txn->rsp.body_len = 0LL;
8268 txn->rsp.msg_state = HTTP_MSG_RPBEFORE; /* at the very beginning of the response */
8269 }
8270
8271 /*
8272 * Initialize a new HTTP transaction for stream <s>. It is assumed that all
8273 * the required fields are properly allocated and that we only need to (re)init
8274 * them. This should be used before processing any new request.
8275 */
http_init_txn(struct stream * s)8276 void http_init_txn(struct stream *s)
8277 {
8278 struct http_txn *txn = s->txn;
8279 struct proxy *fe = strm_fe(s);
8280
8281 txn->flags = 0;
8282 txn->status = -1;
8283 *(unsigned int *)txn->cache_hash = 0;
8284
8285 txn->cookie_first_date = 0;
8286 txn->cookie_last_date = 0;
8287
8288 txn->srv_cookie = NULL;
8289 txn->cli_cookie = NULL;
8290 txn->uri = NULL;
8291
8292 http_txn_reset_req(txn);
8293 http_txn_reset_res(txn);
8294
8295 txn->req.chn = &s->req;
8296 txn->rsp.chn = &s->res;
8297
8298 txn->auth.method = HTTP_AUTH_UNKNOWN;
8299
8300 txn->req.err_pos = txn->rsp.err_pos = -2; /* block buggy requests/responses */
8301 if (fe->options2 & PR_O2_REQBUG_OK)
8302 txn->req.err_pos = -1; /* let buggy requests pass */
8303
8304 if (txn->hdr_idx.v)
8305 hdr_idx_init(&txn->hdr_idx);
8306
8307 vars_init(&s->vars_txn, SCOPE_TXN);
8308 vars_init(&s->vars_reqres, SCOPE_REQ);
8309 }
8310
8311 /* to be used at the end of a transaction */
http_end_txn(struct stream * s)8312 void http_end_txn(struct stream *s)
8313 {
8314 struct http_txn *txn = s->txn;
8315
8316 /* these ones will have been dynamically allocated */
8317 pool_free(pool_head_requri, txn->uri);
8318 pool_free(pool_head_capture, txn->cli_cookie);
8319 pool_free(pool_head_capture, txn->srv_cookie);
8320 pool_free(pool_head_uniqueid, s->unique_id);
8321
8322 s->unique_id = NULL;
8323 txn->uri = NULL;
8324 txn->srv_cookie = NULL;
8325 txn->cli_cookie = NULL;
8326
8327 vars_prune(&s->vars_txn, s->sess, s);
8328 vars_prune(&s->vars_reqres, s->sess, s);
8329 }
8330
8331 /* to be used at the end of a transaction to prepare a new one */
http_reset_txn(struct stream * s)8332 void http_reset_txn(struct stream *s)
8333 {
8334 http_end_txn(s);
8335 http_init_txn(s);
8336
8337 /* reinitialise the current rule list pointer to NULL. We are sure that
8338 * any rulelist match the NULL pointer.
8339 */
8340 s->current_rule_list = NULL;
8341
8342 s->be = strm_fe(s);
8343 s->logs.logwait = strm_fe(s)->to_log;
8344 s->logs.level = 0;
8345 stream_del_srv_conn(s);
8346 s->target = NULL;
8347 /* re-init store persistence */
8348 s->store_count = 0;
8349 s->uniq_id = HA_ATOMIC_XADD(&global.req_count, 1);
8350
8351 s->req.flags |= CF_READ_DONTWAIT; /* one read is usually enough */
8352
8353 /* We must trim any excess data from the response buffer, because we
8354 * may have blocked an invalid response from a server that we don't
8355 * want to accidentely forward once we disable the analysers, nor do
8356 * we want those data to come along with next response. A typical
8357 * example of such data would be from a buggy server responding to
8358 * a HEAD with some data, or sending more than the advertised
8359 * content-length.
8360 */
8361 if (unlikely(s->res.buf->i))
8362 s->res.buf->i = 0;
8363
8364 /* Now we can realign the response buffer */
8365 buffer_realign(s->res.buf);
8366
8367 s->req.rto = strm_fe(s)->timeout.client;
8368 s->req.wto = TICK_ETERNITY;
8369
8370 s->res.rto = TICK_ETERNITY;
8371 s->res.wto = strm_fe(s)->timeout.client;
8372
8373 s->req.rex = TICK_ETERNITY;
8374 s->req.wex = TICK_ETERNITY;
8375 s->req.analyse_exp = TICK_ETERNITY;
8376 s->res.rex = TICK_ETERNITY;
8377 s->res.wex = TICK_ETERNITY;
8378 s->res.analyse_exp = TICK_ETERNITY;
8379 s->si[1].hcto = TICK_ETERNITY;
8380 }
8381
8382 /* parse an "http-request" rule */
parse_http_req_cond(const char ** args,const char * file,int linenum,struct proxy * proxy)8383 struct act_rule *parse_http_req_cond(const char **args, const char *file, int linenum, struct proxy *proxy)
8384 {
8385 struct act_rule *rule;
8386 struct action_kw *custom = NULL;
8387 int cur_arg;
8388 char *error;
8389
8390 rule = calloc(1, sizeof(*rule));
8391 if (!rule) {
8392 ha_alert("parsing [%s:%d]: out of memory.\n", file, linenum);
8393 goto out_err;
8394 }
8395
8396 if (!strcmp(args[0], "allow")) {
8397 rule->action = ACT_ACTION_ALLOW;
8398 cur_arg = 1;
8399 } else if (!strcmp(args[0], "deny") || !strcmp(args[0], "block") || !strcmp(args[0], "tarpit")) {
8400 int code;
8401 int hc;
8402
8403 if (!strcmp(args[0], "tarpit")) {
8404 rule->action = ACT_HTTP_REQ_TARPIT;
8405 rule->deny_status = HTTP_ERR_500;
8406 }
8407 else {
8408 rule->action = ACT_ACTION_DENY;
8409 rule->deny_status = HTTP_ERR_403;
8410 }
8411 cur_arg = 1;
8412 if (strcmp(args[cur_arg], "deny_status") == 0) {
8413 cur_arg++;
8414 if (!args[cur_arg]) {
8415 ha_alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-request %s' rule : missing status code.\n",
8416 file, linenum, proxy_type_str(proxy), proxy->id, args[0]);
8417 goto out_err;
8418 }
8419
8420 code = atol(args[cur_arg]);
8421 cur_arg++;
8422 for (hc = 0; hc < HTTP_ERR_SIZE; hc++) {
8423 if (http_err_codes[hc] == code) {
8424 rule->deny_status = hc;
8425 break;
8426 }
8427 }
8428
8429 if (hc >= HTTP_ERR_SIZE) {
8430 ha_warning("parsing [%s:%d] : status code %d not handled, using default code %d.\n",
8431 file, linenum, code, http_err_codes[rule->deny_status]);
8432 }
8433 }
8434 } else if (!strcmp(args[0], "auth")) {
8435 rule->action = ACT_HTTP_REQ_AUTH;
8436 cur_arg = 1;
8437
8438 while(*args[cur_arg]) {
8439 if (!strcmp(args[cur_arg], "realm")) {
8440 rule->arg.auth.realm = strdup(args[cur_arg + 1]);
8441 cur_arg+=2;
8442 continue;
8443 } else
8444 break;
8445 }
8446 } else if (!strcmp(args[0], "set-nice")) {
8447 rule->action = ACT_HTTP_SET_NICE;
8448 cur_arg = 1;
8449
8450 if (!*args[cur_arg] ||
8451 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
8452 ha_alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument (integer value).\n",
8453 file, linenum, args[0]);
8454 goto out_err;
8455 }
8456 rule->arg.nice = atoi(args[cur_arg]);
8457 if (rule->arg.nice < -1024)
8458 rule->arg.nice = -1024;
8459 else if (rule->arg.nice > 1024)
8460 rule->arg.nice = 1024;
8461 cur_arg++;
8462 } else if (!strcmp(args[0], "set-tos")) {
8463 #ifdef IP_TOS
8464 char *err;
8465 rule->action = ACT_HTTP_SET_TOS;
8466 cur_arg = 1;
8467
8468 if (!*args[cur_arg] ||
8469 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
8470 ha_alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument (integer/hex value).\n",
8471 file, linenum, args[0]);
8472 goto out_err;
8473 }
8474
8475 rule->arg.tos = strtol(args[cur_arg], &err, 0);
8476 if (err && *err != '\0') {
8477 ha_alert("parsing [%s:%d]: invalid character starting at '%s' in 'http-request %s' (integer/hex value expected).\n",
8478 file, linenum, err, args[0]);
8479 goto out_err;
8480 }
8481 cur_arg++;
8482 #else
8483 ha_alert("parsing [%s:%d]: 'http-request %s' is not supported on this platform (IP_TOS undefined).\n", file, linenum, args[0]);
8484 goto out_err;
8485 #endif
8486 } else if (!strcmp(args[0], "set-mark")) {
8487 #ifdef SO_MARK
8488 char *err;
8489 rule->action = ACT_HTTP_SET_MARK;
8490 cur_arg = 1;
8491
8492 if (!*args[cur_arg] ||
8493 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
8494 ha_alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument (integer/hex value).\n",
8495 file, linenum, args[0]);
8496 goto out_err;
8497 }
8498
8499 rule->arg.mark = strtoul(args[cur_arg], &err, 0);
8500 if (err && *err != '\0') {
8501 ha_alert("parsing [%s:%d]: invalid character starting at '%s' in 'http-request %s' (integer/hex value expected).\n",
8502 file, linenum, err, args[0]);
8503 goto out_err;
8504 }
8505 cur_arg++;
8506 global.last_checks |= LSTCHK_NETADM;
8507 #else
8508 ha_alert("parsing [%s:%d]: 'http-request %s' is not supported on this platform (SO_MARK undefined).\n", file, linenum, args[0]);
8509 goto out_err;
8510 #endif
8511 } else if (!strcmp(args[0], "set-log-level")) {
8512 rule->action = ACT_HTTP_SET_LOGL;
8513 cur_arg = 1;
8514
8515 if (!*args[cur_arg] ||
8516 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
8517 bad_log_level:
8518 ha_alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument (log level name or 'silent').\n",
8519 file, linenum, args[0]);
8520 goto out_err;
8521 }
8522 if (strcmp(args[cur_arg], "silent") == 0)
8523 rule->arg.loglevel = -1;
8524 else if ((rule->arg.loglevel = get_log_level(args[cur_arg]) + 1) == 0)
8525 goto bad_log_level;
8526 cur_arg++;
8527 } else if (strcmp(args[0], "add-header") == 0 || strcmp(args[0], "set-header") == 0) {
8528 rule->action = *args[0] == 'a' ? ACT_HTTP_ADD_HDR : ACT_HTTP_SET_HDR;
8529 cur_arg = 1;
8530
8531 if (!*args[cur_arg] || !*args[cur_arg+1] ||
8532 (*args[cur_arg+2] && strcmp(args[cur_arg+2], "if") != 0 && strcmp(args[cur_arg+2], "unless") != 0)) {
8533 ha_alert("parsing [%s:%d]: 'http-request %s' expects exactly 2 arguments.\n",
8534 file, linenum, args[0]);
8535 goto out_err;
8536 }
8537
8538 rule->arg.hdr_add.name = strdup(args[cur_arg]);
8539 rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name);
8540 LIST_INIT(&rule->arg.hdr_add.fmt);
8541
8542 proxy->conf.args.ctx = ARGC_HRQ;
8543 error = NULL;
8544 if (!parse_logformat_string(args[cur_arg + 1], proxy, &rule->arg.hdr_add.fmt, LOG_OPT_HTTP,
8545 (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, &error)) {
8546 ha_alert("parsing [%s:%d]: 'http-request %s': %s.\n",
8547 file, linenum, args[0], error);
8548 free(error);
8549 goto out_err;
8550 }
8551 free(proxy->conf.lfs_file);
8552 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
8553 proxy->conf.lfs_line = proxy->conf.args.line;
8554 cur_arg += 2;
8555 } else if (strcmp(args[0], "replace-header") == 0 || strcmp(args[0], "replace-value") == 0) {
8556 rule->action = args[0][8] == 'h' ? ACT_HTTP_REPLACE_HDR : ACT_HTTP_REPLACE_VAL;
8557 cur_arg = 1;
8558
8559 if (!*args[cur_arg] || !*args[cur_arg+1] || !*args[cur_arg+2] ||
8560 (*args[cur_arg+3] && strcmp(args[cur_arg+3], "if") != 0 && strcmp(args[cur_arg+3], "unless") != 0)) {
8561 ha_alert("parsing [%s:%d]: 'http-request %s' expects exactly 3 arguments.\n",
8562 file, linenum, args[0]);
8563 goto out_err;
8564 }
8565
8566 rule->arg.hdr_add.name = strdup(args[cur_arg]);
8567 rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name);
8568 LIST_INIT(&rule->arg.hdr_add.fmt);
8569
8570 error = NULL;
8571 if (!regex_comp(args[cur_arg + 1], &rule->arg.hdr_add.re, 1, 1, &error)) {
8572 ha_alert("parsing [%s:%d] : '%s' : %s.\n", file, linenum,
8573 args[cur_arg + 1], error);
8574 free(error);
8575 goto out_err;
8576 }
8577
8578 proxy->conf.args.ctx = ARGC_HRQ;
8579 error = NULL;
8580 if (!parse_logformat_string(args[cur_arg + 2], proxy, &rule->arg.hdr_add.fmt, LOG_OPT_HTTP,
8581 (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, &error)) {
8582 ha_alert("parsing [%s:%d]: 'http-request %s': %s.\n",
8583 file, linenum, args[0], error);
8584 free(error);
8585 goto out_err;
8586 }
8587
8588 free(proxy->conf.lfs_file);
8589 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
8590 proxy->conf.lfs_line = proxy->conf.args.line;
8591 cur_arg += 3;
8592 } else if (strcmp(args[0], "del-header") == 0) {
8593 rule->action = ACT_HTTP_DEL_HDR;
8594 cur_arg = 1;
8595
8596 if (!*args[cur_arg] ||
8597 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
8598 ha_alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument.\n",
8599 file, linenum, args[0]);
8600 goto out_err;
8601 }
8602
8603 rule->arg.hdr_add.name = strdup(args[cur_arg]);
8604 rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name);
8605
8606 proxy->conf.args.ctx = ARGC_HRQ;
8607 free(proxy->conf.lfs_file);
8608 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
8609 proxy->conf.lfs_line = proxy->conf.args.line;
8610 cur_arg += 1;
8611 } else if (strncmp(args[0], "track-sc", 8) == 0 &&
8612 args[0][9] == '\0' && args[0][8] >= '0' &&
8613 args[0][8] < '0' + MAX_SESS_STKCTR) { /* track-sc 0..9 */
8614 struct sample_expr *expr;
8615 unsigned int where;
8616 char *err = NULL;
8617
8618 cur_arg = 1;
8619 proxy->conf.args.ctx = ARGC_TRK;
8620
8621 expr = sample_parse_expr((char **)args, &cur_arg, file, linenum, &err, &proxy->conf.args);
8622 if (!expr) {
8623 ha_alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-request %s' rule : %s.\n",
8624 file, linenum, proxy_type_str(proxy), proxy->id, args[0], err);
8625 free(err);
8626 goto out_err;
8627 }
8628
8629 where = 0;
8630 if (proxy->cap & PR_CAP_FE)
8631 where |= SMP_VAL_FE_HRQ_HDR;
8632 if (proxy->cap & PR_CAP_BE)
8633 where |= SMP_VAL_BE_HRQ_HDR;
8634
8635 if (!(expr->fetch->val & where)) {
8636 ha_alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-request %s' rule :"
8637 " fetch method '%s' extracts information from '%s', none of which is available here.\n",
8638 file, linenum, proxy_type_str(proxy), proxy->id, args[0],
8639 args[cur_arg-1], sample_src_names(expr->fetch->use));
8640 free(expr);
8641 goto out_err;
8642 }
8643
8644 if (strcmp(args[cur_arg], "table") == 0) {
8645 cur_arg++;
8646 if (!args[cur_arg]) {
8647 ha_alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-request %s' rule : missing table name.\n",
8648 file, linenum, proxy_type_str(proxy), proxy->id, args[0]);
8649 free(expr);
8650 goto out_err;
8651 }
8652 /* we copy the table name for now, it will be resolved later */
8653 rule->arg.trk_ctr.table.n = strdup(args[cur_arg]);
8654 cur_arg++;
8655 }
8656 rule->arg.trk_ctr.expr = expr;
8657 rule->action = ACT_ACTION_TRK_SC0 + args[0][8] - '0';
8658 rule->check_ptr = check_trk_action;
8659 } else if (strcmp(args[0], "redirect") == 0) {
8660 struct redirect_rule *redir;
8661 char *errmsg = NULL;
8662
8663 if ((redir = http_parse_redirect_rule(file, linenum, proxy, (const char **)args + 1, &errmsg, 1, 0)) == NULL) {
8664 ha_alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-request %s' rule : %s.\n",
8665 file, linenum, proxy_type_str(proxy), proxy->id, args[0], errmsg);
8666 goto out_err;
8667 }
8668
8669 /* this redirect rule might already contain a parsed condition which
8670 * we'll pass to the http-request rule.
8671 */
8672 rule->action = ACT_HTTP_REDIR;
8673 rule->arg.redir = redir;
8674 rule->cond = redir->cond;
8675 redir->cond = NULL;
8676 cur_arg = 2;
8677 return rule;
8678 } else if (strncmp(args[0], "add-acl", 7) == 0) {
8679 /* http-request add-acl(<reference (acl name)>) <key pattern> */
8680 rule->action = ACT_HTTP_ADD_ACL;
8681 /*
8682 * '+ 8' for 'add-acl('
8683 * '- 9' for 'add-acl(' + trailing ')'
8684 */
8685 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
8686
8687 cur_arg = 1;
8688
8689 if (!*args[cur_arg] ||
8690 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
8691 ha_alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument.\n",
8692 file, linenum, args[0]);
8693 goto out_err;
8694 }
8695
8696 LIST_INIT(&rule->arg.map.key);
8697 proxy->conf.args.ctx = ARGC_HRQ;
8698 error = NULL;
8699 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
8700 (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, &error)) {
8701 ha_alert("parsing [%s:%d]: 'http-request %s': %s.\n",
8702 file, linenum, args[0], error);
8703 free(error);
8704 goto out_err;
8705 }
8706 free(proxy->conf.lfs_file);
8707 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
8708 proxy->conf.lfs_line = proxy->conf.args.line;
8709 cur_arg += 1;
8710 } else if (strncmp(args[0], "del-acl", 7) == 0) {
8711 /* http-request del-acl(<reference (acl name)>) <key pattern> */
8712 rule->action = ACT_HTTP_DEL_ACL;
8713 /*
8714 * '+ 8' for 'del-acl('
8715 * '- 9' for 'del-acl(' + trailing ')'
8716 */
8717 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
8718
8719 cur_arg = 1;
8720
8721 if (!*args[cur_arg] ||
8722 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
8723 ha_alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument.\n",
8724 file, linenum, args[0]);
8725 goto out_err;
8726 }
8727
8728 LIST_INIT(&rule->arg.map.key);
8729 proxy->conf.args.ctx = ARGC_HRQ;
8730 error = NULL;
8731 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
8732 (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, &error)) {
8733 ha_alert("parsing [%s:%d]: 'http-request %s': %s.\n",
8734 file, linenum, args[0], error);
8735 free(error);
8736 goto out_err;
8737 }
8738 free(proxy->conf.lfs_file);
8739 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
8740 proxy->conf.lfs_line = proxy->conf.args.line;
8741 cur_arg += 1;
8742 } else if (strncmp(args[0], "del-map", 7) == 0) {
8743 /* http-request del-map(<reference (map name)>) <key pattern> */
8744 rule->action = ACT_HTTP_DEL_MAP;
8745 /*
8746 * '+ 8' for 'del-map('
8747 * '- 9' for 'del-map(' + trailing ')'
8748 */
8749 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
8750
8751 cur_arg = 1;
8752
8753 if (!*args[cur_arg] ||
8754 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
8755 ha_alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument.\n",
8756 file, linenum, args[0]);
8757 goto out_err;
8758 }
8759
8760 LIST_INIT(&rule->arg.map.key);
8761 proxy->conf.args.ctx = ARGC_HRQ;
8762 error = NULL;
8763 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
8764 (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, &error)) {
8765 ha_alert("parsing [%s:%d]: 'http-request %s': %s.\n",
8766 file, linenum, args[0], error);
8767 free(error);
8768 goto out_err;
8769 }
8770 free(proxy->conf.lfs_file);
8771 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
8772 proxy->conf.lfs_line = proxy->conf.args.line;
8773 cur_arg += 1;
8774 } else if (strncmp(args[0], "set-map", 7) == 0) {
8775 /* http-request set-map(<reference (map name)>) <key pattern> <value pattern> */
8776 rule->action = ACT_HTTP_SET_MAP;
8777 /*
8778 * '+ 8' for 'set-map('
8779 * '- 9' for 'set-map(' + trailing ')'
8780 */
8781 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
8782
8783 cur_arg = 1;
8784
8785 if (!*args[cur_arg] || !*args[cur_arg+1] ||
8786 (*args[cur_arg+2] && strcmp(args[cur_arg+2], "if") != 0 && strcmp(args[cur_arg+2], "unless") != 0)) {
8787 ha_alert("parsing [%s:%d]: 'http-request %s' expects exactly 2 arguments.\n",
8788 file, linenum, args[0]);
8789 goto out_err;
8790 }
8791
8792 LIST_INIT(&rule->arg.map.key);
8793 LIST_INIT(&rule->arg.map.value);
8794 proxy->conf.args.ctx = ARGC_HRQ;
8795
8796 /* key pattern */
8797 error = NULL;
8798 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
8799 (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, &error)) {
8800 ha_alert("parsing [%s:%d]: 'http-request %s' key: %s.\n",
8801 file, linenum, args[0], error);
8802 free(error);
8803 goto out_err;
8804 }
8805
8806 /* value pattern */
8807 error = NULL;
8808 if (!parse_logformat_string(args[cur_arg + 1], proxy, &rule->arg.map.value, LOG_OPT_HTTP,
8809 (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, &error)) {
8810 ha_alert("parsing [%s:%d]: 'http-request %s' pattern: %s.\n",
8811 file, linenum, args[0], error);
8812 free(error);
8813 goto out_err;
8814 }
8815 free(proxy->conf.lfs_file);
8816 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
8817 proxy->conf.lfs_line = proxy->conf.args.line;
8818
8819 cur_arg += 2;
8820 } else if (((custom = action_http_req_custom(args[0])) != NULL)) {
8821 char *errmsg = NULL;
8822 cur_arg = 1;
8823 /* try in the module list */
8824 rule->from = ACT_F_HTTP_REQ;
8825 rule->kw = custom;
8826 if (custom->parse(args, &cur_arg, proxy, rule, &errmsg) == ACT_RET_PRS_ERR) {
8827 ha_alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-request %s' rule : %s.\n",
8828 file, linenum, proxy_type_str(proxy), proxy->id, args[0], errmsg);
8829 free(errmsg);
8830 goto out_err;
8831 }
8832 } else {
8833 action_build_list(&http_req_keywords.list, &trash);
8834 ha_alert("parsing [%s:%d]: 'http-request' expects 'allow', 'deny', 'auth', 'redirect', "
8835 "'tarpit', 'add-header', 'set-header', 'replace-header', 'replace-value', 'set-nice', "
8836 "'set-tos', 'set-mark', 'set-log-level', 'add-acl', 'del-acl', 'del-map', 'set-map', 'track-sc*'"
8837 "%s%s, but got '%s'%s.\n",
8838 file, linenum, *trash.str ? ", " : "", trash.str, args[0], *args[0] ? "" : " (missing argument)");
8839 goto out_err;
8840 }
8841
8842 if (strcmp(args[cur_arg], "if") == 0 || strcmp(args[cur_arg], "unless") == 0) {
8843 struct acl_cond *cond;
8844 char *errmsg = NULL;
8845
8846 if ((cond = build_acl_cond(file, linenum, &proxy->acl, proxy, args+cur_arg, &errmsg)) == NULL) {
8847 ha_alert("parsing [%s:%d] : error detected while parsing an 'http-request %s' condition : %s.\n",
8848 file, linenum, args[0], errmsg);
8849 free(errmsg);
8850 goto out_err;
8851 }
8852 rule->cond = cond;
8853 }
8854 else if (*args[cur_arg]) {
8855 ha_alert("parsing [%s:%d]: 'http-request %s' expects 'realm' for 'auth',"
8856 " 'deny_status' for 'deny', or"
8857 " either 'if' or 'unless' followed by a condition but found '%s'.\n",
8858 file, linenum, args[0], args[cur_arg]);
8859 goto out_err;
8860 }
8861
8862 return rule;
8863 out_err:
8864 free(rule);
8865 return NULL;
8866 }
8867
8868 /* parse an "http-respose" rule */
parse_http_res_cond(const char ** args,const char * file,int linenum,struct proxy * proxy)8869 struct act_rule *parse_http_res_cond(const char **args, const char *file, int linenum, struct proxy *proxy)
8870 {
8871 struct act_rule *rule;
8872 struct action_kw *custom = NULL;
8873 int cur_arg;
8874 char *error;
8875
8876 rule = calloc(1, sizeof(*rule));
8877 if (!rule) {
8878 ha_alert("parsing [%s:%d]: out of memory.\n", file, linenum);
8879 goto out_err;
8880 }
8881
8882 if (!strcmp(args[0], "allow")) {
8883 rule->action = ACT_ACTION_ALLOW;
8884 cur_arg = 1;
8885 } else if (!strcmp(args[0], "deny")) {
8886 rule->action = ACT_ACTION_DENY;
8887 cur_arg = 1;
8888 } else if (!strcmp(args[0], "set-nice")) {
8889 rule->action = ACT_HTTP_SET_NICE;
8890 cur_arg = 1;
8891
8892 if (!*args[cur_arg] ||
8893 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
8894 ha_alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument (integer value).\n",
8895 file, linenum, args[0]);
8896 goto out_err;
8897 }
8898 rule->arg.nice = atoi(args[cur_arg]);
8899 if (rule->arg.nice < -1024)
8900 rule->arg.nice = -1024;
8901 else if (rule->arg.nice > 1024)
8902 rule->arg.nice = 1024;
8903 cur_arg++;
8904 } else if (!strcmp(args[0], "set-tos")) {
8905 #ifdef IP_TOS
8906 char *err;
8907 rule->action = ACT_HTTP_SET_TOS;
8908 cur_arg = 1;
8909
8910 if (!*args[cur_arg] ||
8911 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
8912 ha_alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument (integer/hex value).\n",
8913 file, linenum, args[0]);
8914 goto out_err;
8915 }
8916
8917 rule->arg.tos = strtol(args[cur_arg], &err, 0);
8918 if (err && *err != '\0') {
8919 ha_alert("parsing [%s:%d]: invalid character starting at '%s' in 'http-response %s' (integer/hex value expected).\n",
8920 file, linenum, err, args[0]);
8921 goto out_err;
8922 }
8923 cur_arg++;
8924 #else
8925 ha_alert("parsing [%s:%d]: 'http-response %s' is not supported on this platform (IP_TOS undefined).\n", file, linenum, args[0]);
8926 goto out_err;
8927 #endif
8928 } else if (!strcmp(args[0], "set-mark")) {
8929 #ifdef SO_MARK
8930 char *err;
8931 rule->action = ACT_HTTP_SET_MARK;
8932 cur_arg = 1;
8933
8934 if (!*args[cur_arg] ||
8935 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
8936 ha_alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument (integer/hex value).\n",
8937 file, linenum, args[0]);
8938 goto out_err;
8939 }
8940
8941 rule->arg.mark = strtoul(args[cur_arg], &err, 0);
8942 if (err && *err != '\0') {
8943 ha_alert("parsing [%s:%d]: invalid character starting at '%s' in 'http-response %s' (integer/hex value expected).\n",
8944 file, linenum, err, args[0]);
8945 goto out_err;
8946 }
8947 cur_arg++;
8948 global.last_checks |= LSTCHK_NETADM;
8949 #else
8950 ha_alert("parsing [%s:%d]: 'http-response %s' is not supported on this platform (SO_MARK undefined).\n", file, linenum, args[0]);
8951 goto out_err;
8952 #endif
8953 } else if (!strcmp(args[0], "set-log-level")) {
8954 rule->action = ACT_HTTP_SET_LOGL;
8955 cur_arg = 1;
8956
8957 if (!*args[cur_arg] ||
8958 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
8959 bad_log_level:
8960 ha_alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument (log level name or 'silent').\n",
8961 file, linenum, args[0]);
8962 goto out_err;
8963 }
8964 if (strcmp(args[cur_arg], "silent") == 0)
8965 rule->arg.loglevel = -1;
8966 else if ((rule->arg.loglevel = get_log_level(args[cur_arg]) + 1) == 0)
8967 goto bad_log_level;
8968 cur_arg++;
8969 } else if (strcmp(args[0], "add-header") == 0 || strcmp(args[0], "set-header") == 0) {
8970 rule->action = *args[0] == 'a' ? ACT_HTTP_ADD_HDR : ACT_HTTP_SET_HDR;
8971 cur_arg = 1;
8972
8973 if (!*args[cur_arg] || !*args[cur_arg+1] ||
8974 (*args[cur_arg+2] && strcmp(args[cur_arg+2], "if") != 0 && strcmp(args[cur_arg+2], "unless") != 0)) {
8975 ha_alert("parsing [%s:%d]: 'http-response %s' expects exactly 2 arguments.\n",
8976 file, linenum, args[0]);
8977 goto out_err;
8978 }
8979
8980 rule->arg.hdr_add.name = strdup(args[cur_arg]);
8981 rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name);
8982 LIST_INIT(&rule->arg.hdr_add.fmt);
8983
8984 proxy->conf.args.ctx = ARGC_HRS;
8985 error = NULL;
8986 if (!parse_logformat_string(args[cur_arg + 1], proxy, &rule->arg.hdr_add.fmt, LOG_OPT_HTTP,
8987 (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, &error)) {
8988 ha_alert("parsing [%s:%d]: 'http-response %s': %s.\n",
8989 file, linenum, args[0], error);
8990 free(error);
8991 goto out_err;
8992 }
8993 free(proxy->conf.lfs_file);
8994 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
8995 proxy->conf.lfs_line = proxy->conf.args.line;
8996 cur_arg += 2;
8997 } else if (strcmp(args[0], "replace-header") == 0 || strcmp(args[0], "replace-value") == 0) {
8998 rule->action = args[0][8] == 'h' ? ACT_HTTP_REPLACE_HDR : ACT_HTTP_REPLACE_VAL;
8999 cur_arg = 1;
9000
9001 if (!*args[cur_arg] || !*args[cur_arg+1] || !*args[cur_arg+2] ||
9002 (*args[cur_arg+3] && strcmp(args[cur_arg+3], "if") != 0 && strcmp(args[cur_arg+3], "unless") != 0)) {
9003 ha_alert("parsing [%s:%d]: 'http-response %s' expects exactly 3 arguments.\n",
9004 file, linenum, args[0]);
9005 goto out_err;
9006 }
9007
9008 rule->arg.hdr_add.name = strdup(args[cur_arg]);
9009 rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name);
9010 LIST_INIT(&rule->arg.hdr_add.fmt);
9011
9012 error = NULL;
9013 if (!regex_comp(args[cur_arg + 1], &rule->arg.hdr_add.re, 1, 1, &error)) {
9014 ha_alert("parsing [%s:%d] : '%s' : %s.\n", file, linenum,
9015 args[cur_arg + 1], error);
9016 free(error);
9017 goto out_err;
9018 }
9019
9020 proxy->conf.args.ctx = ARGC_HRQ;
9021 error = NULL;
9022 if (!parse_logformat_string(args[cur_arg + 2], proxy, &rule->arg.hdr_add.fmt, LOG_OPT_HTTP,
9023 (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, &error)) {
9024 ha_alert("parsing [%s:%d]: 'http-response %s': %s.\n",
9025 file, linenum, args[0], error);
9026 free(error);
9027 goto out_err;
9028 }
9029
9030 free(proxy->conf.lfs_file);
9031 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9032 proxy->conf.lfs_line = proxy->conf.args.line;
9033 cur_arg += 3;
9034 } else if (strcmp(args[0], "del-header") == 0) {
9035 rule->action = ACT_HTTP_DEL_HDR;
9036 cur_arg = 1;
9037
9038 if (!*args[cur_arg] ||
9039 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
9040 ha_alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument.\n",
9041 file, linenum, args[0]);
9042 goto out_err;
9043 }
9044
9045 rule->arg.hdr_add.name = strdup(args[cur_arg]);
9046 rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name);
9047
9048 proxy->conf.args.ctx = ARGC_HRS;
9049 free(proxy->conf.lfs_file);
9050 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9051 proxy->conf.lfs_line = proxy->conf.args.line;
9052 cur_arg += 1;
9053 } else if (strncmp(args[0], "add-acl", 7) == 0) {
9054 /* http-request add-acl(<reference (acl name)>) <key pattern> */
9055 rule->action = ACT_HTTP_ADD_ACL;
9056 /*
9057 * '+ 8' for 'add-acl('
9058 * '- 9' for 'add-acl(' + trailing ')'
9059 */
9060 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
9061
9062 cur_arg = 1;
9063
9064 if (!*args[cur_arg] ||
9065 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
9066 ha_alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument.\n",
9067 file, linenum, args[0]);
9068 goto out_err;
9069 }
9070
9071 LIST_INIT(&rule->arg.map.key);
9072 proxy->conf.args.ctx = ARGC_HRS;
9073 error = NULL;
9074 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
9075 (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, &error)) {
9076 ha_alert("parsing [%s:%d]: 'http-response %s': %s.\n",
9077 file, linenum, args[0], error);
9078 free(error);
9079 goto out_err;
9080 }
9081 free(proxy->conf.lfs_file);
9082 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9083 proxy->conf.lfs_line = proxy->conf.args.line;
9084
9085 cur_arg += 1;
9086 } else if (strncmp(args[0], "del-acl", 7) == 0) {
9087 /* http-response del-acl(<reference (acl name)>) <key pattern> */
9088 rule->action = ACT_HTTP_DEL_ACL;
9089 /*
9090 * '+ 8' for 'del-acl('
9091 * '- 9' for 'del-acl(' + trailing ')'
9092 */
9093 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
9094
9095 cur_arg = 1;
9096
9097 if (!*args[cur_arg] ||
9098 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
9099 ha_alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument.\n",
9100 file, linenum, args[0]);
9101 goto out_err;
9102 }
9103
9104 LIST_INIT(&rule->arg.map.key);
9105 proxy->conf.args.ctx = ARGC_HRS;
9106 error = NULL;
9107 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
9108 (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, &error)) {
9109 ha_alert("parsing [%s:%d]: 'http-response %s': %s.\n",
9110 file, linenum, args[0], error);
9111 free(error);
9112 goto out_err;
9113 }
9114 free(proxy->conf.lfs_file);
9115 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9116 proxy->conf.lfs_line = proxy->conf.args.line;
9117 cur_arg += 1;
9118 } else if (strncmp(args[0], "del-map", 7) == 0) {
9119 /* http-response del-map(<reference (map name)>) <key pattern> */
9120 rule->action = ACT_HTTP_DEL_MAP;
9121 /*
9122 * '+ 8' for 'del-map('
9123 * '- 9' for 'del-map(' + trailing ')'
9124 */
9125 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
9126
9127 cur_arg = 1;
9128
9129 if (!*args[cur_arg] ||
9130 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
9131 ha_alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument.\n",
9132 file, linenum, args[0]);
9133 goto out_err;
9134 }
9135
9136 LIST_INIT(&rule->arg.map.key);
9137 proxy->conf.args.ctx = ARGC_HRS;
9138 error = NULL;
9139 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
9140 (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, &error)) {
9141 ha_alert("parsing [%s:%d]: 'http-response %s' %s.\n",
9142 file, linenum, args[0], error);
9143 free(error);
9144 goto out_err;
9145 }
9146 free(proxy->conf.lfs_file);
9147 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9148 proxy->conf.lfs_line = proxy->conf.args.line;
9149 cur_arg += 1;
9150 } else if (strncmp(args[0], "set-map", 7) == 0) {
9151 /* http-response set-map(<reference (map name)>) <key pattern> <value pattern> */
9152 rule->action = ACT_HTTP_SET_MAP;
9153 /*
9154 * '+ 8' for 'set-map('
9155 * '- 9' for 'set-map(' + trailing ')'
9156 */
9157 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
9158
9159 cur_arg = 1;
9160
9161 if (!*args[cur_arg] || !*args[cur_arg+1] ||
9162 (*args[cur_arg+2] && strcmp(args[cur_arg+2], "if") != 0 && strcmp(args[cur_arg+2], "unless") != 0)) {
9163 ha_alert("parsing [%s:%d]: 'http-response %s' expects exactly 2 arguments.\n",
9164 file, linenum, args[0]);
9165 goto out_err;
9166 }
9167
9168 LIST_INIT(&rule->arg.map.key);
9169 LIST_INIT(&rule->arg.map.value);
9170
9171 proxy->conf.args.ctx = ARGC_HRS;
9172
9173 /* key pattern */
9174 error = NULL;
9175 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
9176 (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, &error)) {
9177 ha_alert("parsing [%s:%d]: 'http-response %s' name: %s.\n",
9178 file, linenum, args[0], error);
9179 free(error);
9180 goto out_err;
9181 }
9182
9183 /* value pattern */
9184 error = NULL;
9185 if (!parse_logformat_string(args[cur_arg + 1], proxy, &rule->arg.map.value, LOG_OPT_HTTP,
9186 (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, &error)) {
9187 ha_alert("parsing [%s:%d]: 'http-response %s' value: %s.\n",
9188 file, linenum, args[0], error);
9189 free(error);
9190 goto out_err;
9191 }
9192
9193 free(proxy->conf.lfs_file);
9194 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9195 proxy->conf.lfs_line = proxy->conf.args.line;
9196
9197 cur_arg += 2;
9198 } else if (strcmp(args[0], "redirect") == 0) {
9199 struct redirect_rule *redir;
9200 char *errmsg = NULL;
9201
9202 if ((redir = http_parse_redirect_rule(file, linenum, proxy, (const char **)args + 1, &errmsg, 1, 1)) == NULL) {
9203 ha_alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-response %s' rule : %s.\n",
9204 file, linenum, proxy_type_str(proxy), proxy->id, args[0], errmsg);
9205 goto out_err;
9206 }
9207
9208 /* this redirect rule might already contain a parsed condition which
9209 * we'll pass to the http-request rule.
9210 */
9211 rule->action = ACT_HTTP_REDIR;
9212 rule->arg.redir = redir;
9213 rule->cond = redir->cond;
9214 redir->cond = NULL;
9215 cur_arg = 2;
9216 return rule;
9217 } else if (strncmp(args[0], "track-sc", 8) == 0 &&
9218 args[0][9] == '\0' && args[0][8] >= '0' &&
9219 args[0][8] < '0' + MAX_SESS_STKCTR) { /* track-sc 0..9 */
9220 struct sample_expr *expr;
9221 unsigned int where;
9222 char *err = NULL;
9223
9224 cur_arg = 1;
9225 proxy->conf.args.ctx = ARGC_TRK;
9226
9227 expr = sample_parse_expr((char **)args, &cur_arg, file, linenum, &err, &proxy->conf.args);
9228 if (!expr) {
9229 ha_alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-response %s' rule : %s.\n",
9230 file, linenum, proxy_type_str(proxy), proxy->id, args[0], err);
9231 free(err);
9232 goto out_err;
9233 }
9234
9235 where = 0;
9236 if (proxy->cap & PR_CAP_FE)
9237 where |= SMP_VAL_FE_HRS_HDR;
9238 if (proxy->cap & PR_CAP_BE)
9239 where |= SMP_VAL_BE_HRS_HDR;
9240
9241 if (!(expr->fetch->val & where)) {
9242 ha_alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-response %s' rule :"
9243 " fetch method '%s' extracts information from '%s', none of which is available here.\n",
9244 file, linenum, proxy_type_str(proxy), proxy->id, args[0],
9245 args[cur_arg-1], sample_src_names(expr->fetch->use));
9246 free(expr);
9247 goto out_err;
9248 }
9249
9250 if (strcmp(args[cur_arg], "table") == 0) {
9251 cur_arg++;
9252 if (!args[cur_arg]) {
9253 ha_alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-response %s' rule : missing table name.\n",
9254 file, linenum, proxy_type_str(proxy), proxy->id, args[0]);
9255 free(expr);
9256 goto out_err;
9257 }
9258 /* we copy the table name for now, it will be resolved later */
9259 rule->arg.trk_ctr.table.n = strdup(args[cur_arg]);
9260 cur_arg++;
9261 }
9262 rule->arg.trk_ctr.expr = expr;
9263 rule->action = ACT_ACTION_TRK_SC0 + args[0][8] - '0';
9264 rule->check_ptr = check_trk_action;
9265 } else if (((custom = action_http_res_custom(args[0])) != NULL)) {
9266 char *errmsg = NULL;
9267 cur_arg = 1;
9268 /* try in the module list */
9269 rule->from = ACT_F_HTTP_RES;
9270 rule->kw = custom;
9271 if (custom->parse(args, &cur_arg, proxy, rule, &errmsg) == ACT_RET_PRS_ERR) {
9272 ha_alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-response %s' rule : %s.\n",
9273 file, linenum, proxy_type_str(proxy), proxy->id, args[0], errmsg);
9274 free(errmsg);
9275 goto out_err;
9276 }
9277 } else {
9278 action_build_list(&http_res_keywords.list, &trash);
9279 ha_alert("parsing [%s:%d]: 'http-response' expects 'allow', 'deny', 'redirect', "
9280 "'add-header', 'del-header', 'set-header', 'replace-header', 'replace-value', 'set-nice', "
9281 "'set-tos', 'set-mark', 'set-log-level', 'add-acl', 'del-acl', 'del-map', 'set-map', 'track-sc*'"
9282 "%s%s, but got '%s'%s.\n",
9283 file, linenum, *trash.str ? ", " : "", trash.str, args[0], *args[0] ? "" : " (missing argument)");
9284 goto out_err;
9285 }
9286
9287 if (strcmp(args[cur_arg], "if") == 0 || strcmp(args[cur_arg], "unless") == 0) {
9288 struct acl_cond *cond;
9289 char *errmsg = NULL;
9290
9291 if ((cond = build_acl_cond(file, linenum, &proxy->acl, proxy, args+cur_arg, &errmsg)) == NULL) {
9292 ha_alert("parsing [%s:%d] : error detected while parsing an 'http-response %s' condition : %s.\n",
9293 file, linenum, args[0], errmsg);
9294 free(errmsg);
9295 goto out_err;
9296 }
9297 rule->cond = cond;
9298 }
9299 else if (*args[cur_arg]) {
9300 ha_alert("parsing [%s:%d]: 'http-response %s' expects"
9301 " either 'if' or 'unless' followed by a condition but found '%s'.\n",
9302 file, linenum, args[0], args[cur_arg]);
9303 goto out_err;
9304 }
9305
9306 return rule;
9307 out_err:
9308 free(rule);
9309 return NULL;
9310 }
9311
9312 /* Parses a redirect rule. Returns the redirect rule on success or NULL on error,
9313 * with <err> filled with the error message. If <use_fmt> is not null, builds a
9314 * dynamic log-format rule instead of a static string. Parameter <dir> indicates
9315 * the direction of the rule, and equals 0 for request, non-zero for responses.
9316 */
http_parse_redirect_rule(const char * file,int linenum,struct proxy * curproxy,const char ** args,char ** errmsg,int use_fmt,int dir)9317 struct redirect_rule *http_parse_redirect_rule(const char *file, int linenum, struct proxy *curproxy,
9318 const char **args, char **errmsg, int use_fmt, int dir)
9319 {
9320 struct redirect_rule *rule;
9321 int cur_arg;
9322 int type = REDIRECT_TYPE_NONE;
9323 int code = 302;
9324 const char *destination = NULL;
9325 const char *cookie = NULL;
9326 int cookie_set = 0;
9327 unsigned int flags = (!dir ? REDIRECT_FLAG_FROM_REQ : REDIRECT_FLAG_NONE);
9328 struct acl_cond *cond = NULL;
9329
9330 cur_arg = 0;
9331 while (*(args[cur_arg])) {
9332 if (strcmp(args[cur_arg], "location") == 0) {
9333 if (!*args[cur_arg + 1])
9334 goto missing_arg;
9335
9336 type = REDIRECT_TYPE_LOCATION;
9337 cur_arg++;
9338 destination = args[cur_arg];
9339 }
9340 else if (strcmp(args[cur_arg], "prefix") == 0) {
9341 if (!*args[cur_arg + 1])
9342 goto missing_arg;
9343 type = REDIRECT_TYPE_PREFIX;
9344 cur_arg++;
9345 destination = args[cur_arg];
9346 }
9347 else if (strcmp(args[cur_arg], "scheme") == 0) {
9348 if (!*args[cur_arg + 1])
9349 goto missing_arg;
9350
9351 type = REDIRECT_TYPE_SCHEME;
9352 cur_arg++;
9353 destination = args[cur_arg];
9354 }
9355 else if (strcmp(args[cur_arg], "set-cookie") == 0) {
9356 if (!*args[cur_arg + 1])
9357 goto missing_arg;
9358
9359 cur_arg++;
9360 cookie = args[cur_arg];
9361 cookie_set = 1;
9362 }
9363 else if (strcmp(args[cur_arg], "clear-cookie") == 0) {
9364 if (!*args[cur_arg + 1])
9365 goto missing_arg;
9366
9367 cur_arg++;
9368 cookie = args[cur_arg];
9369 cookie_set = 0;
9370 }
9371 else if (strcmp(args[cur_arg], "code") == 0) {
9372 if (!*args[cur_arg + 1])
9373 goto missing_arg;
9374
9375 cur_arg++;
9376 code = atol(args[cur_arg]);
9377 if (code < 301 || code > 308 || (code > 303 && code < 307)) {
9378 memprintf(errmsg,
9379 "'%s': unsupported HTTP code '%s' (must be one of 301, 302, 303, 307 or 308)",
9380 args[cur_arg - 1], args[cur_arg]);
9381 return NULL;
9382 }
9383 }
9384 else if (!strcmp(args[cur_arg],"drop-query")) {
9385 flags |= REDIRECT_FLAG_DROP_QS;
9386 }
9387 else if (!strcmp(args[cur_arg],"append-slash")) {
9388 flags |= REDIRECT_FLAG_APPEND_SLASH;
9389 }
9390 else if (strcmp(args[cur_arg], "if") == 0 ||
9391 strcmp(args[cur_arg], "unless") == 0) {
9392 cond = build_acl_cond(file, linenum, &curproxy->acl, curproxy, (const char **)args + cur_arg, errmsg);
9393 if (!cond) {
9394 memprintf(errmsg, "error in condition: %s", *errmsg);
9395 return NULL;
9396 }
9397 break;
9398 }
9399 else {
9400 memprintf(errmsg,
9401 "expects 'code', 'prefix', 'location', 'scheme', 'set-cookie', 'clear-cookie', 'drop-query' or 'append-slash' (was '%s')",
9402 args[cur_arg]);
9403 return NULL;
9404 }
9405 cur_arg++;
9406 }
9407
9408 if (type == REDIRECT_TYPE_NONE) {
9409 memprintf(errmsg, "redirection type expected ('prefix', 'location', or 'scheme')");
9410 return NULL;
9411 }
9412
9413 if (dir && type != REDIRECT_TYPE_LOCATION) {
9414 memprintf(errmsg, "response only supports redirect type 'location'");
9415 return NULL;
9416 }
9417
9418 rule = calloc(1, sizeof(*rule));
9419 rule->cond = cond;
9420 LIST_INIT(&rule->rdr_fmt);
9421
9422 if (!use_fmt) {
9423 /* old-style static redirect rule */
9424 rule->rdr_str = strdup(destination);
9425 rule->rdr_len = strlen(destination);
9426 }
9427 else {
9428 /* log-format based redirect rule */
9429
9430 /* Parse destination. Note that in the REDIRECT_TYPE_PREFIX case,
9431 * if prefix == "/", we don't want to add anything, otherwise it
9432 * makes it hard for the user to configure a self-redirection.
9433 */
9434 curproxy->conf.args.ctx = ARGC_RDR;
9435 if (!(type == REDIRECT_TYPE_PREFIX && destination[0] == '/' && destination[1] == '\0')) {
9436 if (!parse_logformat_string(destination, curproxy, &rule->rdr_fmt, LOG_OPT_HTTP,
9437 dir ? (curproxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRS_HDR : SMP_VAL_BE_HRS_HDR
9438 : (curproxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR,
9439 errmsg)) {
9440 return NULL;
9441 }
9442 free(curproxy->conf.lfs_file);
9443 curproxy->conf.lfs_file = strdup(curproxy->conf.args.file);
9444 curproxy->conf.lfs_line = curproxy->conf.args.line;
9445 }
9446 }
9447
9448 if (cookie) {
9449 /* depending on cookie_set, either we want to set the cookie, or to clear it.
9450 * a clear consists in appending "; path=/; Max-Age=0;" at the end.
9451 */
9452 rule->cookie_len = strlen(cookie);
9453 if (cookie_set) {
9454 rule->cookie_str = malloc(rule->cookie_len + 10);
9455 memcpy(rule->cookie_str, cookie, rule->cookie_len);
9456 memcpy(rule->cookie_str + rule->cookie_len, "; path=/;", 10);
9457 rule->cookie_len += 9;
9458 } else {
9459 rule->cookie_str = malloc(rule->cookie_len + 21);
9460 memcpy(rule->cookie_str, cookie, rule->cookie_len);
9461 memcpy(rule->cookie_str + rule->cookie_len, "; path=/; Max-Age=0;", 21);
9462 rule->cookie_len += 20;
9463 }
9464 }
9465 rule->type = type;
9466 rule->code = code;
9467 rule->flags = flags;
9468 LIST_INIT(&rule->list);
9469 return rule;
9470
9471 missing_arg:
9472 memprintf(errmsg, "missing argument for '%s'", args[cur_arg]);
9473 return NULL;
9474 }
9475
9476 /************************************************************************/
9477 /* The code below is dedicated to ACL parsing and matching */
9478 /************************************************************************/
9479 #define SMP_REQ_CHN(smp) (smp->strm ? &smp->strm->req : NULL)
9480 #define SMP_RES_CHN(smp) (smp->strm ? &smp->strm->res : NULL)
9481
9482
9483 /* This function ensures that the prerequisites for an L7 fetch are ready,
9484 * which means that a request or response is ready. If some data is missing,
9485 * a parsing attempt is made. This is useful in TCP-based ACLs which are able
9486 * to extract data from L7. If <req_vol> is non-null during a request prefetch,
9487 * another test is made to ensure the required information is not gone.
9488 *
9489 * The function returns :
9490 * 0 with SMP_F_MAY_CHANGE in the sample flags if some data is missing to
9491 * decide whether or not an HTTP message is present ;
9492 * 0 if the requested data cannot be fetched or if it is certain that
9493 * we'll never have any HTTP message there ;
9494 * 1 if an HTTP message is ready
9495 */
smp_prefetch_http(struct proxy * px,struct stream * s,unsigned int opt,const struct channel * chn,struct sample * smp,int req_vol)9496 int smp_prefetch_http(struct proxy *px, struct stream *s, unsigned int opt,
9497 const struct channel *chn, struct sample *smp, int req_vol)
9498 {
9499 struct http_txn *txn;
9500 struct http_msg *msg;
9501
9502 /* Note: it is possible that <s> is NULL when called before stream
9503 * initialization (eg: tcp-request connection), so this function is the
9504 * one responsible for guarding against this case for all HTTP users.
9505 */
9506 if (!s || !chn)
9507 return 0;
9508
9509 if (!s->txn) {
9510 if (unlikely(!http_alloc_txn(s)))
9511 return 0; /* not enough memory */
9512 http_init_txn(s);
9513 }
9514 txn = s->txn;
9515
9516 smp->data.type = SMP_T_BOOL;
9517
9518 if (chn->flags & CF_ISRESP) {
9519 /* Check for a dependency on a response */
9520 if (txn->rsp.msg_state < HTTP_MSG_BODY) {
9521 smp->flags |= SMP_F_MAY_CHANGE;
9522 return 0;
9523 }
9524 goto end;
9525 }
9526
9527 /* Check for a dependency on a request */
9528 msg = &txn->req;
9529
9530 if (req_vol && (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES) {
9531 return 0; /* data might have moved and indexes changed */
9532 }
9533
9534 /* If the buffer does not leave enough free space at the end, we must
9535 * first realign it.
9536 */
9537 if (chn->buf->p > chn->buf->data &&
9538 chn->buf->i + chn->buf->p > chn->buf->data + chn->buf->size - global.tune.maxrewrite)
9539 buffer_slow_realign(chn->buf);
9540
9541 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
9542 if (msg->msg_state == HTTP_MSG_ERROR)
9543 return 0;
9544
9545 /* Try to decode HTTP request */
9546 if (likely(msg->next < chn->buf->i))
9547 http_msg_analyzer(msg, &txn->hdr_idx);
9548
9549 /* Still no valid request ? */
9550 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
9551 if ((msg->msg_state == HTTP_MSG_ERROR) ||
9552 buffer_full(chn->buf, global.tune.maxrewrite)) {
9553 return 0;
9554 }
9555 /* wait for final state */
9556 smp->flags |= SMP_F_MAY_CHANGE;
9557 return 0;
9558 }
9559
9560 /* OK we just got a valid HTTP message. We have some minor
9561 * preparation to perform so that further checks can rely
9562 * on HTTP tests.
9563 */
9564
9565 /* If the message was parsed but was too large, we must absolutely
9566 * return an error so that it is not processed. At the moment this
9567 * cannot happen, but if the parsers are to change in the future,
9568 * we want this check to be maintained.
9569 */
9570 if (unlikely(chn->buf->i + chn->buf->p >
9571 chn->buf->data + chn->buf->size - global.tune.maxrewrite)) {
9572 msg->err_state = msg->msg_state;
9573 msg->msg_state = HTTP_MSG_ERROR;
9574 smp->data.u.sint = 1;
9575 return 1;
9576 }
9577
9578 txn->meth = find_http_meth(chn->buf->p, msg->sl.rq.m_l);
9579 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
9580 s->flags |= SF_REDIRECTABLE;
9581
9582 if (unlikely(msg->sl.rq.v_l == 0) && !http_upgrade_v09_to_v10(txn))
9583 return 0;
9584 }
9585
9586 end:
9587 /* everything's OK */
9588 smp->data.u.sint = 1;
9589 return 1;
9590 }
9591
9592 /* 1. Check on METHOD
9593 * We use the pre-parsed method if it is known, and store its number as an
9594 * integer. If it is unknown, we use the pointer and the length.
9595 */
pat_parse_meth(const char * text,struct pattern * pattern,int mflags,char ** err)9596 static int pat_parse_meth(const char *text, struct pattern *pattern, int mflags, char **err)
9597 {
9598 int len, meth;
9599
9600 len = strlen(text);
9601 meth = find_http_meth(text, len);
9602
9603 pattern->val.i = meth;
9604 if (meth == HTTP_METH_OTHER) {
9605 pattern->ptr.str = (char *)text;
9606 pattern->len = len;
9607 }
9608 else {
9609 pattern->ptr.str = NULL;
9610 pattern->len = 0;
9611 }
9612 return 1;
9613 }
9614
9615 /* This function fetches the method of current HTTP request and stores
9616 * it in the global pattern struct as a chunk. There are two possibilities :
9617 * - if the method is known (not HTTP_METH_OTHER), its identifier is stored
9618 * in <len> and <ptr> is NULL ;
9619 * - if the method is unknown (HTTP_METH_OTHER), <ptr> points to the text and
9620 * <len> to its length.
9621 * This is intended to be used with pat_match_meth() only.
9622 */
9623 static int
smp_fetch_meth(const struct arg * args,struct sample * smp,const char * kw,void * private)9624 smp_fetch_meth(const struct arg *args, struct sample *smp, const char *kw, void *private)
9625 {
9626 struct channel *chn = SMP_REQ_CHN(smp);
9627 int meth;
9628 struct http_txn *txn;
9629
9630 CHECK_HTTP_MESSAGE_FIRST_PERM(chn);
9631
9632 txn = smp->strm->txn;
9633 meth = txn->meth;
9634 smp->data.type = SMP_T_METH;
9635 smp->data.u.meth.meth = meth;
9636 if (meth == HTTP_METH_OTHER) {
9637 if ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES) {
9638 /* ensure the indexes are not affected */
9639 return 0;
9640 }
9641 smp->flags |= SMP_F_CONST;
9642 smp->data.u.meth.str.len = txn->req.sl.rq.m_l;
9643 smp->data.u.meth.str.str = txn->req.chn->buf->p;
9644 }
9645 smp->flags |= SMP_F_VOL_1ST;
9646 return 1;
9647 }
9648
9649 /* See above how the method is stored in the global pattern */
pat_match_meth(struct sample * smp,struct pattern_expr * expr,int fill)9650 static struct pattern *pat_match_meth(struct sample *smp, struct pattern_expr *expr, int fill)
9651 {
9652 int icase;
9653 struct pattern_list *lst;
9654 struct pattern *pattern;
9655
9656 list_for_each_entry(lst, &expr->patterns, list) {
9657 pattern = &lst->pat;
9658
9659 /* well-known method */
9660 if (pattern->val.i != HTTP_METH_OTHER) {
9661 if (smp->data.u.meth.meth == pattern->val.i)
9662 return pattern;
9663 else
9664 continue;
9665 }
9666
9667 /* Other method, we must compare the strings */
9668 if (pattern->len != smp->data.u.meth.str.len)
9669 continue;
9670
9671 icase = expr->mflags & PAT_MF_IGNORE_CASE;
9672 if ((icase && strncasecmp(pattern->ptr.str, smp->data.u.meth.str.str, smp->data.u.meth.str.len) == 0) ||
9673 (!icase && strncmp(pattern->ptr.str, smp->data.u.meth.str.str, smp->data.u.meth.str.len) == 0))
9674 return pattern;
9675 }
9676 return NULL;
9677 }
9678
9679 static int
smp_fetch_rqver(const struct arg * args,struct sample * smp,const char * kw,void * private)9680 smp_fetch_rqver(const struct arg *args, struct sample *smp, const char *kw, void *private)
9681 {
9682 struct channel *chn = SMP_REQ_CHN(smp);
9683 struct http_txn *txn;
9684 char *ptr;
9685 int len;
9686
9687 CHECK_HTTP_MESSAGE_FIRST(chn);
9688
9689 txn = smp->strm->txn;
9690 len = txn->req.sl.rq.v_l;
9691 ptr = chn->buf->p + txn->req.sl.rq.v;
9692
9693 while ((len-- > 0) && (*ptr++ != '/'));
9694 if (len <= 0)
9695 return 0;
9696
9697 smp->data.type = SMP_T_STR;
9698 smp->data.u.str.str = ptr;
9699 smp->data.u.str.len = len;
9700
9701 smp->flags = SMP_F_VOL_1ST | SMP_F_CONST;
9702 return 1;
9703 }
9704
9705 static int
smp_fetch_stver(const struct arg * args,struct sample * smp,const char * kw,void * private)9706 smp_fetch_stver(const struct arg *args, struct sample *smp, const char *kw, void *private)
9707 {
9708 struct channel *chn = SMP_RES_CHN(smp);
9709 struct http_txn *txn;
9710 char *ptr;
9711 int len;
9712
9713 CHECK_HTTP_MESSAGE_FIRST(chn);
9714
9715 txn = smp->strm->txn;
9716
9717 len = txn->rsp.sl.st.v_l;
9718 ptr = chn->buf->p;
9719
9720 while ((len-- > 0) && (*ptr++ != '/'));
9721 if (len <= 0)
9722 return 0;
9723
9724 smp->data.type = SMP_T_STR;
9725 smp->data.u.str.str = ptr;
9726 smp->data.u.str.len = len;
9727
9728 smp->flags = SMP_F_VOL_1ST | SMP_F_CONST;
9729 return 1;
9730 }
9731
9732 /* 3. Check on Status Code. We manipulate integers here. */
9733 static int
smp_fetch_stcode(const struct arg * args,struct sample * smp,const char * kw,void * private)9734 smp_fetch_stcode(const struct arg *args, struct sample *smp, const char *kw, void *private)
9735 {
9736 struct channel *chn = SMP_RES_CHN(smp);
9737 struct http_txn *txn;
9738 char *ptr;
9739 int len;
9740
9741 CHECK_HTTP_MESSAGE_FIRST(chn);
9742
9743 txn = smp->strm->txn;
9744 if (txn->rsp.msg_state < HTTP_MSG_BODY)
9745 return 0;
9746
9747 len = txn->rsp.sl.st.c_l;
9748 ptr = chn->buf->p + txn->rsp.sl.st.c;
9749
9750 smp->data.type = SMP_T_SINT;
9751 smp->data.u.sint = __strl2ui(ptr, len);
9752 smp->flags = SMP_F_VOL_1ST;
9753 return 1;
9754 }
9755
9756 static int
smp_fetch_uniqueid(const struct arg * args,struct sample * smp,const char * kw,void * private)9757 smp_fetch_uniqueid(const struct arg *args, struct sample *smp, const char *kw, void *private)
9758 {
9759 if (LIST_ISEMPTY(&smp->sess->fe->format_unique_id))
9760 return 0;
9761
9762 if (!smp->strm)
9763 return 0;
9764
9765 if (!smp->strm->unique_id) {
9766 if ((smp->strm->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
9767 return 0;
9768 smp->strm->unique_id[0] = '\0';
9769 build_logline(smp->strm, smp->strm->unique_id,
9770 UNIQUEID_LEN, &smp->sess->fe->format_unique_id);
9771 }
9772 smp->data.u.str.len = strlen(smp->strm->unique_id);
9773 smp->data.type = SMP_T_STR;
9774 smp->data.u.str.str = smp->strm->unique_id;
9775 smp->flags = SMP_F_CONST;
9776 return 1;
9777 }
9778
9779 /* Returns a string block containing all headers including the
9780 * empty line wich separes headers from the body. This is useful
9781 * form some headers analysis.
9782 */
9783 static int
smp_fetch_hdrs(const struct arg * args,struct sample * smp,const char * kw,void * private)9784 smp_fetch_hdrs(const struct arg *args, struct sample *smp, const char *kw, void *private)
9785 {
9786 struct channel *chn = SMP_REQ_CHN(smp);
9787 struct http_msg *msg;
9788 struct hdr_idx *idx;
9789 struct http_txn *txn;
9790
9791 CHECK_HTTP_MESSAGE_FIRST(chn);
9792
9793 txn = smp->strm->txn;
9794 idx = &txn->hdr_idx;
9795 msg = &txn->req;
9796
9797 smp->data.type = SMP_T_STR;
9798 smp->data.u.str.str = chn->buf->p + hdr_idx_first_pos(idx);
9799 smp->data.u.str.len = msg->eoh - hdr_idx_first_pos(idx) + 1 +
9800 (chn->buf->p[msg->eoh] == '\r');
9801
9802 return 1;
9803 }
9804
9805 /* Returns the header request in a length/value encoded format.
9806 * This is useful for exchanges with the SPOE.
9807 *
9808 * A "length value" is a multibyte code encoding numbers. It uses the
9809 * SPOE format. The encoding is the following:
9810 *
9811 * Each couple "header name" / "header value" is composed
9812 * like this:
9813 * "length value" "header name bytes"
9814 * "length value" "header value bytes"
9815 * When the last header is reached, the header name and the header
9816 * value are empty. Their length are 0
9817 */
9818 static int
smp_fetch_hdrs_bin(const struct arg * args,struct sample * smp,const char * kw,void * private)9819 smp_fetch_hdrs_bin(const struct arg *args, struct sample *smp, const char *kw, void *private)
9820 {
9821 struct channel *chn = SMP_REQ_CHN(smp);
9822 struct chunk *temp;
9823 struct hdr_idx *idx;
9824 const char *cur_ptr, *cur_next, *p;
9825 int old_idx, cur_idx;
9826 struct hdr_idx_elem *cur_hdr;
9827 const char *hn, *hv;
9828 int hnl, hvl;
9829 int ret;
9830 struct http_txn *txn;
9831 char *buf;
9832 char *end;
9833
9834 CHECK_HTTP_MESSAGE_FIRST(chn);
9835
9836 temp = get_trash_chunk();
9837 buf = temp->str;
9838 end = temp->str + temp->size;
9839
9840 txn = smp->strm->txn;
9841 idx = &txn->hdr_idx;
9842
9843 /* Build array of headers. */
9844 old_idx = 0;
9845 cur_next = chn->buf->p + hdr_idx_first_pos(idx);
9846 while (1) {
9847 cur_idx = idx->v[old_idx].next;
9848 if (!cur_idx)
9849 break;
9850 old_idx = cur_idx;
9851
9852 cur_hdr = &idx->v[cur_idx];
9853 cur_ptr = cur_next;
9854 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
9855
9856 /* Now we have one full header at cur_ptr of len cur_hdr->len,
9857 * and the next header starts at cur_next. We'll check
9858 * this header in the list as well as against the default
9859 * rule.
9860 */
9861
9862 /* look for ': *'. */
9863 hn = cur_ptr;
9864 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
9865 if (p >= cur_ptr+cur_hdr->len)
9866 continue;
9867 hnl = p - hn;
9868 p++;
9869 while (p < cur_ptr + cur_hdr->len && (*p == ' ' || *p == '\t'))
9870 p++;
9871 if (p >= cur_ptr + cur_hdr->len)
9872 continue;
9873 hv = p;
9874 hvl = cur_ptr + cur_hdr->len-p;
9875
9876 /* encode the header name. */
9877 ret = encode_varint(hnl, &buf, end);
9878 if (ret == -1)
9879 return 0;
9880 if (buf + hnl > end)
9881 return 0;
9882 memcpy(buf, hn, hnl);
9883 buf += hnl;
9884
9885 /* encode and copy the value. */
9886 ret = encode_varint(hvl, &buf, end);
9887 if (ret == -1)
9888 return 0;
9889 if (buf + hvl > end)
9890 return 0;
9891 memcpy(buf, hv, hvl);
9892 buf += hvl;
9893 }
9894
9895 /* encode the end of the header list with empty
9896 * header name and header value.
9897 */
9898 ret = encode_varint(0, &buf, end);
9899 if (ret == -1)
9900 return 0;
9901 ret = encode_varint(0, &buf, end);
9902 if (ret == -1)
9903 return 0;
9904
9905 /* Initialise sample data which will be filled. */
9906 smp->data.type = SMP_T_BIN;
9907 smp->data.u.str.str = temp->str;
9908 smp->data.u.str.len = buf - temp->str;
9909 smp->data.u.str.size = temp->size;
9910
9911 return 1;
9912 }
9913
9914 /* returns the longest available part of the body. This requires that the body
9915 * has been waited for using http-buffer-request.
9916 */
9917 static int
smp_fetch_body(const struct arg * args,struct sample * smp,const char * kw,void * private)9918 smp_fetch_body(const struct arg *args, struct sample *smp, const char *kw, void *private)
9919 {
9920 struct channel *chn = SMP_REQ_CHN(smp);
9921 struct http_msg *msg;
9922 unsigned long len;
9923 unsigned long block1;
9924 char *body;
9925 struct chunk *temp;
9926
9927 CHECK_HTTP_MESSAGE_FIRST(chn);
9928
9929 msg = &smp->strm->txn->req;
9930
9931 len = http_body_bytes(msg);
9932 body = b_ptr(chn->buf, -http_data_rewind(msg));
9933
9934 block1 = len;
9935 if (block1 > chn->buf->data + chn->buf->size - body)
9936 block1 = chn->buf->data + chn->buf->size - body;
9937
9938 if (block1 == len) {
9939 /* buffer is not wrapped (or empty) */
9940 smp->data.type = SMP_T_BIN;
9941 smp->data.u.str.str = body;
9942 smp->data.u.str.len = len;
9943 smp->flags = SMP_F_VOL_TEST | SMP_F_CONST;
9944 }
9945 else {
9946 /* buffer is wrapped, we need to defragment it */
9947 temp = get_trash_chunk();
9948 memcpy(temp->str, body, block1);
9949 memcpy(temp->str + block1, chn->buf->data, len - block1);
9950 smp->data.type = SMP_T_BIN;
9951 smp->data.u.str.str = temp->str;
9952 smp->data.u.str.len = len;
9953 smp->flags = SMP_F_VOL_TEST;
9954 }
9955 return 1;
9956 }
9957
9958
9959 /* returns the available length of the body. This requires that the body
9960 * has been waited for using http-buffer-request.
9961 */
9962 static int
smp_fetch_body_len(const struct arg * args,struct sample * smp,const char * kw,void * private)9963 smp_fetch_body_len(const struct arg *args, struct sample *smp, const char *kw, void *private)
9964 {
9965 struct channel *chn = SMP_REQ_CHN(smp);
9966 struct http_msg *msg;
9967
9968 CHECK_HTTP_MESSAGE_FIRST(chn);
9969
9970 msg = &smp->strm->txn->req;
9971 smp->data.type = SMP_T_SINT;
9972 smp->data.u.sint = http_body_bytes(msg);
9973
9974 smp->flags = SMP_F_VOL_TEST;
9975 return 1;
9976 }
9977
9978
9979 /* returns the advertised length of the body, or the advertised size of the
9980 * chunks available in the buffer. This requires that the body has been waited
9981 * for using http-buffer-request.
9982 */
9983 static int
smp_fetch_body_size(const struct arg * args,struct sample * smp,const char * kw,void * private)9984 smp_fetch_body_size(const struct arg *args, struct sample *smp, const char *kw, void *private)
9985 {
9986 struct channel *chn = SMP_REQ_CHN(smp);
9987 struct http_msg *msg;
9988
9989 CHECK_HTTP_MESSAGE_FIRST(chn);
9990
9991 msg = &smp->strm->txn->req;
9992 smp->data.type = SMP_T_SINT;
9993 smp->data.u.sint = msg->body_len;
9994
9995 smp->flags = SMP_F_VOL_TEST;
9996 return 1;
9997 }
9998
9999
10000 /* 4. Check on URL/URI. A pointer to the URI is stored. */
10001 static int
smp_fetch_url(const struct arg * args,struct sample * smp,const char * kw,void * private)10002 smp_fetch_url(const struct arg *args, struct sample *smp, const char *kw, void *private)
10003 {
10004 struct channel *chn = SMP_REQ_CHN(smp);
10005 struct http_txn *txn;
10006
10007 CHECK_HTTP_MESSAGE_FIRST(chn);
10008
10009 txn = smp->strm->txn;
10010 smp->data.type = SMP_T_STR;
10011 smp->data.u.str.len = txn->req.sl.rq.u_l;
10012 smp->data.u.str.str = chn->buf->p + txn->req.sl.rq.u;
10013 smp->flags = SMP_F_VOL_1ST | SMP_F_CONST;
10014 return 1;
10015 }
10016
10017 static int
smp_fetch_url_ip(const struct arg * args,struct sample * smp,const char * kw,void * private)10018 smp_fetch_url_ip(const struct arg *args, struct sample *smp, const char *kw, void *private)
10019 {
10020 struct channel *chn = SMP_REQ_CHN(smp);
10021 struct http_txn *txn;
10022 struct sockaddr_storage addr;
10023
10024 CHECK_HTTP_MESSAGE_FIRST(chn);
10025
10026 txn = smp->strm->txn;
10027 url2sa(chn->buf->p + txn->req.sl.rq.u, txn->req.sl.rq.u_l, &addr, NULL);
10028 if (((struct sockaddr_in *)&addr)->sin_family != AF_INET)
10029 return 0;
10030
10031 smp->data.type = SMP_T_IPV4;
10032 smp->data.u.ipv4 = ((struct sockaddr_in *)&addr)->sin_addr;
10033 smp->flags = 0;
10034 return 1;
10035 }
10036
10037 static int
smp_fetch_url_port(const struct arg * args,struct sample * smp,const char * kw,void * private)10038 smp_fetch_url_port(const struct arg *args, struct sample *smp, const char *kw, void *private)
10039 {
10040 struct channel *chn = SMP_REQ_CHN(smp);
10041 struct http_txn *txn;
10042 struct sockaddr_storage addr;
10043
10044 CHECK_HTTP_MESSAGE_FIRST(chn);
10045
10046 txn = smp->strm->txn;
10047 url2sa(chn->buf->p + txn->req.sl.rq.u, txn->req.sl.rq.u_l, &addr, NULL);
10048 if (((struct sockaddr_in *)&addr)->sin_family != AF_INET)
10049 return 0;
10050
10051 smp->data.type = SMP_T_SINT;
10052 smp->data.u.sint = ntohs(((struct sockaddr_in *)&addr)->sin_port);
10053 smp->flags = 0;
10054 return 1;
10055 }
10056
10057 /* Fetch an HTTP header. A pointer to the beginning of the value is returned.
10058 * Accepts an optional argument of type string containing the header field name,
10059 * and an optional argument of type signed or unsigned integer to request an
10060 * explicit occurrence of the header. Note that in the event of a missing name,
10061 * headers are considered from the first one. It does not stop on commas and
10062 * returns full lines instead (useful for User-Agent or Date for example).
10063 */
10064 static int
smp_fetch_fhdr(const struct arg * args,struct sample * smp,const char * kw,void * private)10065 smp_fetch_fhdr(const struct arg *args, struct sample *smp, const char *kw, void *private)
10066 {
10067 /* possible keywords: req.fhdr, res.fhdr */
10068 struct channel *chn = ((kw[2] == 'q') ? SMP_REQ_CHN(smp) : SMP_RES_CHN(smp));
10069 struct hdr_idx *idx;
10070 struct hdr_ctx *ctx = smp->ctx.a[0];
10071 const struct http_msg *msg;
10072 int occ = 0;
10073 const char *name_str = NULL;
10074 int name_len = 0;
10075
10076 if (!ctx) {
10077 /* first call */
10078 ctx = &static_hdr_ctx;
10079 ctx->idx = 0;
10080 smp->ctx.a[0] = ctx;
10081 }
10082
10083 if (args) {
10084 if (args[0].type != ARGT_STR)
10085 return 0;
10086 name_str = args[0].data.str.str;
10087 name_len = args[0].data.str.len;
10088
10089 if (args[1].type == ARGT_SINT)
10090 occ = args[1].data.sint;
10091 }
10092
10093 CHECK_HTTP_MESSAGE_FIRST(chn);
10094 idx = &smp->strm->txn->hdr_idx;
10095 msg = (!(chn->flags & CF_ISRESP) ? &smp->strm->txn->req : &smp->strm->txn->rsp);
10096
10097 if (ctx && !(smp->flags & SMP_F_NOT_LAST))
10098 /* search for header from the beginning */
10099 ctx->idx = 0;
10100
10101 if (!occ && !(smp->opt & SMP_OPT_ITERATE))
10102 /* no explicit occurrence and single fetch => last header by default */
10103 occ = -1;
10104
10105 if (!occ)
10106 /* prepare to report multiple occurrences for ACL fetches */
10107 smp->flags |= SMP_F_NOT_LAST;
10108
10109 smp->data.type = SMP_T_STR;
10110 smp->flags |= SMP_F_VOL_HDR | SMP_F_CONST;
10111 if (http_get_fhdr(msg, name_str, name_len, idx, occ, ctx, &smp->data.u.str.str, &smp->data.u.str.len))
10112 return 1;
10113
10114 smp->flags &= ~SMP_F_NOT_LAST;
10115 return 0;
10116 }
10117
10118 /* 6. Check on HTTP header count. The number of occurrences is returned.
10119 * Accepts exactly 1 argument of type string. It does not stop on commas and
10120 * returns full lines instead (useful for User-Agent or Date for example).
10121 */
10122 static int
smp_fetch_fhdr_cnt(const struct arg * args,struct sample * smp,const char * kw,void * private)10123 smp_fetch_fhdr_cnt(const struct arg *args, struct sample *smp, const char *kw, void *private)
10124 {
10125 /* possible keywords: req.fhdr_cnt, res.fhdr_cnt */
10126 struct channel *chn = ((kw[2] == 'q') ? SMP_REQ_CHN(smp) : SMP_RES_CHN(smp));
10127 struct hdr_idx *idx;
10128 struct hdr_ctx ctx;
10129 int cnt;
10130 const char *name = NULL;
10131 int len = 0;
10132
10133 if (args && args->type == ARGT_STR) {
10134 name = args->data.str.str;
10135 len = args->data.str.len;
10136 }
10137
10138 CHECK_HTTP_MESSAGE_FIRST(chn);
10139
10140 idx = &smp->strm->txn->hdr_idx;
10141 ctx.idx = 0;
10142 cnt = 0;
10143 while (http_find_full_header2(name, len, chn->buf->p, idx, &ctx))
10144 cnt++;
10145
10146 smp->data.type = SMP_T_SINT;
10147 smp->data.u.sint = cnt;
10148 smp->flags = SMP_F_VOL_HDR;
10149 return 1;
10150 }
10151
10152 static int
smp_fetch_hdr_names(const struct arg * args,struct sample * smp,const char * kw,void * private)10153 smp_fetch_hdr_names(const struct arg *args, struct sample *smp, const char *kw, void *private)
10154 {
10155 /* possible keywords: req.hdr_names, res.hdr_names */
10156 struct channel *chn = ((kw[2] == 'q') ? SMP_REQ_CHN(smp) : SMP_RES_CHN(smp));
10157 struct hdr_idx *idx;
10158 struct hdr_ctx ctx;
10159 struct chunk *temp;
10160 char del = ',';
10161
10162 if (args && args->type == ARGT_STR)
10163 del = *args[0].data.str.str;
10164
10165 CHECK_HTTP_MESSAGE_FIRST(chn);
10166
10167 idx = &smp->strm->txn->hdr_idx;
10168
10169 temp = get_trash_chunk();
10170
10171 ctx.idx = 0;
10172 while (http_find_next_header(chn->buf->p, idx, &ctx)) {
10173 if (temp->len)
10174 temp->str[temp->len++] = del;
10175 memcpy(temp->str + temp->len, ctx.line, ctx.del);
10176 temp->len += ctx.del;
10177 }
10178
10179 smp->data.type = SMP_T_STR;
10180 smp->data.u.str.str = temp->str;
10181 smp->data.u.str.len = temp->len;
10182 smp->flags = SMP_F_VOL_HDR;
10183 return 1;
10184 }
10185
10186 /* Fetch an HTTP header. A pointer to the beginning of the value is returned.
10187 * Accepts an optional argument of type string containing the header field name,
10188 * and an optional argument of type signed or unsigned integer to request an
10189 * explicit occurrence of the header. Note that in the event of a missing name,
10190 * headers are considered from the first one.
10191 */
10192 static int
smp_fetch_hdr(const struct arg * args,struct sample * smp,const char * kw,void * private)10193 smp_fetch_hdr(const struct arg *args, struct sample *smp, const char *kw, void *private)
10194 {
10195 /* possible keywords: req.hdr / hdr, res.hdr / shdr */
10196 struct channel *chn = ((kw[0] == 'h' || kw[2] == 'q') ? SMP_REQ_CHN(smp) : SMP_RES_CHN(smp));
10197 struct hdr_idx *idx;
10198 struct hdr_ctx *ctx = smp->ctx.a[0];
10199 const struct http_msg *msg;
10200 int occ = 0;
10201 const char *name_str = NULL;
10202 int name_len = 0;
10203
10204 if (!ctx) {
10205 /* first call */
10206 ctx = &static_hdr_ctx;
10207 ctx->idx = 0;
10208 smp->ctx.a[0] = ctx;
10209 }
10210
10211 if (args) {
10212 if (args[0].type != ARGT_STR)
10213 return 0;
10214 name_str = args[0].data.str.str;
10215 name_len = args[0].data.str.len;
10216
10217 if (args[1].type == ARGT_SINT)
10218 occ = args[1].data.sint;
10219 }
10220
10221 CHECK_HTTP_MESSAGE_FIRST(chn);
10222
10223 idx = &smp->strm->txn->hdr_idx;
10224 msg = (!(chn->flags & CF_ISRESP) ? &smp->strm->txn->req : &smp->strm->txn->rsp);
10225
10226 if (ctx && !(smp->flags & SMP_F_NOT_LAST))
10227 /* search for header from the beginning */
10228 ctx->idx = 0;
10229
10230 if (!occ && !(smp->opt & SMP_OPT_ITERATE))
10231 /* no explicit occurrence and single fetch => last header by default */
10232 occ = -1;
10233
10234 if (!occ)
10235 /* prepare to report multiple occurrences for ACL fetches */
10236 smp->flags |= SMP_F_NOT_LAST;
10237
10238 smp->data.type = SMP_T_STR;
10239 smp->flags |= SMP_F_VOL_HDR | SMP_F_CONST;
10240 if (http_get_hdr(msg, name_str, name_len, idx, occ, ctx, &smp->data.u.str.str, &smp->data.u.str.len))
10241 return 1;
10242
10243 smp->flags &= ~SMP_F_NOT_LAST;
10244 return 0;
10245 }
10246
10247 /* Same than smp_fetch_hdr() but only relies on the sample direction to choose
10248 * the right channel. So instead of duplicating the code, we just change the
10249 * keyword and then fallback on smp_fetch_hdr().
10250 */
10251 static int
smp_fetch_chn_hdr(const struct arg * args,struct sample * smp,const char * kw,void * private)10252 smp_fetch_chn_hdr(const struct arg *args, struct sample *smp, const char *kw, void *private)
10253 {
10254 kw = ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ ? "req.hdr" : "res.hdr");
10255 return smp_fetch_hdr(args, smp, kw, private);
10256 }
10257
10258 /* 6. Check on HTTP header count. The number of occurrences is returned.
10259 * Accepts exactly 1 argument of type string.
10260 */
10261 static int
smp_fetch_hdr_cnt(const struct arg * args,struct sample * smp,const char * kw,void * private)10262 smp_fetch_hdr_cnt(const struct arg *args, struct sample *smp, const char *kw, void *private)
10263 {
10264 /* possible keywords: req.hdr_cnt / hdr_cnt, res.hdr_cnt / shdr_cnt */
10265 struct channel *chn = ((kw[0] == 'h' || kw[2] == 'q') ? SMP_REQ_CHN(smp) : SMP_RES_CHN(smp));
10266 struct hdr_idx *idx;
10267 struct hdr_ctx ctx;
10268 int cnt;
10269 const char *name = NULL;
10270 int len = 0;
10271
10272 if (args && args->type == ARGT_STR) {
10273 name = args->data.str.str;
10274 len = args->data.str.len;
10275 }
10276
10277 CHECK_HTTP_MESSAGE_FIRST(chn);
10278
10279 idx = &smp->strm->txn->hdr_idx;
10280
10281 ctx.idx = 0;
10282 cnt = 0;
10283 while (http_find_header2(name, len, chn->buf->p, idx, &ctx))
10284 cnt++;
10285
10286 smp->data.type = SMP_T_SINT;
10287 smp->data.u.sint = cnt;
10288 smp->flags = SMP_F_VOL_HDR;
10289 return 1;
10290 }
10291
10292 /* Fetch an HTTP header's integer value. The integer value is returned. It
10293 * takes a mandatory argument of type string and an optional one of type int
10294 * to designate a specific occurrence. It returns an unsigned integer, which
10295 * may or may not be appropriate for everything.
10296 */
10297 static int
smp_fetch_hdr_val(const struct arg * args,struct sample * smp,const char * kw,void * private)10298 smp_fetch_hdr_val(const struct arg *args, struct sample *smp, const char *kw, void *private)
10299 {
10300 int ret = smp_fetch_hdr(args, smp, kw, private);
10301
10302 if (ret > 0) {
10303 smp->data.type = SMP_T_SINT;
10304 smp->data.u.sint = strl2ic(smp->data.u.str.str, smp->data.u.str.len);
10305 }
10306
10307 return ret;
10308 }
10309
10310 /* Fetch an HTTP header's IP value. takes a mandatory argument of type string
10311 * and an optional one of type int to designate a specific occurrence.
10312 * It returns an IPv4 or IPv6 address. Addresses surrounded by invalid chars
10313 * are rejected. However IPv4 addresses may be followed with a colon and a
10314 * valid port number.
10315 */
10316 static int
smp_fetch_hdr_ip(const struct arg * args,struct sample * smp,const char * kw,void * private)10317 smp_fetch_hdr_ip(const struct arg *args, struct sample *smp, const char *kw, void *private)
10318 {
10319 struct chunk *temp = get_trash_chunk();
10320 int ret, len;
10321 int port;
10322
10323 while ((ret = smp_fetch_hdr(args, smp, kw, private)) > 0) {
10324 if (smp->data.u.str.len < temp->size - 1) {
10325 memcpy(temp->str, smp->data.u.str.str,
10326 smp->data.u.str.len);
10327 temp->str[smp->data.u.str.len] = '\0';
10328 len = url2ipv4((char *) temp->str, &smp->data.u.ipv4);
10329 if (len > 0 && len == smp->data.u.str.len) {
10330 /* plain IPv4 address */
10331 smp->data.type = SMP_T_IPV4;
10332 break;
10333 } else if (len > 0 && temp->str[len] == ':' &&
10334 strl2irc(temp->str + len + 1, smp->data.u.str.len - len - 1, &port) == 0 &&
10335 port >= 0 && port <= 65535) {
10336 /* IPv4 address suffixed with ':' followed by a valid port number */
10337 smp->data.type = SMP_T_IPV4;
10338 break;
10339 } else if (inet_pton(AF_INET6, temp->str, &smp->data.u.ipv6)) {
10340 smp->data.type = SMP_T_IPV6;
10341 break;
10342 }
10343 }
10344
10345 /* if the header doesn't match an IP address, fetch next one */
10346 if (!(smp->flags & SMP_F_NOT_LAST))
10347 return 0;
10348 }
10349 return ret;
10350 }
10351
10352 /* 8. Check on URI PATH. A pointer to the PATH is stored. The path starts at
10353 * the first '/' after the possible hostname, and ends before the possible '?'.
10354 */
10355 static int
smp_fetch_path(const struct arg * args,struct sample * smp,const char * kw,void * private)10356 smp_fetch_path(const struct arg *args, struct sample *smp, const char *kw, void *private)
10357 {
10358 struct channel *chn = SMP_REQ_CHN(smp);
10359 struct http_txn *txn;
10360 char *ptr, *end;
10361
10362 CHECK_HTTP_MESSAGE_FIRST(chn);
10363
10364 txn = smp->strm->txn;
10365 end = chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
10366 ptr = http_get_path(txn);
10367 if (!ptr)
10368 return 0;
10369
10370 /* OK, we got the '/' ! */
10371 smp->data.type = SMP_T_STR;
10372 smp->data.u.str.str = ptr;
10373
10374 while (ptr < end && *ptr != '?')
10375 ptr++;
10376
10377 smp->data.u.str.len = ptr - smp->data.u.str.str;
10378 smp->flags = SMP_F_VOL_1ST | SMP_F_CONST;
10379 return 1;
10380 }
10381
10382 /* This produces a concatenation of the first occurrence of the Host header
10383 * followed by the path component if it begins with a slash ('/'). This means
10384 * that '*' will not be added, resulting in exactly the first Host entry.
10385 * If no Host header is found, then the path is returned as-is. The returned
10386 * value is stored in the trash so it does not need to be marked constant.
10387 * The returned sample is of type string.
10388 */
10389 static int
smp_fetch_base(const struct arg * args,struct sample * smp,const char * kw,void * private)10390 smp_fetch_base(const struct arg *args, struct sample *smp, const char *kw, void *private)
10391 {
10392 struct channel *chn = SMP_REQ_CHN(smp);
10393 struct http_txn *txn;
10394 char *ptr, *end, *beg;
10395 struct hdr_ctx ctx;
10396 struct chunk *temp;
10397
10398 CHECK_HTTP_MESSAGE_FIRST(chn);
10399
10400 txn = smp->strm->txn;
10401 ctx.idx = 0;
10402 if (!http_find_header2("Host", 4, chn->buf->p, &txn->hdr_idx, &ctx) || !ctx.vlen)
10403 return smp_fetch_path(args, smp, kw, private);
10404
10405 /* OK we have the header value in ctx.line+ctx.val for ctx.vlen bytes */
10406 temp = get_trash_chunk();
10407 memcpy(temp->str, ctx.line + ctx.val, ctx.vlen);
10408 smp->data.type = SMP_T_STR;
10409 smp->data.u.str.str = temp->str;
10410 smp->data.u.str.len = ctx.vlen;
10411
10412 /* now retrieve the path */
10413 end = chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
10414 beg = http_get_path(txn);
10415 if (!beg)
10416 beg = end;
10417
10418 for (ptr = beg; ptr < end && *ptr != '?'; ptr++);
10419
10420 if (beg < ptr && *beg == '/') {
10421 memcpy(smp->data.u.str.str + smp->data.u.str.len, beg, ptr - beg);
10422 smp->data.u.str.len += ptr - beg;
10423 }
10424
10425 smp->flags = SMP_F_VOL_1ST;
10426 return 1;
10427 }
10428
10429 /* This produces a 32-bit hash of the concatenation of the first occurrence of
10430 * the Host header followed by the path component if it begins with a slash ('/').
10431 * This means that '*' will not be added, resulting in exactly the first Host
10432 * entry. If no Host header is found, then the path is used. The resulting value
10433 * is hashed using the path hash followed by a full avalanche hash and provides a
10434 * 32-bit integer value. This fetch is useful for tracking per-path activity on
10435 * high-traffic sites without having to store whole paths.
10436 */
10437 int
smp_fetch_base32(const struct arg * args,struct sample * smp,const char * kw,void * private)10438 smp_fetch_base32(const struct arg *args, struct sample *smp, const char *kw, void *private)
10439 {
10440 struct channel *chn = SMP_REQ_CHN(smp);
10441 struct http_txn *txn;
10442 struct hdr_ctx ctx;
10443 unsigned int hash = 0;
10444 char *ptr, *beg, *end;
10445 int len;
10446
10447 CHECK_HTTP_MESSAGE_FIRST(chn);
10448
10449 txn = smp->strm->txn;
10450 ctx.idx = 0;
10451 if (http_find_header2("Host", 4, chn->buf->p, &txn->hdr_idx, &ctx)) {
10452 /* OK we have the header value in ctx.line+ctx.val for ctx.vlen bytes */
10453 ptr = ctx.line + ctx.val;
10454 len = ctx.vlen;
10455 while (len--)
10456 hash = *(ptr++) + (hash << 6) + (hash << 16) - hash;
10457 }
10458
10459 /* now retrieve the path */
10460 end = chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
10461 beg = http_get_path(txn);
10462 if (!beg)
10463 beg = end;
10464
10465 for (ptr = beg; ptr < end && *ptr != '?'; ptr++);
10466
10467 if (beg < ptr && *beg == '/') {
10468 while (beg < ptr)
10469 hash = *(beg++) + (hash << 6) + (hash << 16) - hash;
10470 }
10471 hash = full_hash(hash);
10472
10473 smp->data.type = SMP_T_SINT;
10474 smp->data.u.sint = hash;
10475 smp->flags = SMP_F_VOL_1ST;
10476 return 1;
10477 }
10478
10479 /* This concatenates the source address with the 32-bit hash of the Host and
10480 * path as returned by smp_fetch_base32(). The idea is to have per-source and
10481 * per-path counters. The result is a binary block from 8 to 20 bytes depending
10482 * on the source address length. The path hash is stored before the address so
10483 * that in environments where IPv6 is insignificant, truncating the output to
10484 * 8 bytes would still work.
10485 */
10486 static int
smp_fetch_base32_src(const struct arg * args,struct sample * smp,const char * kw,void * private)10487 smp_fetch_base32_src(const struct arg *args, struct sample *smp, const char *kw, void *private)
10488 {
10489 struct chunk *temp;
10490 struct connection *cli_conn = objt_conn(smp->sess->origin);
10491
10492 if (!cli_conn)
10493 return 0;
10494
10495 if (!smp_fetch_base32(args, smp, kw, private))
10496 return 0;
10497
10498 temp = get_trash_chunk();
10499 *(unsigned int *)temp->str = htonl(smp->data.u.sint);
10500 temp->len += sizeof(unsigned int);
10501
10502 switch (cli_conn->addr.from.ss_family) {
10503 case AF_INET:
10504 memcpy(temp->str + temp->len, &((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr, 4);
10505 temp->len += 4;
10506 break;
10507 case AF_INET6:
10508 memcpy(temp->str + temp->len, &((struct sockaddr_in6 *)&cli_conn->addr.from)->sin6_addr, 16);
10509 temp->len += 16;
10510 break;
10511 default:
10512 return 0;
10513 }
10514
10515 smp->data.u.str = *temp;
10516 smp->data.type = SMP_T_BIN;
10517 return 1;
10518 }
10519
10520 /* Extracts the query string, which comes after the question mark '?'. If no
10521 * question mark is found, nothing is returned. Otherwise it returns a sample
10522 * of type string carrying the whole query string.
10523 */
10524 static int
smp_fetch_query(const struct arg * args,struct sample * smp,const char * kw,void * private)10525 smp_fetch_query(const struct arg *args, struct sample *smp, const char *kw, void *private)
10526 {
10527 struct channel *chn = SMP_REQ_CHN(smp);
10528 struct http_txn *txn;
10529 char *ptr, *end;
10530
10531 CHECK_HTTP_MESSAGE_FIRST(chn);
10532
10533 txn = smp->strm->txn;
10534 ptr = chn->buf->p + txn->req.sl.rq.u;
10535 end = ptr + txn->req.sl.rq.u_l;
10536
10537 /* look up the '?' */
10538 do {
10539 if (ptr == end)
10540 return 0;
10541 } while (*ptr++ != '?');
10542
10543 smp->data.type = SMP_T_STR;
10544 smp->data.u.str.str = ptr;
10545 smp->data.u.str.len = end - ptr;
10546 smp->flags = SMP_F_VOL_1ST | SMP_F_CONST;
10547 return 1;
10548 }
10549
10550 static int
smp_fetch_proto_http(const struct arg * args,struct sample * smp,const char * kw,void * private)10551 smp_fetch_proto_http(const struct arg *args, struct sample *smp, const char *kw, void *private)
10552 {
10553 struct channel *chn = SMP_REQ_CHN(smp);
10554
10555 /* Note: hdr_idx.v cannot be NULL in this ACL because the ACL is tagged
10556 * as a layer7 ACL, which involves automatic allocation of hdr_idx.
10557 */
10558
10559 CHECK_HTTP_MESSAGE_FIRST_PERM(chn);
10560
10561 smp->data.type = SMP_T_BOOL;
10562 smp->data.u.sint = 1;
10563 return 1;
10564 }
10565
10566 /* return a valid test if the current request is the first one on the connection */
10567 static int
smp_fetch_http_first_req(const struct arg * args,struct sample * smp,const char * kw,void * private)10568 smp_fetch_http_first_req(const struct arg *args, struct sample *smp, const char *kw, void *private)
10569 {
10570 if (!smp->strm)
10571 return 0;
10572
10573 smp->data.type = SMP_T_BOOL;
10574 smp->data.u.sint = !(smp->strm->txn->flags & TX_NOT_FIRST);
10575 return 1;
10576 }
10577
10578 /* Accepts exactly 1 argument of type userlist */
10579 static int
smp_fetch_http_auth(const struct arg * args,struct sample * smp,const char * kw,void * private)10580 smp_fetch_http_auth(const struct arg *args, struct sample *smp, const char *kw, void *private)
10581 {
10582 struct channel *chn = SMP_REQ_CHN(smp);
10583
10584 if (!args || args->type != ARGT_USR)
10585 return 0;
10586
10587 CHECK_HTTP_MESSAGE_FIRST(chn);
10588
10589 if (!get_http_auth(smp->strm))
10590 return 0;
10591
10592 smp->data.type = SMP_T_BOOL;
10593 smp->data.u.sint = check_user(args->data.usr, smp->strm->txn->auth.user,
10594 smp->strm->txn->auth.pass);
10595 return 1;
10596 }
10597
10598 /* Accepts exactly 1 argument of type userlist */
10599 static int
smp_fetch_http_auth_grp(const struct arg * args,struct sample * smp,const char * kw,void * private)10600 smp_fetch_http_auth_grp(const struct arg *args, struct sample *smp, const char *kw, void *private)
10601 {
10602 struct channel *chn = SMP_REQ_CHN(smp);
10603
10604 if (!args || args->type != ARGT_USR)
10605 return 0;
10606
10607 CHECK_HTTP_MESSAGE_FIRST(chn);
10608
10609 if (!get_http_auth(smp->strm))
10610 return 0;
10611
10612 /* if the user does not belong to the userlist or has a wrong password,
10613 * report that it unconditionally does not match. Otherwise we return
10614 * a string containing the username.
10615 */
10616 if (!check_user(args->data.usr, smp->strm->txn->auth.user,
10617 smp->strm->txn->auth.pass))
10618 return 0;
10619
10620 /* pat_match_auth() will need the user list */
10621 smp->ctx.a[0] = args->data.usr;
10622
10623 smp->data.type = SMP_T_STR;
10624 smp->flags = SMP_F_CONST;
10625 smp->data.u.str.str = smp->strm->txn->auth.user;
10626 smp->data.u.str.len = strlen(smp->strm->txn->auth.user);
10627
10628 return 1;
10629 }
10630
10631 /* Try to find the next occurrence of a cookie name in a cookie header value.
10632 * To match on any cookie name, <cookie_name_l> must be set to 0.
10633 * The lookup begins at <hdr>. The pointer and size of the next occurrence of
10634 * the cookie value is returned into *value and *value_l, and the function
10635 * returns a pointer to the next pointer to search from if the value was found.
10636 * Otherwise if the cookie was not found, NULL is returned and neither value
10637 * nor value_l are touched. The input <hdr> string should first point to the
10638 * header's value, and the <hdr_end> pointer must point to the first character
10639 * not part of the value. <list> must be non-zero if value may represent a list
10640 * of values (cookie headers). This makes it faster to abort parsing when no
10641 * list is expected.
10642 */
10643 char *
extract_cookie_value(char * hdr,const char * hdr_end,char * cookie_name,size_t cookie_name_l,int list,char ** value,int * value_l)10644 extract_cookie_value(char *hdr, const char *hdr_end,
10645 char *cookie_name, size_t cookie_name_l, int list,
10646 char **value, int *value_l)
10647 {
10648 char *equal, *att_end, *att_beg, *val_beg, *val_end;
10649 char *next;
10650
10651 /* we search at least a cookie name followed by an equal, and more
10652 * generally something like this :
10653 * Cookie: NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3\r\n
10654 */
10655 for (att_beg = hdr; att_beg + cookie_name_l + 1 < hdr_end; att_beg = next + 1) {
10656 /* Iterate through all cookies on this line */
10657
10658 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
10659 att_beg++;
10660
10661 /* find att_end : this is the first character after the last non
10662 * space before the equal. It may be equal to hdr_end.
10663 */
10664 equal = att_end = att_beg;
10665
10666 while (equal < hdr_end) {
10667 if (*equal == '=' || *equal == ';' || (list && *equal == ','))
10668 break;
10669 if (HTTP_IS_SPHT(*equal++))
10670 continue;
10671 att_end = equal;
10672 }
10673
10674 /* here, <equal> points to '=', a delimitor or the end. <att_end>
10675 * is between <att_beg> and <equal>, both may be identical.
10676 */
10677
10678 /* look for end of cookie if there is an equal sign */
10679 if (equal < hdr_end && *equal == '=') {
10680 /* look for the beginning of the value */
10681 val_beg = equal + 1;
10682 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
10683 val_beg++;
10684
10685 /* find the end of the value, respecting quotes */
10686 next = find_cookie_value_end(val_beg, hdr_end);
10687
10688 /* make val_end point to the first white space or delimitor after the value */
10689 val_end = next;
10690 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
10691 val_end--;
10692 } else {
10693 val_beg = val_end = next = equal;
10694 }
10695
10696 /* We have nothing to do with attributes beginning with '$'. However,
10697 * they will automatically be removed if a header before them is removed,
10698 * since they're supposed to be linked together.
10699 */
10700 if (*att_beg == '$')
10701 continue;
10702
10703 /* Ignore cookies with no equal sign */
10704 if (equal == next)
10705 continue;
10706
10707 /* Now we have the cookie name between att_beg and att_end, and
10708 * its value between val_beg and val_end.
10709 */
10710
10711 if (cookie_name_l == 0 || (att_end - att_beg == cookie_name_l &&
10712 memcmp(att_beg, cookie_name, cookie_name_l) == 0)) {
10713 /* let's return this value and indicate where to go on from */
10714 *value = val_beg;
10715 *value_l = val_end - val_beg;
10716 return next + 1;
10717 }
10718
10719 /* Set-Cookie headers only have the name in the first attr=value part */
10720 if (!list)
10721 break;
10722 }
10723
10724 return NULL;
10725 }
10726
10727 /* Fetch a captured HTTP request header. The index is the position of
10728 * the "capture" option in the configuration file
10729 */
10730 static int
smp_fetch_capture_header_req(const struct arg * args,struct sample * smp,const char * kw,void * private)10731 smp_fetch_capture_header_req(const struct arg *args, struct sample *smp, const char *kw, void *private)
10732 {
10733 struct proxy *fe;
10734 int idx;
10735
10736 if (!args || args->type != ARGT_SINT)
10737 return 0;
10738
10739 if (!smp->strm)
10740 return 0;
10741
10742 fe = strm_fe(smp->strm);
10743 idx = args->data.sint;
10744
10745 if (idx > (fe->nb_req_cap - 1) || smp->strm->req_cap == NULL || smp->strm->req_cap[idx] == NULL)
10746 return 0;
10747
10748 smp->data.type = SMP_T_STR;
10749 smp->flags |= SMP_F_CONST;
10750 smp->data.u.str.str = smp->strm->req_cap[idx];
10751 smp->data.u.str.len = strlen(smp->strm->req_cap[idx]);
10752
10753 return 1;
10754 }
10755
10756 /* Fetch a captured HTTP response header. The index is the position of
10757 * the "capture" option in the configuration file
10758 */
10759 static int
smp_fetch_capture_header_res(const struct arg * args,struct sample * smp,const char * kw,void * private)10760 smp_fetch_capture_header_res(const struct arg *args, struct sample *smp, const char *kw, void *private)
10761 {
10762 struct proxy *fe;
10763 int idx;
10764
10765 if (!args || args->type != ARGT_SINT)
10766 return 0;
10767
10768 if (!smp->strm)
10769 return 0;
10770
10771 fe = strm_fe(smp->strm);
10772 idx = args->data.sint;
10773
10774 if (idx > (fe->nb_rsp_cap - 1) || smp->strm->res_cap == NULL || smp->strm->res_cap[idx] == NULL)
10775 return 0;
10776
10777 smp->data.type = SMP_T_STR;
10778 smp->flags |= SMP_F_CONST;
10779 smp->data.u.str.str = smp->strm->res_cap[idx];
10780 smp->data.u.str.len = strlen(smp->strm->res_cap[idx]);
10781
10782 return 1;
10783 }
10784
10785 /* Extracts the METHOD in the HTTP request, the txn->uri should be filled before the call */
10786 static int
smp_fetch_capture_req_method(const struct arg * args,struct sample * smp,const char * kw,void * private)10787 smp_fetch_capture_req_method(const struct arg *args, struct sample *smp, const char *kw, void *private)
10788 {
10789 struct chunk *temp;
10790 struct http_txn *txn;
10791 char *ptr;
10792
10793 if (!smp->strm)
10794 return 0;
10795
10796 txn = smp->strm->txn;
10797 if (!txn || !txn->uri)
10798 return 0;
10799
10800 ptr = txn->uri;
10801
10802 while (*ptr != ' ' && *ptr != '\0') /* find first space */
10803 ptr++;
10804
10805 temp = get_trash_chunk();
10806 temp->str = txn->uri;
10807 temp->len = ptr - txn->uri;
10808 smp->data.u.str = *temp;
10809 smp->data.type = SMP_T_STR;
10810 smp->flags = SMP_F_CONST;
10811
10812 return 1;
10813
10814 }
10815
10816 /* Extracts the path in the HTTP request, the txn->uri should be filled before the call */
10817 static int
smp_fetch_capture_req_uri(const struct arg * args,struct sample * smp,const char * kw,void * private)10818 smp_fetch_capture_req_uri(const struct arg *args, struct sample *smp, const char *kw, void *private)
10819 {
10820 struct chunk *temp;
10821 struct http_txn *txn;
10822 char *ptr;
10823
10824 if (!smp->strm)
10825 return 0;
10826
10827 txn = smp->strm->txn;
10828 if (!txn || !txn->uri)
10829 return 0;
10830
10831 ptr = txn->uri;
10832
10833 while (*ptr != ' ' && *ptr != '\0') /* find first space */
10834 ptr++;
10835
10836 if (!*ptr)
10837 return 0;
10838
10839 ptr++; /* skip the space */
10840
10841 temp = get_trash_chunk();
10842 ptr = temp->str = http_get_path_from_string(ptr);
10843 if (!ptr)
10844 return 0;
10845 while (*ptr != ' ' && *ptr != '\0') /* find space after URI */
10846 ptr++;
10847
10848 smp->data.u.str = *temp;
10849 smp->data.u.str.len = ptr - temp->str;
10850 smp->data.type = SMP_T_STR;
10851 smp->flags = SMP_F_CONST;
10852
10853 return 1;
10854 }
10855
10856 /* Retrieves the HTTP version from the request (either 1.0 or 1.1) and emits it
10857 * as a string (either "HTTP/1.0" or "HTTP/1.1").
10858 */
10859 static int
smp_fetch_capture_req_ver(const struct arg * args,struct sample * smp,const char * kw,void * private)10860 smp_fetch_capture_req_ver(const struct arg *args, struct sample *smp, const char *kw, void *private)
10861 {
10862 struct http_txn *txn;
10863
10864 if (!smp->strm)
10865 return 0;
10866
10867 txn = smp->strm->txn;
10868 if (!txn || txn->req.msg_state < HTTP_MSG_HDR_FIRST)
10869 return 0;
10870
10871 if (txn->req.flags & HTTP_MSGF_VER_11)
10872 smp->data.u.str.str = "HTTP/1.1";
10873 else
10874 smp->data.u.str.str = "HTTP/1.0";
10875
10876 smp->data.u.str.len = 8;
10877 smp->data.type = SMP_T_STR;
10878 smp->flags = SMP_F_CONST;
10879 return 1;
10880
10881 }
10882
10883 /* Retrieves the HTTP version from the response (either 1.0 or 1.1) and emits it
10884 * as a string (either "HTTP/1.0" or "HTTP/1.1").
10885 */
10886 static int
smp_fetch_capture_res_ver(const struct arg * args,struct sample * smp,const char * kw,void * private)10887 smp_fetch_capture_res_ver(const struct arg *args, struct sample *smp, const char *kw, void *private)
10888 {
10889 struct http_txn *txn;
10890
10891 if (!smp->strm)
10892 return 0;
10893
10894 txn = smp->strm->txn;
10895 if (!txn || txn->rsp.msg_state < HTTP_MSG_HDR_FIRST)
10896 return 0;
10897
10898 if (txn->rsp.flags & HTTP_MSGF_VER_11)
10899 smp->data.u.str.str = "HTTP/1.1";
10900 else
10901 smp->data.u.str.str = "HTTP/1.0";
10902
10903 smp->data.u.str.len = 8;
10904 smp->data.type = SMP_T_STR;
10905 smp->flags = SMP_F_CONST;
10906 return 1;
10907
10908 }
10909
10910
10911 /* Iterate over all cookies present in a message. The context is stored in
10912 * smp->ctx.a[0] for the in-header position, smp->ctx.a[1] for the
10913 * end-of-header-value, and smp->ctx.a[2] for the hdr_ctx. Depending on
10914 * the direction, multiple cookies may be parsed on the same line or not.
10915 * If provided, the searched cookie name is in args, in args->data.str. If
10916 * the input options indicate that no iterating is desired, then only last
10917 * value is fetched if any. If no cookie name is provided, the first cookie
10918 * value found is fetched. The returned sample is of type CSTR. Can be used
10919 * to parse cookies in other files.
10920 */
smp_fetch_cookie(const struct arg * args,struct sample * smp,const char * kw,void * private)10921 int smp_fetch_cookie(const struct arg *args, struct sample *smp, const char *kw, void *private)
10922 {
10923 /* possible keywords: req.cookie / cookie / cook, res.cookie / scook / set-cookie */
10924 struct channel *chn = ((kw[0] == 'c' || kw[2] == 'q') ? SMP_REQ_CHN(smp) : SMP_RES_CHN(smp));
10925 char *cook = NULL;
10926 size_t cook_l = 0;
10927 struct hdr_idx *idx;
10928 struct hdr_ctx *ctx = smp->ctx.a[2];
10929 const char *hdr_name;
10930 int hdr_name_len;
10931 char *sol;
10932 int found = 0;
10933
10934 if (args && args->type == ARGT_STR) {
10935 cook = args->data.str.str;
10936 cook_l = args->data.str.len;
10937 }
10938
10939 if (!ctx) {
10940 /* first call */
10941 ctx = &static_hdr_ctx;
10942 ctx->idx = 0;
10943 smp->ctx.a[2] = ctx;
10944 }
10945
10946 CHECK_HTTP_MESSAGE_FIRST(chn);
10947
10948 idx = &smp->strm->txn->hdr_idx;
10949
10950 if (!(chn->flags & CF_ISRESP)) {
10951 hdr_name = "Cookie";
10952 hdr_name_len = 6;
10953 } else {
10954 hdr_name = "Set-Cookie";
10955 hdr_name_len = 10;
10956 }
10957
10958 /* OK so basically here, either we want only one value or we want to
10959 * iterate over all of them and we fetch the next one. In this last case
10960 * SMP_OPT_ITERATE option is set.
10961 */
10962
10963 sol = chn->buf->p;
10964 if (!(smp->flags & SMP_F_NOT_LAST)) {
10965 /* search for the header from the beginning, we must first initialize
10966 * the search parameters.
10967 */
10968 smp->ctx.a[0] = NULL;
10969 ctx->idx = 0;
10970 }
10971
10972 smp->flags |= SMP_F_VOL_HDR;
10973
10974 while (1) {
10975 /* Note: smp->ctx.a[0] == NULL every time we need to fetch a new header */
10976 if (!smp->ctx.a[0]) {
10977 if (!http_find_header2(hdr_name, hdr_name_len, sol, idx, ctx))
10978 goto out;
10979
10980 if (ctx->vlen < cook_l + 1)
10981 continue;
10982
10983 smp->ctx.a[0] = ctx->line + ctx->val;
10984 smp->ctx.a[1] = smp->ctx.a[0] + ctx->vlen;
10985 }
10986
10987 smp->data.type = SMP_T_STR;
10988 smp->flags |= SMP_F_CONST;
10989 smp->ctx.a[0] = extract_cookie_value(smp->ctx.a[0], smp->ctx.a[1],
10990 cook, cook_l,
10991 (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ,
10992 &smp->data.u.str.str,
10993 &smp->data.u.str.len);
10994 if (smp->ctx.a[0]) {
10995 found = 1;
10996 if (smp->opt & SMP_OPT_ITERATE) {
10997 /* iterate on cookie value */
10998 smp->flags |= SMP_F_NOT_LAST;
10999 return 1;
11000 }
11001 if (args->data.str.len == 0) {
11002 /* No cookie name, first occurrence returned */
11003 break;
11004 }
11005 }
11006 /* if we're looking for last occurrence, let's loop */
11007 }
11008 /* all cookie headers and values were scanned. If we're looking for the
11009 * last occurrence, we may return it now.
11010 */
11011 out:
11012 smp->flags &= ~SMP_F_NOT_LAST;
11013 return found;
11014 }
11015
11016 /* Same than smp_fetch_cookie() but only relies on the sample direction to
11017 * choose the right channel. So instead of duplicating the code, we just change
11018 * the keyword and then fallback on smp_fetch_cookie().
11019 */
11020 static int
smp_fetch_chn_cookie(const struct arg * args,struct sample * smp,const char * kw,void * private)11021 smp_fetch_chn_cookie(const struct arg *args, struct sample *smp, const char *kw, void *private)
11022 {
11023 kw = ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ ? "req.cook" : "res.cook");
11024 return smp_fetch_cookie(args, smp, kw, private);
11025 }
11026
11027 /* Iterate over all cookies present in a request to count how many occurrences
11028 * match the name in args and args->data.str.len. If <multi> is non-null, then
11029 * multiple cookies may be parsed on the same line. The returned sample is of
11030 * type UINT. Accepts exactly 1 argument of type string.
11031 */
11032 static int
smp_fetch_cookie_cnt(const struct arg * args,struct sample * smp,const char * kw,void * private)11033 smp_fetch_cookie_cnt(const struct arg *args, struct sample *smp, const char *kw, void *private)
11034 {
11035 /* possible keywords: req.cook_cnt / cook_cnt, res.cook_cnt / scook_cnt */
11036 struct channel *chn = ((kw[0] == 'c' || kw[2] == 'q') ? SMP_REQ_CHN(smp) : SMP_RES_CHN(smp));
11037 struct hdr_idx *idx;
11038 struct hdr_ctx ctx;
11039 const char *hdr_name;
11040 int hdr_name_len;
11041 int cnt;
11042 char *val_beg, *val_end;
11043 char *cook = NULL;
11044 size_t cook_l = 0;
11045 char *sol;
11046
11047 if (args && args->type == ARGT_STR){
11048 cook = args->data.str.str;
11049 cook_l = args->data.str.len;
11050 }
11051
11052 CHECK_HTTP_MESSAGE_FIRST(chn);
11053
11054 idx = &smp->strm->txn->hdr_idx;
11055
11056 if (!(chn->flags & CF_ISRESP)) {
11057 hdr_name = "Cookie";
11058 hdr_name_len = 6;
11059 } else {
11060 hdr_name = "Set-Cookie";
11061 hdr_name_len = 10;
11062 }
11063
11064 sol = chn->buf->p;
11065 val_end = val_beg = NULL;
11066 ctx.idx = 0;
11067 cnt = 0;
11068
11069 while (1) {
11070 /* Note: val_beg == NULL every time we need to fetch a new header */
11071 if (!val_beg) {
11072 if (!http_find_header2(hdr_name, hdr_name_len, sol, idx, &ctx))
11073 break;
11074
11075 if (ctx.vlen < cook_l + 1)
11076 continue;
11077
11078 val_beg = ctx.line + ctx.val;
11079 val_end = val_beg + ctx.vlen;
11080 }
11081
11082 smp->data.type = SMP_T_STR;
11083 smp->flags |= SMP_F_CONST;
11084 while ((val_beg = extract_cookie_value(val_beg, val_end,
11085 cook, cook_l,
11086 (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ,
11087 &smp->data.u.str.str,
11088 &smp->data.u.str.len))) {
11089 cnt++;
11090 }
11091 }
11092
11093 smp->data.type = SMP_T_SINT;
11094 smp->data.u.sint = cnt;
11095 smp->flags |= SMP_F_VOL_HDR;
11096 return 1;
11097 }
11098
11099 /* Fetch an cookie's integer value. The integer value is returned. It
11100 * takes a mandatory argument of type string. It relies on smp_fetch_cookie().
11101 */
11102 static int
smp_fetch_cookie_val(const struct arg * args,struct sample * smp,const char * kw,void * private)11103 smp_fetch_cookie_val(const struct arg *args, struct sample *smp, const char *kw, void *private)
11104 {
11105 int ret = smp_fetch_cookie(args, smp, kw, private);
11106
11107 if (ret > 0) {
11108 smp->data.type = SMP_T_SINT;
11109 smp->data.u.sint = strl2ic(smp->data.u.str.str, smp->data.u.str.len);
11110 }
11111
11112 return ret;
11113 }
11114
11115 /************************************************************************/
11116 /* The code below is dedicated to sample fetches */
11117 /************************************************************************/
11118
11119 /*
11120 * Given a path string and its length, find the position of beginning of the
11121 * query string. Returns NULL if no query string is found in the path.
11122 *
11123 * Example: if path = "/foo/bar/fubar?yo=mama;ye=daddy", and n = 22:
11124 *
11125 * find_query_string(path, n, '?') points to "yo=mama;ye=daddy" string.
11126 */
find_param_list(char * path,size_t path_l,char delim)11127 static inline char *find_param_list(char *path, size_t path_l, char delim)
11128 {
11129 char *p;
11130
11131 p = memchr(path, delim, path_l);
11132 return p ? p + 1 : NULL;
11133 }
11134
is_param_delimiter(char c,char delim)11135 static inline int is_param_delimiter(char c, char delim)
11136 {
11137 return c == '&' || c == ';' || c == delim;
11138 }
11139
11140 /* after increasing a pointer value, it can exceed the first buffer
11141 * size. This function transform the value of <ptr> according with
11142 * the expected position. <chunks> is an array of the one or two
11143 * avalaible chunks. The first value is the start of the first chunk,
11144 * the second value if the end+1 of the first chunks. The third value
11145 * is NULL or the start of the second chunk and the fourth value is
11146 * the end+1 of the second chunk. The function returns 1 if does a
11147 * wrap, else returns 0.
11148 */
fix_pointer_if_wrap(const char ** chunks,const char ** ptr)11149 static inline int fix_pointer_if_wrap(const char **chunks, const char **ptr)
11150 {
11151 if (*ptr < chunks[1])
11152 return 0;
11153 if (!chunks[2])
11154 return 0;
11155 *ptr = chunks[2] + ( *ptr - chunks[1] );
11156 return 1;
11157 }
11158
11159 /*
11160 * Given a url parameter, find the starting position of the first occurence,
11161 * or NULL if the parameter is not found.
11162 *
11163 * Example: if query_string is "yo=mama;ye=daddy" and url_param_name is "ye",
11164 * the function will return query_string+8.
11165 *
11166 * Warning: this function returns a pointer that can point to the first chunk
11167 * or the second chunk. The caller must be check the position before using the
11168 * result.
11169 */
11170 static const char *
find_url_param_pos(const char ** chunks,const char * url_param_name,size_t url_param_name_l,char delim)11171 find_url_param_pos(const char **chunks,
11172 const char* url_param_name, size_t url_param_name_l,
11173 char delim)
11174 {
11175 const char *pos, *last, *equal;
11176 const char **bufs = chunks;
11177 int l1, l2;
11178
11179
11180 pos = bufs[0];
11181 last = bufs[1];
11182 while (pos < last) {
11183 /* Check the equal. */
11184 equal = pos + url_param_name_l;
11185 if (fix_pointer_if_wrap(chunks, &equal)) {
11186 if (equal >= chunks[3])
11187 return NULL;
11188 } else {
11189 if (equal >= chunks[1])
11190 return NULL;
11191 }
11192 if (*equal == '=') {
11193 if (pos + url_param_name_l > last) {
11194 /* process wrap case, we detect a wrap. In this case, the
11195 * comparison is performed in two parts.
11196 */
11197
11198 /* This is the end, we dont have any other chunk. */
11199 if (bufs != chunks || !bufs[2])
11200 return NULL;
11201
11202 /* Compute the length of each part of the comparison. */
11203 l1 = last - pos;
11204 l2 = url_param_name_l - l1;
11205
11206 /* The second buffer is too short to contain the compared string. */
11207 if (bufs[2] + l2 > bufs[3])
11208 return NULL;
11209
11210 if (memcmp(pos, url_param_name, l1) == 0 &&
11211 memcmp(bufs[2], url_param_name+l1, l2) == 0)
11212 return pos;
11213
11214 /* Perform wrapping and jump the string who fail the comparison. */
11215 bufs += 2;
11216 pos = bufs[0] + l2;
11217 last = bufs[1];
11218
11219 } else {
11220 /* process a simple comparison. */
11221 if (memcmp(pos, url_param_name, url_param_name_l) == 0)
11222 return pos;
11223 pos += url_param_name_l + 1;
11224 if (fix_pointer_if_wrap(chunks, &pos))
11225 last = bufs[2];
11226 }
11227 }
11228
11229 while (1) {
11230 /* Look for the next delimiter. */
11231 while (pos < last && !is_param_delimiter(*pos, delim))
11232 pos++;
11233 if (pos < last)
11234 break;
11235 /* process buffer wrapping. */
11236 if (bufs != chunks || !bufs[2])
11237 return NULL;
11238 bufs += 2;
11239 pos = bufs[0];
11240 last = bufs[1];
11241 }
11242 pos++;
11243 }
11244 return NULL;
11245 }
11246
11247 /*
11248 * Given a url parameter name and a query string, find the next value.
11249 * An empty url_param_name matches the first available parameter.
11250 * If the parameter is found, 1 is returned and *vstart / *vend are updated to
11251 * respectively provide a pointer to the value and its end.
11252 * Otherwise, 0 is returned and vstart/vend are not modified.
11253 */
11254 static int
find_next_url_param(const char ** chunks,const char * url_param_name,size_t url_param_name_l,const char ** vstart,const char ** vend,char delim)11255 find_next_url_param(const char **chunks,
11256 const char* url_param_name, size_t url_param_name_l,
11257 const char **vstart, const char **vend, char delim)
11258 {
11259 const char *arg_start, *qs_end;
11260 const char *value_start, *value_end;
11261
11262 arg_start = chunks[0];
11263 qs_end = chunks[1];
11264 if (url_param_name_l) {
11265 /* Looks for an argument name. */
11266 arg_start = find_url_param_pos(chunks,
11267 url_param_name, url_param_name_l,
11268 delim);
11269 /* Check for wrapping. */
11270 if (arg_start >= qs_end)
11271 qs_end = chunks[3];
11272 }
11273 if (!arg_start)
11274 return 0;
11275
11276 if (!url_param_name_l) {
11277 while (1) {
11278 /* looks for the first argument. */
11279 value_start = memchr(arg_start, '=', qs_end - arg_start);
11280 if (!value_start) {
11281 /* Check for wrapping. */
11282 if (arg_start >= chunks[0] &&
11283 arg_start < chunks[1] &&
11284 chunks[2]) {
11285 arg_start = chunks[2];
11286 qs_end = chunks[3];
11287 continue;
11288 }
11289 return 0;
11290 }
11291 break;
11292 }
11293 value_start++;
11294 }
11295 else {
11296 /* Jump the argument length. */
11297 value_start = arg_start + url_param_name_l + 1;
11298
11299 /* Check for pointer wrapping. */
11300 if (fix_pointer_if_wrap(chunks, &value_start)) {
11301 /* Update the end pointer. */
11302 qs_end = chunks[3];
11303
11304 /* Check for overflow. */
11305 if (value_start >= qs_end)
11306 return 0;
11307 }
11308 }
11309
11310 value_end = value_start;
11311
11312 while (1) {
11313 while ((value_end < qs_end) && !is_param_delimiter(*value_end, delim))
11314 value_end++;
11315 if (value_end < qs_end)
11316 break;
11317 /* process buffer wrapping. */
11318 if (value_end >= chunks[0] &&
11319 value_end < chunks[1] &&
11320 chunks[2]) {
11321 value_end = chunks[2];
11322 qs_end = chunks[3];
11323 continue;
11324 }
11325 break;
11326 }
11327
11328 *vstart = value_start;
11329 *vend = value_end;
11330 return 1;
11331 }
11332
11333 /* This scans a URL-encoded query string. It takes an optionally wrapping
11334 * string whose first contigous chunk has its beginning in ctx->a[0] and end
11335 * in ctx->a[1], and the optional second part in (ctx->a[2]..ctx->a[3]). The
11336 * pointers are updated for next iteration before leaving.
11337 */
11338 static int
smp_fetch_param(char delim,const char * name,int name_len,const struct arg * args,struct sample * smp,const char * kw,void * private)11339 smp_fetch_param(char delim, const char *name, int name_len, const struct arg *args, struct sample *smp, const char *kw, void *private)
11340 {
11341 const char *vstart, *vend;
11342 struct chunk *temp;
11343 const char **chunks = (const char **)smp->ctx.a;
11344
11345 if (!find_next_url_param(chunks,
11346 name, name_len,
11347 &vstart, &vend,
11348 delim))
11349 return 0;
11350
11351 /* Create sample. If the value is contiguous, return the pointer as CONST,
11352 * if the value is wrapped, copy-it in a buffer.
11353 */
11354 smp->data.type = SMP_T_STR;
11355 if (chunks[2] &&
11356 vstart >= chunks[0] && vstart <= chunks[1] &&
11357 vend >= chunks[2] && vend <= chunks[3]) {
11358 /* Wrapped case. */
11359 temp = get_trash_chunk();
11360 memcpy(temp->str, vstart, chunks[1] - vstart);
11361 memcpy(temp->str + ( chunks[1] - vstart ), chunks[2], vend - chunks[2]);
11362 smp->data.u.str.str = temp->str;
11363 smp->data.u.str.len = ( chunks[1] - vstart ) + ( vend - chunks[2] );
11364 } else {
11365 /* Contiguous case. */
11366 smp->data.u.str.str = (char *)vstart;
11367 smp->data.u.str.len = vend - vstart;
11368 smp->flags = SMP_F_VOL_1ST | SMP_F_CONST;
11369 }
11370
11371 /* Update context, check wrapping. */
11372 chunks[0] = vend;
11373 if (chunks[2] && vend >= chunks[2] && vend <= chunks[3]) {
11374 chunks[1] = chunks[3];
11375 chunks[2] = NULL;
11376 }
11377
11378 if (chunks[0] < chunks[1])
11379 smp->flags |= SMP_F_NOT_LAST;
11380
11381 return 1;
11382 }
11383
11384 /* This function iterates over each parameter of the query string. It uses
11385 * ctx->a[0] and ctx->a[1] to store the beginning and end of the current
11386 * parameter. Since it uses smp_fetch_param(), ctx->a[2..3] are both NULL.
11387 * An optional parameter name is passed in args[0], otherwise any parameter is
11388 * considered. It supports an optional delimiter argument for the beginning of
11389 * the string in args[1], which defaults to "?".
11390 */
11391 static int
smp_fetch_url_param(const struct arg * args,struct sample * smp,const char * kw,void * private)11392 smp_fetch_url_param(const struct arg *args, struct sample *smp, const char *kw, void *private)
11393 {
11394 struct channel *chn = SMP_REQ_CHN(smp);
11395 struct http_msg *msg;
11396 char delim = '?';
11397 const char *name;
11398 int name_len;
11399
11400 if (!args ||
11401 (args[0].type && args[0].type != ARGT_STR) ||
11402 (args[1].type && args[1].type != ARGT_STR))
11403 return 0;
11404
11405 name = "";
11406 name_len = 0;
11407 if (args->type == ARGT_STR) {
11408 name = args->data.str.str;
11409 name_len = args->data.str.len;
11410 }
11411
11412 if (args[1].type)
11413 delim = *args[1].data.str.str;
11414
11415 if (!smp->ctx.a[0]) { // first call, find the query string
11416 CHECK_HTTP_MESSAGE_FIRST(chn);
11417
11418 msg = &smp->strm->txn->req;
11419
11420 smp->ctx.a[0] = find_param_list(chn->buf->p + msg->sl.rq.u,
11421 msg->sl.rq.u_l, delim);
11422 if (!smp->ctx.a[0])
11423 return 0;
11424
11425 smp->ctx.a[1] = chn->buf->p + msg->sl.rq.u + msg->sl.rq.u_l;
11426
11427 /* Assume that the context is filled with NULL pointer
11428 * before the first call.
11429 * smp->ctx.a[2] = NULL;
11430 * smp->ctx.a[3] = NULL;
11431 */
11432 }
11433
11434 return smp_fetch_param(delim, name, name_len, args, smp, kw, private);
11435 }
11436
11437 /* This function iterates over each parameter of the body. This requires
11438 * that the body has been waited for using http-buffer-request. It uses
11439 * ctx->a[0] and ctx->a[1] to store the beginning and end of the first
11440 * contigous part of the body, and optionally ctx->a[2..3] to reference the
11441 * optional second part if the body wraps at the end of the buffer. An optional
11442 * parameter name is passed in args[0], otherwise any parameter is considered.
11443 */
11444 static int
smp_fetch_body_param(const struct arg * args,struct sample * smp,const char * kw,void * private)11445 smp_fetch_body_param(const struct arg *args, struct sample *smp, const char *kw, void *private)
11446 {
11447 struct channel *chn = SMP_REQ_CHN(smp);
11448 struct http_msg *msg;
11449 unsigned long len;
11450 unsigned long block1;
11451 char *body;
11452 const char *name;
11453 int name_len;
11454
11455 if (!args || (args[0].type && args[0].type != ARGT_STR))
11456 return 0;
11457
11458 name = "";
11459 name_len = 0;
11460 if (args[0].type == ARGT_STR) {
11461 name = args[0].data.str.str;
11462 name_len = args[0].data.str.len;
11463 }
11464
11465 if (!smp->ctx.a[0]) { // first call, find the query string
11466 CHECK_HTTP_MESSAGE_FIRST(chn);
11467
11468 msg = &smp->strm->txn->req;
11469 len = http_body_bytes(msg);
11470 body = b_ptr(chn->buf, -http_data_rewind(msg));
11471
11472 block1 = len;
11473 if (block1 > chn->buf->data + chn->buf->size - body)
11474 block1 = chn->buf->data + chn->buf->size - body;
11475
11476 if (block1 == len) {
11477 /* buffer is not wrapped (or empty) */
11478 smp->ctx.a[0] = body;
11479 smp->ctx.a[1] = body + len;
11480
11481 /* Assume that the context is filled with NULL pointer
11482 * before the first call.
11483 * smp->ctx.a[2] = NULL;
11484 * smp->ctx.a[3] = NULL;
11485 */
11486 }
11487 else {
11488 /* buffer is wrapped, we need to defragment it */
11489 smp->ctx.a[0] = body;
11490 smp->ctx.a[1] = body + block1;
11491 smp->ctx.a[2] = chn->buf->data;
11492 smp->ctx.a[3] = chn->buf->data + ( len - block1 );
11493 }
11494 }
11495 return smp_fetch_param('&', name, name_len, args, smp, kw, private);
11496 }
11497
11498 /* Return the signed integer value for the specified url parameter (see url_param
11499 * above).
11500 */
11501 static int
smp_fetch_url_param_val(const struct arg * args,struct sample * smp,const char * kw,void * private)11502 smp_fetch_url_param_val(const struct arg *args, struct sample *smp, const char *kw, void *private)
11503 {
11504 int ret = smp_fetch_url_param(args, smp, kw, private);
11505
11506 if (ret > 0) {
11507 smp->data.type = SMP_T_SINT;
11508 smp->data.u.sint = strl2ic(smp->data.u.str.str, smp->data.u.str.len);
11509 }
11510
11511 return ret;
11512 }
11513
11514 /* This produces a 32-bit hash of the concatenation of the first occurrence of
11515 * the Host header followed by the path component if it begins with a slash ('/').
11516 * This means that '*' will not be added, resulting in exactly the first Host
11517 * entry. If no Host header is found, then the path is used. The resulting value
11518 * is hashed using the url hash followed by a full avalanche hash and provides a
11519 * 32-bit integer value. This fetch is useful for tracking per-URL activity on
11520 * high-traffic sites without having to store whole paths.
11521 * this differs from the base32 functions in that it includes the url parameters
11522 * as well as the path
11523 */
11524 static int
smp_fetch_url32(const struct arg * args,struct sample * smp,const char * kw,void * private)11525 smp_fetch_url32(const struct arg *args, struct sample *smp, const char *kw, void *private)
11526 {
11527 struct channel *chn = SMP_REQ_CHN(smp);
11528 struct http_txn *txn;
11529 struct hdr_ctx ctx;
11530 unsigned int hash = 0;
11531 char *ptr, *beg, *end;
11532 int len;
11533
11534 CHECK_HTTP_MESSAGE_FIRST(chn);
11535
11536 txn = smp->strm->txn;
11537 ctx.idx = 0;
11538 if (http_find_header2("Host", 4, chn->buf->p, &txn->hdr_idx, &ctx)) {
11539 /* OK we have the header value in ctx.line+ctx.val for ctx.vlen bytes */
11540 ptr = ctx.line + ctx.val;
11541 len = ctx.vlen;
11542 while (len--)
11543 hash = *(ptr++) + (hash << 6) + (hash << 16) - hash;
11544 }
11545
11546 /* now retrieve the path */
11547 end = chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
11548 beg = http_get_path(txn);
11549 if (!beg)
11550 beg = end;
11551
11552 for (ptr = beg; ptr < end ; ptr++);
11553
11554 if (beg < ptr && *beg == '/') {
11555 while (beg < ptr)
11556 hash = *(beg++) + (hash << 6) + (hash << 16) - hash;
11557 }
11558 hash = full_hash(hash);
11559
11560 smp->data.type = SMP_T_SINT;
11561 smp->data.u.sint = hash;
11562 smp->flags = SMP_F_VOL_1ST;
11563 return 1;
11564 }
11565
11566 /* This concatenates the source address with the 32-bit hash of the Host and
11567 * URL as returned by smp_fetch_base32(). The idea is to have per-source and
11568 * per-url counters. The result is a binary block from 8 to 20 bytes depending
11569 * on the source address length. The URL hash is stored before the address so
11570 * that in environments where IPv6 is insignificant, truncating the output to
11571 * 8 bytes would still work.
11572 */
11573 static int
smp_fetch_url32_src(const struct arg * args,struct sample * smp,const char * kw,void * private)11574 smp_fetch_url32_src(const struct arg *args, struct sample *smp, const char *kw, void *private)
11575 {
11576 struct chunk *temp;
11577 struct connection *cli_conn = objt_conn(smp->sess->origin);
11578
11579 if (!cli_conn)
11580 return 0;
11581
11582 if (!smp_fetch_url32(args, smp, kw, private))
11583 return 0;
11584
11585 temp = get_trash_chunk();
11586 *(unsigned int *)temp->str = htonl(smp->data.u.sint);
11587 temp->len += sizeof(unsigned int);
11588
11589 switch (cli_conn->addr.from.ss_family) {
11590 case AF_INET:
11591 memcpy(temp->str + temp->len, &((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr, 4);
11592 temp->len += 4;
11593 break;
11594 case AF_INET6:
11595 memcpy(temp->str + temp->len, &((struct sockaddr_in6 *)&cli_conn->addr.from)->sin6_addr, 16);
11596 temp->len += 16;
11597 break;
11598 default:
11599 return 0;
11600 }
11601
11602 smp->data.u.str = *temp;
11603 smp->data.type = SMP_T_BIN;
11604 return 1;
11605 }
11606
11607 /* This function is used to validate the arguments passed to any "hdr" fetch
11608 * keyword. These keywords support an optional positive or negative occurrence
11609 * number. We must ensure that the number is greater than -MAX_HDR_HISTORY. It
11610 * is assumed that the types are already the correct ones. Returns 0 on error,
11611 * non-zero if OK. If <err> is not NULL, it will be filled with a pointer to an
11612 * error message in case of error, that the caller is responsible for freeing.
11613 * The initial location must either be freeable or NULL.
11614 */
val_hdr(struct arg * arg,char ** err_msg)11615 int val_hdr(struct arg *arg, char **err_msg)
11616 {
11617 if (arg && arg[1].type == ARGT_SINT && arg[1].data.sint < -MAX_HDR_HISTORY) {
11618 memprintf(err_msg, "header occurrence must be >= %d", -MAX_HDR_HISTORY);
11619 return 0;
11620 }
11621 return 1;
11622 }
11623
11624 /* takes an UINT value on input supposed to represent the time since EPOCH,
11625 * adds an optional offset found in args[0] and emits a string representing
11626 * the date in RFC-1123/5322 format.
11627 */
sample_conv_http_date(const struct arg * args,struct sample * smp,void * private)11628 static int sample_conv_http_date(const struct arg *args, struct sample *smp, void *private)
11629 {
11630 const char day[7][4] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
11631 const char mon[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
11632 struct chunk *temp;
11633 struct tm *tm;
11634 /* With high numbers, the date returned can be negative, the 55 bits mask prevent this. */
11635 time_t curr_date = smp->data.u.sint & 0x007fffffffffffffLL;
11636
11637 /* add offset */
11638 if (args && (args[0].type == ARGT_SINT))
11639 curr_date += args[0].data.sint;
11640
11641 tm = gmtime(&curr_date);
11642 if (!tm)
11643 return 0;
11644
11645 temp = get_trash_chunk();
11646 temp->len = snprintf(temp->str, temp->size - temp->len,
11647 "%s, %02d %s %04d %02d:%02d:%02d GMT",
11648 day[tm->tm_wday], tm->tm_mday, mon[tm->tm_mon], 1900+tm->tm_year,
11649 tm->tm_hour, tm->tm_min, tm->tm_sec);
11650
11651 smp->data.u.str = *temp;
11652 smp->data.type = SMP_T_STR;
11653 return 1;
11654 }
11655
11656 /* Match language range with language tag. RFC2616 14.4:
11657 *
11658 * A language-range matches a language-tag if it exactly equals
11659 * the tag, or if it exactly equals a prefix of the tag such
11660 * that the first tag character following the prefix is "-".
11661 *
11662 * Return 1 if the strings match, else return 0.
11663 */
language_range_match(const char * range,int range_len,const char * tag,int tag_len)11664 static inline int language_range_match(const char *range, int range_len,
11665 const char *tag, int tag_len)
11666 {
11667 const char *end = range + range_len;
11668 const char *tend = tag + tag_len;
11669 while (range < end) {
11670 if (*range == '-' && tag == tend)
11671 return 1;
11672 if (*range != *tag || tag == tend)
11673 return 0;
11674 range++;
11675 tag++;
11676 }
11677 /* Return true only if the last char of the tag is matched. */
11678 return tag == tend;
11679 }
11680
11681 /* Arguments: The list of expected value, the number of parts returned and the separator */
sample_conv_q_prefered(const struct arg * args,struct sample * smp,void * private)11682 static int sample_conv_q_prefered(const struct arg *args, struct sample *smp, void *private)
11683 {
11684 const char *al = smp->data.u.str.str;
11685 const char *end = al + smp->data.u.str.len;
11686 const char *token;
11687 int toklen;
11688 int qvalue;
11689 const char *str;
11690 const char *w;
11691 int best_q = 0;
11692
11693 /* Set the constant to the sample, because the output of the
11694 * function will be peek in the constant configuration string.
11695 */
11696 smp->flags |= SMP_F_CONST;
11697 smp->data.u.str.size = 0;
11698 smp->data.u.str.str = "";
11699 smp->data.u.str.len = 0;
11700
11701 /* Parse the accept language */
11702 while (1) {
11703
11704 /* Jump spaces, quit if the end is detected. */
11705 while (al < end && isspace((unsigned char)*al))
11706 al++;
11707 if (al >= end)
11708 break;
11709
11710 /* Start of the fisrt word. */
11711 token = al;
11712
11713 /* Look for separator: isspace(), ',' or ';'. Next value if 0 length word. */
11714 while (al < end && *al != ';' && *al != ',' && !isspace((unsigned char)*al))
11715 al++;
11716 if (al == token)
11717 goto expect_comma;
11718
11719 /* Length of the token. */
11720 toklen = al - token;
11721 qvalue = 1000;
11722
11723 /* Check if the token exists in the list. If the token not exists,
11724 * jump to the next token.
11725 */
11726 str = args[0].data.str.str;
11727 w = str;
11728 while (1) {
11729 if (*str == ';' || *str == '\0') {
11730 if (language_range_match(token, toklen, w, str-w))
11731 goto look_for_q;
11732 if (*str == '\0')
11733 goto expect_comma;
11734 w = str + 1;
11735 }
11736 str++;
11737 }
11738 goto expect_comma;
11739
11740 look_for_q:
11741
11742 /* Jump spaces, quit if the end is detected. */
11743 while (al < end && isspace((unsigned char)*al))
11744 al++;
11745 if (al >= end)
11746 goto process_value;
11747
11748 /* If ',' is found, process the result */
11749 if (*al == ',')
11750 goto process_value;
11751
11752 /* If the character is different from ';', look
11753 * for the end of the header part in best effort.
11754 */
11755 if (*al != ';')
11756 goto expect_comma;
11757
11758 /* Assumes that the char is ';', now expect "q=". */
11759 al++;
11760
11761 /* Jump spaces, process value if the end is detected. */
11762 while (al < end && isspace((unsigned char)*al))
11763 al++;
11764 if (al >= end)
11765 goto process_value;
11766
11767 /* Expect 'q'. If no 'q', continue in best effort */
11768 if (*al != 'q')
11769 goto process_value;
11770 al++;
11771
11772 /* Jump spaces, process value if the end is detected. */
11773 while (al < end && isspace((unsigned char)*al))
11774 al++;
11775 if (al >= end)
11776 goto process_value;
11777
11778 /* Expect '='. If no '=', continue in best effort */
11779 if (*al != '=')
11780 goto process_value;
11781 al++;
11782
11783 /* Jump spaces, process value if the end is detected. */
11784 while (al < end && isspace((unsigned char)*al))
11785 al++;
11786 if (al >= end)
11787 goto process_value;
11788
11789 /* Parse the q value. */
11790 qvalue = parse_qvalue(al, &al);
11791
11792 process_value:
11793
11794 /* If the new q value is the best q value, then store the associated
11795 * language in the response. If qvalue is the biggest value (1000),
11796 * break the process.
11797 */
11798 if (qvalue > best_q) {
11799 smp->data.u.str.str = (char *)w;
11800 smp->data.u.str.len = str - w;
11801 if (qvalue >= 1000)
11802 break;
11803 best_q = qvalue;
11804 }
11805
11806 expect_comma:
11807
11808 /* Expect comma or end. If the end is detected, quit the loop. */
11809 while (al < end && *al != ',')
11810 al++;
11811 if (al >= end)
11812 break;
11813
11814 /* Comma is found, jump it and restart the analyzer. */
11815 al++;
11816 }
11817
11818 /* Set default value if required. */
11819 if (smp->data.u.str.len == 0 && args[1].type == ARGT_STR) {
11820 smp->data.u.str.str = args[1].data.str.str;
11821 smp->data.u.str.len = args[1].data.str.len;
11822 }
11823
11824 /* Return true only if a matching language was found. */
11825 return smp->data.u.str.len != 0;
11826 }
11827
11828 /* This fetch url-decode any input string. */
sample_conv_url_dec(const struct arg * args,struct sample * smp,void * private)11829 static int sample_conv_url_dec(const struct arg *args, struct sample *smp, void *private)
11830 {
11831 int in_form = 0;
11832
11833 /* If the constant flag is set or if not size is avalaible at
11834 * the end of the buffer, copy the string in other buffer
11835 * before decoding.
11836 */
11837 if (smp->flags & SMP_F_CONST || smp->data.u.str.size <= smp->data.u.str.len) {
11838 struct chunk *str = get_trash_chunk();
11839 memcpy(str->str, smp->data.u.str.str, smp->data.u.str.len);
11840 smp->data.u.str.str = str->str;
11841 smp->data.u.str.size = str->size;
11842 smp->flags &= ~SMP_F_CONST;
11843 }
11844
11845 /* Add final \0 required by url_decode(), and convert the input string. */
11846 smp->data.u.str.str[smp->data.u.str.len] = '\0';
11847
11848 if (args && (args[0].type == ARGT_SINT))
11849 in_form = !!args[0].data.sint;
11850
11851 smp->data.u.str.len = url_decode(smp->data.u.str.str, in_form);
11852 return (smp->data.u.str.len >= 0);
11853 }
11854
smp_conv_req_capture(const struct arg * args,struct sample * smp,void * private)11855 static int smp_conv_req_capture(const struct arg *args, struct sample *smp, void *private)
11856 {
11857 struct proxy *fe;
11858 int idx, i;
11859 struct cap_hdr *hdr;
11860 int len;
11861
11862 if (!args || args->type != ARGT_SINT)
11863 return 0;
11864
11865 if (!smp->strm)
11866 return 0;
11867
11868 fe = strm_fe(smp->strm);
11869 idx = args->data.sint;
11870
11871 /* Check the availibity of the capture id. */
11872 if (idx > fe->nb_req_cap - 1)
11873 return 0;
11874
11875 /* Look for the original configuration. */
11876 for (hdr = fe->req_cap, i = fe->nb_req_cap - 1;
11877 hdr != NULL && i != idx ;
11878 i--, hdr = hdr->next);
11879 if (!hdr)
11880 return 0;
11881
11882 /* check for the memory allocation */
11883 if (smp->strm->req_cap[hdr->index] == NULL)
11884 smp->strm->req_cap[hdr->index] = pool_alloc(hdr->pool);
11885 if (smp->strm->req_cap[hdr->index] == NULL)
11886 return 0;
11887
11888 /* Check length. */
11889 len = smp->data.u.str.len;
11890 if (len > hdr->len)
11891 len = hdr->len;
11892
11893 /* Capture input data. */
11894 memcpy(smp->strm->req_cap[idx], smp->data.u.str.str, len);
11895 smp->strm->req_cap[idx][len] = '\0';
11896
11897 return 1;
11898 }
11899
smp_conv_res_capture(const struct arg * args,struct sample * smp,void * private)11900 static int smp_conv_res_capture(const struct arg *args, struct sample *smp, void *private)
11901 {
11902 struct proxy *fe;
11903 int idx, i;
11904 struct cap_hdr *hdr;
11905 int len;
11906
11907 if (!args || args->type != ARGT_SINT)
11908 return 0;
11909
11910 if (!smp->strm)
11911 return 0;
11912
11913 fe = strm_fe(smp->strm);
11914 idx = args->data.sint;
11915
11916 /* Check the availibity of the capture id. */
11917 if (idx > fe->nb_rsp_cap - 1)
11918 return 0;
11919
11920 /* Look for the original configuration. */
11921 for (hdr = fe->rsp_cap, i = fe->nb_rsp_cap - 1;
11922 hdr != NULL && i != idx ;
11923 i--, hdr = hdr->next);
11924 if (!hdr)
11925 return 0;
11926
11927 /* check for the memory allocation */
11928 if (smp->strm->res_cap[hdr->index] == NULL)
11929 smp->strm->res_cap[hdr->index] = pool_alloc(hdr->pool);
11930 if (smp->strm->res_cap[hdr->index] == NULL)
11931 return 0;
11932
11933 /* Check length. */
11934 len = smp->data.u.str.len;
11935 if (len > hdr->len)
11936 len = hdr->len;
11937
11938 /* Capture input data. */
11939 memcpy(smp->strm->res_cap[idx], smp->data.u.str.str, len);
11940 smp->strm->res_cap[idx][len] = '\0';
11941
11942 return 1;
11943 }
11944
11945 /* This function executes one of the set-{method,path,query,uri} actions. It
11946 * takes the string from the variable 'replace' with length 'len', then modifies
11947 * the relevant part of the request line accordingly. Then it updates various
11948 * pointers to the next elements which were moved, and the total buffer length.
11949 * It finds the action to be performed in p[2], previously filled by function
11950 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
11951 * error, though this can be revisited when this code is finally exploited.
11952 *
11953 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
11954 * query string and 3 to replace uri.
11955 *
11956 * In query string case, the mark question '?' must be set at the start of the
11957 * string by the caller, event if the replacement query string is empty.
11958 */
http_replace_req_line(int action,const char * replace,int len,struct proxy * px,struct stream * s)11959 int http_replace_req_line(int action, const char *replace, int len,
11960 struct proxy *px, struct stream *s)
11961 {
11962 struct http_txn *txn = s->txn;
11963 char *cur_ptr, *cur_end;
11964 int offset = 0;
11965 int delta;
11966
11967 switch (action) {
11968 case 0: // method
11969 cur_ptr = s->req.buf->p;
11970 cur_end = cur_ptr + txn->req.sl.rq.m_l;
11971
11972 /* adjust req line offsets and lengths */
11973 delta = len - offset - (cur_end - cur_ptr);
11974 txn->req.sl.rq.m_l += delta;
11975 txn->req.sl.rq.u += delta;
11976 txn->req.sl.rq.v += delta;
11977 break;
11978
11979 case 1: // path
11980 cur_ptr = http_get_path(txn);
11981 if (!cur_ptr)
11982 cur_ptr = s->req.buf->p + txn->req.sl.rq.u;
11983
11984 cur_end = cur_ptr;
11985 while (cur_end < s->req.buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l && *cur_end != '?')
11986 cur_end++;
11987
11988 /* adjust req line offsets and lengths */
11989 delta = len - offset - (cur_end - cur_ptr);
11990 txn->req.sl.rq.u_l += delta;
11991 txn->req.sl.rq.v += delta;
11992 break;
11993
11994 case 2: // query
11995 offset = 1;
11996 cur_ptr = s->req.buf->p + txn->req.sl.rq.u;
11997 cur_end = cur_ptr + txn->req.sl.rq.u_l;
11998 while (cur_ptr < cur_end && *cur_ptr != '?')
11999 cur_ptr++;
12000
12001 /* skip the question mark or indicate that we must insert it
12002 * (but only if the format string is not empty then).
12003 */
12004 if (cur_ptr < cur_end)
12005 cur_ptr++;
12006 else if (len > 1)
12007 offset = 0;
12008
12009 /* adjust req line offsets and lengths */
12010 delta = len - offset - (cur_end - cur_ptr);
12011 txn->req.sl.rq.u_l += delta;
12012 txn->req.sl.rq.v += delta;
12013 break;
12014
12015 case 3: // uri
12016 cur_ptr = s->req.buf->p + txn->req.sl.rq.u;
12017 cur_end = cur_ptr + txn->req.sl.rq.u_l;
12018
12019 /* adjust req line offsets and lengths */
12020 delta = len - offset - (cur_end - cur_ptr);
12021 txn->req.sl.rq.u_l += delta;
12022 txn->req.sl.rq.v += delta;
12023 break;
12024
12025 default:
12026 return -1;
12027 }
12028
12029 /* commit changes and adjust end of message */
12030 delta = buffer_replace2(s->req.buf, cur_ptr, cur_end, replace + offset, len - offset);
12031 txn->req.sl.rq.l += delta;
12032 txn->hdr_idx.v[0].len += delta;
12033 http_msg_move_end(&txn->req, delta);
12034 return 0;
12035 }
12036
12037 /* This function replace the HTTP status code and the associated message. The
12038 * variable <status> contains the new status code. This function never fails.
12039 */
http_set_status(unsigned int status,const char * reason,struct stream * s)12040 void http_set_status(unsigned int status, const char *reason, struct stream *s)
12041 {
12042 struct http_txn *txn = s->txn;
12043 char *cur_ptr, *cur_end;
12044 int delta;
12045 char *res;
12046 int c_l;
12047 const char *msg = reason;
12048 int msg_len;
12049
12050 chunk_reset(&trash);
12051
12052 res = ultoa_o(status, trash.str, trash.size);
12053 c_l = res - trash.str;
12054
12055 trash.str[c_l] = ' ';
12056 trash.len = c_l + 1;
12057
12058 /* Do we have a custom reason format string? */
12059 if (msg == NULL)
12060 msg = get_reason(status);
12061 msg_len = strlen(msg);
12062 strncpy(&trash.str[trash.len], msg, trash.size - trash.len);
12063 trash.len += msg_len;
12064
12065 cur_ptr = s->res.buf->p + txn->rsp.sl.st.c;
12066 cur_end = s->res.buf->p + txn->rsp.sl.st.r + txn->rsp.sl.st.r_l;
12067
12068 /* commit changes and adjust message */
12069 delta = buffer_replace2(s->res.buf, cur_ptr, cur_end, trash.str, trash.len);
12070
12071 /* adjust res line offsets and lengths */
12072 txn->rsp.sl.st.r += c_l - txn->rsp.sl.st.c_l;
12073 txn->rsp.sl.st.c_l = c_l;
12074 txn->rsp.sl.st.r_l = msg_len;
12075
12076 delta = trash.len - (cur_end - cur_ptr);
12077 txn->rsp.sl.st.l += delta;
12078 txn->hdr_idx.v[0].len += delta;
12079 http_msg_move_end(&txn->rsp, delta);
12080 }
12081
12082 /* This function executes one of the set-{method,path,query,uri} actions. It
12083 * builds a string in the trash from the specified format string. It finds
12084 * the action to be performed in <http.action>, previously filled by function
12085 * parse_set_req_line(). The replacement action is excuted by the function
12086 * http_action_set_req_line(). It always returns ACT_RET_CONT. If an error
12087 * occurs the action is canceled, but the rule processing continue.
12088 */
http_action_set_req_line(struct act_rule * rule,struct proxy * px,struct session * sess,struct stream * s,int flags)12089 enum act_return http_action_set_req_line(struct act_rule *rule, struct proxy *px,
12090 struct session *sess, struct stream *s, int flags)
12091 {
12092 struct chunk *replace;
12093 enum act_return ret = ACT_RET_ERR;
12094
12095 replace = alloc_trash_chunk();
12096 if (!replace)
12097 goto leave;
12098
12099 /* If we have to create a query string, prepare a '?'. */
12100 if (rule->arg.http.action == 2)
12101 replace->str[replace->len++] = '?';
12102 replace->len += build_logline(s, replace->str + replace->len, replace->size - replace->len,
12103 &rule->arg.http.logfmt);
12104
12105 http_replace_req_line(rule->arg.http.action, replace->str, replace->len, px, s);
12106
12107 ret = ACT_RET_CONT;
12108
12109 leave:
12110 free_trash_chunk(replace);
12111 return ret;
12112 }
12113
12114 /* This function is just a compliant action wrapper for "set-status". */
action_http_set_status(struct act_rule * rule,struct proxy * px,struct session * sess,struct stream * s,int flags)12115 enum act_return action_http_set_status(struct act_rule *rule, struct proxy *px,
12116 struct session *sess, struct stream *s, int flags)
12117 {
12118 http_set_status(rule->arg.status.code, rule->arg.status.reason, s);
12119 return ACT_RET_CONT;
12120 }
12121
12122 /* parse an http-request action among :
12123 * set-method
12124 * set-path
12125 * set-query
12126 * set-uri
12127 *
12128 * All of them accept a single argument of type string representing a log-format.
12129 * The resulting rule makes use of arg->act.p[0..1] to store the log-format list
12130 * head, and p[2] to store the action as an int (0=method, 1=path, 2=query, 3=uri).
12131 * It returns ACT_RET_PRS_OK on success, ACT_RET_PRS_ERR on error.
12132 */
parse_set_req_line(const char ** args,int * orig_arg,struct proxy * px,struct act_rule * rule,char ** err)12133 enum act_parse_ret parse_set_req_line(const char **args, int *orig_arg, struct proxy *px,
12134 struct act_rule *rule, char **err)
12135 {
12136 int cur_arg = *orig_arg;
12137
12138 rule->action = ACT_CUSTOM;
12139
12140 switch (args[0][4]) {
12141 case 'm' :
12142 rule->arg.http.action = 0;
12143 rule->action_ptr = http_action_set_req_line;
12144 break;
12145 case 'p' :
12146 rule->arg.http.action = 1;
12147 rule->action_ptr = http_action_set_req_line;
12148 break;
12149 case 'q' :
12150 rule->arg.http.action = 2;
12151 rule->action_ptr = http_action_set_req_line;
12152 break;
12153 case 'u' :
12154 rule->arg.http.action = 3;
12155 rule->action_ptr = http_action_set_req_line;
12156 break;
12157 default:
12158 memprintf(err, "internal error: unhandled action '%s'", args[0]);
12159 return ACT_RET_PRS_ERR;
12160 }
12161
12162 if (!*args[cur_arg] ||
12163 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
12164 memprintf(err, "expects exactly 1 argument <format>");
12165 return ACT_RET_PRS_ERR;
12166 }
12167
12168 LIST_INIT(&rule->arg.http.logfmt);
12169 px->conf.args.ctx = ARGC_HRQ;
12170 if (!parse_logformat_string(args[cur_arg], px, &rule->arg.http.logfmt, LOG_OPT_HTTP,
12171 (px->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, err)) {
12172 return ACT_RET_PRS_ERR;
12173 }
12174
12175 (*orig_arg)++;
12176 return ACT_RET_PRS_OK;
12177 }
12178
12179 /* parse set-status action:
12180 * This action accepts a single argument of type int representing
12181 * an http status code. It returns ACT_RET_PRS_OK on success,
12182 * ACT_RET_PRS_ERR on error.
12183 */
parse_http_set_status(const char ** args,int * orig_arg,struct proxy * px,struct act_rule * rule,char ** err)12184 enum act_parse_ret parse_http_set_status(const char **args, int *orig_arg, struct proxy *px,
12185 struct act_rule *rule, char **err)
12186 {
12187 char *error;
12188
12189 rule->action = ACT_CUSTOM;
12190 rule->action_ptr = action_http_set_status;
12191
12192 /* Check if an argument is available */
12193 if (!*args[*orig_arg]) {
12194 memprintf(err, "expects 1 argument: <status>; or 3 arguments: <status> reason <fmt>");
12195 return ACT_RET_PRS_ERR;
12196 }
12197
12198 /* convert status code as integer */
12199 rule->arg.status.code = strtol(args[*orig_arg], &error, 10);
12200 if (*error != '\0' || rule->arg.status.code < 100 || rule->arg.status.code > 999) {
12201 memprintf(err, "expects an integer status code between 100 and 999");
12202 return ACT_RET_PRS_ERR;
12203 }
12204
12205 (*orig_arg)++;
12206
12207 /* set custom reason string */
12208 rule->arg.status.reason = NULL; // If null, we use the default reason for the status code.
12209 if (*args[*orig_arg] && strcmp(args[*orig_arg], "reason") == 0 &&
12210 (*args[*orig_arg + 1] && strcmp(args[*orig_arg + 1], "if") != 0 && strcmp(args[*orig_arg + 1], "unless") != 0)) {
12211 (*orig_arg)++;
12212 rule->arg.status.reason = strdup(args[*orig_arg]);
12213 (*orig_arg)++;
12214 }
12215
12216 return ACT_RET_PRS_OK;
12217 }
12218
12219 /* This function executes the "reject" HTTP action. It clears the request and
12220 * response buffer without sending any response. It can be useful as an HTTP
12221 * alternative to the silent-drop action to defend against DoS attacks, and may
12222 * also be used with HTTP/2 to close a connection instead of just a stream.
12223 * The txn status is unchanged, indicating no response was sent. The termination
12224 * flags will indicate "PR". It always returns ACT_RET_STOP.
12225 */
http_action_reject(struct act_rule * rule,struct proxy * px,struct session * sess,struct stream * s,int flags)12226 enum act_return http_action_reject(struct act_rule *rule, struct proxy *px,
12227 struct session *sess, struct stream *s, int flags)
12228 {
12229 si_must_kill_conn(chn_prod(&s->req));
12230 channel_abort(&s->req);
12231 channel_abort(&s->res);
12232 s->req.analysers &= AN_REQ_FLT_END;
12233 s->res.analysers &= AN_RES_FLT_END;
12234
12235 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
12236 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
12237 if (sess->listener && sess->listener->counters)
12238 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
12239
12240 if (!(s->flags & SF_ERR_MASK))
12241 s->flags |= SF_ERR_PRXCOND;
12242 if (!(s->flags & SF_FINST_MASK))
12243 s->flags |= SF_FINST_R;
12244
12245 return ACT_RET_STOP;
12246 }
12247
12248 /* parse the "reject" action:
12249 * This action takes no argument and returns ACT_RET_PRS_OK on success,
12250 * ACT_RET_PRS_ERR on error.
12251 */
parse_http_action_reject(const char ** args,int * orig_arg,struct proxy * px,struct act_rule * rule,char ** err)12252 enum act_parse_ret parse_http_action_reject(const char **args, int *orig_arg, struct proxy *px,
12253 struct act_rule *rule, char **err)
12254 {
12255 rule->action = ACT_CUSTOM;
12256 rule->action_ptr = http_action_reject;
12257 return ACT_RET_PRS_OK;
12258 }
12259
12260 /* This function executes the "capture" action. It executes a fetch expression,
12261 * turns the result into a string and puts it in a capture slot. It always
12262 * returns 1. If an error occurs the action is cancelled, but the rule
12263 * processing continues.
12264 */
http_action_req_capture(struct act_rule * rule,struct proxy * px,struct session * sess,struct stream * s,int flags)12265 enum act_return http_action_req_capture(struct act_rule *rule, struct proxy *px,
12266 struct session *sess, struct stream *s, int flags)
12267 {
12268 struct sample *key;
12269 struct cap_hdr *h = rule->arg.cap.hdr;
12270 char **cap = s->req_cap;
12271 int len;
12272
12273 key = sample_fetch_as_type(s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.cap.expr, SMP_T_STR);
12274 if (!key)
12275 return ACT_RET_CONT;
12276
12277 if (cap[h->index] == NULL)
12278 cap[h->index] = pool_alloc(h->pool);
12279
12280 if (cap[h->index] == NULL) /* no more capture memory */
12281 return ACT_RET_CONT;
12282
12283 len = key->data.u.str.len;
12284 if (len > h->len)
12285 len = h->len;
12286
12287 memcpy(cap[h->index], key->data.u.str.str, len);
12288 cap[h->index][len] = 0;
12289 return ACT_RET_CONT;
12290 }
12291
12292 /* This function executes the "capture" action and store the result in a
12293 * capture slot if exists. It executes a fetch expression, turns the result
12294 * into a string and puts it in a capture slot. It always returns 1. If an
12295 * error occurs the action is cancelled, but the rule processing continues.
12296 */
http_action_req_capture_by_id(struct act_rule * rule,struct proxy * px,struct session * sess,struct stream * s,int flags)12297 enum act_return http_action_req_capture_by_id(struct act_rule *rule, struct proxy *px,
12298 struct session *sess, struct stream *s, int flags)
12299 {
12300 struct sample *key;
12301 struct cap_hdr *h;
12302 char **cap = s->req_cap;
12303 struct proxy *fe = strm_fe(s);
12304 int len;
12305 int i;
12306
12307 /* Look for the original configuration. */
12308 for (h = fe->req_cap, i = fe->nb_req_cap - 1;
12309 h != NULL && i != rule->arg.capid.idx ;
12310 i--, h = h->next);
12311 if (!h)
12312 return ACT_RET_CONT;
12313
12314 key = sample_fetch_as_type(s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.capid.expr, SMP_T_STR);
12315 if (!key)
12316 return ACT_RET_CONT;
12317
12318 if (cap[h->index] == NULL)
12319 cap[h->index] = pool_alloc(h->pool);
12320
12321 if (cap[h->index] == NULL) /* no more capture memory */
12322 return ACT_RET_CONT;
12323
12324 len = key->data.u.str.len;
12325 if (len > h->len)
12326 len = h->len;
12327
12328 memcpy(cap[h->index], key->data.u.str.str, len);
12329 cap[h->index][len] = 0;
12330 return ACT_RET_CONT;
12331 }
12332
12333 /* Check an "http-request capture" action.
12334 *
12335 * The function returns 1 in success case, otherwise, it returns 0 and err is
12336 * filled.
12337 */
check_http_req_capture(struct act_rule * rule,struct proxy * px,char ** err)12338 int check_http_req_capture(struct act_rule *rule, struct proxy *px, char **err)
12339 {
12340 if (rule->action_ptr != http_action_req_capture_by_id)
12341 return 1;
12342
12343 /* capture slots can only be declared in frontends, so we can't check their
12344 * existence in backends at configuration parsing step
12345 */
12346 if (px->cap & PR_CAP_FE && rule->arg.capid.idx >= px->nb_req_cap) {
12347 memprintf(err, "unable to find capture id '%d' referenced by http-request capture rule",
12348 rule->arg.capid.idx);
12349 return 0;
12350 }
12351
12352 return 1;
12353 }
12354
12355 /* parse an "http-request capture" action. It takes a single argument which is
12356 * a sample fetch expression. It stores the expression into arg->act.p[0] and
12357 * the allocated hdr_cap struct or the preallocated "id" into arg->act.p[1].
12358 * It returns ACT_RET_PRS_OK on success, ACT_RET_PRS_ERR on error.
12359 */
parse_http_req_capture(const char ** args,int * orig_arg,struct proxy * px,struct act_rule * rule,char ** err)12360 enum act_parse_ret parse_http_req_capture(const char **args, int *orig_arg, struct proxy *px,
12361 struct act_rule *rule, char **err)
12362 {
12363 struct sample_expr *expr;
12364 struct cap_hdr *hdr;
12365 int cur_arg;
12366 int len = 0;
12367
12368 for (cur_arg = *orig_arg; cur_arg < *orig_arg + 3 && *args[cur_arg]; cur_arg++)
12369 if (strcmp(args[cur_arg], "if") == 0 ||
12370 strcmp(args[cur_arg], "unless") == 0)
12371 break;
12372
12373 if (cur_arg < *orig_arg + 3) {
12374 memprintf(err, "expects <expression> [ 'len' <length> | id <idx> ]");
12375 return ACT_RET_PRS_ERR;
12376 }
12377
12378 cur_arg = *orig_arg;
12379 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args);
12380 if (!expr)
12381 return ACT_RET_PRS_ERR;
12382
12383 if (!(expr->fetch->val & SMP_VAL_FE_HRQ_HDR)) {
12384 memprintf(err,
12385 "fetch method '%s' extracts information from '%s', none of which is available here",
12386 args[cur_arg-1], sample_src_names(expr->fetch->use));
12387 free(expr);
12388 return ACT_RET_PRS_ERR;
12389 }
12390
12391 if (!args[cur_arg] || !*args[cur_arg]) {
12392 memprintf(err, "expects 'len or 'id'");
12393 free(expr);
12394 return ACT_RET_PRS_ERR;
12395 }
12396
12397 if (strcmp(args[cur_arg], "len") == 0) {
12398 cur_arg++;
12399
12400 if (!(px->cap & PR_CAP_FE)) {
12401 memprintf(err, "proxy '%s' has no frontend capability", px->id);
12402 return ACT_RET_PRS_ERR;
12403 }
12404
12405 px->conf.args.ctx = ARGC_CAP;
12406
12407 if (!args[cur_arg]) {
12408 memprintf(err, "missing length value");
12409 free(expr);
12410 return ACT_RET_PRS_ERR;
12411 }
12412 /* we copy the table name for now, it will be resolved later */
12413 len = atoi(args[cur_arg]);
12414 if (len <= 0) {
12415 memprintf(err, "length must be > 0");
12416 free(expr);
12417 return ACT_RET_PRS_ERR;
12418 }
12419 cur_arg++;
12420
12421 if (!len) {
12422 memprintf(err, "a positive 'len' argument is mandatory");
12423 free(expr);
12424 return ACT_RET_PRS_ERR;
12425 }
12426
12427 hdr = calloc(1, sizeof(*hdr));
12428 hdr->next = px->req_cap;
12429 hdr->name = NULL; /* not a header capture */
12430 hdr->namelen = 0;
12431 hdr->len = len;
12432 hdr->pool = create_pool("caphdr", hdr->len + 1, MEM_F_SHARED);
12433 hdr->index = px->nb_req_cap++;
12434
12435 px->req_cap = hdr;
12436 px->to_log |= LW_REQHDR;
12437
12438 rule->action = ACT_CUSTOM;
12439 rule->action_ptr = http_action_req_capture;
12440 rule->arg.cap.expr = expr;
12441 rule->arg.cap.hdr = hdr;
12442 }
12443
12444 else if (strcmp(args[cur_arg], "id") == 0) {
12445 int id;
12446 char *error;
12447
12448 cur_arg++;
12449
12450 if (!args[cur_arg]) {
12451 memprintf(err, "missing id value");
12452 free(expr);
12453 return ACT_RET_PRS_ERR;
12454 }
12455
12456 id = strtol(args[cur_arg], &error, 10);
12457 if (*error != '\0') {
12458 memprintf(err, "cannot parse id '%s'", args[cur_arg]);
12459 free(expr);
12460 return ACT_RET_PRS_ERR;
12461 }
12462 cur_arg++;
12463
12464 px->conf.args.ctx = ARGC_CAP;
12465
12466 rule->action = ACT_CUSTOM;
12467 rule->action_ptr = http_action_req_capture_by_id;
12468 rule->check_ptr = check_http_req_capture;
12469 rule->arg.capid.expr = expr;
12470 rule->arg.capid.idx = id;
12471 }
12472
12473 else {
12474 memprintf(err, "expects 'len' or 'id', found '%s'", args[cur_arg]);
12475 free(expr);
12476 return ACT_RET_PRS_ERR;
12477 }
12478
12479 *orig_arg = cur_arg;
12480 return ACT_RET_PRS_OK;
12481 }
12482
12483 /* This function executes the "capture" action and store the result in a
12484 * capture slot if exists. It executes a fetch expression, turns the result
12485 * into a string and puts it in a capture slot. It always returns 1. If an
12486 * error occurs the action is cancelled, but the rule processing continues.
12487 */
http_action_res_capture_by_id(struct act_rule * rule,struct proxy * px,struct session * sess,struct stream * s,int flags)12488 enum act_return http_action_res_capture_by_id(struct act_rule *rule, struct proxy *px,
12489 struct session *sess, struct stream *s, int flags)
12490 {
12491 struct sample *key;
12492 struct cap_hdr *h;
12493 char **cap = s->res_cap;
12494 struct proxy *fe = strm_fe(s);
12495 int len;
12496 int i;
12497
12498 /* Look for the original configuration. */
12499 for (h = fe->rsp_cap, i = fe->nb_rsp_cap - 1;
12500 h != NULL && i != rule->arg.capid.idx ;
12501 i--, h = h->next);
12502 if (!h)
12503 return ACT_RET_CONT;
12504
12505 key = sample_fetch_as_type(s->be, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL, rule->arg.capid.expr, SMP_T_STR);
12506 if (!key)
12507 return ACT_RET_CONT;
12508
12509 if (cap[h->index] == NULL)
12510 cap[h->index] = pool_alloc(h->pool);
12511
12512 if (cap[h->index] == NULL) /* no more capture memory */
12513 return ACT_RET_CONT;
12514
12515 len = key->data.u.str.len;
12516 if (len > h->len)
12517 len = h->len;
12518
12519 memcpy(cap[h->index], key->data.u.str.str, len);
12520 cap[h->index][len] = 0;
12521 return ACT_RET_CONT;
12522 }
12523
12524 /* Check an "http-response capture" action.
12525 *
12526 * The function returns 1 in success case, otherwise, it returns 0 and err is
12527 * filled.
12528 */
check_http_res_capture(struct act_rule * rule,struct proxy * px,char ** err)12529 int check_http_res_capture(struct act_rule *rule, struct proxy *px, char **err)
12530 {
12531 if (rule->action_ptr != http_action_res_capture_by_id)
12532 return 1;
12533
12534 /* capture slots can only be declared in frontends, so we can't check their
12535 * existence in backends at configuration parsing step
12536 */
12537 if (px->cap & PR_CAP_FE && rule->arg.capid.idx >= px->nb_rsp_cap) {
12538 memprintf(err, "unable to find capture id '%d' referenced by http-response capture rule",
12539 rule->arg.capid.idx);
12540 return 0;
12541 }
12542
12543 return 1;
12544 }
12545
12546 /* parse an "http-response capture" action. It takes a single argument which is
12547 * a sample fetch expression. It stores the expression into arg->act.p[0] and
12548 * the allocated hdr_cap struct od the preallocated id into arg->act.p[1].
12549 * It returns ACT_RET_PRS_OK on success, ACT_RET_PRS_ERR on error.
12550 */
parse_http_res_capture(const char ** args,int * orig_arg,struct proxy * px,struct act_rule * rule,char ** err)12551 enum act_parse_ret parse_http_res_capture(const char **args, int *orig_arg, struct proxy *px,
12552 struct act_rule *rule, char **err)
12553 {
12554 struct sample_expr *expr;
12555 int cur_arg;
12556 int id;
12557 char *error;
12558
12559 for (cur_arg = *orig_arg; cur_arg < *orig_arg + 3 && *args[cur_arg]; cur_arg++)
12560 if (strcmp(args[cur_arg], "if") == 0 ||
12561 strcmp(args[cur_arg], "unless") == 0)
12562 break;
12563
12564 if (cur_arg < *orig_arg + 3) {
12565 memprintf(err, "expects <expression> id <idx>");
12566 return ACT_RET_PRS_ERR;
12567 }
12568
12569 cur_arg = *orig_arg;
12570 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args);
12571 if (!expr)
12572 return ACT_RET_PRS_ERR;
12573
12574 if (!(expr->fetch->val & SMP_VAL_FE_HRS_HDR)) {
12575 memprintf(err,
12576 "fetch method '%s' extracts information from '%s', none of which is available here",
12577 args[cur_arg-1], sample_src_names(expr->fetch->use));
12578 free(expr);
12579 return ACT_RET_PRS_ERR;
12580 }
12581
12582 if (!args[cur_arg] || !*args[cur_arg]) {
12583 memprintf(err, "expects 'id'");
12584 free(expr);
12585 return ACT_RET_PRS_ERR;
12586 }
12587
12588 if (strcmp(args[cur_arg], "id") != 0) {
12589 memprintf(err, "expects 'id', found '%s'", args[cur_arg]);
12590 free(expr);
12591 return ACT_RET_PRS_ERR;
12592 }
12593
12594 cur_arg++;
12595
12596 if (!args[cur_arg]) {
12597 memprintf(err, "missing id value");
12598 free(expr);
12599 return ACT_RET_PRS_ERR;
12600 }
12601
12602 id = strtol(args[cur_arg], &error, 10);
12603 if (*error != '\0') {
12604 memprintf(err, "cannot parse id '%s'", args[cur_arg]);
12605 free(expr);
12606 return ACT_RET_PRS_ERR;
12607 }
12608 cur_arg++;
12609
12610 px->conf.args.ctx = ARGC_CAP;
12611
12612 rule->action = ACT_CUSTOM;
12613 rule->action_ptr = http_action_res_capture_by_id;
12614 rule->check_ptr = check_http_res_capture;
12615 rule->arg.capid.expr = expr;
12616 rule->arg.capid.idx = id;
12617
12618 *orig_arg = cur_arg;
12619 return ACT_RET_PRS_OK;
12620 }
12621
12622 /*
12623 * Return the struct http_req_action_kw associated to a keyword.
12624 */
action_http_req_custom(const char * kw)12625 struct action_kw *action_http_req_custom(const char *kw)
12626 {
12627 return action_lookup(&http_req_keywords.list, kw);
12628 }
12629
12630 /*
12631 * Return the struct http_res_action_kw associated to a keyword.
12632 */
action_http_res_custom(const char * kw)12633 struct action_kw *action_http_res_custom(const char *kw)
12634 {
12635 return action_lookup(&http_res_keywords.list, kw);
12636 }
12637
12638
12639 /* "show errors" handler for the CLI. Returns 0 if wants to continue, 1 to stop
12640 * now.
12641 */
cli_parse_show_errors(char ** args,struct appctx * appctx,void * private)12642 static int cli_parse_show_errors(char **args, struct appctx *appctx, void *private)
12643 {
12644 if (!cli_has_level(appctx, ACCESS_LVL_OPER))
12645 return 1;
12646
12647 if (*args[2]) {
12648 struct proxy *px;
12649
12650 px = proxy_find_by_name(args[2], 0, 0);
12651 if (px)
12652 appctx->ctx.errors.iid = px->uuid;
12653 else
12654 appctx->ctx.errors.iid = atoi(args[2]);
12655
12656 if (!appctx->ctx.errors.iid) {
12657 appctx->ctx.cli.severity = LOG_ERR;
12658 appctx->ctx.cli.msg = "No such proxy.\n";
12659 appctx->st0 = CLI_ST_PRINT;
12660 return 1;
12661 }
12662 }
12663 else
12664 appctx->ctx.errors.iid = -1; // dump all proxies
12665
12666 appctx->ctx.errors.flag = 0;
12667 if (strcmp(args[3], "request") == 0)
12668 appctx->ctx.errors.flag |= 4; // ignore response
12669 else if (strcmp(args[3], "response") == 0)
12670 appctx->ctx.errors.flag |= 2; // ignore request
12671 appctx->ctx.errors.px = NULL;
12672 return 0;
12673 }
12674
12675 /* This function dumps all captured errors onto the stream interface's
12676 * read buffer. It returns 0 if the output buffer is full and it needs
12677 * to be called again, otherwise non-zero.
12678 */
cli_io_handler_show_errors(struct appctx * appctx)12679 static int cli_io_handler_show_errors(struct appctx *appctx)
12680 {
12681 struct stream_interface *si = appctx->owner;
12682 extern const char *monthname[12];
12683
12684 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
12685 return 1;
12686
12687 chunk_reset(&trash);
12688
12689 if (!appctx->ctx.errors.px) {
12690 /* the function had not been called yet, let's prepare the
12691 * buffer for a response.
12692 */
12693 struct tm tm;
12694
12695 get_localtime(date.tv_sec, &tm);
12696 chunk_appendf(&trash, "Total events captured on [%02d/%s/%04d:%02d:%02d:%02d.%03d] : %u\n",
12697 tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
12698 tm.tm_hour, tm.tm_min, tm.tm_sec, (int)(date.tv_usec/1000),
12699 error_snapshot_id);
12700
12701 if (ci_putchk(si_ic(si), &trash) == -1)
12702 goto cant_send;
12703
12704 appctx->ctx.errors.px = proxies_list;
12705 appctx->ctx.errors.bol = 0;
12706 appctx->ctx.errors.ptr = -1;
12707 }
12708
12709 /* we have two inner loops here, one for the proxy, the other one for
12710 * the buffer.
12711 */
12712 while (appctx->ctx.errors.px) {
12713 struct error_snapshot *es;
12714
12715 HA_SPIN_LOCK(PROXY_LOCK, &appctx->ctx.errors.px->lock);
12716
12717 if ((appctx->ctx.errors.flag & 1) == 0) {
12718 es = &appctx->ctx.errors.px->invalid_req;
12719 if (appctx->ctx.errors.flag & 2) // skip req
12720 goto next;
12721 }
12722 else {
12723 es = &appctx->ctx.errors.px->invalid_rep;
12724 if (appctx->ctx.errors.flag & 4) // skip resp
12725 goto next;
12726 }
12727
12728 if (!es->when.tv_sec)
12729 goto next;
12730
12731 if (appctx->ctx.errors.iid >= 0 &&
12732 appctx->ctx.errors.px->uuid != appctx->ctx.errors.iid &&
12733 es->oe->uuid != appctx->ctx.errors.iid)
12734 goto next;
12735
12736 if (appctx->ctx.errors.ptr < 0) {
12737 /* just print headers now */
12738
12739 char pn[INET6_ADDRSTRLEN];
12740 struct tm tm;
12741 int port;
12742
12743 get_localtime(es->when.tv_sec, &tm);
12744 chunk_appendf(&trash, " \n[%02d/%s/%04d:%02d:%02d:%02d.%03d]",
12745 tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
12746 tm.tm_hour, tm.tm_min, tm.tm_sec, (int)(es->when.tv_usec/1000));
12747
12748 switch (addr_to_str(&es->src, pn, sizeof(pn))) {
12749 case AF_INET:
12750 case AF_INET6:
12751 port = get_host_port(&es->src);
12752 break;
12753 default:
12754 port = 0;
12755 }
12756
12757 switch (appctx->ctx.errors.flag & 1) {
12758 case 0:
12759 chunk_appendf(&trash,
12760 " frontend %s (#%d): invalid request\n"
12761 " backend %s (#%d)",
12762 appctx->ctx.errors.px->id, appctx->ctx.errors.px->uuid,
12763 (es->oe->cap & PR_CAP_BE) ? es->oe->id : "<NONE>",
12764 (es->oe->cap & PR_CAP_BE) ? es->oe->uuid : -1);
12765 break;
12766 case 1:
12767 chunk_appendf(&trash,
12768 " backend %s (#%d): invalid response\n"
12769 " frontend %s (#%d)",
12770 appctx->ctx.errors.px->id, appctx->ctx.errors.px->uuid,
12771 es->oe->id, es->oe->uuid);
12772 break;
12773 }
12774
12775 chunk_appendf(&trash,
12776 ", server %s (#%d), event #%u\n"
12777 " src %s:%d, session #%d, session flags 0x%08x\n"
12778 " HTTP msg state %s(%d), msg flags 0x%08x, tx flags 0x%08x\n"
12779 " HTTP chunk len %lld bytes, HTTP body len %lld bytes\n"
12780 " buffer flags 0x%08x, out %d bytes, total %lld bytes\n"
12781 " pending %d bytes, wrapping at %d, error at position %d:\n \n",
12782 es->srv ? es->srv->id : "<NONE>", es->srv ? es->srv->puid : -1,
12783 es->ev_id,
12784 pn, port, es->sid, es->s_flags,
12785 h1_msg_state_str(es->state), es->state, es->m_flags, es->t_flags,
12786 es->m_clen, es->m_blen,
12787 es->b_flags, es->b_out, es->b_tot,
12788 es->len, es->b_wrap, es->pos);
12789
12790 if (ci_putchk(si_ic(si), &trash) == -1)
12791 goto cant_send_unlock;
12792
12793 appctx->ctx.errors.ptr = 0;
12794 appctx->ctx.errors.sid = es->sid;
12795 }
12796
12797 if (appctx->ctx.errors.sid != es->sid) {
12798 /* the snapshot changed while we were dumping it */
12799 chunk_appendf(&trash,
12800 " WARNING! update detected on this snapshot, dump interrupted. Please re-check!\n");
12801 if (ci_putchk(si_ic(si), &trash) == -1)
12802 goto cant_send_unlock;
12803
12804 goto next;
12805 }
12806
12807 /* OK, ptr >= 0, so we have to dump the current line */
12808 while (es->buf && appctx->ctx.errors.ptr < es->len && appctx->ctx.errors.ptr < global.tune.bufsize) {
12809 int newptr;
12810 int newline;
12811
12812 newline = appctx->ctx.errors.bol;
12813 newptr = dump_text_line(&trash, es->buf, global.tune.bufsize, es->len, &newline, appctx->ctx.errors.ptr);
12814 if (newptr == appctx->ctx.errors.ptr)
12815 goto cant_send_unlock;
12816
12817 if (ci_putchk(si_ic(si), &trash) == -1)
12818 goto cant_send_unlock;
12819
12820 appctx->ctx.errors.ptr = newptr;
12821 appctx->ctx.errors.bol = newline;
12822 };
12823 next:
12824 HA_SPIN_UNLOCK(PROXY_LOCK, &appctx->ctx.errors.px->lock);
12825 appctx->ctx.errors.bol = 0;
12826 appctx->ctx.errors.ptr = -1;
12827 appctx->ctx.errors.flag ^= 1;
12828 if (!(appctx->ctx.errors.flag & 1))
12829 appctx->ctx.errors.px = appctx->ctx.errors.px->next;
12830 }
12831
12832 /* dump complete */
12833 return 1;
12834
12835 cant_send_unlock:
12836 HA_SPIN_UNLOCK(PROXY_LOCK, &appctx->ctx.errors.px->lock);
12837 cant_send:
12838 si_applet_cant_put(si);
12839 return 0;
12840 }
12841
12842 /* register cli keywords */
12843 static struct cli_kw_list cli_kws = {{ },{
12844 { { "show", "errors", NULL },
12845 "show errors : report last request and response errors for each proxy",
12846 cli_parse_show_errors, cli_io_handler_show_errors, NULL,
12847 },
12848 {{},}
12849 }};
12850
12851 /************************************************************************/
12852 /* All supported ACL keywords must be declared here. */
12853 /************************************************************************/
12854
12855 /* Note: must not be declared <const> as its list will be overwritten.
12856 * Please take care of keeping this list alphabetically sorted.
12857 */
12858 static struct acl_kw_list acl_kws = {ILH, {
12859 { "base", "base", PAT_MATCH_STR },
12860 { "base_beg", "base", PAT_MATCH_BEG },
12861 { "base_dir", "base", PAT_MATCH_DIR },
12862 { "base_dom", "base", PAT_MATCH_DOM },
12863 { "base_end", "base", PAT_MATCH_END },
12864 { "base_len", "base", PAT_MATCH_LEN },
12865 { "base_reg", "base", PAT_MATCH_REG },
12866 { "base_sub", "base", PAT_MATCH_SUB },
12867
12868 { "cook", "req.cook", PAT_MATCH_STR },
12869 { "cook_beg", "req.cook", PAT_MATCH_BEG },
12870 { "cook_dir", "req.cook", PAT_MATCH_DIR },
12871 { "cook_dom", "req.cook", PAT_MATCH_DOM },
12872 { "cook_end", "req.cook", PAT_MATCH_END },
12873 { "cook_len", "req.cook", PAT_MATCH_LEN },
12874 { "cook_reg", "req.cook", PAT_MATCH_REG },
12875 { "cook_sub", "req.cook", PAT_MATCH_SUB },
12876
12877 { "hdr", "req.hdr", PAT_MATCH_STR },
12878 { "hdr_beg", "req.hdr", PAT_MATCH_BEG },
12879 { "hdr_dir", "req.hdr", PAT_MATCH_DIR },
12880 { "hdr_dom", "req.hdr", PAT_MATCH_DOM },
12881 { "hdr_end", "req.hdr", PAT_MATCH_END },
12882 { "hdr_len", "req.hdr", PAT_MATCH_LEN },
12883 { "hdr_reg", "req.hdr", PAT_MATCH_REG },
12884 { "hdr_sub", "req.hdr", PAT_MATCH_SUB },
12885
12886 /* these two declarations uses strings with list storage (in place
12887 * of tree storage). The basic match is PAT_MATCH_STR, but the indexation
12888 * and delete functions are relative to the list management. The parse
12889 * and match method are related to the corresponding fetch methods. This
12890 * is very particular ACL declaration mode.
12891 */
12892 { "http_auth_group", NULL, PAT_MATCH_STR, NULL, pat_idx_list_str, pat_del_list_ptr, NULL, pat_match_auth },
12893 { "method", NULL, PAT_MATCH_STR, pat_parse_meth, pat_idx_list_str, pat_del_list_ptr, NULL, pat_match_meth },
12894
12895 { "path", "path", PAT_MATCH_STR },
12896 { "path_beg", "path", PAT_MATCH_BEG },
12897 { "path_dir", "path", PAT_MATCH_DIR },
12898 { "path_dom", "path", PAT_MATCH_DOM },
12899 { "path_end", "path", PAT_MATCH_END },
12900 { "path_len", "path", PAT_MATCH_LEN },
12901 { "path_reg", "path", PAT_MATCH_REG },
12902 { "path_sub", "path", PAT_MATCH_SUB },
12903
12904 { "req_ver", "req.ver", PAT_MATCH_STR },
12905 { "resp_ver", "res.ver", PAT_MATCH_STR },
12906
12907 { "scook", "res.cook", PAT_MATCH_STR },
12908 { "scook_beg", "res.cook", PAT_MATCH_BEG },
12909 { "scook_dir", "res.cook", PAT_MATCH_DIR },
12910 { "scook_dom", "res.cook", PAT_MATCH_DOM },
12911 { "scook_end", "res.cook", PAT_MATCH_END },
12912 { "scook_len", "res.cook", PAT_MATCH_LEN },
12913 { "scook_reg", "res.cook", PAT_MATCH_REG },
12914 { "scook_sub", "res.cook", PAT_MATCH_SUB },
12915
12916 { "shdr", "res.hdr", PAT_MATCH_STR },
12917 { "shdr_beg", "res.hdr", PAT_MATCH_BEG },
12918 { "shdr_dir", "res.hdr", PAT_MATCH_DIR },
12919 { "shdr_dom", "res.hdr", PAT_MATCH_DOM },
12920 { "shdr_end", "res.hdr", PAT_MATCH_END },
12921 { "shdr_len", "res.hdr", PAT_MATCH_LEN },
12922 { "shdr_reg", "res.hdr", PAT_MATCH_REG },
12923 { "shdr_sub", "res.hdr", PAT_MATCH_SUB },
12924
12925 { "url", "url", PAT_MATCH_STR },
12926 { "url_beg", "url", PAT_MATCH_BEG },
12927 { "url_dir", "url", PAT_MATCH_DIR },
12928 { "url_dom", "url", PAT_MATCH_DOM },
12929 { "url_end", "url", PAT_MATCH_END },
12930 { "url_len", "url", PAT_MATCH_LEN },
12931 { "url_reg", "url", PAT_MATCH_REG },
12932 { "url_sub", "url", PAT_MATCH_SUB },
12933
12934 { "urlp", "urlp", PAT_MATCH_STR },
12935 { "urlp_beg", "urlp", PAT_MATCH_BEG },
12936 { "urlp_dir", "urlp", PAT_MATCH_DIR },
12937 { "urlp_dom", "urlp", PAT_MATCH_DOM },
12938 { "urlp_end", "urlp", PAT_MATCH_END },
12939 { "urlp_len", "urlp", PAT_MATCH_LEN },
12940 { "urlp_reg", "urlp", PAT_MATCH_REG },
12941 { "urlp_sub", "urlp", PAT_MATCH_SUB },
12942
12943 { /* END */ },
12944 }};
12945
12946 /************************************************************************/
12947 /* All supported pattern keywords must be declared here. */
12948 /************************************************************************/
12949 /* Note: must not be declared <const> as its list will be overwritten */
12950 static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, {
12951 { "base", smp_fetch_base, 0, NULL, SMP_T_STR, SMP_USE_HRQHV },
12952 { "base32", smp_fetch_base32, 0, NULL, SMP_T_SINT, SMP_USE_HRQHV },
12953 { "base32+src", smp_fetch_base32_src, 0, NULL, SMP_T_BIN, SMP_USE_HRQHV },
12954
12955 /* capture are allocated and are permanent in the stream */
12956 { "capture.req.hdr", smp_fetch_capture_header_req, ARG1(1,SINT), NULL, SMP_T_STR, SMP_USE_HRQHP },
12957
12958 /* retrieve these captures from the HTTP logs */
12959 { "capture.req.method", smp_fetch_capture_req_method, 0, NULL, SMP_T_STR, SMP_USE_HRQHP },
12960 { "capture.req.uri", smp_fetch_capture_req_uri, 0, NULL, SMP_T_STR, SMP_USE_HRQHP },
12961 { "capture.req.ver", smp_fetch_capture_req_ver, 0, NULL, SMP_T_STR, SMP_USE_HRQHP },
12962
12963 { "capture.res.hdr", smp_fetch_capture_header_res, ARG1(1,SINT), NULL, SMP_T_STR, SMP_USE_HRSHP },
12964 { "capture.res.ver", smp_fetch_capture_res_ver, 0, NULL, SMP_T_STR, SMP_USE_HRQHP },
12965
12966 /* cookie is valid in both directions (eg: for "stick ...") but cook*
12967 * are only here to match the ACL's name, are request-only and are used
12968 * for ACL compatibility only.
12969 */
12970 { "cook", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRQHV },
12971 { "cookie", smp_fetch_chn_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRQHV|SMP_USE_HRSHV },
12972 { "cook_cnt", smp_fetch_cookie_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
12973 { "cook_val", smp_fetch_cookie_val, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
12974
12975 /* hdr is valid in both directions (eg: for "stick ...") but hdr_* are
12976 * only here to match the ACL's name, are request-only and are used for
12977 * ACL compatibility only.
12978 */
12979 { "hdr", smp_fetch_chn_hdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRQHV|SMP_USE_HRSHV },
12980 { "hdr_cnt", smp_fetch_hdr_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
12981 { "hdr_ip", smp_fetch_hdr_ip, ARG2(0,STR,SINT), val_hdr, SMP_T_IPV4, SMP_USE_HRQHV },
12982 { "hdr_val", smp_fetch_hdr_val, ARG2(0,STR,SINT), val_hdr, SMP_T_SINT, SMP_USE_HRQHV },
12983
12984 { "http_auth", smp_fetch_http_auth, ARG1(1,USR), NULL, SMP_T_BOOL, SMP_USE_HRQHV },
12985 { "http_auth_group", smp_fetch_http_auth_grp, ARG1(1,USR), NULL, SMP_T_STR, SMP_USE_HRQHV },
12986 { "http_first_req", smp_fetch_http_first_req, 0, NULL, SMP_T_BOOL, SMP_USE_HRQHP },
12987 { "method", smp_fetch_meth, 0, NULL, SMP_T_METH, SMP_USE_HRQHP },
12988 { "path", smp_fetch_path, 0, NULL, SMP_T_STR, SMP_USE_HRQHV },
12989 { "query", smp_fetch_query, 0, NULL, SMP_T_STR, SMP_USE_HRQHV },
12990
12991 /* HTTP protocol on the request path */
12992 { "req.proto_http", smp_fetch_proto_http, 0, NULL, SMP_T_BOOL, SMP_USE_HRQHP },
12993 { "req_proto_http", smp_fetch_proto_http, 0, NULL, SMP_T_BOOL, SMP_USE_HRQHP },
12994
12995 /* HTTP version on the request path */
12996 { "req.ver", smp_fetch_rqver, 0, NULL, SMP_T_STR, SMP_USE_HRQHV },
12997 { "req_ver", smp_fetch_rqver, 0, NULL, SMP_T_STR, SMP_USE_HRQHV },
12998
12999 { "req.body", smp_fetch_body, 0, NULL, SMP_T_BIN, SMP_USE_HRQHV },
13000 { "req.body_len", smp_fetch_body_len, 0, NULL, SMP_T_SINT, SMP_USE_HRQHV },
13001 { "req.body_size", smp_fetch_body_size, 0, NULL, SMP_T_SINT, SMP_USE_HRQHV },
13002 { "req.body_param", smp_fetch_body_param, ARG1(0,STR), NULL, SMP_T_BIN, SMP_USE_HRQHV },
13003
13004 { "req.hdrs", smp_fetch_hdrs, 0, NULL, SMP_T_BIN, SMP_USE_HRQHV },
13005 { "req.hdrs_bin", smp_fetch_hdrs_bin, 0, NULL, SMP_T_BIN, SMP_USE_HRQHV },
13006
13007 /* HTTP version on the response path */
13008 { "res.ver", smp_fetch_stver, 0, NULL, SMP_T_STR, SMP_USE_HRSHV },
13009 { "resp_ver", smp_fetch_stver, 0, NULL, SMP_T_STR, SMP_USE_HRSHV },
13010
13011 /* explicit req.{cook,hdr} are used to force the fetch direction to be request-only */
13012 { "req.cook", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRQHV },
13013 { "req.cook_cnt", smp_fetch_cookie_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
13014 { "req.cook_val", smp_fetch_cookie_val, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
13015
13016 { "req.fhdr", smp_fetch_fhdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRQHV },
13017 { "req.fhdr_cnt", smp_fetch_fhdr_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
13018 { "req.hdr", smp_fetch_hdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRQHV },
13019 { "req.hdr_cnt", smp_fetch_hdr_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
13020 { "req.hdr_ip", smp_fetch_hdr_ip, ARG2(0,STR,SINT), val_hdr, SMP_T_IPV4, SMP_USE_HRQHV },
13021 { "req.hdr_names", smp_fetch_hdr_names, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRQHV },
13022 { "req.hdr_val", smp_fetch_hdr_val, ARG2(0,STR,SINT), val_hdr, SMP_T_SINT, SMP_USE_HRQHV },
13023
13024 /* explicit req.{cook,hdr} are used to force the fetch direction to be response-only */
13025 { "res.cook", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRSHV },
13026 { "res.cook_cnt", smp_fetch_cookie_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRSHV },
13027 { "res.cook_val", smp_fetch_cookie_val, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRSHV },
13028
13029 { "res.fhdr", smp_fetch_fhdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRSHV },
13030 { "res.fhdr_cnt", smp_fetch_fhdr_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRSHV },
13031 { "res.hdr", smp_fetch_hdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRSHV },
13032 { "res.hdr_cnt", smp_fetch_hdr_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRSHV },
13033 { "res.hdr_ip", smp_fetch_hdr_ip, ARG2(0,STR,SINT), val_hdr, SMP_T_IPV4, SMP_USE_HRSHV },
13034 { "res.hdr_names", smp_fetch_hdr_names, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRSHV },
13035 { "res.hdr_val", smp_fetch_hdr_val, ARG2(0,STR,SINT), val_hdr, SMP_T_SINT, SMP_USE_HRSHV },
13036
13037 /* scook is valid only on the response and is used for ACL compatibility */
13038 { "scook", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRSHV },
13039 { "scook_cnt", smp_fetch_cookie_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRSHV },
13040 { "scook_val", smp_fetch_cookie_val, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRSHV },
13041 { "set-cookie", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRSHV }, /* deprecated */
13042
13043 /* shdr is valid only on the response and is used for ACL compatibility */
13044 { "shdr", smp_fetch_hdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRSHV },
13045 { "shdr_cnt", smp_fetch_hdr_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRSHV },
13046 { "shdr_ip", smp_fetch_hdr_ip, ARG2(0,STR,SINT), val_hdr, SMP_T_IPV4, SMP_USE_HRSHV },
13047 { "shdr_val", smp_fetch_hdr_val, ARG2(0,STR,SINT), val_hdr, SMP_T_SINT, SMP_USE_HRSHV },
13048
13049 { "status", smp_fetch_stcode, 0, NULL, SMP_T_SINT, SMP_USE_HRSHP },
13050 { "unique-id", smp_fetch_uniqueid, 0, NULL, SMP_T_STR, SMP_SRC_L4SRV },
13051 { "url", smp_fetch_url, 0, NULL, SMP_T_STR, SMP_USE_HRQHV },
13052 { "url32", smp_fetch_url32, 0, NULL, SMP_T_SINT, SMP_USE_HRQHV },
13053 { "url32+src", smp_fetch_url32_src, 0, NULL, SMP_T_BIN, SMP_USE_HRQHV },
13054 { "url_ip", smp_fetch_url_ip, 0, NULL, SMP_T_IPV4, SMP_USE_HRQHV },
13055 { "url_port", smp_fetch_url_port, 0, NULL, SMP_T_SINT, SMP_USE_HRQHV },
13056 { "url_param", smp_fetch_url_param, ARG2(0,STR,STR), NULL, SMP_T_STR, SMP_USE_HRQHV },
13057 { "urlp" , smp_fetch_url_param, ARG2(0,STR,STR), NULL, SMP_T_STR, SMP_USE_HRQHV },
13058 { "urlp_val", smp_fetch_url_param_val, ARG2(0,STR,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
13059 { /* END */ },
13060 }};
13061
13062
13063 /************************************************************************/
13064 /* All supported converter keywords must be declared here. */
13065 /************************************************************************/
13066 /* Note: must not be declared <const> as its list will be overwritten */
13067 static struct sample_conv_kw_list sample_conv_kws = {ILH, {
13068 { "http_date", sample_conv_http_date, ARG1(0,SINT), NULL, SMP_T_SINT, SMP_T_STR},
13069 { "language", sample_conv_q_prefered, ARG2(1,STR,STR), NULL, SMP_T_STR, SMP_T_STR},
13070 { "capture-req", smp_conv_req_capture, ARG1(1,SINT), NULL, SMP_T_STR, SMP_T_STR},
13071 { "capture-res", smp_conv_res_capture, ARG1(1,SINT), NULL, SMP_T_STR, SMP_T_STR},
13072 { "url_dec", sample_conv_url_dec, ARG1(0,SINT), NULL, SMP_T_STR, SMP_T_STR},
13073 { NULL, NULL, 0, 0, 0 },
13074 }};
13075
13076
13077 /************************************************************************/
13078 /* All supported http-request action keywords must be declared here. */
13079 /************************************************************************/
13080 struct action_kw_list http_req_actions = {
13081 .kw = {
13082 { "capture", parse_http_req_capture },
13083 { "reject", parse_http_action_reject },
13084 { "set-method", parse_set_req_line },
13085 { "set-path", parse_set_req_line },
13086 { "set-query", parse_set_req_line },
13087 { "set-uri", parse_set_req_line },
13088 { NULL, NULL }
13089 }
13090 };
13091
13092 struct action_kw_list http_res_actions = {
13093 .kw = {
13094 { "capture", parse_http_res_capture },
13095 { "set-status", parse_http_set_status },
13096 { NULL, NULL }
13097 }
13098 };
13099
13100 __attribute__((constructor))
__http_protocol_init(void)13101 static void __http_protocol_init(void)
13102 {
13103 acl_register_keywords(&acl_kws);
13104 sample_register_fetches(&sample_fetch_keywords);
13105 sample_register_convs(&sample_conv_kws);
13106 http_req_keywords_register(&http_req_actions);
13107 http_res_keywords_register(&http_res_actions);
13108 cli_register_kw(&cli_kws);
13109 }
13110
13111
13112 /*
13113 * Local variables:
13114 * c-indent-level: 8
13115 * c-basic-offset: 8
13116 * End:
13117 */
13118