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/stats.h>
46
47 #include <proto/acl.h>
48 #include <proto/action.h>
49 #include <proto/arg.h>
50 #include <proto/auth.h>
51 #include <proto/backend.h>
52 #include <proto/channel.h>
53 #include <proto/checks.h>
54 #include <proto/cli.h>
55 #include <proto/compression.h>
56 #include <proto/stats.h>
57 #include <proto/fd.h>
58 #include <proto/filters.h>
59 #include <proto/frontend.h>
60 #include <proto/log.h>
61 #include <proto/hdr_idx.h>
62 #include <proto/hlua.h>
63 #include <proto/pattern.h>
64 #include <proto/proto_tcp.h>
65 #include <proto/proto_http.h>
66 #include <proto/proxy.h>
67 #include <proto/queue.h>
68 #include <proto/sample.h>
69 #include <proto/server.h>
70 #include <proto/stream.h>
71 #include <proto/stream_interface.h>
72 #include <proto/task.h>
73 #include <proto/pattern.h>
74 #include <proto/vars.h>
75
76 const char HTTP_100[] =
77 "HTTP/1.1 100 Continue\r\n\r\n";
78
79 const struct chunk http_100_chunk = {
80 .str = (char *)&HTTP_100,
81 .len = sizeof(HTTP_100)-1
82 };
83
84 /* Warning: no "connection" header is provided with the 3xx messages below */
85 const char *HTTP_301 =
86 "HTTP/1.1 301 Moved Permanently\r\n"
87 "Content-length: 0\r\n"
88 "Location: "; /* not terminated since it will be concatenated with the URL */
89
90 const char *HTTP_302 =
91 "HTTP/1.1 302 Found\r\n"
92 "Cache-Control: no-cache\r\n"
93 "Content-length: 0\r\n"
94 "Location: "; /* not terminated since it will be concatenated with the URL */
95
96 /* same as 302 except that the browser MUST retry with the GET method */
97 const char *HTTP_303 =
98 "HTTP/1.1 303 See Other\r\n"
99 "Cache-Control: no-cache\r\n"
100 "Content-length: 0\r\n"
101 "Location: "; /* not terminated since it will be concatenated with the URL */
102
103
104 /* same as 302 except that the browser MUST retry with the same method */
105 const char *HTTP_307 =
106 "HTTP/1.1 307 Temporary Redirect\r\n"
107 "Cache-Control: no-cache\r\n"
108 "Content-length: 0\r\n"
109 "Location: "; /* not terminated since it will be concatenated with the URL */
110
111 /* same as 301 except that the browser MUST retry with the same method */
112 const char *HTTP_308 =
113 "HTTP/1.1 308 Permanent Redirect\r\n"
114 "Content-length: 0\r\n"
115 "Location: "; /* not terminated since it will be concatenated with the URL */
116
117 /* Warning: this one is an sprintf() fmt string, with <realm> as its only argument */
118 const char *HTTP_401_fmt =
119 "HTTP/1.0 401 Unauthorized\r\n"
120 "Cache-Control: no-cache\r\n"
121 "Connection: close\r\n"
122 "Content-Type: text/html\r\n"
123 "WWW-Authenticate: Basic realm=\"%s\"\r\n"
124 "\r\n"
125 "<html><body><h1>401 Unauthorized</h1>\nYou need a valid user and password to access this content.\n</body></html>\n";
126
127 const char *HTTP_407_fmt =
128 "HTTP/1.0 407 Unauthorized\r\n"
129 "Cache-Control: no-cache\r\n"
130 "Connection: close\r\n"
131 "Content-Type: text/html\r\n"
132 "Proxy-Authenticate: Basic realm=\"%s\"\r\n"
133 "\r\n"
134 "<html><body><h1>407 Unauthorized</h1>\nYou need a valid user and password to access this content.\n</body></html>\n";
135
136
137 const int http_err_codes[HTTP_ERR_SIZE] = {
138 [HTTP_ERR_200] = 200, /* used by "monitor-uri" */
139 [HTTP_ERR_400] = 400,
140 [HTTP_ERR_403] = 403,
141 [HTTP_ERR_405] = 405,
142 [HTTP_ERR_408] = 408,
143 [HTTP_ERR_429] = 429,
144 [HTTP_ERR_500] = 500,
145 [HTTP_ERR_502] = 502,
146 [HTTP_ERR_503] = 503,
147 [HTTP_ERR_504] = 504,
148 };
149
150 static const char *http_err_msgs[HTTP_ERR_SIZE] = {
151 [HTTP_ERR_200] =
152 "HTTP/1.0 200 OK\r\n"
153 "Cache-Control: no-cache\r\n"
154 "Connection: close\r\n"
155 "Content-Type: text/html\r\n"
156 "\r\n"
157 "<html><body><h1>200 OK</h1>\nService ready.\n</body></html>\n",
158
159 [HTTP_ERR_400] =
160 "HTTP/1.0 400 Bad request\r\n"
161 "Cache-Control: no-cache\r\n"
162 "Connection: close\r\n"
163 "Content-Type: text/html\r\n"
164 "\r\n"
165 "<html><body><h1>400 Bad request</h1>\nYour browser sent an invalid request.\n</body></html>\n",
166
167 [HTTP_ERR_403] =
168 "HTTP/1.0 403 Forbidden\r\n"
169 "Cache-Control: no-cache\r\n"
170 "Connection: close\r\n"
171 "Content-Type: text/html\r\n"
172 "\r\n"
173 "<html><body><h1>403 Forbidden</h1>\nRequest forbidden by administrative rules.\n</body></html>\n",
174
175 [HTTP_ERR_405] =
176 "HTTP/1.0 405 Method Not Allowed\r\n"
177 "Cache-Control: no-cache\r\n"
178 "Connection: close\r\n"
179 "Content-Type: text/html\r\n"
180 "\r\n"
181 "<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",
182
183 [HTTP_ERR_408] =
184 "HTTP/1.0 408 Request Time-out\r\n"
185 "Cache-Control: no-cache\r\n"
186 "Connection: close\r\n"
187 "Content-Type: text/html\r\n"
188 "\r\n"
189 "<html><body><h1>408 Request Time-out</h1>\nYour browser didn't send a complete request in time.\n</body></html>\n",
190
191 [HTTP_ERR_429] =
192 "HTTP/1.0 429 Too Many Requests\r\n"
193 "Cache-Control: no-cache\r\n"
194 "Connection: close\r\n"
195 "Content-Type: text/html\r\n"
196 "\r\n"
197 "<html><body><h1>429 Too Many Requests</h1>\nYou have sent too many requests in a given amount of time.\n</body></html>\n",
198
199 [HTTP_ERR_500] =
200 "HTTP/1.0 500 Server Error\r\n"
201 "Cache-Control: no-cache\r\n"
202 "Connection: close\r\n"
203 "Content-Type: text/html\r\n"
204 "\r\n"
205 "<html><body><h1>500 Server Error</h1>\nAn internal server error occured.\n</body></html>\n",
206
207 [HTTP_ERR_502] =
208 "HTTP/1.0 502 Bad Gateway\r\n"
209 "Cache-Control: no-cache\r\n"
210 "Connection: close\r\n"
211 "Content-Type: text/html\r\n"
212 "\r\n"
213 "<html><body><h1>502 Bad Gateway</h1>\nThe server returned an invalid or incomplete response.\n</body></html>\n",
214
215 [HTTP_ERR_503] =
216 "HTTP/1.0 503 Service Unavailable\r\n"
217 "Cache-Control: no-cache\r\n"
218 "Connection: close\r\n"
219 "Content-Type: text/html\r\n"
220 "\r\n"
221 "<html><body><h1>503 Service Unavailable</h1>\nNo server is available to handle this request.\n</body></html>\n",
222
223 [HTTP_ERR_504] =
224 "HTTP/1.0 504 Gateway Time-out\r\n"
225 "Cache-Control: no-cache\r\n"
226 "Connection: close\r\n"
227 "Content-Type: text/html\r\n"
228 "\r\n"
229 "<html><body><h1>504 Gateway Time-out</h1>\nThe server didn't respond in time.\n</body></html>\n",
230
231 };
232
233 /* status codes available for the stats admin page (strictly 4 chars length) */
234 const char *stat_status_codes[STAT_STATUS_SIZE] = {
235 [STAT_STATUS_DENY] = "DENY",
236 [STAT_STATUS_DONE] = "DONE",
237 [STAT_STATUS_ERRP] = "ERRP",
238 [STAT_STATUS_EXCD] = "EXCD",
239 [STAT_STATUS_NONE] = "NONE",
240 [STAT_STATUS_PART] = "PART",
241 [STAT_STATUS_UNKN] = "UNKN",
242 };
243
244
245 /* List head of all known action keywords for "http-request" */
246 struct action_kw_list http_req_keywords = {
247 .list = LIST_HEAD_INIT(http_req_keywords.list)
248 };
249
250 /* List head of all known action keywords for "http-response" */
251 struct action_kw_list http_res_keywords = {
252 .list = LIST_HEAD_INIT(http_res_keywords.list)
253 };
254
255 /* We must put the messages here since GCC cannot initialize consts depending
256 * on strlen().
257 */
258 struct chunk http_err_chunks[HTTP_ERR_SIZE];
259
260 /* this struct is used between calls to smp_fetch_hdr() or smp_fetch_cookie() */
261 static struct hdr_ctx static_hdr_ctx;
262
263 #define FD_SETS_ARE_BITFIELDS
264 #ifdef FD_SETS_ARE_BITFIELDS
265 /*
266 * This map is used with all the FD_* macros to check whether a particular bit
267 * is set or not. Each bit represents an ACSII code. FD_SET() sets those bytes
268 * which should be encoded. When FD_ISSET() returns non-zero, it means that the
269 * byte should be encoded. Be careful to always pass bytes from 0 to 255
270 * exclusively to the macros.
271 */
272 fd_set hdr_encode_map[(sizeof(fd_set) > (256/8)) ? 1 : ((256/8) / sizeof(fd_set))];
273 fd_set url_encode_map[(sizeof(fd_set) > (256/8)) ? 1 : ((256/8) / sizeof(fd_set))];
274 fd_set http_encode_map[(sizeof(fd_set) > (256/8)) ? 1 : ((256/8) / sizeof(fd_set))];
275
276 #else
277 #error "Check if your OS uses bitfields for fd_sets"
278 #endif
279
280 static int http_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn);
281
282 static inline int http_msg_forward_body(struct stream *s, struct http_msg *msg);
283 static inline int http_msg_forward_chunked_body(struct stream *s, struct http_msg *msg);
284
285 /* This function returns a reason associated with the HTTP status.
286 * This function never fails, a message is always returned.
287 */
get_reason(unsigned int status)288 const char *get_reason(unsigned int status)
289 {
290 switch (status) {
291 case 100: return "Continue";
292 case 101: return "Switching Protocols";
293 case 102: return "Processing";
294 case 200: return "OK";
295 case 201: return "Created";
296 case 202: return "Accepted";
297 case 203: return "Non-Authoritative Information";
298 case 204: return "No Content";
299 case 205: return "Reset Content";
300 case 206: return "Partial Content";
301 case 207: return "Multi-Status";
302 case 210: return "Content Different";
303 case 226: return "IM Used";
304 case 300: return "Multiple Choices";
305 case 301: return "Moved Permanently";
306 case 302: return "Moved Temporarily";
307 case 303: return "See Other";
308 case 304: return "Not Modified";
309 case 305: return "Use Proxy";
310 case 307: return "Temporary Redirect";
311 case 308: return "Permanent Redirect";
312 case 310: return "Too many Redirects";
313 case 400: return "Bad Request";
314 case 401: return "Unauthorized";
315 case 402: return "Payment Required";
316 case 403: return "Forbidden";
317 case 404: return "Not Found";
318 case 405: return "Method Not Allowed";
319 case 406: return "Not Acceptable";
320 case 407: return "Proxy Authentication Required";
321 case 408: return "Request Time-out";
322 case 409: return "Conflict";
323 case 410: return "Gone";
324 case 411: return "Length Required";
325 case 412: return "Precondition Failed";
326 case 413: return "Request Entity Too Large";
327 case 414: return "Request-URI Too Long";
328 case 415: return "Unsupported Media Type";
329 case 416: return "Requested range unsatisfiable";
330 case 417: return "Expectation failed";
331 case 418: return "I'm a teapot";
332 case 422: return "Unprocessable entity";
333 case 423: return "Locked";
334 case 424: return "Method failure";
335 case 425: return "Unordered Collection";
336 case 426: return "Upgrade Required";
337 case 428: return "Precondition Required";
338 case 429: return "Too Many Requests";
339 case 431: return "Request Header Fields Too Large";
340 case 449: return "Retry With";
341 case 450: return "Blocked by Windows Parental Controls";
342 case 451: return "Unavailable For Legal Reasons";
343 case 456: return "Unrecoverable Error";
344 case 499: return "client has closed connection";
345 case 500: return "Internal Server Error";
346 case 501: return "Not Implemented";
347 case 502: return "Bad Gateway or Proxy Error";
348 case 503: return "Service Unavailable";
349 case 504: return "Gateway Time-out";
350 case 505: return "HTTP Version not supported";
351 case 506: return "Variant also negociate";
352 case 507: return "Insufficient storage";
353 case 508: return "Loop detected";
354 case 509: return "Bandwidth Limit Exceeded";
355 case 510: return "Not extended";
356 case 511: return "Network authentication required";
357 case 520: return "Web server is returning an unknown error";
358 default:
359 switch (status) {
360 case 100 ... 199: return "Informational";
361 case 200 ... 299: return "Success";
362 case 300 ... 399: return "Redirection";
363 case 400 ... 499: return "Client Error";
364 case 500 ... 599: return "Server Error";
365 default: return "Other";
366 }
367 }
368 }
369
init_proto_http()370 void init_proto_http()
371 {
372 int i;
373 char *tmp;
374 int msg;
375
376 for (msg = 0; msg < HTTP_ERR_SIZE; msg++) {
377 if (!http_err_msgs[msg]) {
378 Alert("Internal error: no message defined for HTTP return code %d. Aborting.\n", msg);
379 abort();
380 }
381
382 http_err_chunks[msg].str = (char *)http_err_msgs[msg];
383 http_err_chunks[msg].len = strlen(http_err_msgs[msg]);
384 }
385
386 /* initialize the log header encoding map : '{|}"#' should be encoded with
387 * '#' as prefix, as well as non-printable characters ( <32 or >= 127 ).
388 * URL encoding only requires '"', '#' to be encoded as well as non-
389 * printable characters above.
390 */
391 memset(hdr_encode_map, 0, sizeof(hdr_encode_map));
392 memset(url_encode_map, 0, sizeof(url_encode_map));
393 memset(http_encode_map, 0, sizeof(url_encode_map));
394 for (i = 0; i < 32; i++) {
395 FD_SET(i, hdr_encode_map);
396 FD_SET(i, url_encode_map);
397 }
398 for (i = 127; i < 256; i++) {
399 FD_SET(i, hdr_encode_map);
400 FD_SET(i, url_encode_map);
401 }
402
403 tmp = "\"#{|}";
404 while (*tmp) {
405 FD_SET(*tmp, hdr_encode_map);
406 tmp++;
407 }
408
409 tmp = "\"#";
410 while (*tmp) {
411 FD_SET(*tmp, url_encode_map);
412 tmp++;
413 }
414
415 /* initialize the http header encoding map. The draft httpbis define the
416 * header content as:
417 *
418 * HTTP-message = start-line
419 * *( header-field CRLF )
420 * CRLF
421 * [ message-body ]
422 * header-field = field-name ":" OWS field-value OWS
423 * field-value = *( field-content / obs-fold )
424 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
425 * obs-fold = CRLF 1*( SP / HTAB )
426 * field-vchar = VCHAR / obs-text
427 * VCHAR = %x21-7E
428 * obs-text = %x80-FF
429 *
430 * All the chars are encoded except "VCHAR", "obs-text", SP and HTAB.
431 * The encoded chars are form 0x00 to 0x08, 0x0a to 0x1f and 0x7f. The
432 * "obs-fold" is volontary forgotten because haproxy remove this.
433 */
434 memset(http_encode_map, 0, sizeof(http_encode_map));
435 for (i = 0x00; i <= 0x08; i++)
436 FD_SET(i, http_encode_map);
437 for (i = 0x0a; i <= 0x1f; i++)
438 FD_SET(i, http_encode_map);
439 FD_SET(0x7f, http_encode_map);
440
441 /* memory allocations */
442 pool2_http_txn = create_pool("http_txn", sizeof(struct http_txn), MEM_F_SHARED);
443 pool2_requri = create_pool("requri", REQURI_LEN, MEM_F_SHARED);
444 pool2_uniqueid = create_pool("uniqueid", UNIQUEID_LEN, MEM_F_SHARED);
445 }
446
447 /*
448 * We have 26 list of methods (1 per first letter), each of which can have
449 * up to 3 entries (2 valid, 1 null).
450 */
451 struct http_method_desc {
452 enum http_meth_t meth;
453 int len;
454 const char text[8];
455 };
456
457 const struct http_method_desc http_methods[26][3] = {
458 ['C' - 'A'] = {
459 [0] = { .meth = HTTP_METH_CONNECT , .len=7, .text="CONNECT" },
460 },
461 ['D' - 'A'] = {
462 [0] = { .meth = HTTP_METH_DELETE , .len=6, .text="DELETE" },
463 },
464 ['G' - 'A'] = {
465 [0] = { .meth = HTTP_METH_GET , .len=3, .text="GET" },
466 },
467 ['H' - 'A'] = {
468 [0] = { .meth = HTTP_METH_HEAD , .len=4, .text="HEAD" },
469 },
470 ['O' - 'A'] = {
471 [0] = { .meth = HTTP_METH_OPTIONS , .len=7, .text="OPTIONS" },
472 },
473 ['P' - 'A'] = {
474 [0] = { .meth = HTTP_METH_POST , .len=4, .text="POST" },
475 [1] = { .meth = HTTP_METH_PUT , .len=3, .text="PUT" },
476 },
477 ['T' - 'A'] = {
478 [0] = { .meth = HTTP_METH_TRACE , .len=5, .text="TRACE" },
479 },
480 /* rest is empty like this :
481 * [0] = { .meth = HTTP_METH_OTHER , .len=0, .text="" },
482 */
483 };
484
485 const struct http_method_name http_known_methods[HTTP_METH_OTHER] = {
486 [HTTP_METH_OPTIONS] = { "OPTIONS", 7 },
487 [HTTP_METH_GET] = { "GET", 3 },
488 [HTTP_METH_HEAD] = { "HEAD", 4 },
489 [HTTP_METH_POST] = { "POST", 4 },
490 [HTTP_METH_PUT] = { "PUT", 3 },
491 [HTTP_METH_DELETE] = { "DELETE", 6 },
492 [HTTP_METH_TRACE] = { "TRACE", 5 },
493 [HTTP_METH_CONNECT] = { "CONNECT", 7 },
494 };
495
496 /* It is about twice as fast on recent architectures to lookup a byte in a
497 * table than to perform a boolean AND or OR between two tests. Refer to
498 * RFC2616/RFC5234/RFC7230 for those chars. A token is any ASCII char that is
499 * neither a separator nor a CTL char. An http ver_token is any ASCII which can
500 * be found in an HTTP version, which includes 'H', 'T', 'P', '/', '.' and any
501 * digit. Note: please do not overwrite values in assignment since gcc-2.95
502 * will not handle them correctly. It's worth noting that chars 128..255 are
503 * nothing, not even control chars.
504 */
505 const unsigned char http_char_classes[256] = {
506 [ 0] = HTTP_FLG_CTL,
507 [ 1] = HTTP_FLG_CTL,
508 [ 2] = HTTP_FLG_CTL,
509 [ 3] = HTTP_FLG_CTL,
510 [ 4] = HTTP_FLG_CTL,
511 [ 5] = HTTP_FLG_CTL,
512 [ 6] = HTTP_FLG_CTL,
513 [ 7] = HTTP_FLG_CTL,
514 [ 8] = HTTP_FLG_CTL,
515 [ 9] = HTTP_FLG_SPHT | HTTP_FLG_LWS | HTTP_FLG_SEP | HTTP_FLG_CTL,
516 [ 10] = HTTP_FLG_CRLF | HTTP_FLG_LWS | HTTP_FLG_CTL,
517 [ 11] = HTTP_FLG_CTL,
518 [ 12] = HTTP_FLG_CTL,
519 [ 13] = HTTP_FLG_CRLF | HTTP_FLG_LWS | HTTP_FLG_CTL,
520 [ 14] = HTTP_FLG_CTL,
521 [ 15] = HTTP_FLG_CTL,
522 [ 16] = HTTP_FLG_CTL,
523 [ 17] = HTTP_FLG_CTL,
524 [ 18] = HTTP_FLG_CTL,
525 [ 19] = HTTP_FLG_CTL,
526 [ 20] = HTTP_FLG_CTL,
527 [ 21] = HTTP_FLG_CTL,
528 [ 22] = HTTP_FLG_CTL,
529 [ 23] = HTTP_FLG_CTL,
530 [ 24] = HTTP_FLG_CTL,
531 [ 25] = HTTP_FLG_CTL,
532 [ 26] = HTTP_FLG_CTL,
533 [ 27] = HTTP_FLG_CTL,
534 [ 28] = HTTP_FLG_CTL,
535 [ 29] = HTTP_FLG_CTL,
536 [ 30] = HTTP_FLG_CTL,
537 [ 31] = HTTP_FLG_CTL,
538 [' '] = HTTP_FLG_SPHT | HTTP_FLG_LWS | HTTP_FLG_SEP,
539 ['!'] = HTTP_FLG_TOK,
540 ['"'] = HTTP_FLG_SEP,
541 ['#'] = HTTP_FLG_TOK,
542 ['$'] = HTTP_FLG_TOK,
543 ['%'] = HTTP_FLG_TOK,
544 ['&'] = HTTP_FLG_TOK,
545 [ 39] = HTTP_FLG_TOK,
546 ['('] = HTTP_FLG_SEP,
547 [')'] = HTTP_FLG_SEP,
548 ['*'] = HTTP_FLG_TOK,
549 ['+'] = HTTP_FLG_TOK,
550 [','] = HTTP_FLG_SEP,
551 ['-'] = HTTP_FLG_TOK,
552 ['.'] = HTTP_FLG_TOK | HTTP_FLG_VER,
553 ['/'] = HTTP_FLG_SEP | HTTP_FLG_VER,
554 ['0'] = HTTP_FLG_TOK | HTTP_FLG_VER,
555 ['1'] = HTTP_FLG_TOK | HTTP_FLG_VER,
556 ['2'] = HTTP_FLG_TOK | HTTP_FLG_VER,
557 ['3'] = HTTP_FLG_TOK | HTTP_FLG_VER,
558 ['4'] = HTTP_FLG_TOK | HTTP_FLG_VER,
559 ['5'] = HTTP_FLG_TOK | HTTP_FLG_VER,
560 ['6'] = HTTP_FLG_TOK | HTTP_FLG_VER,
561 ['7'] = HTTP_FLG_TOK | HTTP_FLG_VER,
562 ['8'] = HTTP_FLG_TOK | HTTP_FLG_VER,
563 ['9'] = HTTP_FLG_TOK | HTTP_FLG_VER,
564 [':'] = HTTP_FLG_SEP,
565 [';'] = HTTP_FLG_SEP,
566 ['<'] = HTTP_FLG_SEP,
567 ['='] = HTTP_FLG_SEP,
568 ['>'] = HTTP_FLG_SEP,
569 ['?'] = HTTP_FLG_SEP,
570 ['@'] = HTTP_FLG_SEP,
571 ['A'] = HTTP_FLG_TOK,
572 ['B'] = HTTP_FLG_TOK,
573 ['C'] = HTTP_FLG_TOK,
574 ['D'] = HTTP_FLG_TOK,
575 ['E'] = HTTP_FLG_TOK,
576 ['F'] = HTTP_FLG_TOK,
577 ['G'] = HTTP_FLG_TOK,
578 ['H'] = HTTP_FLG_TOK | HTTP_FLG_VER,
579 ['I'] = HTTP_FLG_TOK,
580 ['J'] = HTTP_FLG_TOK,
581 ['K'] = HTTP_FLG_TOK,
582 ['L'] = HTTP_FLG_TOK,
583 ['M'] = HTTP_FLG_TOK,
584 ['N'] = HTTP_FLG_TOK,
585 ['O'] = HTTP_FLG_TOK,
586 ['P'] = HTTP_FLG_TOK | HTTP_FLG_VER,
587 ['Q'] = HTTP_FLG_TOK,
588 ['R'] = HTTP_FLG_TOK | HTTP_FLG_VER,
589 ['S'] = HTTP_FLG_TOK | HTTP_FLG_VER,
590 ['T'] = HTTP_FLG_TOK | HTTP_FLG_VER,
591 ['U'] = HTTP_FLG_TOK,
592 ['V'] = HTTP_FLG_TOK,
593 ['W'] = HTTP_FLG_TOK,
594 ['X'] = HTTP_FLG_TOK,
595 ['Y'] = HTTP_FLG_TOK,
596 ['Z'] = HTTP_FLG_TOK,
597 ['['] = HTTP_FLG_SEP,
598 [ 92] = HTTP_FLG_SEP,
599 [']'] = HTTP_FLG_SEP,
600 ['^'] = HTTP_FLG_TOK,
601 ['_'] = HTTP_FLG_TOK,
602 ['`'] = HTTP_FLG_TOK,
603 ['a'] = HTTP_FLG_TOK,
604 ['b'] = HTTP_FLG_TOK,
605 ['c'] = HTTP_FLG_TOK,
606 ['d'] = HTTP_FLG_TOK,
607 ['e'] = HTTP_FLG_TOK,
608 ['f'] = HTTP_FLG_TOK,
609 ['g'] = HTTP_FLG_TOK,
610 ['h'] = HTTP_FLG_TOK,
611 ['i'] = HTTP_FLG_TOK,
612 ['j'] = HTTP_FLG_TOK,
613 ['k'] = HTTP_FLG_TOK,
614 ['l'] = HTTP_FLG_TOK,
615 ['m'] = HTTP_FLG_TOK,
616 ['n'] = HTTP_FLG_TOK,
617 ['o'] = HTTP_FLG_TOK,
618 ['p'] = HTTP_FLG_TOK,
619 ['q'] = HTTP_FLG_TOK,
620 ['r'] = HTTP_FLG_TOK,
621 ['s'] = HTTP_FLG_TOK,
622 ['t'] = HTTP_FLG_TOK,
623 ['u'] = HTTP_FLG_TOK,
624 ['v'] = HTTP_FLG_TOK,
625 ['w'] = HTTP_FLG_TOK,
626 ['x'] = HTTP_FLG_TOK,
627 ['y'] = HTTP_FLG_TOK,
628 ['z'] = HTTP_FLG_TOK,
629 ['{'] = HTTP_FLG_SEP,
630 ['|'] = HTTP_FLG_TOK,
631 ['}'] = HTTP_FLG_SEP,
632 ['~'] = HTTP_FLG_TOK,
633 [127] = HTTP_FLG_CTL,
634 };
635
636 /*
637 * Adds a header and its CRLF at the tail of the message's buffer, just before
638 * the last CRLF. Text length is measured first, so it cannot be NULL.
639 * The header is also automatically added to the index <hdr_idx>, and the end
640 * of headers is automatically adjusted. The number of bytes added is returned
641 * on success, otherwise <0 is returned indicating an error.
642 */
http_header_add_tail(struct http_msg * msg,struct hdr_idx * hdr_idx,const char * text)643 int http_header_add_tail(struct http_msg *msg, struct hdr_idx *hdr_idx, const char *text)
644 {
645 int bytes, len;
646
647 len = strlen(text);
648 bytes = buffer_insert_line2(msg->chn->buf, msg->chn->buf->p + msg->eoh, text, len);
649 if (!bytes)
650 return -1;
651 http_msg_move_end(msg, bytes);
652 return hdr_idx_add(len, 1, hdr_idx, hdr_idx->tail);
653 }
654
655 /*
656 * Adds a header and its CRLF at the tail of the message's buffer, just before
657 * the last CRLF. <len> bytes are copied, not counting the CRLF. If <text> is NULL, then
658 * the buffer is only opened and the space reserved, but nothing is copied.
659 * The header is also automatically added to the index <hdr_idx>, and the end
660 * of headers is automatically adjusted. The number of bytes added is returned
661 * on success, otherwise <0 is returned indicating an error.
662 */
http_header_add_tail2(struct http_msg * msg,struct hdr_idx * hdr_idx,const char * text,int len)663 int http_header_add_tail2(struct http_msg *msg,
664 struct hdr_idx *hdr_idx, const char *text, int len)
665 {
666 int bytes;
667
668 bytes = buffer_insert_line2(msg->chn->buf, msg->chn->buf->p + msg->eoh, text, len);
669 if (!bytes)
670 return -1;
671 http_msg_move_end(msg, bytes);
672 return hdr_idx_add(len, 1, hdr_idx, hdr_idx->tail);
673 }
674
675 /*
676 * Checks if <hdr> is exactly <name> for <len> chars, and ends with a colon.
677 * If so, returns the position of the first non-space character relative to
678 * <hdr>, or <end>-<hdr> if not found before. If no value is found, it tries
679 * to return a pointer to the place after the first space. Returns 0 if the
680 * header name does not match. Checks are case-insensitive.
681 */
http_header_match2(const char * hdr,const char * end,const char * name,int len)682 int http_header_match2(const char *hdr, const char *end,
683 const char *name, int len)
684 {
685 const char *val;
686
687 if (hdr + len >= end)
688 return 0;
689 if (hdr[len] != ':')
690 return 0;
691 if (strncasecmp(hdr, name, len) != 0)
692 return 0;
693 val = hdr + len + 1;
694 while (val < end && HTTP_IS_SPHT(*val))
695 val++;
696 if ((val >= end) && (len + 2 <= end - hdr))
697 return len + 2; /* we may replace starting from second space */
698 return val - hdr;
699 }
700
701 /* Find the first or next occurrence of header <name> in message buffer <sol>
702 * using headers index <idx>, and return it in the <ctx> structure. This
703 * structure holds everything necessary to use the header and find next
704 * occurrence. If its <idx> member is 0, the header is searched from the
705 * beginning. Otherwise, the next occurrence is returned. The function returns
706 * 1 when it finds a value, and 0 when there is no more. It is very similar to
707 * http_find_header2() except that it is designed to work with full-line headers
708 * whose comma is not a delimiter but is part of the syntax. As a special case,
709 * if ctx->val is NULL when searching for a new values of a header, the current
710 * header is rescanned. This allows rescanning after a header deletion.
711 */
http_find_full_header2(const char * name,int len,char * sol,struct hdr_idx * idx,struct hdr_ctx * ctx)712 int http_find_full_header2(const char *name, int len,
713 char *sol, struct hdr_idx *idx,
714 struct hdr_ctx *ctx)
715 {
716 char *eol, *sov;
717 int cur_idx, old_idx;
718
719 cur_idx = ctx->idx;
720 if (cur_idx) {
721 /* We have previously returned a header, let's search another one */
722 sol = ctx->line;
723 eol = sol + idx->v[cur_idx].len;
724 goto next_hdr;
725 }
726
727 /* first request for this header */
728 sol += hdr_idx_first_pos(idx);
729 old_idx = 0;
730 cur_idx = hdr_idx_first_idx(idx);
731 while (cur_idx) {
732 eol = sol + idx->v[cur_idx].len;
733
734 if (len == 0) {
735 /* No argument was passed, we want any header.
736 * To achieve this, we simply build a fake request. */
737 while (sol + len < eol && sol[len] != ':')
738 len++;
739 name = sol;
740 }
741
742 if ((len < eol - sol) &&
743 (sol[len] == ':') &&
744 (strncasecmp(sol, name, len) == 0)) {
745 ctx->del = len;
746 sov = sol + len + 1;
747 while (sov < eol && HTTP_IS_LWS(*sov))
748 sov++;
749
750 ctx->line = sol;
751 ctx->prev = old_idx;
752 ctx->idx = cur_idx;
753 ctx->val = sov - sol;
754 ctx->tws = 0;
755 while (eol > sov && HTTP_IS_LWS(*(eol - 1))) {
756 eol--;
757 ctx->tws++;
758 }
759 ctx->vlen = eol - sov;
760 return 1;
761 }
762 next_hdr:
763 sol = eol + idx->v[cur_idx].cr + 1;
764 old_idx = cur_idx;
765 cur_idx = idx->v[cur_idx].next;
766 }
767 return 0;
768 }
769
770 /* Find the first or next header field in message buffer <sol> using headers
771 * index <idx>, and return it in the <ctx> structure. This structure holds
772 * everything necessary to use the header and find next occurrence. If its
773 * <idx> member is 0, the first header is retrieved. Otherwise, the next
774 * occurrence is returned. The function returns 1 when it finds a value, and
775 * 0 when there is no more. It is equivalent to http_find_full_header2() with
776 * no header name.
777 */
http_find_next_header(char * sol,struct hdr_idx * idx,struct hdr_ctx * ctx)778 int http_find_next_header(char *sol, struct hdr_idx *idx, struct hdr_ctx *ctx)
779 {
780 char *eol, *sov;
781 int cur_idx, old_idx;
782 int len;
783
784 cur_idx = ctx->idx;
785 if (cur_idx) {
786 /* We have previously returned a header, let's search another one */
787 sol = ctx->line;
788 eol = sol + idx->v[cur_idx].len;
789 goto next_hdr;
790 }
791
792 /* first request for this header */
793 sol += hdr_idx_first_pos(idx);
794 old_idx = 0;
795 cur_idx = hdr_idx_first_idx(idx);
796 while (cur_idx) {
797 eol = sol + idx->v[cur_idx].len;
798
799 len = 0;
800 while (1) {
801 if (len >= eol - sol)
802 goto next_hdr;
803 if (sol[len] == ':')
804 break;
805 len++;
806 }
807
808 ctx->del = len;
809 sov = sol + len + 1;
810 while (sov < eol && HTTP_IS_LWS(*sov))
811 sov++;
812
813 ctx->line = sol;
814 ctx->prev = old_idx;
815 ctx->idx = cur_idx;
816 ctx->val = sov - sol;
817 ctx->tws = 0;
818
819 while (eol > sov && HTTP_IS_LWS(*(eol - 1))) {
820 eol--;
821 ctx->tws++;
822 }
823 ctx->vlen = eol - sov;
824 return 1;
825
826 next_hdr:
827 sol = eol + idx->v[cur_idx].cr + 1;
828 old_idx = cur_idx;
829 cur_idx = idx->v[cur_idx].next;
830 }
831 return 0;
832 }
833
834 /* Find the end of the header value contained between <s> and <e>. See RFC7230,
835 * par 3.2 for more information. Note that it requires a valid header to return
836 * a valid result. This works for headers defined as comma-separated lists.
837 */
find_hdr_value_end(char * s,const char * e)838 char *find_hdr_value_end(char *s, const char *e)
839 {
840 int quoted, qdpair;
841
842 quoted = qdpair = 0;
843
844 #if defined(__x86_64__) || \
845 defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) || \
846 defined(__ARM_ARCH_7A__)
847 /* speedup: skip everything not a comma nor a double quote */
848 for (; s <= e - sizeof(int); s += sizeof(int)) {
849 unsigned int c = *(int *)s; // comma
850 unsigned int q = c; // quote
851
852 c ^= 0x2c2c2c2c; // contains one zero on a comma
853 q ^= 0x22222222; // contains one zero on a quote
854
855 c = (c - 0x01010101) & ~c; // contains 0x80 below a comma
856 q = (q - 0x01010101) & ~q; // contains 0x80 below a quote
857
858 if ((c | q) & 0x80808080)
859 break; // found a comma or a quote
860 }
861 #endif
862 for (; s < e; s++) {
863 if (qdpair) qdpair = 0;
864 else if (quoted) {
865 if (*s == '\\') qdpair = 1;
866 else if (*s == '"') quoted = 0;
867 }
868 else if (*s == '"') quoted = 1;
869 else if (*s == ',') return s;
870 }
871 return s;
872 }
873
874 /* Find the first or next occurrence of header <name> in message buffer <sol>
875 * using headers index <idx>, and return it in the <ctx> structure. This
876 * structure holds everything necessary to use the header and find next
877 * occurrence. If its <idx> member is 0, the header is searched from the
878 * beginning. Otherwise, the next occurrence is returned. The function returns
879 * 1 when it finds a value, and 0 when there is no more. It is designed to work
880 * with headers defined as comma-separated lists. As a special case, if ctx->val
881 * is NULL when searching for a new values of a header, the current header is
882 * rescanned. This allows rescanning after a header deletion.
883 */
http_find_header2(const char * name,int len,char * sol,struct hdr_idx * idx,struct hdr_ctx * ctx)884 int http_find_header2(const char *name, int len,
885 char *sol, struct hdr_idx *idx,
886 struct hdr_ctx *ctx)
887 {
888 char *eol, *sov;
889 int cur_idx, old_idx;
890
891 cur_idx = ctx->idx;
892 if (cur_idx) {
893 /* We have previously returned a value, let's search
894 * another one on the same line.
895 */
896 sol = ctx->line;
897 ctx->del = ctx->val + ctx->vlen + ctx->tws;
898 sov = sol + ctx->del;
899 eol = sol + idx->v[cur_idx].len;
900
901 if (sov >= eol)
902 /* no more values in this header */
903 goto next_hdr;
904
905 /* values remaining for this header, skip the comma but save it
906 * for later use (eg: for header deletion).
907 */
908 sov++;
909 while (sov < eol && HTTP_IS_LWS((*sov)))
910 sov++;
911
912 goto return_hdr;
913 }
914
915 /* first request for this header */
916 sol += hdr_idx_first_pos(idx);
917 old_idx = 0;
918 cur_idx = hdr_idx_first_idx(idx);
919 while (cur_idx) {
920 eol = sol + idx->v[cur_idx].len;
921
922 if (len == 0) {
923 /* No argument was passed, we want any header.
924 * To achieve this, we simply build a fake request. */
925 while (sol + len < eol && sol[len] != ':')
926 len++;
927 name = sol;
928 }
929
930 if ((len < eol - sol) &&
931 (sol[len] == ':') &&
932 (strncasecmp(sol, name, len) == 0)) {
933 ctx->del = len;
934 sov = sol + len + 1;
935 while (sov < eol && HTTP_IS_LWS(*sov))
936 sov++;
937
938 ctx->line = sol;
939 ctx->prev = old_idx;
940 return_hdr:
941 ctx->idx = cur_idx;
942 ctx->val = sov - sol;
943
944 eol = find_hdr_value_end(sov, eol);
945 ctx->tws = 0;
946 while (eol > sov && HTTP_IS_LWS(*(eol - 1))) {
947 eol--;
948 ctx->tws++;
949 }
950 ctx->vlen = eol - sov;
951 return 1;
952 }
953 next_hdr:
954 sol = eol + idx->v[cur_idx].cr + 1;
955 old_idx = cur_idx;
956 cur_idx = idx->v[cur_idx].next;
957 }
958 return 0;
959 }
960
http_find_header(const char * name,char * sol,struct hdr_idx * idx,struct hdr_ctx * ctx)961 int http_find_header(const char *name,
962 char *sol, struct hdr_idx *idx,
963 struct hdr_ctx *ctx)
964 {
965 return http_find_header2(name, strlen(name), sol, idx, ctx);
966 }
967
968 /* Remove one value of a header. This only works on a <ctx> returned by one of
969 * the http_find_header functions. The value is removed, as well as surrounding
970 * commas if any. If the removed value was alone, the whole header is removed.
971 * The ctx is always updated accordingly, as well as the buffer and HTTP
972 * message <msg>. The new index is returned. If it is zero, it means there is
973 * no more header, so any processing may stop. The ctx is always left in a form
974 * that can be handled by http_find_header2() to find next occurrence.
975 */
http_remove_header2(struct http_msg * msg,struct hdr_idx * idx,struct hdr_ctx * ctx)976 int http_remove_header2(struct http_msg *msg, struct hdr_idx *idx, struct hdr_ctx *ctx)
977 {
978 int cur_idx = ctx->idx;
979 char *sol = ctx->line;
980 struct hdr_idx_elem *hdr;
981 int delta, skip_comma;
982
983 if (!cur_idx)
984 return 0;
985
986 hdr = &idx->v[cur_idx];
987 if (sol[ctx->del] == ':' && ctx->val + ctx->vlen + ctx->tws == hdr->len) {
988 /* This was the only value of the header, we must now remove it entirely. */
989 delta = buffer_replace2(msg->chn->buf, sol, sol + hdr->len + hdr->cr + 1, NULL, 0);
990 http_msg_move_end(msg, delta);
991 idx->used--;
992 hdr->len = 0; /* unused entry */
993 idx->v[ctx->prev].next = idx->v[ctx->idx].next;
994 if (idx->tail == ctx->idx)
995 idx->tail = ctx->prev;
996 ctx->idx = ctx->prev; /* walk back to the end of previous header */
997 ctx->line -= idx->v[ctx->idx].len + idx->v[ctx->idx].cr + 1;
998 ctx->val = idx->v[ctx->idx].len; /* point to end of previous header */
999 ctx->tws = ctx->vlen = 0;
1000 return ctx->idx;
1001 }
1002
1003 /* This was not the only value of this header. We have to remove between
1004 * ctx->del+1 and ctx->val+ctx->vlen+ctx->tws+1 included. If it is the
1005 * last entry of the list, we remove the last separator.
1006 */
1007
1008 skip_comma = (ctx->val + ctx->vlen + ctx->tws == hdr->len) ? 0 : 1;
1009 delta = buffer_replace2(msg->chn->buf, sol + ctx->del + skip_comma,
1010 sol + ctx->val + ctx->vlen + ctx->tws + skip_comma,
1011 NULL, 0);
1012 hdr->len += delta;
1013 http_msg_move_end(msg, delta);
1014 ctx->val = ctx->del;
1015 ctx->tws = ctx->vlen = 0;
1016 return ctx->idx;
1017 }
1018
1019 /* This function handles a server error at the stream interface level. The
1020 * stream interface is assumed to be already in a closed state. An optional
1021 * message is copied into the input buffer, and an HTTP status code stored.
1022 * The error flags are set to the values in arguments. Any pending request
1023 * in this buffer will be lost.
1024 */
http_server_error(struct stream * s,struct stream_interface * si,int err,int finst,int status,const struct chunk * msg)1025 static void http_server_error(struct stream *s, struct stream_interface *si,
1026 int err, int finst, int status, const struct chunk *msg)
1027 {
1028 FLT_STRM_CB(s, flt_http_reply(s, status, msg));
1029 channel_auto_read(si_oc(si));
1030 channel_abort(si_oc(si));
1031 channel_auto_close(si_oc(si));
1032 channel_erase(si_oc(si));
1033 channel_auto_close(si_ic(si));
1034 channel_auto_read(si_ic(si));
1035 if (status > 0 && msg) {
1036 s->txn->status = status;
1037 bo_inject(si_ic(si), msg->str, msg->len);
1038 }
1039 if (!(s->flags & SF_ERR_MASK))
1040 s->flags |= err;
1041 if (!(s->flags & SF_FINST_MASK))
1042 s->flags |= finst;
1043 }
1044
1045 /* This function returns the appropriate error location for the given stream
1046 * and message.
1047 */
1048
http_error_message(struct stream * s,int msgnum)1049 struct chunk *http_error_message(struct stream *s, int msgnum)
1050 {
1051 if (s->be->errmsg[msgnum].str)
1052 return &s->be->errmsg[msgnum];
1053 else if (strm_fe(s)->errmsg[msgnum].str)
1054 return &strm_fe(s)->errmsg[msgnum];
1055 else
1056 return &http_err_chunks[msgnum];
1057 }
1058
1059 void
http_reply_and_close(struct stream * s,short status,struct chunk * msg)1060 http_reply_and_close(struct stream *s, short status, struct chunk *msg)
1061 {
1062 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
1063 FLT_STRM_CB(s, flt_http_reply(s, status, msg));
1064 stream_int_retnclose(&s->si[0], msg);
1065 }
1066
1067 /*
1068 * returns a known method among HTTP_METH_* or HTTP_METH_OTHER for all unknown
1069 * ones.
1070 */
find_http_meth(const char * str,const int len)1071 enum http_meth_t find_http_meth(const char *str, const int len)
1072 {
1073 unsigned char m;
1074 const struct http_method_desc *h;
1075
1076 m = ((unsigned)*str - 'A');
1077
1078 if (m < 26) {
1079 for (h = http_methods[m]; h->len > 0; h++) {
1080 if (unlikely(h->len != len))
1081 continue;
1082 if (likely(memcmp(str, h->text, h->len) == 0))
1083 return h->meth;
1084 };
1085 }
1086 return HTTP_METH_OTHER;
1087 }
1088
1089 /* Parse the URI from the given transaction (which is assumed to be in request
1090 * phase) and look for the "/" beginning the PATH. If not found, return NULL.
1091 * It is returned otherwise.
1092 */
http_get_path(struct http_txn * txn)1093 char *http_get_path(struct http_txn *txn)
1094 {
1095 char *ptr, *end;
1096
1097 ptr = txn->req.chn->buf->p + txn->req.sl.rq.u;
1098 end = ptr + txn->req.sl.rq.u_l;
1099
1100 if (ptr >= end)
1101 return NULL;
1102
1103 /* RFC7230, par. 2.7 :
1104 * Request-URI = "*" | absuri | abspath | authority
1105 */
1106
1107 if (*ptr == '*')
1108 return NULL;
1109
1110 if (isalpha((unsigned char)*ptr)) {
1111 /* this is a scheme as described by RFC3986, par. 3.1 */
1112 ptr++;
1113 while (ptr < end &&
1114 (isalnum((unsigned char)*ptr) || *ptr == '+' || *ptr == '-' || *ptr == '.'))
1115 ptr++;
1116 /* skip '://' */
1117 if (ptr == end || *ptr++ != ':')
1118 return NULL;
1119 if (ptr == end || *ptr++ != '/')
1120 return NULL;
1121 if (ptr == end || *ptr++ != '/')
1122 return NULL;
1123 }
1124 /* skip [user[:passwd]@]host[:[port]] */
1125
1126 while (ptr < end && *ptr != '/')
1127 ptr++;
1128
1129 if (ptr == end)
1130 return NULL;
1131
1132 /* OK, we got the '/' ! */
1133 return ptr;
1134 }
1135
1136 /* Parse the URI from the given string and look for the "/" beginning the PATH.
1137 * If not found, return NULL. It is returned otherwise.
1138 */
1139 static char *
http_get_path_from_string(char * str)1140 http_get_path_from_string(char *str)
1141 {
1142 char *ptr = str;
1143
1144 /* RFC2616, par. 5.1.2 :
1145 * Request-URI = "*" | absuri | abspath | authority
1146 */
1147
1148 if (*ptr == '*')
1149 return NULL;
1150
1151 if (isalpha((unsigned char)*ptr)) {
1152 /* this is a scheme as described by RFC3986, par. 3.1 */
1153 ptr++;
1154 while (isalnum((unsigned char)*ptr) || *ptr == '+' || *ptr == '-' || *ptr == '.')
1155 ptr++;
1156 /* skip '://' */
1157 if (*ptr == '\0' || *ptr++ != ':')
1158 return NULL;
1159 if (*ptr == '\0' || *ptr++ != '/')
1160 return NULL;
1161 if (*ptr == '\0' || *ptr++ != '/')
1162 return NULL;
1163 }
1164 /* skip [user[:passwd]@]host[:[port]] */
1165
1166 while (*ptr != '\0' && *ptr != ' ' && *ptr != '/')
1167 ptr++;
1168
1169 if (*ptr == '\0' || *ptr == ' ')
1170 return NULL;
1171
1172 /* OK, we got the '/' ! */
1173 return ptr;
1174 }
1175
1176 /* Returns a 302 for a redirectable request that reaches a server working in
1177 * in redirect mode. This may only be called just after the stream interface
1178 * has moved to SI_ST_ASS. Unprocessable requests are left unchanged and will
1179 * follow normal proxy processing. NOTE: this function is designed to support
1180 * being called once data are scheduled for forwarding.
1181 */
http_perform_server_redirect(struct stream * s,struct stream_interface * si)1182 void http_perform_server_redirect(struct stream *s, struct stream_interface *si)
1183 {
1184 struct http_txn *txn;
1185 struct server *srv;
1186 char *path;
1187 int len, rewind;
1188
1189 /* 1: create the response header */
1190 trash.len = strlen(HTTP_302);
1191 memcpy(trash.str, HTTP_302, trash.len);
1192
1193 srv = objt_server(s->target);
1194
1195 /* 2: add the server's prefix */
1196 if (trash.len + srv->rdr_len > trash.size)
1197 return;
1198
1199 /* special prefix "/" means don't change URL */
1200 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
1201 memcpy(trash.str + trash.len, srv->rdr_pfx, srv->rdr_len);
1202 trash.len += srv->rdr_len;
1203 }
1204
1205 /* 3: add the request URI. Since it was already forwarded, we need
1206 * to temporarily rewind the buffer.
1207 */
1208 txn = s->txn;
1209 b_rew(s->req.buf, rewind = http_hdr_rewind(&txn->req));
1210
1211 path = http_get_path(txn);
1212 len = buffer_count(s->req.buf, path, b_ptr(s->req.buf, txn->req.sl.rq.u + txn->req.sl.rq.u_l));
1213
1214 b_adv(s->req.buf, rewind);
1215
1216 if (!path)
1217 return;
1218
1219 if (trash.len + len > trash.size - 4) /* 4 for CRLF-CRLF */
1220 return;
1221
1222 memcpy(trash.str + trash.len, path, len);
1223 trash.len += len;
1224
1225 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
1226 memcpy(trash.str + trash.len, "\r\nProxy-Connection: close\r\n\r\n", 29);
1227 trash.len += 29;
1228 } else {
1229 memcpy(trash.str + trash.len, "\r\nConnection: close\r\n\r\n", 23);
1230 trash.len += 23;
1231 }
1232
1233 /* prepare to return without error. */
1234 si_shutr(si);
1235 si_shutw(si);
1236 si->err_type = SI_ET_NONE;
1237 si->state = SI_ST_CLO;
1238
1239 /* send the message */
1240 http_server_error(s, si, SF_ERR_LOCAL, SF_FINST_C, 302, &trash);
1241
1242 /* FIXME: we should increase a counter of redirects per server and per backend. */
1243 srv_inc_sess_ctr(srv);
1244 srv_set_sess_last(srv);
1245 }
1246
1247 /* Return the error message corresponding to si->err_type. It is assumed
1248 * that the server side is closed. Note that err_type is actually a
1249 * bitmask, where almost only aborts may be cumulated with other
1250 * values. We consider that aborted operations are more important
1251 * than timeouts or errors due to the fact that nobody else in the
1252 * logs might explain incomplete retries. All others should avoid
1253 * being cumulated. It should normally not be possible to have multiple
1254 * aborts at once, but just in case, the first one in sequence is reported.
1255 * Note that connection errors appearing on the second request of a keep-alive
1256 * connection are not reported since this allows the client to retry.
1257 */
http_return_srv_error(struct stream * s,struct stream_interface * si)1258 void http_return_srv_error(struct stream *s, struct stream_interface *si)
1259 {
1260 int err_type = si->err_type;
1261
1262 if (err_type & SI_ET_QUEUE_ABRT)
1263 http_server_error(s, si, SF_ERR_CLICL, SF_FINST_Q,
1264 503, http_error_message(s, HTTP_ERR_503));
1265 else if (err_type & SI_ET_CONN_ABRT)
1266 http_server_error(s, si, SF_ERR_CLICL, SF_FINST_C,
1267 503, (s->txn->flags & TX_NOT_FIRST) ? NULL :
1268 http_error_message(s, HTTP_ERR_503));
1269 else if (err_type & SI_ET_QUEUE_TO)
1270 http_server_error(s, si, SF_ERR_SRVTO, SF_FINST_Q,
1271 503, http_error_message(s, HTTP_ERR_503));
1272 else if (err_type & SI_ET_QUEUE_ERR)
1273 http_server_error(s, si, SF_ERR_SRVCL, SF_FINST_Q,
1274 503, http_error_message(s, HTTP_ERR_503));
1275 else if (err_type & SI_ET_CONN_TO)
1276 http_server_error(s, si, SF_ERR_SRVTO, SF_FINST_C,
1277 503, (s->txn->flags & TX_NOT_FIRST) ? NULL :
1278 http_error_message(s, HTTP_ERR_503));
1279 else if (err_type & SI_ET_CONN_ERR)
1280 http_server_error(s, si, SF_ERR_SRVCL, SF_FINST_C,
1281 503, (s->flags & SF_SRV_REUSED) ? NULL :
1282 http_error_message(s, HTTP_ERR_503));
1283 else if (err_type & SI_ET_CONN_RES)
1284 http_server_error(s, si, SF_ERR_RESOURCE, SF_FINST_C,
1285 503, (s->txn->flags & TX_NOT_FIRST) ? NULL :
1286 http_error_message(s, HTTP_ERR_503));
1287 else /* SI_ET_CONN_OTHER and others */
1288 http_server_error(s, si, SF_ERR_INTERNAL, SF_FINST_C,
1289 500, http_error_message(s, HTTP_ERR_500));
1290 }
1291
1292 extern const char sess_term_cond[8];
1293 extern const char sess_fin_state[8];
1294 extern const char *monthname[12];
1295 struct pool_head *pool2_http_txn;
1296 struct pool_head *pool2_requri;
1297 struct pool_head *pool2_capture = NULL;
1298 struct pool_head *pool2_uniqueid;
1299
1300 /*
1301 * Capture headers from message starting at <som> according to header list
1302 * <cap_hdr>, and fill the <cap> pointers appropriately.
1303 */
capture_headers(char * som,struct hdr_idx * idx,char ** cap,struct cap_hdr * cap_hdr)1304 void capture_headers(char *som, struct hdr_idx *idx,
1305 char **cap, struct cap_hdr *cap_hdr)
1306 {
1307 char *eol, *sol, *col, *sov;
1308 int cur_idx;
1309 struct cap_hdr *h;
1310 int len;
1311
1312 sol = som + hdr_idx_first_pos(idx);
1313 cur_idx = hdr_idx_first_idx(idx);
1314
1315 while (cur_idx) {
1316 eol = sol + idx->v[cur_idx].len;
1317
1318 col = sol;
1319 while (col < eol && *col != ':')
1320 col++;
1321
1322 sov = col + 1;
1323 while (sov < eol && HTTP_IS_LWS(*sov))
1324 sov++;
1325
1326 for (h = cap_hdr; h; h = h->next) {
1327 if (h->namelen && (h->namelen == col - sol) &&
1328 (strncasecmp(sol, h->name, h->namelen) == 0)) {
1329 if (cap[h->index] == NULL)
1330 cap[h->index] =
1331 pool_alloc2(h->pool);
1332
1333 if (cap[h->index] == NULL) {
1334 Alert("HTTP capture : out of memory.\n");
1335 continue;
1336 }
1337
1338 len = eol - sov;
1339 if (len > h->len)
1340 len = h->len;
1341
1342 memcpy(cap[h->index], sov, len);
1343 cap[h->index][len]=0;
1344 }
1345 }
1346 sol = eol + idx->v[cur_idx].cr + 1;
1347 cur_idx = idx->v[cur_idx].next;
1348 }
1349 }
1350
1351
1352 /* either we find an LF at <ptr> or we jump to <bad>.
1353 */
1354 #define EXPECT_LF_HERE(ptr, bad, st) do { if (unlikely(*(ptr) != '\n')) { state = st; goto bad;}; } while (0)
1355
1356 /* plays with variables <ptr>, <end> and <state>. Jumps to <good> if OK,
1357 * otherwise to <http_msg_ood> with <state> set to <st>.
1358 */
1359 #define EAT_AND_JUMP_OR_RETURN(good, st) do { \
1360 ptr++; \
1361 if (likely(ptr < end)) \
1362 goto good; \
1363 else { \
1364 state = (st); \
1365 goto http_msg_ood; \
1366 } \
1367 } while (0)
1368
1369
1370 /*
1371 * This function parses a status line between <ptr> and <end>, starting with
1372 * parser state <state>. Only states HTTP_MSG_RPVER, HTTP_MSG_RPVER_SP,
1373 * HTTP_MSG_RPCODE, HTTP_MSG_RPCODE_SP and HTTP_MSG_RPREASON are handled. Others
1374 * will give undefined results.
1375 * Note that it is upon the caller's responsibility to ensure that ptr < end,
1376 * and that msg->sol points to the beginning of the response.
1377 * If a complete line is found (which implies that at least one CR or LF is
1378 * found before <end>, the updated <ptr> is returned, otherwise NULL is
1379 * returned indicating an incomplete line (which does not mean that parts have
1380 * not been updated). In the incomplete case, if <ret_ptr> or <ret_state> are
1381 * non-NULL, they are fed with the new <ptr> and <state> values to be passed
1382 * upon next call.
1383 *
1384 * This function was intentionally designed to be called from
1385 * http_msg_analyzer() with the lowest overhead. It should integrate perfectly
1386 * within its state machine and use the same macros, hence the need for same
1387 * labels and variable names. Note that msg->sol is left unchanged.
1388 */
http_parse_stsline(struct http_msg * msg,enum ht_state state,const char * ptr,const char * end,unsigned int * ret_ptr,enum ht_state * ret_state)1389 const char *http_parse_stsline(struct http_msg *msg,
1390 enum ht_state state, const char *ptr, const char *end,
1391 unsigned int *ret_ptr, enum ht_state *ret_state)
1392 {
1393 const char *msg_start = msg->chn->buf->p;
1394
1395 switch (state) {
1396 case HTTP_MSG_RPVER:
1397 http_msg_rpver:
1398 if (likely(HTTP_IS_VER_TOKEN(*ptr)))
1399 EAT_AND_JUMP_OR_RETURN(http_msg_rpver, HTTP_MSG_RPVER);
1400
1401 if (likely(HTTP_IS_SPHT(*ptr))) {
1402 msg->sl.st.v_l = ptr - msg_start;
1403 EAT_AND_JUMP_OR_RETURN(http_msg_rpver_sp, HTTP_MSG_RPVER_SP);
1404 }
1405 msg->err_state = HTTP_MSG_RPVER;
1406 state = HTTP_MSG_ERROR;
1407 break;
1408
1409 case HTTP_MSG_RPVER_SP:
1410 http_msg_rpver_sp:
1411 if (likely(!HTTP_IS_LWS(*ptr))) {
1412 msg->sl.st.c = ptr - msg_start;
1413 goto http_msg_rpcode;
1414 }
1415 if (likely(HTTP_IS_SPHT(*ptr)))
1416 EAT_AND_JUMP_OR_RETURN(http_msg_rpver_sp, HTTP_MSG_RPVER_SP);
1417 /* so it's a CR/LF, this is invalid */
1418 msg->err_state = HTTP_MSG_RPVER_SP;
1419 state = HTTP_MSG_ERROR;
1420 break;
1421
1422 case HTTP_MSG_RPCODE:
1423 http_msg_rpcode:
1424 if (likely(!HTTP_IS_LWS(*ptr)))
1425 EAT_AND_JUMP_OR_RETURN(http_msg_rpcode, HTTP_MSG_RPCODE);
1426
1427 if (likely(HTTP_IS_SPHT(*ptr))) {
1428 msg->sl.st.c_l = ptr - msg_start - msg->sl.st.c;
1429 EAT_AND_JUMP_OR_RETURN(http_msg_rpcode_sp, HTTP_MSG_RPCODE_SP);
1430 }
1431
1432 /* so it's a CR/LF, so there is no reason phrase */
1433 msg->sl.st.c_l = ptr - msg_start - msg->sl.st.c;
1434 http_msg_rsp_reason:
1435 /* FIXME: should we support HTTP responses without any reason phrase ? */
1436 msg->sl.st.r = ptr - msg_start;
1437 msg->sl.st.r_l = 0;
1438 goto http_msg_rpline_eol;
1439
1440 case HTTP_MSG_RPCODE_SP:
1441 http_msg_rpcode_sp:
1442 if (likely(!HTTP_IS_LWS(*ptr))) {
1443 msg->sl.st.r = ptr - msg_start;
1444 goto http_msg_rpreason;
1445 }
1446 if (likely(HTTP_IS_SPHT(*ptr)))
1447 EAT_AND_JUMP_OR_RETURN(http_msg_rpcode_sp, HTTP_MSG_RPCODE_SP);
1448 /* so it's a CR/LF, so there is no reason phrase */
1449 goto http_msg_rsp_reason;
1450
1451 case HTTP_MSG_RPREASON:
1452 http_msg_rpreason:
1453 if (likely(!HTTP_IS_CRLF(*ptr)))
1454 EAT_AND_JUMP_OR_RETURN(http_msg_rpreason, HTTP_MSG_RPREASON);
1455 msg->sl.st.r_l = ptr - msg_start - msg->sl.st.r;
1456 http_msg_rpline_eol:
1457 /* We have seen the end of line. Note that we do not
1458 * necessarily have the \n yet, but at least we know that we
1459 * have EITHER \r OR \n, otherwise the response would not be
1460 * complete. We can then record the response length and return
1461 * to the caller which will be able to register it.
1462 */
1463 msg->sl.st.l = ptr - msg_start - msg->sol;
1464 return ptr;
1465
1466 default:
1467 #ifdef DEBUG_FULL
1468 fprintf(stderr, "FIXME !!!! impossible state at %s:%d = %d\n", __FILE__, __LINE__, state);
1469 exit(1);
1470 #endif
1471 ;
1472 }
1473
1474 http_msg_ood:
1475 /* out of valid data */
1476 if (ret_state)
1477 *ret_state = state;
1478 if (ret_ptr)
1479 *ret_ptr = ptr - msg_start;
1480 return NULL;
1481 }
1482
1483 /*
1484 * This function parses a request line between <ptr> and <end>, starting with
1485 * parser state <state>. Only states HTTP_MSG_RQMETH, HTTP_MSG_RQMETH_SP,
1486 * HTTP_MSG_RQURI, HTTP_MSG_RQURI_SP and HTTP_MSG_RQVER are handled. Others
1487 * will give undefined results.
1488 * Note that it is upon the caller's responsibility to ensure that ptr < end,
1489 * and that msg->sol points to the beginning of the request.
1490 * If a complete line is found (which implies that at least one CR or LF is
1491 * found before <end>, the updated <ptr> is returned, otherwise NULL is
1492 * returned indicating an incomplete line (which does not mean that parts have
1493 * not been updated). In the incomplete case, if <ret_ptr> or <ret_state> are
1494 * non-NULL, they are fed with the new <ptr> and <state> values to be passed
1495 * upon next call.
1496 *
1497 * This function was intentionally designed to be called from
1498 * http_msg_analyzer() with the lowest overhead. It should integrate perfectly
1499 * within its state machine and use the same macros, hence the need for same
1500 * labels and variable names. Note that msg->sol is left unchanged.
1501 */
http_parse_reqline(struct http_msg * msg,enum ht_state state,const char * ptr,const char * end,unsigned int * ret_ptr,enum ht_state * ret_state)1502 const char *http_parse_reqline(struct http_msg *msg,
1503 enum ht_state state, const char *ptr, const char *end,
1504 unsigned int *ret_ptr, enum ht_state *ret_state)
1505 {
1506 const char *msg_start = msg->chn->buf->p;
1507
1508 switch (state) {
1509 case HTTP_MSG_RQMETH:
1510 http_msg_rqmeth:
1511 if (likely(HTTP_IS_TOKEN(*ptr)))
1512 EAT_AND_JUMP_OR_RETURN(http_msg_rqmeth, HTTP_MSG_RQMETH);
1513
1514 if (likely(HTTP_IS_SPHT(*ptr))) {
1515 msg->sl.rq.m_l = ptr - msg_start;
1516 EAT_AND_JUMP_OR_RETURN(http_msg_rqmeth_sp, HTTP_MSG_RQMETH_SP);
1517 }
1518
1519 if (likely(HTTP_IS_CRLF(*ptr))) {
1520 /* HTTP 0.9 request */
1521 msg->sl.rq.m_l = ptr - msg_start;
1522 http_msg_req09_uri:
1523 msg->sl.rq.u = ptr - msg_start;
1524 http_msg_req09_uri_e:
1525 msg->sl.rq.u_l = ptr - msg_start - msg->sl.rq.u;
1526 http_msg_req09_ver:
1527 msg->sl.rq.v = ptr - msg_start;
1528 msg->sl.rq.v_l = 0;
1529 goto http_msg_rqline_eol;
1530 }
1531 msg->err_state = HTTP_MSG_RQMETH;
1532 state = HTTP_MSG_ERROR;
1533 break;
1534
1535 case HTTP_MSG_RQMETH_SP:
1536 http_msg_rqmeth_sp:
1537 if (likely(!HTTP_IS_LWS(*ptr))) {
1538 msg->sl.rq.u = ptr - msg_start;
1539 goto http_msg_rquri;
1540 }
1541 if (likely(HTTP_IS_SPHT(*ptr)))
1542 EAT_AND_JUMP_OR_RETURN(http_msg_rqmeth_sp, HTTP_MSG_RQMETH_SP);
1543 /* so it's a CR/LF, meaning an HTTP 0.9 request */
1544 goto http_msg_req09_uri;
1545
1546 case HTTP_MSG_RQURI:
1547 http_msg_rquri:
1548 #if defined(__x86_64__) || \
1549 defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) || \
1550 defined(__ARM_ARCH_7A__)
1551 /* speedup: skip bytes not between 0x21 and 0x7e inclusive */
1552 while (ptr <= end - sizeof(int)) {
1553 int x = *(int *)ptr - 0x21212121;
1554 if (x & 0x80808080)
1555 break;
1556
1557 x -= 0x5e5e5e5e;
1558 if (!(x & 0x80808080))
1559 break;
1560
1561 ptr += sizeof(int);
1562 }
1563 #endif
1564 if (ptr >= end) {
1565 state = HTTP_MSG_RQURI;
1566 goto http_msg_ood;
1567 }
1568 http_msg_rquri2:
1569 if (likely((unsigned char)(*ptr - 33) <= 93)) /* 33 to 126 included */
1570 EAT_AND_JUMP_OR_RETURN(http_msg_rquri2, HTTP_MSG_RQURI);
1571
1572 if (likely(HTTP_IS_SPHT(*ptr))) {
1573 msg->sl.rq.u_l = ptr - msg_start - msg->sl.rq.u;
1574 EAT_AND_JUMP_OR_RETURN(http_msg_rquri_sp, HTTP_MSG_RQURI_SP);
1575 }
1576
1577 if (likely((unsigned char)*ptr >= 128)) {
1578 /* non-ASCII chars are forbidden unless option
1579 * accept-invalid-http-request is enabled in the frontend.
1580 * In any case, we capture the faulty char.
1581 */
1582 if (msg->err_pos < -1)
1583 goto invalid_char;
1584 if (msg->err_pos == -1)
1585 msg->err_pos = ptr - msg_start;
1586 EAT_AND_JUMP_OR_RETURN(http_msg_rquri, HTTP_MSG_RQURI);
1587 }
1588
1589 if (likely(HTTP_IS_CRLF(*ptr))) {
1590 /* so it's a CR/LF, meaning an HTTP 0.9 request */
1591 goto http_msg_req09_uri_e;
1592 }
1593
1594 /* OK forbidden chars, 0..31 or 127 */
1595 invalid_char:
1596 msg->err_pos = ptr - msg_start;
1597 msg->err_state = HTTP_MSG_RQURI;
1598 state = HTTP_MSG_ERROR;
1599 break;
1600
1601 case HTTP_MSG_RQURI_SP:
1602 http_msg_rquri_sp:
1603 if (likely(!HTTP_IS_LWS(*ptr))) {
1604 msg->sl.rq.v = ptr - msg_start;
1605 goto http_msg_rqver;
1606 }
1607 if (likely(HTTP_IS_SPHT(*ptr)))
1608 EAT_AND_JUMP_OR_RETURN(http_msg_rquri_sp, HTTP_MSG_RQURI_SP);
1609 /* so it's a CR/LF, meaning an HTTP 0.9 request */
1610 goto http_msg_req09_ver;
1611
1612 case HTTP_MSG_RQVER:
1613 http_msg_rqver:
1614 if (likely(HTTP_IS_VER_TOKEN(*ptr)))
1615 EAT_AND_JUMP_OR_RETURN(http_msg_rqver, HTTP_MSG_RQVER);
1616
1617 if (likely(HTTP_IS_CRLF(*ptr))) {
1618 msg->sl.rq.v_l = ptr - msg_start - msg->sl.rq.v;
1619 http_msg_rqline_eol:
1620 /* We have seen the end of line. Note that we do not
1621 * necessarily have the \n yet, but at least we know that we
1622 * have EITHER \r OR \n, otherwise the request would not be
1623 * complete. We can then record the request length and return
1624 * to the caller which will be able to register it.
1625 */
1626 msg->sl.rq.l = ptr - msg_start - msg->sol;
1627 return ptr;
1628 }
1629
1630 /* neither an HTTP_VER token nor a CRLF */
1631 msg->err_state = HTTP_MSG_RQVER;
1632 state = HTTP_MSG_ERROR;
1633 break;
1634
1635 default:
1636 #ifdef DEBUG_FULL
1637 fprintf(stderr, "FIXME !!!! impossible state at %s:%d = %d\n", __FILE__, __LINE__, state);
1638 exit(1);
1639 #endif
1640 ;
1641 }
1642
1643 http_msg_ood:
1644 /* out of valid data */
1645 if (ret_state)
1646 *ret_state = state;
1647 if (ret_ptr)
1648 *ret_ptr = ptr - msg_start;
1649 return NULL;
1650 }
1651
1652 /*
1653 * Returns the data from Authorization header. Function may be called more
1654 * than once so data is stored in txn->auth_data. When no header is found
1655 * or auth method is unknown auth_method is set to HTTP_AUTH_WRONG to avoid
1656 * searching again for something we are unable to find anyway. However, if
1657 * the result if valid, the cache is not reused because we would risk to
1658 * have the credentials overwritten by another stream in parallel.
1659 */
1660
1661 /* This bufffer is initialized in the file 'src/haproxy.c'. This length is
1662 * set according to global.tune.bufsize.
1663 */
1664 char *get_http_auth_buff;
1665
1666 int
get_http_auth(struct stream * s)1667 get_http_auth(struct stream *s)
1668 {
1669
1670 struct http_txn *txn = s->txn;
1671 struct chunk auth_method;
1672 struct hdr_ctx ctx;
1673 char *h, *p;
1674 int len;
1675
1676 #ifdef DEBUG_AUTH
1677 printf("Auth for stream %p: %d\n", s, txn->auth.method);
1678 #endif
1679
1680 if (txn->auth.method == HTTP_AUTH_WRONG)
1681 return 0;
1682
1683 txn->auth.method = HTTP_AUTH_WRONG;
1684
1685 ctx.idx = 0;
1686
1687 if (txn->flags & TX_USE_PX_CONN) {
1688 h = "Proxy-Authorization";
1689 len = strlen(h);
1690 } else {
1691 h = "Authorization";
1692 len = strlen(h);
1693 }
1694
1695 if (!http_find_header2(h, len, s->req.buf->p, &txn->hdr_idx, &ctx))
1696 return 0;
1697
1698 h = ctx.line + ctx.val;
1699
1700 p = memchr(h, ' ', ctx.vlen);
1701 len = p - h;
1702 if (!p || len <= 0)
1703 return 0;
1704
1705 if (chunk_initlen(&auth_method, h, 0, len) != 1)
1706 return 0;
1707
1708 chunk_initlen(&txn->auth.method_data, p + 1, 0, ctx.vlen - len - 1);
1709
1710 if (!strncasecmp("Basic", auth_method.str, auth_method.len)) {
1711
1712 len = base64dec(txn->auth.method_data.str, txn->auth.method_data.len,
1713 get_http_auth_buff, global.tune.bufsize - 1);
1714
1715 if (len < 0)
1716 return 0;
1717
1718
1719 get_http_auth_buff[len] = '\0';
1720
1721 p = strchr(get_http_auth_buff, ':');
1722
1723 if (!p)
1724 return 0;
1725
1726 txn->auth.user = get_http_auth_buff;
1727 *p = '\0';
1728 txn->auth.pass = p+1;
1729
1730 txn->auth.method = HTTP_AUTH_BASIC;
1731 return 1;
1732 }
1733
1734 return 0;
1735 }
1736
1737
1738 /*
1739 * This function parses an HTTP message, either a request or a response,
1740 * depending on the initial msg->msg_state. The caller is responsible for
1741 * ensuring that the message does not wrap. The function can be preempted
1742 * everywhere when data are missing and recalled at the exact same location
1743 * with no information loss. The message may even be realigned between two
1744 * calls. The header index is re-initialized when switching from
1745 * MSG_R[PQ]BEFORE to MSG_RPVER|MSG_RQMETH. It modifies msg->sol among other
1746 * fields. Note that msg->sol will be initialized after completing the first
1747 * state, so that none of the msg pointers has to be initialized prior to the
1748 * first call.
1749 */
http_msg_analyzer(struct http_msg * msg,struct hdr_idx * idx)1750 void http_msg_analyzer(struct http_msg *msg, struct hdr_idx *idx)
1751 {
1752 enum ht_state state; /* updated only when leaving the FSM */
1753 register char *ptr, *end; /* request pointers, to avoid dereferences */
1754 struct buffer *buf;
1755
1756 state = msg->msg_state;
1757 buf = msg->chn->buf;
1758 ptr = buf->p + msg->next;
1759 end = buf->p + buf->i;
1760
1761 if (unlikely(ptr >= end))
1762 goto http_msg_ood;
1763
1764 switch (state) {
1765 /*
1766 * First, states that are specific to the response only.
1767 * We check them first so that request and headers are
1768 * closer to each other (accessed more often).
1769 */
1770 case HTTP_MSG_RPBEFORE:
1771 http_msg_rpbefore:
1772 if (likely(HTTP_IS_TOKEN(*ptr))) {
1773 /* we have a start of message, but we have to check
1774 * first if we need to remove some CRLF. We can only
1775 * do this when o=0.
1776 */
1777 if (unlikely(ptr != buf->p)) {
1778 if (buf->o)
1779 goto http_msg_ood;
1780 /* Remove empty leading lines, as recommended by RFC2616. */
1781 bi_fast_delete(buf, ptr - buf->p);
1782 }
1783 msg->sol = 0;
1784 msg->sl.st.l = 0; /* used in debug mode */
1785 hdr_idx_init(idx);
1786 state = HTTP_MSG_RPVER;
1787 goto http_msg_rpver;
1788 }
1789
1790 if (unlikely(!HTTP_IS_CRLF(*ptr))) {
1791 state = HTTP_MSG_RPBEFORE;
1792 goto http_msg_invalid;
1793 }
1794
1795 if (unlikely(*ptr == '\n'))
1796 EAT_AND_JUMP_OR_RETURN(http_msg_rpbefore, HTTP_MSG_RPBEFORE);
1797 EAT_AND_JUMP_OR_RETURN(http_msg_rpbefore_cr, HTTP_MSG_RPBEFORE_CR);
1798 /* stop here */
1799
1800 case HTTP_MSG_RPBEFORE_CR:
1801 http_msg_rpbefore_cr:
1802 EXPECT_LF_HERE(ptr, http_msg_invalid, HTTP_MSG_RPBEFORE_CR);
1803 EAT_AND_JUMP_OR_RETURN(http_msg_rpbefore, HTTP_MSG_RPBEFORE);
1804 /* stop here */
1805
1806 case HTTP_MSG_RPVER:
1807 http_msg_rpver:
1808 case HTTP_MSG_RPVER_SP:
1809 case HTTP_MSG_RPCODE:
1810 case HTTP_MSG_RPCODE_SP:
1811 case HTTP_MSG_RPREASON:
1812 ptr = (char *)http_parse_stsline(msg,
1813 state, ptr, end,
1814 &msg->next, &msg->msg_state);
1815 if (unlikely(!ptr))
1816 return;
1817
1818 /* we have a full response and we know that we have either a CR
1819 * or an LF at <ptr>.
1820 */
1821 hdr_idx_set_start(idx, msg->sl.st.l, *ptr == '\r');
1822
1823 msg->sol = ptr - buf->p;
1824 if (likely(*ptr == '\r'))
1825 EAT_AND_JUMP_OR_RETURN(http_msg_rpline_end, HTTP_MSG_RPLINE_END);
1826 goto http_msg_rpline_end;
1827
1828 case HTTP_MSG_RPLINE_END:
1829 http_msg_rpline_end:
1830 /* msg->sol must point to the first of CR or LF. */
1831 EXPECT_LF_HERE(ptr, http_msg_invalid, HTTP_MSG_RPLINE_END);
1832 EAT_AND_JUMP_OR_RETURN(http_msg_hdr_first, HTTP_MSG_HDR_FIRST);
1833 /* stop here */
1834
1835 /*
1836 * Second, states that are specific to the request only
1837 */
1838 case HTTP_MSG_RQBEFORE:
1839 http_msg_rqbefore:
1840 if (likely(HTTP_IS_TOKEN(*ptr))) {
1841 /* we have a start of message, but we have to check
1842 * first if we need to remove some CRLF. We can only
1843 * do this when o=0.
1844 */
1845 if (likely(ptr != buf->p)) {
1846 if (buf->o)
1847 goto http_msg_ood;
1848 /* Remove empty leading lines, as recommended by RFC2616. */
1849 bi_fast_delete(buf, ptr - buf->p);
1850 }
1851 msg->sol = 0;
1852 msg->sl.rq.l = 0; /* used in debug mode */
1853 state = HTTP_MSG_RQMETH;
1854 goto http_msg_rqmeth;
1855 }
1856
1857 if (unlikely(!HTTP_IS_CRLF(*ptr))) {
1858 state = HTTP_MSG_RQBEFORE;
1859 goto http_msg_invalid;
1860 }
1861
1862 if (unlikely(*ptr == '\n'))
1863 EAT_AND_JUMP_OR_RETURN(http_msg_rqbefore, HTTP_MSG_RQBEFORE);
1864 EAT_AND_JUMP_OR_RETURN(http_msg_rqbefore_cr, HTTP_MSG_RQBEFORE_CR);
1865 /* stop here */
1866
1867 case HTTP_MSG_RQBEFORE_CR:
1868 http_msg_rqbefore_cr:
1869 EXPECT_LF_HERE(ptr, http_msg_invalid, HTTP_MSG_RQBEFORE_CR);
1870 EAT_AND_JUMP_OR_RETURN(http_msg_rqbefore, HTTP_MSG_RQBEFORE);
1871 /* stop here */
1872
1873 case HTTP_MSG_RQMETH:
1874 http_msg_rqmeth:
1875 case HTTP_MSG_RQMETH_SP:
1876 case HTTP_MSG_RQURI:
1877 case HTTP_MSG_RQURI_SP:
1878 case HTTP_MSG_RQVER:
1879 ptr = (char *)http_parse_reqline(msg,
1880 state, ptr, end,
1881 &msg->next, &msg->msg_state);
1882 if (unlikely(!ptr))
1883 return;
1884
1885 /* we have a full request and we know that we have either a CR
1886 * or an LF at <ptr>.
1887 */
1888 hdr_idx_set_start(idx, msg->sl.rq.l, *ptr == '\r');
1889
1890 msg->sol = ptr - buf->p;
1891 if (likely(*ptr == '\r'))
1892 EAT_AND_JUMP_OR_RETURN(http_msg_rqline_end, HTTP_MSG_RQLINE_END);
1893 goto http_msg_rqline_end;
1894
1895 case HTTP_MSG_RQLINE_END:
1896 http_msg_rqline_end:
1897 /* check for HTTP/0.9 request : no version information available.
1898 * msg->sol must point to the first of CR or LF.
1899 */
1900 if (unlikely(msg->sl.rq.v_l == 0))
1901 goto http_msg_last_lf;
1902
1903 EXPECT_LF_HERE(ptr, http_msg_invalid, HTTP_MSG_RQLINE_END);
1904 EAT_AND_JUMP_OR_RETURN(http_msg_hdr_first, HTTP_MSG_HDR_FIRST);
1905 /* stop here */
1906
1907 /*
1908 * Common states below
1909 */
1910 case HTTP_MSG_HDR_FIRST:
1911 http_msg_hdr_first:
1912 msg->sol = ptr - buf->p;
1913 if (likely(!HTTP_IS_CRLF(*ptr))) {
1914 goto http_msg_hdr_name;
1915 }
1916
1917 if (likely(*ptr == '\r'))
1918 EAT_AND_JUMP_OR_RETURN(http_msg_last_lf, HTTP_MSG_LAST_LF);
1919 goto http_msg_last_lf;
1920
1921 case HTTP_MSG_HDR_NAME:
1922 http_msg_hdr_name:
1923 /* assumes msg->sol points to the first char */
1924 if (likely(HTTP_IS_TOKEN(*ptr)))
1925 EAT_AND_JUMP_OR_RETURN(http_msg_hdr_name, HTTP_MSG_HDR_NAME);
1926
1927 if (likely(*ptr == ':'))
1928 EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_sp, HTTP_MSG_HDR_L1_SP);
1929
1930 if (likely(msg->err_pos < -1) || *ptr == '\n') {
1931 state = HTTP_MSG_HDR_NAME;
1932 goto http_msg_invalid;
1933 }
1934
1935 if (msg->err_pos == -1) /* capture error pointer */
1936 msg->err_pos = ptr - buf->p; /* >= 0 now */
1937
1938 /* and we still accept this non-token character */
1939 EAT_AND_JUMP_OR_RETURN(http_msg_hdr_name, HTTP_MSG_HDR_NAME);
1940
1941 case HTTP_MSG_HDR_L1_SP:
1942 http_msg_hdr_l1_sp:
1943 /* assumes msg->sol points to the first char */
1944 if (likely(HTTP_IS_SPHT(*ptr)))
1945 EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_sp, HTTP_MSG_HDR_L1_SP);
1946
1947 /* header value can be basically anything except CR/LF */
1948 msg->sov = ptr - buf->p;
1949
1950 if (likely(!HTTP_IS_CRLF(*ptr))) {
1951 goto http_msg_hdr_val;
1952 }
1953
1954 if (likely(*ptr == '\r'))
1955 EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_lf, HTTP_MSG_HDR_L1_LF);
1956 goto http_msg_hdr_l1_lf;
1957
1958 case HTTP_MSG_HDR_L1_LF:
1959 http_msg_hdr_l1_lf:
1960 EXPECT_LF_HERE(ptr, http_msg_invalid, HTTP_MSG_HDR_L1_LF);
1961 EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_lws, HTTP_MSG_HDR_L1_LWS);
1962
1963 case HTTP_MSG_HDR_L1_LWS:
1964 http_msg_hdr_l1_lws:
1965 if (likely(HTTP_IS_SPHT(*ptr))) {
1966 /* replace HT,CR,LF with spaces */
1967 for (; buf->p + msg->sov < ptr; msg->sov++)
1968 buf->p[msg->sov] = ' ';
1969 goto http_msg_hdr_l1_sp;
1970 }
1971 /* we had a header consisting only in spaces ! */
1972 msg->eol = msg->sov;
1973 goto http_msg_complete_header;
1974
1975 case HTTP_MSG_HDR_VAL:
1976 http_msg_hdr_val:
1977 /* assumes msg->sol points to the first char, and msg->sov
1978 * points to the first character of the value.
1979 */
1980
1981 /* speedup: we'll skip packs of 4 or 8 bytes not containing bytes 0x0D
1982 * and lower. In fact since most of the time is spent in the loop, we
1983 * also remove the sign bit test so that bytes 0x8e..0x0d break the
1984 * loop, but we don't care since they're very rare in header values.
1985 */
1986 #if defined(__x86_64__)
1987 while (ptr <= end - sizeof(long)) {
1988 if ((*(long *)ptr - 0x0e0e0e0e0e0e0e0eULL) & 0x8080808080808080ULL)
1989 goto http_msg_hdr_val2;
1990 ptr += sizeof(long);
1991 }
1992 #endif
1993 #if defined(__x86_64__) || \
1994 defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) || \
1995 defined(__ARM_ARCH_7A__)
1996 while (ptr <= end - sizeof(int)) {
1997 if ((*(int*)ptr - 0x0e0e0e0e) & 0x80808080)
1998 goto http_msg_hdr_val2;
1999 ptr += sizeof(int);
2000 }
2001 #endif
2002 if (ptr >= end) {
2003 state = HTTP_MSG_HDR_VAL;
2004 goto http_msg_ood;
2005 }
2006 http_msg_hdr_val2:
2007 if (likely(!HTTP_IS_CRLF(*ptr)))
2008 EAT_AND_JUMP_OR_RETURN(http_msg_hdr_val2, HTTP_MSG_HDR_VAL);
2009
2010 msg->eol = ptr - buf->p;
2011 /* Note: we could also copy eol into ->eoh so that we have the
2012 * real header end in case it ends with lots of LWS, but is this
2013 * really needed ?
2014 */
2015 if (likely(*ptr == '\r'))
2016 EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l2_lf, HTTP_MSG_HDR_L2_LF);
2017 goto http_msg_hdr_l2_lf;
2018
2019 case HTTP_MSG_HDR_L2_LF:
2020 http_msg_hdr_l2_lf:
2021 EXPECT_LF_HERE(ptr, http_msg_invalid, HTTP_MSG_HDR_L2_LF);
2022 EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l2_lws, HTTP_MSG_HDR_L2_LWS);
2023
2024 case HTTP_MSG_HDR_L2_LWS:
2025 http_msg_hdr_l2_lws:
2026 if (unlikely(HTTP_IS_SPHT(*ptr))) {
2027 /* LWS: replace HT,CR,LF with spaces */
2028 for (; buf->p + msg->eol < ptr; msg->eol++)
2029 buf->p[msg->eol] = ' ';
2030 goto http_msg_hdr_val;
2031 }
2032 http_msg_complete_header:
2033 /*
2034 * It was a new header, so the last one is finished.
2035 * Assumes msg->sol points to the first char, msg->sov points
2036 * to the first character of the value and msg->eol to the
2037 * first CR or LF so we know how the line ends. We insert last
2038 * header into the index.
2039 */
2040 if (unlikely(hdr_idx_add(msg->eol - msg->sol, buf->p[msg->eol] == '\r',
2041 idx, idx->tail) < 0)) {
2042 state = HTTP_MSG_HDR_L2_LWS;
2043 goto http_msg_invalid;
2044 }
2045
2046 msg->sol = ptr - buf->p;
2047 if (likely(!HTTP_IS_CRLF(*ptr))) {
2048 goto http_msg_hdr_name;
2049 }
2050
2051 if (likely(*ptr == '\r'))
2052 EAT_AND_JUMP_OR_RETURN(http_msg_last_lf, HTTP_MSG_LAST_LF);
2053 goto http_msg_last_lf;
2054
2055 case HTTP_MSG_LAST_LF:
2056 http_msg_last_lf:
2057 /* Assumes msg->sol points to the first of either CR or LF.
2058 * Sets ->sov and ->next to the total header length, ->eoh to
2059 * the last CRLF, and ->eol to the last CRLF length (1 or 2).
2060 */
2061 EXPECT_LF_HERE(ptr, http_msg_invalid, HTTP_MSG_LAST_LF);
2062 ptr++;
2063 msg->sov = msg->next = ptr - buf->p;
2064 msg->eoh = msg->sol;
2065 msg->sol = 0;
2066 msg->eol = msg->sov - msg->eoh;
2067 msg->msg_state = HTTP_MSG_BODY;
2068 return;
2069
2070 case HTTP_MSG_ERROR:
2071 /* this may only happen if we call http_msg_analyser() twice with an error */
2072 break;
2073
2074 default:
2075 #ifdef DEBUG_FULL
2076 fprintf(stderr, "FIXME !!!! impossible state at %s:%d = %d\n", __FILE__, __LINE__, state);
2077 exit(1);
2078 #endif
2079 ;
2080 }
2081 http_msg_ood:
2082 /* out of data */
2083 msg->msg_state = state;
2084 msg->next = ptr - buf->p;
2085 return;
2086
2087 http_msg_invalid:
2088 /* invalid message */
2089 msg->err_state = state;
2090 msg->msg_state = HTTP_MSG_ERROR;
2091 msg->next = ptr - buf->p;
2092 return;
2093 }
2094
2095 /* convert an HTTP/0.9 request into an HTTP/1.0 request. Returns 1 if the
2096 * conversion succeeded, 0 in case of error. If the request was already 1.X,
2097 * nothing is done and 1 is returned.
2098 */
http_upgrade_v09_to_v10(struct http_txn * txn)2099 static int http_upgrade_v09_to_v10(struct http_txn *txn)
2100 {
2101 int delta;
2102 char *cur_end;
2103 struct http_msg *msg = &txn->req;
2104
2105 if (msg->sl.rq.v_l != 0)
2106 return 1;
2107
2108 /* RFC 1945 allows only GET for HTTP/0.9 requests */
2109 if (txn->meth != HTTP_METH_GET)
2110 return 0;
2111
2112 cur_end = msg->chn->buf->p + msg->sl.rq.l;
2113
2114 if (msg->sl.rq.u_l == 0) {
2115 /* HTTP/0.9 requests *must* have a request URI, per RFC 1945 */
2116 return 0;
2117 }
2118 /* add HTTP version */
2119 delta = buffer_replace2(msg->chn->buf, cur_end, cur_end, " HTTP/1.0\r\n", 11);
2120 http_msg_move_end(msg, delta);
2121 cur_end += delta;
2122 cur_end = (char *)http_parse_reqline(msg,
2123 HTTP_MSG_RQMETH,
2124 msg->chn->buf->p, cur_end + 1,
2125 NULL, NULL);
2126 if (unlikely(!cur_end))
2127 return 0;
2128
2129 /* we have a full HTTP/1.0 request now and we know that
2130 * we have either a CR or an LF at <ptr>.
2131 */
2132 hdr_idx_set_start(&txn->hdr_idx, msg->sl.rq.l, *cur_end == '\r');
2133 return 1;
2134 }
2135
2136 /* Parse the Connection: header of an HTTP request, looking for both "close"
2137 * and "keep-alive" values. If we already know that some headers may safely
2138 * be removed, we remove them now. The <to_del> flags are used for that :
2139 * - bit 0 means remove "close" headers (in HTTP/1.0 requests/responses)
2140 * - bit 1 means remove "keep-alive" headers (in HTTP/1.1 reqs/resp to 1.1).
2141 * Presence of the "Upgrade" token is also checked and reported.
2142 * The TX_HDR_CONN_* flags are adjusted in txn->flags depending on what was
2143 * found, and TX_CON_*_SET is adjusted depending on what is left so only
2144 * harmless combinations may be removed. Do not call that after changes have
2145 * been processed.
2146 */
http_parse_connection_header(struct http_txn * txn,struct http_msg * msg,int to_del)2147 void http_parse_connection_header(struct http_txn *txn, struct http_msg *msg, int to_del)
2148 {
2149 struct hdr_ctx ctx;
2150 const char *hdr_val = "Connection";
2151 int hdr_len = 10;
2152
2153 if (txn->flags & TX_HDR_CONN_PRS)
2154 return;
2155
2156 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
2157 hdr_val = "Proxy-Connection";
2158 hdr_len = 16;
2159 }
2160
2161 ctx.idx = 0;
2162 txn->flags &= ~(TX_CON_KAL_SET|TX_CON_CLO_SET);
2163 while (http_find_header2(hdr_val, hdr_len, msg->chn->buf->p, &txn->hdr_idx, &ctx)) {
2164 if (ctx.vlen >= 10 && word_match(ctx.line + ctx.val, ctx.vlen, "keep-alive", 10)) {
2165 txn->flags |= TX_HDR_CONN_KAL;
2166 if (to_del & 2)
2167 http_remove_header2(msg, &txn->hdr_idx, &ctx);
2168 else
2169 txn->flags |= TX_CON_KAL_SET;
2170 }
2171 else if (ctx.vlen >= 5 && word_match(ctx.line + ctx.val, ctx.vlen, "close", 5)) {
2172 txn->flags |= TX_HDR_CONN_CLO;
2173 if (to_del & 1)
2174 http_remove_header2(msg, &txn->hdr_idx, &ctx);
2175 else
2176 txn->flags |= TX_CON_CLO_SET;
2177 }
2178 else if (ctx.vlen >= 7 && word_match(ctx.line + ctx.val, ctx.vlen, "upgrade", 7)) {
2179 txn->flags |= TX_HDR_CONN_UPG;
2180 }
2181 }
2182
2183 txn->flags |= TX_HDR_CONN_PRS;
2184 return;
2185 }
2186
2187 /* Apply desired changes on the Connection: header. Values may be removed and/or
2188 * added depending on the <wanted> flags, which are exclusively composed of
2189 * TX_CON_CLO_SET and TX_CON_KAL_SET, depending on what flags are desired. The
2190 * TX_CON_*_SET flags are adjusted in txn->flags depending on what is left.
2191 */
http_change_connection_header(struct http_txn * txn,struct http_msg * msg,int wanted)2192 void http_change_connection_header(struct http_txn *txn, struct http_msg *msg, int wanted)
2193 {
2194 struct hdr_ctx ctx;
2195 const char *hdr_val = "Connection";
2196 int hdr_len = 10;
2197
2198 ctx.idx = 0;
2199
2200
2201 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
2202 hdr_val = "Proxy-Connection";
2203 hdr_len = 16;
2204 }
2205
2206 txn->flags &= ~(TX_CON_CLO_SET | TX_CON_KAL_SET);
2207 while (http_find_header2(hdr_val, hdr_len, msg->chn->buf->p, &txn->hdr_idx, &ctx)) {
2208 if (ctx.vlen >= 10 && word_match(ctx.line + ctx.val, ctx.vlen, "keep-alive", 10)) {
2209 if (wanted & TX_CON_KAL_SET)
2210 txn->flags |= TX_CON_KAL_SET;
2211 else
2212 http_remove_header2(msg, &txn->hdr_idx, &ctx);
2213 }
2214 else if (ctx.vlen >= 5 && word_match(ctx.line + ctx.val, ctx.vlen, "close", 5)) {
2215 if (wanted & TX_CON_CLO_SET)
2216 txn->flags |= TX_CON_CLO_SET;
2217 else
2218 http_remove_header2(msg, &txn->hdr_idx, &ctx);
2219 }
2220 }
2221
2222 if (wanted == (txn->flags & (TX_CON_CLO_SET|TX_CON_KAL_SET)))
2223 return;
2224
2225 if ((wanted & TX_CON_CLO_SET) && !(txn->flags & TX_CON_CLO_SET)) {
2226 txn->flags |= TX_CON_CLO_SET;
2227 hdr_val = "Connection: close";
2228 hdr_len = 17;
2229 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
2230 hdr_val = "Proxy-Connection: close";
2231 hdr_len = 23;
2232 }
2233 http_header_add_tail2(msg, &txn->hdr_idx, hdr_val, hdr_len);
2234 }
2235
2236 if ((wanted & TX_CON_KAL_SET) && !(txn->flags & TX_CON_KAL_SET)) {
2237 txn->flags |= TX_CON_KAL_SET;
2238 hdr_val = "Connection: keep-alive";
2239 hdr_len = 22;
2240 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
2241 hdr_val = "Proxy-Connection: keep-alive";
2242 hdr_len = 28;
2243 }
2244 http_header_add_tail2(msg, &txn->hdr_idx, hdr_val, hdr_len);
2245 }
2246 return;
2247 }
2248
2249 /* Parse the chunk size at msg->next. Once done, caller should adjust ->next to
2250 * point to the first byte of data after the chunk size, so that we know we can
2251 * forward exactly msg->next bytes. msg->sol contains the exact number of bytes
2252 * forming the chunk size. That way it is always possible to differentiate
2253 * between the start of the body and the start of the data. Return the number
2254 * of byte parsed on success, 0 when some data is missing, <0 on error. Note:
2255 * this function is designed to parse wrapped CRLF at the end of the buffer.
2256 */
http_parse_chunk_size(struct http_msg * msg)2257 static inline int http_parse_chunk_size(struct http_msg *msg)
2258 {
2259 const struct buffer *buf = msg->chn->buf;
2260 const char *ptr = b_ptr(buf, msg->next);
2261 const char *ptr_old = ptr;
2262 const char *end = buf->data + buf->size;
2263 const char *stop = bi_end(buf);
2264 unsigned int chunk = 0;
2265
2266 /* The chunk size is in the following form, though we are only
2267 * interested in the size and CRLF :
2268 * 1*HEXDIGIT *WSP *[ ';' extensions ] CRLF
2269 */
2270 while (1) {
2271 int c;
2272 if (ptr == stop)
2273 return 0;
2274 c = hex2i(*ptr);
2275 if (c < 0) /* not a hex digit anymore */
2276 break;
2277 if (unlikely(++ptr >= end))
2278 ptr = buf->data;
2279 if (chunk & 0xF8000000) /* integer overflow will occur if result >= 2GB */
2280 goto error;
2281 chunk = (chunk << 4) + c;
2282 }
2283
2284 /* empty size not allowed */
2285 if (unlikely(ptr == ptr_old))
2286 goto error;
2287
2288 while (HTTP_IS_SPHT(*ptr)) {
2289 if (++ptr >= end)
2290 ptr = buf->data;
2291 if (unlikely(ptr == stop))
2292 return 0;
2293 }
2294
2295 /* Up to there, we know that at least one byte is present at *ptr. Check
2296 * for the end of chunk size.
2297 */
2298 while (1) {
2299 if (likely(HTTP_IS_CRLF(*ptr))) {
2300 /* we now have a CR or an LF at ptr */
2301 if (likely(*ptr == '\r')) {
2302 if (++ptr >= end)
2303 ptr = buf->data;
2304 if (ptr == stop)
2305 return 0;
2306 }
2307
2308 if (*ptr != '\n')
2309 goto error;
2310 if (++ptr >= end)
2311 ptr = buf->data;
2312 /* done */
2313 break;
2314 }
2315 else if (*ptr == ';') {
2316 /* chunk extension, ends at next CRLF */
2317 if (++ptr >= end)
2318 ptr = buf->data;
2319 if (ptr == stop)
2320 return 0;
2321
2322 while (!HTTP_IS_CRLF(*ptr)) {
2323 if (++ptr >= end)
2324 ptr = buf->data;
2325 if (ptr == stop)
2326 return 0;
2327 }
2328 /* we have a CRLF now, loop above */
2329 continue;
2330 }
2331 else
2332 goto error;
2333 }
2334
2335 /* OK we found our CRLF and now <ptr> points to the next byte, which may
2336 * or may not be present. We save the number of bytes parsed into
2337 * msg->sol.
2338 */
2339 msg->sol = ptr - ptr_old;
2340 if (unlikely(ptr < ptr_old))
2341 msg->sol += buf->size;
2342 msg->chunk_len = chunk;
2343 msg->body_len += chunk;
2344 return msg->sol;
2345 error:
2346 msg->err_pos = buffer_count(buf, buf->p, ptr);
2347 return -1;
2348 }
2349
2350 /* This function skips trailers in the buffer associated with HTTP message
2351 * <msg>. The first visited position is msg->next. If the end of the trailers is
2352 * found, the function returns >0. So, the caller can automatically schedul it
2353 * to be forwarded, and switch msg->msg_state to HTTP_MSG_DONE. If not enough
2354 * data are available, the function does not change anything except maybe
2355 * msg->sol if it could parse some lines, and returns zero. If a parse error
2356 * is encountered, the function returns < 0 and does not change anything except
2357 * maybe msg->sol. Note that the message must already be in HTTP_MSG_TRAILERS
2358 * state before calling this function, which implies that all non-trailers data
2359 * have already been scheduled for forwarding, and that msg->next exactly
2360 * matches the length of trailers already parsed and not forwarded. It is also
2361 * important to note that this function is designed to be able to parse wrapped
2362 * headers at end of buffer.
2363 */
http_forward_trailers(struct http_msg * msg)2364 static int http_forward_trailers(struct http_msg *msg)
2365 {
2366 const struct buffer *buf = msg->chn->buf;
2367
2368 /* we have msg->next which points to next line. Look for CRLF. But
2369 * first, we reset msg->sol */
2370 msg->sol = 0;
2371 while (1) {
2372 const char *p1 = NULL, *p2 = NULL;
2373 const char *start = b_ptr(buf, msg->next + msg->sol);
2374 const char *stop = bi_end(buf);
2375 const char *ptr = start;
2376 int bytes = 0;
2377
2378 /* scan current line and stop at LF or CRLF */
2379 while (1) {
2380 if (ptr == stop)
2381 return 0;
2382
2383 if (*ptr == '\n') {
2384 if (!p1)
2385 p1 = ptr;
2386 p2 = ptr;
2387 break;
2388 }
2389
2390 if (*ptr == '\r') {
2391 if (p1) {
2392 msg->err_pos = buffer_count(buf, buf->p, ptr);
2393 return -1;
2394 }
2395 p1 = ptr;
2396 }
2397
2398 ptr++;
2399 if (ptr >= buf->data + buf->size)
2400 ptr = buf->data;
2401 }
2402
2403 /* after LF; point to beginning of next line */
2404 p2++;
2405 if (p2 >= buf->data + buf->size)
2406 p2 = buf->data;
2407
2408 bytes = p2 - start;
2409 if (bytes < 0)
2410 bytes += buf->size;
2411 msg->sol += bytes;
2412
2413 /* LF/CRLF at beginning of line => end of trailers at p2.
2414 * Everything was scheduled for forwarding, there's nothing left
2415 * from this message. */
2416 if (p1 == start)
2417 return 1;
2418
2419 /* OK, next line then */
2420 }
2421 }
2422
2423 /* This function may be called only in HTTP_MSG_CHUNK_CRLF. It reads the CRLF or
2424 * a possible LF alone at the end of a chunk. The caller should adjust msg->next
2425 * in order to include this part into the next forwarding phase. Note that the
2426 * caller must ensure that ->p points to the first byte to parse. It returns
2427 * the number of bytes parsed on success, so the caller can set msg_state to
2428 * HTTP_MSG_CHUNK_SIZE. If not enough data are available, the function does not
2429 * change anything and returns zero. If a parse error is encountered, the
2430 * function returns < 0. Note: this function is designed to parse wrapped CRLF
2431 * at the end of the buffer.
2432 */
http_skip_chunk_crlf(struct http_msg * msg)2433 static inline int http_skip_chunk_crlf(struct http_msg *msg)
2434 {
2435 const struct buffer *buf = msg->chn->buf;
2436 const char *ptr;
2437 int bytes;
2438
2439 /* NB: we'll check data availabilty at the end. It's not a
2440 * problem because whatever we match first will be checked
2441 * against the correct length.
2442 */
2443 bytes = 1;
2444 ptr = b_ptr(buf, msg->next);
2445 if (*ptr == '\r') {
2446 bytes++;
2447 ptr++;
2448 if (ptr >= buf->data + buf->size)
2449 ptr = buf->data;
2450 }
2451
2452 if (msg->next + bytes > buf->i)
2453 return 0;
2454
2455 if (*ptr != '\n') {
2456 msg->err_pos = buffer_count(buf, buf->p, ptr);
2457 return -1;
2458 }
2459 return bytes;
2460 }
2461
2462 /* Parses a qvalue and returns it multipled by 1000, from 0 to 1000. If the
2463 * value is larger than 1000, it is bound to 1000. The parser consumes up to
2464 * 1 digit, one dot and 3 digits and stops on the first invalid character.
2465 * Unparsable qvalues return 1000 as "q=1.000".
2466 */
parse_qvalue(const char * qvalue,const char ** end)2467 int parse_qvalue(const char *qvalue, const char **end)
2468 {
2469 int q = 1000;
2470
2471 if (!isdigit((unsigned char)*qvalue))
2472 goto out;
2473 q = (*qvalue++ - '0') * 1000;
2474
2475 if (*qvalue++ != '.')
2476 goto out;
2477
2478 if (!isdigit((unsigned char)*qvalue))
2479 goto out;
2480 q += (*qvalue++ - '0') * 100;
2481
2482 if (!isdigit((unsigned char)*qvalue))
2483 goto out;
2484 q += (*qvalue++ - '0') * 10;
2485
2486 if (!isdigit((unsigned char)*qvalue))
2487 goto out;
2488 q += (*qvalue++ - '0') * 1;
2489 out:
2490 if (q > 1000)
2491 q = 1000;
2492 if (end)
2493 *end = qvalue;
2494 return q;
2495 }
2496
http_adjust_conn_mode(struct stream * s,struct http_txn * txn,struct http_msg * msg)2497 void http_adjust_conn_mode(struct stream *s, struct http_txn *txn, struct http_msg *msg)
2498 {
2499 struct proxy *fe = strm_fe(s);
2500 int tmp = TX_CON_WANT_KAL;
2501
2502 if (!((fe->options2|s->be->options2) & PR_O2_FAKE_KA)) {
2503 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN ||
2504 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2505 tmp = TX_CON_WANT_TUN;
2506
2507 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||
2508 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL)
2509 tmp = TX_CON_WANT_TUN;
2510 }
2511
2512 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_SCL ||
2513 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_SCL) {
2514 /* option httpclose + server_close => forceclose */
2515 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||
2516 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL)
2517 tmp = TX_CON_WANT_CLO;
2518 else
2519 tmp = TX_CON_WANT_SCL;
2520 }
2521
2522 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_FCL ||
2523 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_FCL)
2524 tmp = TX_CON_WANT_CLO;
2525
2526 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
2527 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
2528
2529 if (!(txn->flags & TX_HDR_CONN_PRS) &&
2530 (txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN) {
2531 /* parse the Connection header and possibly clean it */
2532 int to_del = 0;
2533 if ((msg->flags & HTTP_MSGF_VER_11) ||
2534 ((txn->flags & TX_CON_WANT_MSK) >= TX_CON_WANT_SCL &&
2535 !((fe->options2|s->be->options2) & PR_O2_FAKE_KA)))
2536 to_del |= 2; /* remove "keep-alive" */
2537 if (!(msg->flags & HTTP_MSGF_VER_11))
2538 to_del |= 1; /* remove "close" */
2539 http_parse_connection_header(txn, msg, to_del);
2540 }
2541
2542 /* check if client or config asks for explicit close in KAL/SCL */
2543 if (((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL ||
2544 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) &&
2545 ((txn->flags & TX_HDR_CONN_CLO) || /* "connection: close" */
2546 (!(msg->flags & HTTP_MSGF_VER_11) && !(txn->flags & TX_HDR_CONN_KAL)) || /* no "connection: k-a" in 1.0 */
2547 !(msg->flags & HTTP_MSGF_XFER_LEN) || /* no length known => close */
2548 fe->state == PR_STSTOPPED)) /* frontend is stopping */
2549 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
2550 }
2551
2552 /* This stream analyser waits for a complete HTTP request. It returns 1 if the
2553 * processing can continue on next analysers, or zero if it either needs more
2554 * data or wants to immediately abort the request (eg: timeout, error, ...). It
2555 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
2556 * when it has nothing left to do, and may remove any analyser when it wants to
2557 * abort.
2558 */
http_wait_for_request(struct stream * s,struct channel * req,int an_bit)2559 int http_wait_for_request(struct stream *s, struct channel *req, int an_bit)
2560 {
2561 /*
2562 * We will parse the partial (or complete) lines.
2563 * We will check the request syntax, and also join multi-line
2564 * headers. An index of all the lines will be elaborated while
2565 * parsing.
2566 *
2567 * For the parsing, we use a 28 states FSM.
2568 *
2569 * Here is the information we currently have :
2570 * req->buf->p = beginning of request
2571 * req->buf->p + msg->eoh = end of processed headers / start of current one
2572 * req->buf->p + req->buf->i = end of input data
2573 * msg->eol = end of current header or line (LF or CRLF)
2574 * msg->next = first non-visited byte
2575 *
2576 * At end of parsing, we may perform a capture of the error (if any), and
2577 * we will set a few fields (txn->meth, sn->flags/SF_REDIRECTABLE).
2578 * We also check for monitor-uri, logging, HTTP/0.9 to 1.0 conversion, and
2579 * finally headers capture.
2580 */
2581
2582 int cur_idx;
2583 struct session *sess = s->sess;
2584 struct http_txn *txn = s->txn;
2585 struct http_msg *msg = &txn->req;
2586 struct hdr_ctx ctx;
2587
2588 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n",
2589 now_ms, __FUNCTION__,
2590 s,
2591 req,
2592 req->rex, req->wex,
2593 req->flags,
2594 req->buf->i,
2595 req->analysers);
2596
2597 /* we're speaking HTTP here, so let's speak HTTP to the client */
2598 s->srv_error = http_return_srv_error;
2599
2600 /* There's a protected area at the end of the buffer for rewriting
2601 * purposes. We don't want to start to parse the request if the
2602 * protected area is affected, because we may have to move processed
2603 * data later, which is much more complicated.
2604 */
2605 if (buffer_not_empty(req->buf) && msg->msg_state < HTTP_MSG_ERROR) {
2606
2607 /* This point is executed when some data is avalaible for analysis,
2608 * so we log the end of the idle time. */
2609 if (s->logs.t_idle == -1)
2610 s->logs.t_idle = tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake;
2611
2612 if (txn->flags & TX_NOT_FIRST) {
2613 if (unlikely(!channel_is_rewritable(req) && req->buf->o)) {
2614 if (req->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_WRITE_ERROR|CF_WRITE_TIMEOUT))
2615 goto failed_keep_alive;
2616 /* some data has still not left the buffer, wake us once that's done */
2617 channel_dont_connect(req);
2618 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
2619 req->flags |= CF_WAKE_WRITE;
2620 return 0;
2621 }
2622 if (unlikely(bi_end(req->buf) < b_ptr(req->buf, msg->next) ||
2623 bi_end(req->buf) > req->buf->data + req->buf->size - global.tune.maxrewrite))
2624 buffer_slow_realign(req->buf);
2625 }
2626
2627 if (likely(msg->next < req->buf->i)) /* some unparsed data are available */
2628 http_msg_analyzer(msg, &txn->hdr_idx);
2629 }
2630
2631 /* 1: we might have to print this header in debug mode */
2632 if (unlikely((global.mode & MODE_DEBUG) &&
2633 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) &&
2634 msg->msg_state >= HTTP_MSG_BODY)) {
2635 char *eol, *sol;
2636
2637 sol = req->buf->p;
2638 /* this is a bit complex : in case of error on the request line,
2639 * we know that rq.l is still zero, so we display only the part
2640 * up to the end of the line (truncated by debug_hdr).
2641 */
2642 eol = sol + (msg->sl.rq.l ? msg->sl.rq.l : req->buf->i);
2643 debug_hdr("clireq", s, sol, eol);
2644
2645 sol += hdr_idx_first_pos(&txn->hdr_idx);
2646 cur_idx = hdr_idx_first_idx(&txn->hdr_idx);
2647
2648 while (cur_idx) {
2649 eol = sol + txn->hdr_idx.v[cur_idx].len;
2650 debug_hdr("clihdr", s, sol, eol);
2651 sol = eol + txn->hdr_idx.v[cur_idx].cr + 1;
2652 cur_idx = txn->hdr_idx.v[cur_idx].next;
2653 }
2654 }
2655
2656
2657 /*
2658 * Now we quickly check if we have found a full valid request.
2659 * If not so, we check the FD and buffer states before leaving.
2660 * A full request is indicated by the fact that we have seen
2661 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
2662 * requests are checked first. When waiting for a second request
2663 * on a keep-alive stream, if we encounter and error, close, t/o,
2664 * we note the error in the stream flags but don't set any state.
2665 * Since the error will be noted there, it will not be counted by
2666 * process_stream() as a frontend error.
2667 * Last, we may increase some tracked counters' http request errors on
2668 * the cases that are deliberately the client's fault. For instance,
2669 * a timeout or connection reset is not counted as an error. However
2670 * a bad request is.
2671 */
2672
2673 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
2674 /*
2675 * First, let's catch bad requests.
2676 */
2677 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2678 stream_inc_http_req_ctr(s);
2679 stream_inc_http_err_ctr(s);
2680 proxy_inc_fe_req_ctr(sess->fe);
2681 goto return_bad_req;
2682 }
2683
2684 /* 1: Since we are in header mode, if there's no space
2685 * left for headers, we won't be able to free more
2686 * later, so the stream will never terminate. We
2687 * must terminate it now.
2688 */
2689 if (unlikely(buffer_full(req->buf, global.tune.maxrewrite))) {
2690 /* FIXME: check if URI is set and return Status
2691 * 414 Request URI too long instead.
2692 */
2693 stream_inc_http_req_ctr(s);
2694 stream_inc_http_err_ctr(s);
2695 proxy_inc_fe_req_ctr(sess->fe);
2696 if (msg->err_pos < 0)
2697 msg->err_pos = req->buf->i;
2698 goto return_bad_req;
2699 }
2700
2701 /* 2: have we encountered a read error ? */
2702 else if (req->flags & CF_READ_ERROR) {
2703 if (!(s->flags & SF_ERR_MASK))
2704 s->flags |= SF_ERR_CLICL;
2705
2706 if (txn->flags & TX_WAIT_NEXT_RQ)
2707 goto failed_keep_alive;
2708
2709 if (sess->fe->options & PR_O_IGNORE_PRB)
2710 goto failed_keep_alive;
2711
2712 /* we cannot return any message on error */
2713 if (msg->err_pos >= 0) {
2714 http_capture_bad_message(&sess->fe->invalid_req, s, msg, msg->err_state, sess->fe);
2715 stream_inc_http_err_ctr(s);
2716 }
2717
2718 txn->status = 400;
2719 msg->err_state = msg->msg_state;
2720 msg->msg_state = HTTP_MSG_ERROR;
2721 http_reply_and_close(s, txn->status, NULL);
2722 req->analysers &= AN_REQ_FLT_END;
2723 stream_inc_http_req_ctr(s);
2724 proxy_inc_fe_req_ctr(sess->fe);
2725 sess->fe->fe_counters.failed_req++;
2726 if (sess->listener->counters)
2727 sess->listener->counters->failed_req++;
2728
2729 if (!(s->flags & SF_FINST_MASK))
2730 s->flags |= SF_FINST_R;
2731 return 0;
2732 }
2733
2734 /* 3: has the read timeout expired ? */
2735 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
2736 if (!(s->flags & SF_ERR_MASK))
2737 s->flags |= SF_ERR_CLITO;
2738
2739 if (txn->flags & TX_WAIT_NEXT_RQ)
2740 goto failed_keep_alive;
2741
2742 if (sess->fe->options & PR_O_IGNORE_PRB)
2743 goto failed_keep_alive;
2744
2745 /* read timeout : give up with an error message. */
2746 if (msg->err_pos >= 0) {
2747 http_capture_bad_message(&sess->fe->invalid_req, s, msg, msg->err_state, sess->fe);
2748 stream_inc_http_err_ctr(s);
2749 }
2750 txn->status = 408;
2751 msg->err_state = msg->msg_state;
2752 msg->msg_state = HTTP_MSG_ERROR;
2753 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_408));
2754 req->analysers &= AN_REQ_FLT_END;
2755
2756 stream_inc_http_req_ctr(s);
2757 proxy_inc_fe_req_ctr(sess->fe);
2758 sess->fe->fe_counters.failed_req++;
2759 if (sess->listener->counters)
2760 sess->listener->counters->failed_req++;
2761
2762 if (!(s->flags & SF_FINST_MASK))
2763 s->flags |= SF_FINST_R;
2764 return 0;
2765 }
2766
2767 /* 4: have we encountered a close ? */
2768 else if (req->flags & CF_SHUTR) {
2769 if (!(s->flags & SF_ERR_MASK))
2770 s->flags |= SF_ERR_CLICL;
2771
2772 if (txn->flags & TX_WAIT_NEXT_RQ)
2773 goto failed_keep_alive;
2774
2775 if (sess->fe->options & PR_O_IGNORE_PRB)
2776 goto failed_keep_alive;
2777
2778 if (msg->err_pos >= 0)
2779 http_capture_bad_message(&sess->fe->invalid_req, s, msg, msg->err_state, sess->fe);
2780 txn->status = 400;
2781 msg->err_state = msg->msg_state;
2782 msg->msg_state = HTTP_MSG_ERROR;
2783 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_400));
2784 req->analysers &= AN_REQ_FLT_END;
2785 stream_inc_http_err_ctr(s);
2786 stream_inc_http_req_ctr(s);
2787 proxy_inc_fe_req_ctr(sess->fe);
2788 sess->fe->fe_counters.failed_req++;
2789 if (sess->listener->counters)
2790 sess->listener->counters->failed_req++;
2791
2792 if (!(s->flags & SF_FINST_MASK))
2793 s->flags |= SF_FINST_R;
2794 return 0;
2795 }
2796
2797 channel_dont_connect(req);
2798 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
2799 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
2800 #ifdef TCP_QUICKACK
2801 if (sess->listener->options & LI_O_NOQUICKACK && req->buf->i &&
2802 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
2803 /* We need more data, we have to re-enable quick-ack in case we
2804 * previously disabled it, otherwise we might cause the client
2805 * to delay next data.
2806 */
2807 setsockopt(__objt_conn(sess->origin)->t.sock.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
2808 }
2809 #endif
2810
2811 if ((msg->msg_state != HTTP_MSG_RQBEFORE) && (txn->flags & TX_WAIT_NEXT_RQ)) {
2812 /* If the client starts to talk, let's fall back to
2813 * request timeout processing.
2814 */
2815 txn->flags &= ~TX_WAIT_NEXT_RQ;
2816 req->analyse_exp = TICK_ETERNITY;
2817 }
2818
2819 /* just set the request timeout once at the beginning of the request */
2820 if (!tick_isset(req->analyse_exp)) {
2821 if ((msg->msg_state == HTTP_MSG_RQBEFORE) &&
2822 (txn->flags & TX_WAIT_NEXT_RQ) &&
2823 tick_isset(s->be->timeout.httpka))
2824 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
2825 else
2826 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
2827 }
2828
2829 /* we're not ready yet */
2830 return 0;
2831
2832 failed_keep_alive:
2833 /* Here we process low-level errors for keep-alive requests. In
2834 * short, if the request is not the first one and it experiences
2835 * a timeout, read error or shutdown, we just silently close so
2836 * that the client can try again.
2837 */
2838 txn->status = 0;
2839 msg->msg_state = HTTP_MSG_RQBEFORE;
2840 req->analysers &= AN_REQ_FLT_END;
2841 s->logs.logwait = 0;
2842 s->logs.level = 0;
2843 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
2844 http_reply_and_close(s, txn->status, NULL);
2845 return 0;
2846 }
2847
2848 /* OK now we have a complete HTTP request with indexed headers. Let's
2849 * complete the request parsing by setting a few fields we will need
2850 * later. At this point, we have the last CRLF at req->buf->data + msg->eoh.
2851 * If the request is in HTTP/0.9 form, the rule is still true, and eoh
2852 * points to the CRLF of the request line. msg->next points to the first
2853 * byte after the last LF. msg->sov points to the first byte of data.
2854 * msg->eol cannot be trusted because it may have been left uninitialized
2855 * (for instance in the absence of headers).
2856 */
2857
2858 stream_inc_http_req_ctr(s);
2859 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
2860
2861 if (txn->flags & TX_WAIT_NEXT_RQ) {
2862 /* kill the pending keep-alive timeout */
2863 txn->flags &= ~TX_WAIT_NEXT_RQ;
2864 req->analyse_exp = TICK_ETERNITY;
2865 }
2866
2867
2868 /* Maybe we found in invalid header name while we were configured not
2869 * to block on that, so we have to capture it now.
2870 */
2871 if (unlikely(msg->err_pos >= 0))
2872 http_capture_bad_message(&sess->fe->invalid_req, s, msg, msg->err_state, sess->fe);
2873
2874 /*
2875 * 1: identify the method
2876 */
2877 txn->meth = find_http_meth(req->buf->p, msg->sl.rq.m_l);
2878
2879 /* we can make use of server redirect on GET and HEAD */
2880 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
2881 s->flags |= SF_REDIRECTABLE;
2882 else if (txn->meth == HTTP_METH_OTHER &&
2883 msg->sl.rq.m_l == 3 && memcmp(req->buf->p, "PRI", 3) == 0) {
2884 /* PRI is reserved for the HTTP/2 preface */
2885 msg->err_pos = 0;
2886 goto return_bad_req;
2887 }
2888
2889 /*
2890 * 2: check if the URI matches the monitor_uri.
2891 * We have to do this for every request which gets in, because
2892 * the monitor-uri is defined by the frontend.
2893 */
2894 if (unlikely((sess->fe->monitor_uri_len != 0) &&
2895 (sess->fe->monitor_uri_len == msg->sl.rq.u_l) &&
2896 !memcmp(req->buf->p + msg->sl.rq.u,
2897 sess->fe->monitor_uri,
2898 sess->fe->monitor_uri_len))) {
2899 /*
2900 * We have found the monitor URI
2901 */
2902 struct acl_cond *cond;
2903
2904 s->flags |= SF_MONITOR;
2905 sess->fe->fe_counters.intercepted_req++;
2906
2907 /* Check if we want to fail this monitor request or not */
2908 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
2909 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2910
2911 ret = acl_pass(ret);
2912 if (cond->pol == ACL_COND_UNLESS)
2913 ret = !ret;
2914
2915 if (ret) {
2916 /* we fail this request, let's return 503 service unavail */
2917 txn->status = 503;
2918 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_503));
2919 if (!(s->flags & SF_ERR_MASK))
2920 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
2921 goto return_prx_cond;
2922 }
2923 }
2924
2925 /* nothing to fail, let's reply normaly */
2926 txn->status = 200;
2927 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_200));
2928 if (!(s->flags & SF_ERR_MASK))
2929 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
2930 goto return_prx_cond;
2931 }
2932
2933 /*
2934 * 3: Maybe we have to copy the original REQURI for the logs ?
2935 * Note: we cannot log anymore if the request has been
2936 * classified as invalid.
2937 */
2938 if (unlikely(s->logs.logwait & LW_REQ)) {
2939 /* we have a complete HTTP request that we must log */
2940 if ((txn->uri = pool_alloc2(pool2_requri)) != NULL) {
2941 int urilen = msg->sl.rq.l;
2942
2943 if (urilen >= REQURI_LEN)
2944 urilen = REQURI_LEN - 1;
2945 memcpy(txn->uri, req->buf->p, urilen);
2946 txn->uri[urilen] = 0;
2947
2948 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
2949 s->do_log(s);
2950 } else {
2951 Alert("HTTP logging : out of memory.\n");
2952 }
2953 }
2954
2955 /* RFC7230#2.6 has enforced the format of the HTTP version string to be
2956 * exactly one digit "." one digit. This check may be disabled using
2957 * option accept-invalid-http-request.
2958 */
2959 if (!(sess->fe->options2 & PR_O2_REQBUG_OK)) {
2960 if (msg->sl.rq.v_l != 8) {
2961 msg->err_pos = msg->sl.rq.v;
2962 goto return_bad_req;
2963 }
2964
2965 if (req->buf->p[msg->sl.rq.v + 4] != '/' ||
2966 !isdigit((unsigned char)req->buf->p[msg->sl.rq.v + 5]) ||
2967 req->buf->p[msg->sl.rq.v + 6] != '.' ||
2968 !isdigit((unsigned char)req->buf->p[msg->sl.rq.v + 7])) {
2969 msg->err_pos = msg->sl.rq.v + 4;
2970 goto return_bad_req;
2971 }
2972 }
2973 else {
2974 /* 4. We may have to convert HTTP/0.9 requests to HTTP/1.0 */
2975 if (unlikely(msg->sl.rq.v_l == 0) && !http_upgrade_v09_to_v10(txn))
2976 goto return_bad_req;
2977 }
2978
2979 /* ... and check if the request is HTTP/1.1 or above */
2980 if ((msg->sl.rq.v_l == 8) &&
2981 ((req->buf->p[msg->sl.rq.v + 5] > '1') ||
2982 ((req->buf->p[msg->sl.rq.v + 5] == '1') &&
2983 (req->buf->p[msg->sl.rq.v + 7] >= '1'))))
2984 msg->flags |= HTTP_MSGF_VER_11;
2985
2986 /* "connection" has not been parsed yet */
2987 txn->flags &= ~(TX_HDR_CONN_PRS | TX_HDR_CONN_CLO | TX_HDR_CONN_KAL | TX_HDR_CONN_UPG);
2988
2989 /* if the frontend has "option http-use-proxy-header", we'll check if
2990 * we have what looks like a proxied connection instead of a connection,
2991 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
2992 * Note that this is *not* RFC-compliant, however browsers and proxies
2993 * happen to do that despite being non-standard :-(
2994 * We consider that a request not beginning with either '/' or '*' is
2995 * a proxied connection, which covers both "scheme://location" and
2996 * CONNECT ip:port.
2997 */
2998 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
2999 req->buf->p[msg->sl.rq.u] != '/' && req->buf->p[msg->sl.rq.u] != '*')
3000 txn->flags |= TX_USE_PX_CONN;
3001
3002 /* transfer length unknown*/
3003 msg->flags &= ~HTTP_MSGF_XFER_LEN;
3004
3005 /* 5: we may need to capture headers */
3006 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
3007 capture_headers(req->buf->p, &txn->hdr_idx,
3008 s->req_cap, sess->fe->req_cap);
3009
3010 /* 6: determine the transfer-length according to RFC2616 #4.4, updated
3011 * by RFC7230#3.3.3 :
3012 *
3013 * The length of a message body is determined by one of the following
3014 * (in order of precedence):
3015 *
3016 * 1. Any response to a HEAD request and any response with a 1xx
3017 * (Informational), 204 (No Content), or 304 (Not Modified) status
3018 * code is always terminated by the first empty line after the
3019 * header fields, regardless of the header fields present in the
3020 * message, and thus cannot contain a message body.
3021 *
3022 * 2. Any 2xx (Successful) response to a CONNECT request implies that
3023 * the connection will become a tunnel immediately after the empty
3024 * line that concludes the header fields. A client MUST ignore any
3025 * Content-Length or Transfer-Encoding header fields received in
3026 * such a message.
3027 *
3028 * 3. If a Transfer-Encoding header field is present and the chunked
3029 * transfer coding (Section 4.1) is the final encoding, the message
3030 * body length is determined by reading and decoding the chunked
3031 * data until the transfer coding indicates the data is complete.
3032 *
3033 * If a Transfer-Encoding header field is present in a response and
3034 * the chunked transfer coding is not the final encoding, the
3035 * message body length is determined by reading the connection until
3036 * it is closed by the server. If a Transfer-Encoding header field
3037 * is present in a request and the chunked transfer coding is not
3038 * the final encoding, the message body length cannot be determined
3039 * reliably; the server MUST respond with the 400 (Bad Request)
3040 * status code and then close the connection.
3041 *
3042 * If a message is received with both a Transfer-Encoding and a
3043 * Content-Length header field, the Transfer-Encoding overrides the
3044 * Content-Length. Such a message might indicate an attempt to
3045 * perform request smuggling (Section 9.5) or response splitting
3046 * (Section 9.4) and ought to be handled as an error. A sender MUST
3047 * remove the received Content-Length field prior to forwarding such
3048 * a message downstream.
3049 *
3050 * 4. If a message is received without Transfer-Encoding and with
3051 * either multiple Content-Length header fields having differing
3052 * field-values or a single Content-Length header field having an
3053 * invalid value, then the message framing is invalid and the
3054 * recipient MUST treat it as an unrecoverable error. If this is a
3055 * request message, the server MUST respond with a 400 (Bad Request)
3056 * status code and then close the connection. If this is a response
3057 * message received by a proxy, the proxy MUST close the connection
3058 * to the server, discard the received response, and send a 502 (Bad
3059 * Gateway) response to the client. If this is a response message
3060 * received by a user agent, the user agent MUST close the
3061 * connection to the server and discard the received response.
3062 *
3063 * 5. If a valid Content-Length header field is present without
3064 * Transfer-Encoding, its decimal value defines the expected message
3065 * body length in octets. If the sender closes the connection or
3066 * the recipient times out before the indicated number of octets are
3067 * received, the recipient MUST consider the message to be
3068 * incomplete and close the connection.
3069 *
3070 * 6. If this is a request message and none of the above are true, then
3071 * the message body length is zero (no message body is present).
3072 *
3073 * 7. Otherwise, this is a response message without a declared message
3074 * body length, so the message body length is determined by the
3075 * number of octets received prior to the server closing the
3076 * connection.
3077 */
3078
3079 ctx.idx = 0;
3080 /* set TE_CHNK and XFER_LEN only if "chunked" is seen last */
3081 while (http_find_header2("Transfer-Encoding", 17, req->buf->p, &txn->hdr_idx, &ctx)) {
3082 if (ctx.vlen == 7 && strncasecmp(ctx.line + ctx.val, "chunked", 7) == 0)
3083 msg->flags |= (HTTP_MSGF_TE_CHNK | HTTP_MSGF_XFER_LEN);
3084 else if (msg->flags & HTTP_MSGF_TE_CHNK) {
3085 /* chunked not last, return badreq */
3086 goto return_bad_req;
3087 }
3088 }
3089
3090 /* "chunked" mandatory if transfer-encoding is used */
3091 if (ctx.idx && !(msg->flags & HTTP_MSGF_TE_CHNK))
3092 goto return_bad_req;
3093
3094 /* Chunked requests must have their content-length removed */
3095 ctx.idx = 0;
3096 if (msg->flags & HTTP_MSGF_TE_CHNK) {
3097 while (http_find_header2("Content-Length", 14, req->buf->p, &txn->hdr_idx, &ctx))
3098 http_remove_header2(msg, &txn->hdr_idx, &ctx);
3099 }
3100 else while (http_find_header2("Content-Length", 14, req->buf->p, &txn->hdr_idx, &ctx)) {
3101 signed long long cl;
3102
3103 if (!ctx.vlen) {
3104 msg->err_pos = ctx.line + ctx.val - req->buf->p;
3105 goto return_bad_req;
3106 }
3107
3108 if (strl2llrc(ctx.line + ctx.val, ctx.vlen, &cl)) {
3109 msg->err_pos = ctx.line + ctx.val - req->buf->p;
3110 goto return_bad_req; /* parse failure */
3111 }
3112
3113 if (cl < 0) {
3114 msg->err_pos = ctx.line + ctx.val - req->buf->p;
3115 goto return_bad_req;
3116 }
3117
3118 if ((msg->flags & HTTP_MSGF_CNT_LEN) && (msg->chunk_len != cl)) {
3119 msg->err_pos = ctx.line + ctx.val - req->buf->p;
3120 goto return_bad_req; /* already specified, was different */
3121 }
3122
3123 msg->flags |= HTTP_MSGF_CNT_LEN | HTTP_MSGF_XFER_LEN;
3124 msg->body_len = msg->chunk_len = cl;
3125 }
3126
3127 /* even bodyless requests have a known length */
3128 msg->flags |= HTTP_MSGF_XFER_LEN;
3129
3130 /* Until set to anything else, the connection mode is set as Keep-Alive. It will
3131 * only change if both the request and the config reference something else.
3132 * Option httpclose by itself sets tunnel mode where headers are mangled.
3133 * However, if another mode is set, it will affect it (eg: server-close/
3134 * keep-alive + httpclose = close). Note that we avoid to redo the same work
3135 * if FE and BE have the same settings (common). The method consists in
3136 * checking if options changed between the two calls (implying that either
3137 * one is non-null, or one of them is non-null and we are there for the first
3138 * time.
3139 */
3140 if (!(txn->flags & TX_HDR_CONN_PRS) ||
3141 ((sess->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE)))
3142 http_adjust_conn_mode(s, txn, msg);
3143
3144 /* we may have to wait for the request's body */
3145 if ((s->be->options & PR_O_WREQ_BODY) &&
3146 (msg->body_len || (msg->flags & HTTP_MSGF_TE_CHNK)))
3147 req->analysers |= AN_REQ_HTTP_BODY;
3148
3149 /* end of job, return OK */
3150 req->analysers &= ~an_bit;
3151 req->analyse_exp = TICK_ETERNITY;
3152 return 1;
3153
3154 return_bad_req:
3155 /* We centralize bad requests processing here */
3156 if (unlikely(msg->msg_state == HTTP_MSG_ERROR) || msg->err_pos >= 0) {
3157 /* we detected a parsing error. We want to archive this request
3158 * in the dedicated proxy area for later troubleshooting.
3159 */
3160 http_capture_bad_message(&sess->fe->invalid_req, s, msg, msg->err_state, sess->fe);
3161 }
3162
3163 txn->req.err_state = txn->req.msg_state;
3164 txn->req.msg_state = HTTP_MSG_ERROR;
3165 txn->status = 400;
3166 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_400));
3167
3168 sess->fe->fe_counters.failed_req++;
3169 if (sess->listener->counters)
3170 sess->listener->counters->failed_req++;
3171
3172 return_prx_cond:
3173 if (!(s->flags & SF_ERR_MASK))
3174 s->flags |= SF_ERR_PRXCOND;
3175 if (!(s->flags & SF_FINST_MASK))
3176 s->flags |= SF_FINST_R;
3177
3178 req->analysers &= AN_REQ_FLT_END;
3179 req->analyse_exp = TICK_ETERNITY;
3180 return 0;
3181 }
3182
3183
3184 /* This function prepares an applet to handle the stats. It can deal with the
3185 * "100-continue" expectation, check that admin rules are met for POST requests,
3186 * and program a response message if something was unexpected. It cannot fail
3187 * and always relies on the stats applet to complete the job. It does not touch
3188 * analysers nor counters, which are left to the caller. It does not touch
3189 * s->target which is supposed to already point to the stats applet. The caller
3190 * is expected to have already assigned an appctx to the stream.
3191 */
http_handle_stats(struct stream * s,struct channel * req)3192 int http_handle_stats(struct stream *s, struct channel *req)
3193 {
3194 struct stats_admin_rule *stats_admin_rule;
3195 struct stream_interface *si = &s->si[1];
3196 struct session *sess = s->sess;
3197 struct http_txn *txn = s->txn;
3198 struct http_msg *msg = &txn->req;
3199 struct uri_auth *uri_auth = s->be->uri_auth;
3200 const char *uri, *h, *lookup;
3201 struct appctx *appctx;
3202
3203 appctx = si_appctx(si);
3204 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
3205 appctx->st1 = appctx->st2 = 0;
3206 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
3207 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
3208 if ((msg->flags & HTTP_MSGF_VER_11) && (s->txn->meth != HTTP_METH_HEAD))
3209 appctx->ctx.stats.flags |= STAT_CHUNKED;
3210
3211 uri = msg->chn->buf->p + msg->sl.rq.u;
3212 lookup = uri + uri_auth->uri_len;
3213
3214 for (h = lookup; h <= uri + msg->sl.rq.u_l - 3; h++) {
3215 if (memcmp(h, ";up", 3) == 0) {
3216 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
3217 break;
3218 }
3219 }
3220
3221 if (uri_auth->refresh) {
3222 for (h = lookup; h <= uri + msg->sl.rq.u_l - 10; h++) {
3223 if (memcmp(h, ";norefresh", 10) == 0) {
3224 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
3225 break;
3226 }
3227 }
3228 }
3229
3230 for (h = lookup; h <= uri + msg->sl.rq.u_l - 4; h++) {
3231 if (memcmp(h, ";csv", 4) == 0) {
3232 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
3233 break;
3234 }
3235 }
3236
3237 for (h = lookup; h <= uri + msg->sl.rq.u_l - 6; h++) {
3238 if (memcmp(h, ";typed", 6) == 0) {
3239 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
3240 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
3241 break;
3242 }
3243 }
3244
3245 for (h = lookup; h <= uri + msg->sl.rq.u_l - 8; h++) {
3246 if (memcmp(h, ";st=", 4) == 0) {
3247 int i;
3248 h += 4;
3249 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
3250 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
3251 if (strncmp(stat_status_codes[i], h, 4) == 0) {
3252 appctx->ctx.stats.st_code = i;
3253 break;
3254 }
3255 }
3256 break;
3257 }
3258 }
3259
3260 appctx->ctx.stats.scope_str = 0;
3261 appctx->ctx.stats.scope_len = 0;
3262 for (h = lookup; h <= uri + msg->sl.rq.u_l - 8; h++) {
3263 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
3264 int itx = 0;
3265 const char *h2;
3266 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
3267 const char *err;
3268
3269 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
3270 h2 = h;
3271 appctx->ctx.stats.scope_str = h2 - msg->chn->buf->p;
3272 while (*h != ';' && *h != '\0' && *h != '&' && *h != ' ' && *h != '\n') {
3273 itx++;
3274 h++;
3275 }
3276
3277 if (itx > STAT_SCOPE_TXT_MAXLEN)
3278 itx = STAT_SCOPE_TXT_MAXLEN;
3279 appctx->ctx.stats.scope_len = itx;
3280
3281 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
3282 memcpy(scope_txt, h2, itx);
3283 scope_txt[itx] = '\0';
3284 err = invalid_char(scope_txt);
3285 if (err) {
3286 /* bad char in search text => clear scope */
3287 appctx->ctx.stats.scope_str = 0;
3288 appctx->ctx.stats.scope_len = 0;
3289 }
3290 break;
3291 }
3292 }
3293
3294 /* now check whether we have some admin rules for this request */
3295 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
3296 int ret = 1;
3297
3298 if (stats_admin_rule->cond) {
3299 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3300 ret = acl_pass(ret);
3301 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
3302 ret = !ret;
3303 }
3304
3305 if (ret) {
3306 /* no rule, or the rule matches */
3307 appctx->ctx.stats.flags |= STAT_ADMIN;
3308 break;
3309 }
3310 }
3311
3312 /* Was the status page requested with a POST ? */
3313 if (unlikely(txn->meth == HTTP_METH_POST && txn->req.body_len > 0)) {
3314 if (appctx->ctx.stats.flags & STAT_ADMIN) {
3315 /* we'll need the request body, possibly after sending 100-continue */
3316 if (msg->msg_state < HTTP_MSG_CHUNK_SIZE)
3317 req->analysers |= AN_REQ_HTTP_BODY;
3318 appctx->st0 = STAT_HTTP_POST;
3319 }
3320 else {
3321 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
3322 appctx->st0 = STAT_HTTP_LAST;
3323 }
3324 }
3325 else {
3326 /* So it was another method (GET/HEAD) */
3327 appctx->st0 = STAT_HTTP_HEAD;
3328 }
3329
3330 s->task->nice = -32; /* small boost for HTTP statistics */
3331 return 1;
3332 }
3333
3334 /* Sets the TOS header in IPv4 and the traffic class header in IPv6 packets
3335 * (as per RFC3260 #4 and BCP37 #4.2 and #5.2).
3336 */
inet_set_tos(int fd,const struct sockaddr_storage * from,int tos)3337 void inet_set_tos(int fd, const struct sockaddr_storage *from, int tos)
3338 {
3339 #ifdef IP_TOS
3340 if (from->ss_family == AF_INET)
3341 setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
3342 #endif
3343 #ifdef IPV6_TCLASS
3344 if (from->ss_family == AF_INET6) {
3345 if (IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)from)->sin6_addr))
3346 /* v4-mapped addresses need IP_TOS */
3347 setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
3348 else
3349 setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos));
3350 }
3351 #endif
3352 }
3353
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)3354 int http_transform_header_str(struct stream* s, struct http_msg *msg,
3355 const char* name, unsigned int name_len,
3356 const char *str, struct my_regex *re,
3357 int action)
3358 {
3359 struct hdr_ctx ctx;
3360 char *buf = msg->chn->buf->p;
3361 struct hdr_idx *idx = &s->txn->hdr_idx;
3362 int (*http_find_hdr_func)(const char *name, int len, char *sol,
3363 struct hdr_idx *idx, struct hdr_ctx *ctx);
3364 struct chunk *output = get_trash_chunk();
3365
3366 ctx.idx = 0;
3367
3368 /* Choose the header browsing function. */
3369 switch (action) {
3370 case ACT_HTTP_REPLACE_VAL:
3371 http_find_hdr_func = http_find_header2;
3372 break;
3373 case ACT_HTTP_REPLACE_HDR:
3374 http_find_hdr_func = http_find_full_header2;
3375 break;
3376 default: /* impossible */
3377 return -1;
3378 }
3379
3380 while (http_find_hdr_func(name, name_len, buf, idx, &ctx)) {
3381 struct hdr_idx_elem *hdr = idx->v + ctx.idx;
3382 int delta;
3383 char *val = ctx.line + ctx.val;
3384 char* val_end = val + ctx.vlen;
3385
3386 if (!regex_exec_match2(re, val, val_end-val, MAX_MATCH, pmatch, 0))
3387 continue;
3388
3389 output->len = exp_replace(output->str, output->size, val, str, pmatch);
3390 if (output->len == -1)
3391 return -1;
3392
3393 delta = buffer_replace2(msg->chn->buf, val, val_end, output->str, output->len);
3394
3395 hdr->len += delta;
3396 http_msg_move_end(msg, delta);
3397
3398 /* Adjust the length of the current value of the index. */
3399 ctx.vlen += delta;
3400 }
3401
3402 return 0;
3403 }
3404
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)3405 static int http_transform_header(struct stream* s, struct http_msg *msg,
3406 const char* name, unsigned int name_len,
3407 struct list *fmt, struct my_regex *re,
3408 int action)
3409 {
3410 struct chunk *replace;
3411 int ret = -1;
3412
3413 replace = alloc_trash_chunk();
3414 if (!replace)
3415 goto leave;
3416
3417 replace->len = build_logline(s, replace->str, replace->size, fmt);
3418 if (replace->len >= replace->size - 1)
3419 goto leave;
3420
3421 ret = http_transform_header_str(s, msg, name, name_len, replace->str, re, action);
3422
3423 leave:
3424 free_trash_chunk(replace);
3425 return ret;
3426 }
3427
3428 /* Executes the http-request rules <rules> for stream <s>, proxy <px> and
3429 * transaction <txn>. Returns the verdict of the first rule that prevents
3430 * further processing of the request (auth, deny, ...), and defaults to
3431 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
3432 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
3433 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
3434 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
3435 * status.
3436 */
3437 enum rule_result
http_req_get_intercept_rule(struct proxy * px,struct list * rules,struct stream * s,int * deny_status)3438 http_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s, int *deny_status)
3439 {
3440 struct session *sess = strm_sess(s);
3441 struct http_txn *txn = s->txn;
3442 struct connection *cli_conn;
3443 struct act_rule *rule;
3444 struct hdr_ctx ctx;
3445 const char *auth_realm;
3446 int act_flags = 0;
3447 int len;
3448
3449 /* If "the current_rule_list" match the executed rule list, we are in
3450 * resume condition. If a resume is needed it is always in the action
3451 * and never in the ACL or converters. In this case, we initialise the
3452 * current rule, and go to the action execution point.
3453 */
3454 if (s->current_rule) {
3455 rule = s->current_rule;
3456 s->current_rule = NULL;
3457 if (s->current_rule_list == rules)
3458 goto resume_execution;
3459 }
3460 s->current_rule_list = rules;
3461
3462 list_for_each_entry(rule, rules, list) {
3463
3464 /* check optional condition */
3465 if (rule->cond) {
3466 int ret;
3467
3468 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3469 ret = acl_pass(ret);
3470
3471 if (rule->cond->pol == ACL_COND_UNLESS)
3472 ret = !ret;
3473
3474 if (!ret) /* condition not matched */
3475 continue;
3476 }
3477
3478 act_flags |= ACT_FLAG_FIRST;
3479 resume_execution:
3480 switch (rule->action) {
3481 case ACT_ACTION_ALLOW:
3482 return HTTP_RULE_RES_STOP;
3483
3484 case ACT_ACTION_DENY:
3485 if (deny_status)
3486 *deny_status = rule->deny_status;
3487 return HTTP_RULE_RES_DENY;
3488
3489 case ACT_HTTP_REQ_TARPIT:
3490 txn->flags |= TX_CLTARPIT;
3491 if (deny_status)
3492 *deny_status = rule->deny_status;
3493 return HTTP_RULE_RES_DENY;
3494
3495 case ACT_HTTP_REQ_AUTH:
3496 /* Auth might be performed on regular http-req rules as well as on stats */
3497 auth_realm = rule->arg.auth.realm;
3498 if (!auth_realm) {
3499 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
3500 auth_realm = STATS_DEFAULT_REALM;
3501 else
3502 auth_realm = px->id;
3503 }
3504 /* send 401/407 depending on whether we use a proxy or not. We still
3505 * count one error, because normal browsing won't significantly
3506 * increase the counter but brute force attempts will.
3507 */
3508 chunk_printf(&trash, (txn->flags & TX_USE_PX_CONN) ? HTTP_407_fmt : HTTP_401_fmt, auth_realm);
3509 txn->status = (txn->flags & TX_USE_PX_CONN) ? 407 : 401;
3510 http_reply_and_close(s, txn->status, &trash);
3511 stream_inc_http_err_ctr(s);
3512 return HTTP_RULE_RES_ABRT;
3513
3514 case ACT_HTTP_REDIR:
3515 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3516 return HTTP_RULE_RES_BADREQ;
3517 return HTTP_RULE_RES_DONE;
3518
3519 case ACT_HTTP_SET_NICE:
3520 s->task->nice = rule->arg.nice;
3521 break;
3522
3523 case ACT_HTTP_SET_TOS:
3524 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3525 inet_set_tos(cli_conn->t.sock.fd, &cli_conn->addr.from, rule->arg.tos);
3526 break;
3527
3528 case ACT_HTTP_SET_MARK:
3529 #ifdef SO_MARK
3530 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3531 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
3532 #endif
3533 break;
3534
3535 case ACT_HTTP_SET_LOGL:
3536 s->logs.level = rule->arg.loglevel;
3537 break;
3538
3539 case ACT_HTTP_REPLACE_HDR:
3540 case ACT_HTTP_REPLACE_VAL:
3541 if (http_transform_header(s, &txn->req, rule->arg.hdr_add.name,
3542 rule->arg.hdr_add.name_len,
3543 &rule->arg.hdr_add.fmt,
3544 &rule->arg.hdr_add.re, rule->action))
3545 return HTTP_RULE_RES_BADREQ;
3546 break;
3547
3548 case ACT_HTTP_DEL_HDR:
3549 ctx.idx = 0;
3550 /* remove all occurrences of the header */
3551 while (http_find_header2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len,
3552 txn->req.chn->buf->p, &txn->hdr_idx, &ctx)) {
3553 http_remove_header2(&txn->req, &txn->hdr_idx, &ctx);
3554 }
3555 break;
3556
3557 case ACT_HTTP_SET_HDR:
3558 case ACT_HTTP_ADD_HDR: {
3559 /* The scope of the trash buffer must be limited to this function. The
3560 * build_logline() function can execute a lot of other function which
3561 * can use the trash buffer. So for limiting the scope of this global
3562 * buffer, we build first the header value using build_logline, and
3563 * after we store the header name.
3564 */
3565 struct chunk *replace;
3566
3567 replace = alloc_trash_chunk();
3568 if (!replace)
3569 return HTTP_RULE_RES_BADREQ;
3570
3571 len = rule->arg.hdr_add.name_len + 2,
3572 len += build_logline(s, replace->str + len, replace->size - len, &rule->arg.hdr_add.fmt);
3573 memcpy(replace->str, rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3574 replace->str[rule->arg.hdr_add.name_len] = ':';
3575 replace->str[rule->arg.hdr_add.name_len + 1] = ' ';
3576 replace->len = len;
3577
3578 if (rule->action == ACT_HTTP_SET_HDR) {
3579 /* remove all occurrences of the header */
3580 ctx.idx = 0;
3581 while (http_find_header2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len,
3582 txn->req.chn->buf->p, &txn->hdr_idx, &ctx)) {
3583 http_remove_header2(&txn->req, &txn->hdr_idx, &ctx);
3584 }
3585 }
3586
3587 http_header_add_tail2(&txn->req, &txn->hdr_idx, replace->str, replace->len);
3588
3589 free_trash_chunk(replace);
3590 break;
3591 }
3592
3593 case ACT_HTTP_DEL_ACL:
3594 case ACT_HTTP_DEL_MAP: {
3595 struct pat_ref *ref;
3596 struct chunk *key;
3597
3598 /* collect reference */
3599 ref = pat_ref_lookup(rule->arg.map.ref);
3600 if (!ref)
3601 continue;
3602
3603 /* allocate key */
3604 key = alloc_trash_chunk();
3605 if (!key)
3606 return HTTP_RULE_RES_BADREQ;
3607
3608 /* collect key */
3609 key->len = build_logline(s, key->str, key->size, &rule->arg.map.key);
3610 key->str[key->len] = '\0';
3611
3612 /* perform update */
3613 /* returned code: 1=ok, 0=ko */
3614 pat_ref_delete(ref, key->str);
3615
3616 free_trash_chunk(key);
3617 break;
3618 }
3619
3620 case ACT_HTTP_ADD_ACL: {
3621 struct pat_ref *ref;
3622 struct chunk *key;
3623
3624 /* collect reference */
3625 ref = pat_ref_lookup(rule->arg.map.ref);
3626 if (!ref)
3627 continue;
3628
3629 /* allocate key */
3630 key = alloc_trash_chunk();
3631 if (!key)
3632 return HTTP_RULE_RES_BADREQ;
3633
3634 /* collect key */
3635 key->len = build_logline(s, key->str, key->size, &rule->arg.map.key);
3636 key->str[key->len] = '\0';
3637
3638 /* perform update */
3639 /* add entry only if it does not already exist */
3640 if (pat_ref_find_elt(ref, key->str) == NULL)
3641 pat_ref_add(ref, key->str, NULL, NULL);
3642
3643 free_trash_chunk(key);
3644 break;
3645 }
3646
3647 case ACT_HTTP_SET_MAP: {
3648 struct pat_ref *ref;
3649 struct chunk *key, *value;
3650
3651 /* collect reference */
3652 ref = pat_ref_lookup(rule->arg.map.ref);
3653 if (!ref)
3654 continue;
3655
3656 /* allocate key */
3657 key = alloc_trash_chunk();
3658 if (!key)
3659 return HTTP_RULE_RES_BADREQ;
3660
3661 /* allocate value */
3662 value = alloc_trash_chunk();
3663 if (!value) {
3664 free_trash_chunk(key);
3665 return HTTP_RULE_RES_BADREQ;
3666 }
3667
3668 /* collect key */
3669 key->len = build_logline(s, key->str, key->size, &rule->arg.map.key);
3670 key->str[key->len] = '\0';
3671
3672 /* collect value */
3673 value->len = build_logline(s, value->str, value->size, &rule->arg.map.value);
3674 value->str[value->len] = '\0';
3675
3676 /* perform update */
3677 if (pat_ref_find_elt(ref, key->str) != NULL)
3678 /* update entry if it exists */
3679 pat_ref_set(ref, key->str, value->str, NULL);
3680 else
3681 /* insert a new entry */
3682 pat_ref_add(ref, key->str, value->str, NULL);
3683
3684 free_trash_chunk(key);
3685 free_trash_chunk(value);
3686 break;
3687 }
3688
3689 case ACT_CUSTOM:
3690 if ((px->options & PR_O_ABRT_CLOSE) && (s->req.flags & (CF_SHUTR|CF_READ_NULL|CF_READ_ERROR)))
3691 act_flags |= ACT_FLAG_FINAL;
3692
3693 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3694 case ACT_RET_ERR:
3695 case ACT_RET_CONT:
3696 break;
3697 case ACT_RET_STOP:
3698 return HTTP_RULE_RES_DONE;
3699 case ACT_RET_YIELD:
3700 s->current_rule = rule;
3701 return HTTP_RULE_RES_YIELD;
3702 }
3703 break;
3704
3705 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3706 /* Note: only the first valid tracking parameter of each
3707 * applies.
3708 */
3709
3710 if (stkctr_entry(&s->stkctr[http_trk_idx(rule->action)]) == NULL) {
3711 struct stktable *t;
3712 struct stksess *ts;
3713 struct stktable_key *key;
3714 void *ptr;
3715
3716 t = rule->arg.trk_ctr.table.t;
3717 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL, rule->arg.trk_ctr.expr, NULL);
3718
3719 if (key && (ts = stktable_get_entry(t, key))) {
3720 stream_track_stkctr(&s->stkctr[http_trk_idx(rule->action)], t, ts);
3721
3722 /* let's count a new HTTP request as it's the first time we do it */
3723 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3724 if (ptr)
3725 stktable_data_cast(ptr, http_req_cnt)++;
3726
3727 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3728 if (ptr)
3729 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3730 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3731
3732 stkctr_set_flags(&s->stkctr[http_trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3733 if (sess->fe != s->be)
3734 stkctr_set_flags(&s->stkctr[http_trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3735 }
3736 }
3737 break;
3738
3739 /* other flags exists, but normaly, they never be matched. */
3740 default:
3741 break;
3742 }
3743 }
3744
3745 /* we reached the end of the rules, nothing to report */
3746 return HTTP_RULE_RES_CONT;
3747 }
3748
3749
3750 /* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3751 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3752 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3753 * is returned, the process can continue the evaluation of next rule list. If
3754 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3755 * is returned, it means the operation could not be processed and a server error
3756 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3757 * deny rule. If *YIELD is returned, the caller must call again the function
3758 * with the same context.
3759 */
3760 static enum rule_result
http_res_get_intercept_rule(struct proxy * px,struct list * rules,struct stream * s)3761 http_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s)
3762 {
3763 struct session *sess = strm_sess(s);
3764 struct http_txn *txn = s->txn;
3765 struct connection *cli_conn;
3766 struct act_rule *rule;
3767 struct hdr_ctx ctx;
3768 int act_flags = 0;
3769
3770 /* If "the current_rule_list" match the executed rule list, we are in
3771 * resume condition. If a resume is needed it is always in the action
3772 * and never in the ACL or converters. In this case, we initialise the
3773 * current rule, and go to the action execution point.
3774 */
3775 if (s->current_rule) {
3776 rule = s->current_rule;
3777 s->current_rule = NULL;
3778 if (s->current_rule_list == rules)
3779 goto resume_execution;
3780 }
3781 s->current_rule_list = rules;
3782
3783 list_for_each_entry(rule, rules, list) {
3784
3785 /* check optional condition */
3786 if (rule->cond) {
3787 int ret;
3788
3789 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3790 ret = acl_pass(ret);
3791
3792 if (rule->cond->pol == ACL_COND_UNLESS)
3793 ret = !ret;
3794
3795 if (!ret) /* condition not matched */
3796 continue;
3797 }
3798
3799 act_flags |= ACT_FLAG_FIRST;
3800 resume_execution:
3801 switch (rule->action) {
3802 case ACT_ACTION_ALLOW:
3803 return HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3804
3805 case ACT_ACTION_DENY:
3806 txn->flags |= TX_SVDENY;
3807 return HTTP_RULE_RES_STOP;
3808
3809 case ACT_HTTP_SET_NICE:
3810 s->task->nice = rule->arg.nice;
3811 break;
3812
3813 case ACT_HTTP_SET_TOS:
3814 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3815 inet_set_tos(cli_conn->t.sock.fd, &cli_conn->addr.from, rule->arg.tos);
3816 break;
3817
3818 case ACT_HTTP_SET_MARK:
3819 #ifdef SO_MARK
3820 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3821 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
3822 #endif
3823 break;
3824
3825 case ACT_HTTP_SET_LOGL:
3826 s->logs.level = rule->arg.loglevel;
3827 break;
3828
3829 case ACT_HTTP_REPLACE_HDR:
3830 case ACT_HTTP_REPLACE_VAL:
3831 if (http_transform_header(s, &txn->rsp, rule->arg.hdr_add.name,
3832 rule->arg.hdr_add.name_len,
3833 &rule->arg.hdr_add.fmt,
3834 &rule->arg.hdr_add.re, rule->action))
3835 return HTTP_RULE_RES_BADREQ;
3836 break;
3837
3838 case ACT_HTTP_DEL_HDR:
3839 ctx.idx = 0;
3840 /* remove all occurrences of the header */
3841 while (http_find_header2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len,
3842 txn->rsp.chn->buf->p, &txn->hdr_idx, &ctx)) {
3843 http_remove_header2(&txn->rsp, &txn->hdr_idx, &ctx);
3844 }
3845 break;
3846
3847 case ACT_HTTP_SET_HDR:
3848 case ACT_HTTP_ADD_HDR: {
3849 struct chunk *replace;
3850
3851 replace = alloc_trash_chunk();
3852 if (!replace)
3853 return HTTP_RULE_RES_BADREQ;
3854
3855 chunk_printf(replace, "%s: ", rule->arg.hdr_add.name);
3856 memcpy(replace->str, rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3857 replace->len = rule->arg.hdr_add.name_len;
3858 replace->str[replace->len++] = ':';
3859 replace->str[replace->len++] = ' ';
3860 replace->len += build_logline(s, replace->str + replace->len, replace->size - replace->len,
3861 &rule->arg.hdr_add.fmt);
3862
3863 if (rule->action == ACT_HTTP_SET_HDR) {
3864 /* remove all occurrences of the header */
3865 ctx.idx = 0;
3866 while (http_find_header2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len,
3867 txn->rsp.chn->buf->p, &txn->hdr_idx, &ctx)) {
3868 http_remove_header2(&txn->rsp, &txn->hdr_idx, &ctx);
3869 }
3870 }
3871 http_header_add_tail2(&txn->rsp, &txn->hdr_idx, replace->str, replace->len);
3872
3873 free_trash_chunk(replace);
3874 break;
3875 }
3876
3877 case ACT_HTTP_DEL_ACL:
3878 case ACT_HTTP_DEL_MAP: {
3879 struct pat_ref *ref;
3880 struct chunk *key;
3881
3882 /* collect reference */
3883 ref = pat_ref_lookup(rule->arg.map.ref);
3884 if (!ref)
3885 continue;
3886
3887 /* allocate key */
3888 key = alloc_trash_chunk();
3889 if (!key)
3890 return HTTP_RULE_RES_BADREQ;
3891
3892 /* collect key */
3893 key->len = build_logline(s, key->str, key->size, &rule->arg.map.key);
3894 key->str[key->len] = '\0';
3895
3896 /* perform update */
3897 /* returned code: 1=ok, 0=ko */
3898 pat_ref_delete(ref, key->str);
3899
3900 free_trash_chunk(key);
3901 break;
3902 }
3903
3904 case ACT_HTTP_ADD_ACL: {
3905 struct pat_ref *ref;
3906 struct chunk *key;
3907
3908 /* collect reference */
3909 ref = pat_ref_lookup(rule->arg.map.ref);
3910 if (!ref)
3911 continue;
3912
3913 /* allocate key */
3914 key = alloc_trash_chunk();
3915 if (!key)
3916 return HTTP_RULE_RES_BADREQ;
3917
3918 /* collect key */
3919 key->len = build_logline(s, key->str, key->size, &rule->arg.map.key);
3920 key->str[key->len] = '\0';
3921
3922 /* perform update */
3923 /* check if the entry already exists */
3924 if (pat_ref_find_elt(ref, key->str) == NULL)
3925 pat_ref_add(ref, key->str, NULL, NULL);
3926
3927 free_trash_chunk(key);
3928 break;
3929 }
3930
3931 case ACT_HTTP_SET_MAP: {
3932 struct pat_ref *ref;
3933 struct chunk *key, *value;
3934
3935 /* collect reference */
3936 ref = pat_ref_lookup(rule->arg.map.ref);
3937 if (!ref)
3938 continue;
3939
3940 /* allocate key */
3941 key = alloc_trash_chunk();
3942 if (!key)
3943 return HTTP_RULE_RES_BADREQ;
3944
3945 /* allocate value */
3946 value = alloc_trash_chunk();
3947 if (!value) {
3948 free_trash_chunk(key);
3949 return HTTP_RULE_RES_BADREQ;
3950 }
3951
3952 /* collect key */
3953 key->len = build_logline(s, key->str, key->size, &rule->arg.map.key);
3954 key->str[key->len] = '\0';
3955
3956 /* collect value */
3957 value->len = build_logline(s, value->str, value->size, &rule->arg.map.value);
3958 value->str[value->len] = '\0';
3959
3960 /* perform update */
3961 if (pat_ref_find_elt(ref, key->str) != NULL)
3962 /* update entry if it exists */
3963 pat_ref_set(ref, key->str, value->str, NULL);
3964 else
3965 /* insert a new entry */
3966 pat_ref_add(ref, key->str, value->str, NULL);
3967
3968 free_trash_chunk(key);
3969 free_trash_chunk(value);
3970 break;
3971 }
3972
3973 case ACT_HTTP_REDIR:
3974 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3975 return HTTP_RULE_RES_BADREQ;
3976 return HTTP_RULE_RES_DONE;
3977
3978 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3979 /* Note: only the first valid tracking parameter of each
3980 * applies.
3981 */
3982
3983 if (stkctr_entry(&s->stkctr[http_trk_idx(rule->action)]) == NULL) {
3984 struct stktable *t;
3985 struct stksess *ts;
3986 struct stktable_key *key;
3987 void *ptr;
3988
3989 t = rule->arg.trk_ctr.table.t;
3990 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL, rule->arg.trk_ctr.expr, NULL);
3991
3992 if (key && (ts = stktable_get_entry(t, key))) {
3993 stream_track_stkctr(&s->stkctr[http_trk_idx(rule->action)], t, ts);
3994
3995 /* let's count a new HTTP request as it's the first time we do it */
3996 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3997 if (ptr)
3998 stktable_data_cast(ptr, http_req_cnt)++;
3999
4000 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
4001 if (ptr)
4002 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
4003 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
4004
4005 stkctr_set_flags(&s->stkctr[http_trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
4006 if (sess->fe != s->be)
4007 stkctr_set_flags(&s->stkctr[http_trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
4008
4009 /* When the client triggers a 4xx from the server, it's most often due
4010 * to a missing object or permission. These events should be tracked
4011 * because if they happen often, it may indicate a brute force or a
4012 * vulnerability scan. Normally this is done when receiving the response
4013 * but here we're tracking after this ought to have been done so we have
4014 * to do it on purpose.
4015 */
4016 if ((unsigned)(txn->status - 400) < 100) {
4017 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
4018 if (ptr)
4019 stktable_data_cast(ptr, http_err_cnt)++;
4020
4021 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
4022 if (ptr)
4023 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
4024 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
4025 }
4026 }
4027 }
4028 break;
4029
4030 case ACT_CUSTOM:
4031 if ((px->options & PR_O_ABRT_CLOSE) && (s->req.flags & (CF_SHUTR|CF_READ_NULL|CF_READ_ERROR)))
4032 act_flags |= ACT_FLAG_FINAL;
4033
4034 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
4035 case ACT_RET_ERR:
4036 case ACT_RET_CONT:
4037 break;
4038 case ACT_RET_STOP:
4039 return HTTP_RULE_RES_STOP;
4040 case ACT_RET_YIELD:
4041 s->current_rule = rule;
4042 return HTTP_RULE_RES_YIELD;
4043 }
4044 break;
4045
4046 /* other flags exists, but normaly, they never be matched. */
4047 default:
4048 break;
4049 }
4050 }
4051
4052 /* we reached the end of the rules, nothing to report */
4053 return HTTP_RULE_RES_CONT;
4054 }
4055
4056
4057 /* Perform an HTTP redirect based on the information in <rule>. The function
4058 * returns non-zero on success, or zero in case of a, irrecoverable error such
4059 * as too large a request to build a valid response.
4060 */
http_apply_redirect_rule(struct redirect_rule * rule,struct stream * s,struct http_txn * txn)4061 static int http_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
4062 {
4063 struct http_msg *req = &txn->req;
4064 struct http_msg *res = &txn->rsp;
4065 const char *msg_fmt;
4066 struct chunk *chunk;
4067 int ret = 0;
4068
4069 chunk = alloc_trash_chunk();
4070 if (!chunk)
4071 goto leave;
4072
4073 /* build redirect message */
4074 switch(rule->code) {
4075 case 308:
4076 msg_fmt = HTTP_308;
4077 break;
4078 case 307:
4079 msg_fmt = HTTP_307;
4080 break;
4081 case 303:
4082 msg_fmt = HTTP_303;
4083 break;
4084 case 301:
4085 msg_fmt = HTTP_301;
4086 break;
4087 case 302:
4088 default:
4089 msg_fmt = HTTP_302;
4090 break;
4091 }
4092
4093 if (unlikely(!chunk_strcpy(chunk, msg_fmt)))
4094 goto leave;
4095
4096 switch(rule->type) {
4097 case REDIRECT_TYPE_SCHEME: {
4098 const char *path;
4099 const char *host;
4100 struct hdr_ctx ctx;
4101 int pathlen;
4102 int hostlen;
4103
4104 host = "";
4105 hostlen = 0;
4106 ctx.idx = 0;
4107 if (http_find_header2("Host", 4, req->chn->buf->p, &txn->hdr_idx, &ctx)) {
4108 host = ctx.line + ctx.val;
4109 hostlen = ctx.vlen;
4110 }
4111
4112 path = http_get_path(txn);
4113 /* build message using path */
4114 if (path) {
4115 pathlen = req->sl.rq.u_l + (req->chn->buf->p + req->sl.rq.u) - path;
4116 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
4117 int qs = 0;
4118 while (qs < pathlen) {
4119 if (path[qs] == '?') {
4120 pathlen = qs;
4121 break;
4122 }
4123 qs++;
4124 }
4125 }
4126 } else {
4127 path = "/";
4128 pathlen = 1;
4129 }
4130
4131 if (rule->rdr_str) { /* this is an old "redirect" rule */
4132 /* check if we can add scheme + "://" + host + path */
4133 if (chunk->len + rule->rdr_len + 3 + hostlen + pathlen > chunk->size - 4)
4134 goto leave;
4135
4136 /* add scheme */
4137 memcpy(chunk->str + chunk->len, rule->rdr_str, rule->rdr_len);
4138 chunk->len += rule->rdr_len;
4139 }
4140 else {
4141 /* add scheme with executing log format */
4142 chunk->len += build_logline(s, chunk->str + chunk->len, chunk->size - chunk->len, &rule->rdr_fmt);
4143
4144 /* check if we can add scheme + "://" + host + path */
4145 if (chunk->len + 3 + hostlen + pathlen > chunk->size - 4)
4146 goto leave;
4147 }
4148 /* add "://" */
4149 memcpy(chunk->str + chunk->len, "://", 3);
4150 chunk->len += 3;
4151
4152 /* add host */
4153 memcpy(chunk->str + chunk->len, host, hostlen);
4154 chunk->len += hostlen;
4155
4156 /* add path */
4157 memcpy(chunk->str + chunk->len, path, pathlen);
4158 chunk->len += pathlen;
4159
4160 /* append a slash at the end of the location if needed and missing */
4161 if (chunk->len && chunk->str[chunk->len - 1] != '/' &&
4162 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
4163 if (chunk->len > chunk->size - 5)
4164 goto leave;
4165 chunk->str[chunk->len] = '/';
4166 chunk->len++;
4167 }
4168
4169 break;
4170 }
4171 case REDIRECT_TYPE_PREFIX: {
4172 const char *path;
4173 int pathlen;
4174
4175 path = http_get_path(txn);
4176 /* build message using path */
4177 if (path) {
4178 pathlen = req->sl.rq.u_l + (req->chn->buf->p + req->sl.rq.u) - path;
4179 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
4180 int qs = 0;
4181 while (qs < pathlen) {
4182 if (path[qs] == '?') {
4183 pathlen = qs;
4184 break;
4185 }
4186 qs++;
4187 }
4188 }
4189 } else {
4190 path = "/";
4191 pathlen = 1;
4192 }
4193
4194 if (rule->rdr_str) { /* this is an old "redirect" rule */
4195 if (chunk->len + rule->rdr_len + pathlen > chunk->size - 4)
4196 goto leave;
4197
4198 /* add prefix. Note that if prefix == "/", we don't want to
4199 * add anything, otherwise it makes it hard for the user to
4200 * configure a self-redirection.
4201 */
4202 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
4203 memcpy(chunk->str + chunk->len, rule->rdr_str, rule->rdr_len);
4204 chunk->len += rule->rdr_len;
4205 }
4206 }
4207 else {
4208 /* add prefix with executing log format */
4209 chunk->len += build_logline(s, chunk->str + chunk->len, chunk->size - chunk->len, &rule->rdr_fmt);
4210
4211 /* Check length */
4212 if (chunk->len + pathlen > chunk->size - 4)
4213 goto leave;
4214 }
4215
4216 /* add path */
4217 memcpy(chunk->str + chunk->len, path, pathlen);
4218 chunk->len += pathlen;
4219
4220 /* append a slash at the end of the location if needed and missing */
4221 if (chunk->len && chunk->str[chunk->len - 1] != '/' &&
4222 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
4223 if (chunk->len > chunk->size - 5)
4224 goto leave;
4225 chunk->str[chunk->len] = '/';
4226 chunk->len++;
4227 }
4228
4229 break;
4230 }
4231 case REDIRECT_TYPE_LOCATION:
4232 default:
4233 if (rule->rdr_str) { /* this is an old "redirect" rule */
4234 if (chunk->len + rule->rdr_len > chunk->size - 4)
4235 goto leave;
4236
4237 /* add location */
4238 memcpy(chunk->str + chunk->len, rule->rdr_str, rule->rdr_len);
4239 chunk->len += rule->rdr_len;
4240 }
4241 else {
4242 /* add location with executing log format */
4243 chunk->len += build_logline(s, chunk->str + chunk->len, chunk->size - chunk->len, &rule->rdr_fmt);
4244
4245 /* Check left length */
4246 if (chunk->len > chunk->size - 4)
4247 goto leave;
4248 }
4249 break;
4250 }
4251
4252 if (rule->cookie_len) {
4253 memcpy(chunk->str + chunk->len, "\r\nSet-Cookie: ", 14);
4254 chunk->len += 14;
4255 memcpy(chunk->str + chunk->len, rule->cookie_str, rule->cookie_len);
4256 chunk->len += rule->cookie_len;
4257 }
4258
4259 /* add end of headers and the keep-alive/close status. */
4260 txn->status = rule->code;
4261
4262 if ((req->flags & HTTP_MSGF_XFER_LEN) &&
4263 ((!(req->flags & HTTP_MSGF_TE_CHNK) && !req->body_len) || (req->msg_state == HTTP_MSG_DONE)) &&
4264 ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL ||
4265 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)) {
4266 /* keep-alive possible */
4267 if (!(req->flags & HTTP_MSGF_VER_11)) {
4268 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
4269 memcpy(chunk->str + chunk->len, "\r\nProxy-Connection: keep-alive", 30);
4270 chunk->len += 30;
4271 } else {
4272 memcpy(chunk->str + chunk->len, "\r\nConnection: keep-alive", 24);
4273 chunk->len += 24;
4274 }
4275 }
4276 memcpy(chunk->str + chunk->len, "\r\n\r\n", 4);
4277 chunk->len += 4;
4278 FLT_STRM_CB(s, flt_http_reply(s, txn->status, chunk));
4279 bo_inject(res->chn, chunk->str, chunk->len);
4280 /* "eat" the request */
4281 bi_fast_delete(req->chn->buf, req->sov);
4282 req->next -= req->sov;
4283 req->sov = 0;
4284 s->req.analysers = AN_REQ_HTTP_XFER_BODY | (s->req.analysers & AN_REQ_FLT_END);
4285 s->res.analysers = AN_RES_HTTP_XFER_BODY | (s->res.analysers & AN_RES_FLT_END);
4286 req->msg_state = HTTP_MSG_CLOSED;
4287 res->msg_state = HTTP_MSG_DONE;
4288 /* Trim any possible response */
4289 res->chn->buf->i = 0;
4290 res->next = res->sov = 0;
4291 /* let the server side turn to SI_ST_CLO */
4292 channel_shutw_now(req->chn);
4293 channel_dont_connect(req->chn);
4294
4295 if (rule->flags & REDIRECT_FLAG_FROM_REQ) {
4296 /* let's log the request time */
4297 s->logs.tv_request = now;
4298 }
4299 } else {
4300 /* keep-alive not possible */
4301 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
4302 memcpy(chunk->str + chunk->len, "\r\nProxy-Connection: close\r\n\r\n", 29);
4303 chunk->len += 29;
4304 } else {
4305 memcpy(chunk->str + chunk->len, "\r\nConnection: close\r\n\r\n", 23);
4306 chunk->len += 23;
4307 }
4308 http_reply_and_close(s, txn->status, chunk);
4309
4310 if (rule->flags & REDIRECT_FLAG_FROM_REQ) {
4311 /* let's log the request time */
4312 s->logs.tv_request = now;
4313 req->chn->analysers &= AN_REQ_FLT_END;
4314 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
4315 s->sess->fe->fe_counters.intercepted_req++;
4316
4317 }
4318 }
4319
4320 if (!(s->flags & SF_ERR_MASK))
4321 s->flags |= SF_ERR_LOCAL;
4322 if (!(s->flags & SF_FINST_MASK))
4323 s->flags |= ((rule->flags & REDIRECT_FLAG_FROM_REQ) ? SF_FINST_R : SF_FINST_H);
4324
4325 ret = 1;
4326 leave:
4327 free_trash_chunk(chunk);
4328 return ret;
4329 }
4330
4331 /* This stream analyser runs all HTTP request processing which is common to
4332 * frontends and backends, which means blocking ACLs, filters, connection-close,
4333 * reqadd, stats and redirects. This is performed for the designated proxy.
4334 * It returns 1 if the processing can continue on next analysers, or zero if it
4335 * either needs more data or wants to immediately abort the request (eg: deny,
4336 * error, ...).
4337 */
http_process_req_common(struct stream * s,struct channel * req,int an_bit,struct proxy * px)4338 int http_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
4339 {
4340 struct session *sess = s->sess;
4341 struct http_txn *txn = s->txn;
4342 struct http_msg *msg = &txn->req;
4343 struct redirect_rule *rule;
4344 struct cond_wordlist *wl;
4345 enum rule_result verdict;
4346 int deny_status = HTTP_ERR_403;
4347
4348 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
4349 /* we need more data */
4350 goto return_prx_yield;
4351 }
4352
4353 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n",
4354 now_ms, __FUNCTION__,
4355 s,
4356 req,
4357 req->rex, req->wex,
4358 req->flags,
4359 req->buf->i,
4360 req->analysers);
4361
4362 /* just in case we have some per-backend tracking. Only called the first
4363 * execution of the analyser. */
4364 if (!s->current_rule || s->current_rule_list != &px->http_req_rules)
4365 stream_inc_be_http_req_ctr(s);
4366
4367 /* evaluate http-request rules */
4368 if (!LIST_ISEMPTY(&px->http_req_rules)) {
4369 verdict = http_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
4370
4371 switch (verdict) {
4372 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
4373 goto return_prx_yield;
4374
4375 case HTTP_RULE_RES_CONT:
4376 case HTTP_RULE_RES_STOP: /* nothing to do */
4377 break;
4378
4379 case HTTP_RULE_RES_DENY: /* deny or tarpit */
4380 if (txn->flags & TX_CLTARPIT)
4381 goto tarpit;
4382 goto deny;
4383
4384 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
4385 goto return_prx_cond;
4386
4387 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
4388 goto done;
4389
4390 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
4391 goto return_bad_req;
4392 }
4393 }
4394
4395 /* OK at this stage, we know that the request was accepted according to
4396 * the http-request rules, we can check for the stats. Note that the
4397 * URI is detected *before* the req* rules in order not to be affected
4398 * by a possible reqrep, while they are processed *after* so that a
4399 * reqdeny can still block them. This clearly needs to change in 1.6!
4400 */
4401 if (stats_check_uri(&s->si[1], txn, px)) {
4402 s->target = &http_stats_applet.obj_type;
4403 if (unlikely(!stream_int_register_handler(&s->si[1], objt_applet(s->target)))) {
4404 txn->status = 500;
4405 s->logs.tv_request = now;
4406 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_500));
4407
4408 if (!(s->flags & SF_ERR_MASK))
4409 s->flags |= SF_ERR_RESOURCE;
4410 goto return_prx_cond;
4411 }
4412
4413 /* parse the whole stats request and extract the relevant information */
4414 http_handle_stats(s, req);
4415 verdict = http_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
4416 /* not all actions implemented: deny, allow, auth */
4417
4418 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
4419 goto deny;
4420
4421 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
4422 goto return_prx_cond;
4423 }
4424
4425 /* evaluate the req* rules except reqadd */
4426 if (px->req_exp != NULL) {
4427 if (apply_filters_to_request(s, req, px) < 0)
4428 goto return_bad_req;
4429
4430 if (txn->flags & TX_CLDENY)
4431 goto deny;
4432
4433 if (txn->flags & TX_CLTARPIT)
4434 goto tarpit;
4435 }
4436
4437 /* add request headers from the rule sets in the same order */
4438 list_for_each_entry(wl, &px->req_add, list) {
4439 if (wl->cond) {
4440 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4441 ret = acl_pass(ret);
4442 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
4443 ret = !ret;
4444 if (!ret)
4445 continue;
4446 }
4447
4448 if (unlikely(http_header_add_tail(&txn->req, &txn->hdr_idx, wl->s) < 0))
4449 goto return_bad_req;
4450 }
4451
4452
4453 /* Proceed with the stats now. */
4454 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
4455 /* process the stats request now */
4456 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
4457 sess->fe->fe_counters.intercepted_req++;
4458
4459 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
4460 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
4461 if (!(s->flags & SF_FINST_MASK))
4462 s->flags |= SF_FINST_R;
4463
4464 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
4465 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
4466 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
4467 req->analysers |= AN_REQ_HTTP_XFER_BODY;
4468 goto done;
4469 }
4470
4471 /* check whether we have some ACLs set to redirect this request */
4472 list_for_each_entry(rule, &px->redirect_rules, list) {
4473 if (rule->cond) {
4474 int ret;
4475
4476 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4477 ret = acl_pass(ret);
4478 if (rule->cond->pol == ACL_COND_UNLESS)
4479 ret = !ret;
4480 if (!ret)
4481 continue;
4482 }
4483 if (!http_apply_redirect_rule(rule, s, txn))
4484 goto return_bad_req;
4485 goto done;
4486 }
4487
4488 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
4489 * If this happens, then the data will not come immediately, so we must
4490 * send all what we have without waiting. Note that due to the small gain
4491 * in waiting for the body of the request, it's easier to simply put the
4492 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
4493 * itself once used.
4494 */
4495 req->flags |= CF_SEND_DONTWAIT;
4496
4497 done: /* done with this analyser, continue with next ones that the calling
4498 * points will have set, if any.
4499 */
4500 req->analyse_exp = TICK_ETERNITY;
4501 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
4502 req->analysers &= ~an_bit;
4503 return 1;
4504
4505 tarpit:
4506 /* Allow cookie logging
4507 */
4508 if (s->be->cookie_name || sess->fe->capture_name)
4509 manage_client_side_cookies(s, req);
4510
4511 /* When a connection is tarpitted, we use the tarpit timeout,
4512 * which may be the same as the connect timeout if unspecified.
4513 * If unset, then set it to zero because we really want it to
4514 * eventually expire. We build the tarpit as an analyser.
4515 */
4516 channel_erase(&s->req);
4517
4518 /* wipe the request out so that we can drop the connection early
4519 * if the client closes first.
4520 */
4521 channel_dont_connect(req);
4522
4523 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
4524 req->analysers |= AN_REQ_HTTP_TARPIT;
4525 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
4526 if (!req->analyse_exp)
4527 req->analyse_exp = tick_add(now_ms, 0);
4528 stream_inc_http_err_ctr(s);
4529 sess->fe->fe_counters.denied_req++;
4530 if (sess->fe != s->be)
4531 s->be->be_counters.denied_req++;
4532 if (sess->listener->counters)
4533 sess->listener->counters->denied_req++;
4534 goto done_without_exp;
4535
4536 deny: /* this request was blocked (denied) */
4537
4538 /* Allow cookie logging
4539 */
4540 if (s->be->cookie_name || sess->fe->capture_name)
4541 manage_client_side_cookies(s, req);
4542
4543 txn->flags |= TX_CLDENY;
4544 txn->status = http_err_codes[deny_status];
4545 s->logs.tv_request = now;
4546 http_reply_and_close(s, txn->status, http_error_message(s, deny_status));
4547 stream_inc_http_err_ctr(s);
4548 sess->fe->fe_counters.denied_req++;
4549 if (sess->fe != s->be)
4550 s->be->be_counters.denied_req++;
4551 if (sess->listener->counters)
4552 sess->listener->counters->denied_req++;
4553 goto return_prx_cond;
4554
4555 return_bad_req:
4556 /* We centralize bad requests processing here */
4557 if (unlikely(msg->msg_state == HTTP_MSG_ERROR) || msg->err_pos >= 0) {
4558 /* we detected a parsing error. We want to archive this request
4559 * in the dedicated proxy area for later troubleshooting.
4560 */
4561 http_capture_bad_message(&sess->fe->invalid_req, s, msg, msg->err_state, sess->fe);
4562 }
4563
4564 txn->req.err_state = txn->req.msg_state;
4565 txn->req.msg_state = HTTP_MSG_ERROR;
4566 txn->status = 400;
4567 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_400));
4568
4569 sess->fe->fe_counters.failed_req++;
4570 if (sess->listener->counters)
4571 sess->listener->counters->failed_req++;
4572
4573 return_prx_cond:
4574 if (!(s->flags & SF_ERR_MASK))
4575 s->flags |= SF_ERR_PRXCOND;
4576 if (!(s->flags & SF_FINST_MASK))
4577 s->flags |= SF_FINST_R;
4578
4579 req->analysers &= AN_REQ_FLT_END;
4580 req->analyse_exp = TICK_ETERNITY;
4581 return 0;
4582
4583 return_prx_yield:
4584 channel_dont_connect(req);
4585 return 0;
4586 }
4587
4588 /* This function performs all the processing enabled for the current request.
4589 * It returns 1 if the processing can continue on next analysers, or zero if it
4590 * needs more data, encounters an error, or wants to immediately abort the
4591 * request. It relies on buffers flags, and updates s->req.analysers.
4592 */
http_process_request(struct stream * s,struct channel * req,int an_bit)4593 int http_process_request(struct stream *s, struct channel *req, int an_bit)
4594 {
4595 struct session *sess = s->sess;
4596 struct http_txn *txn = s->txn;
4597 struct http_msg *msg = &txn->req;
4598 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
4599
4600 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
4601 /* we need more data */
4602 channel_dont_connect(req);
4603 return 0;
4604 }
4605
4606 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n",
4607 now_ms, __FUNCTION__,
4608 s,
4609 req,
4610 req->rex, req->wex,
4611 req->flags,
4612 req->buf->i,
4613 req->analysers);
4614
4615 /*
4616 * Right now, we know that we have processed the entire headers
4617 * and that unwanted requests have been filtered out. We can do
4618 * whatever we want with the remaining request. Also, now we
4619 * may have separate values for ->fe, ->be.
4620 */
4621
4622 /*
4623 * If HTTP PROXY is set we simply get remote server address parsing
4624 * incoming request. Note that this requires that a connection is
4625 * allocated on the server side.
4626 */
4627 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
4628 struct connection *conn;
4629 char *path;
4630
4631 /* Note that for now we don't reuse existing proxy connections */
4632 if (unlikely((conn = si_alloc_conn(&s->si[1])) == NULL)) {
4633 txn->req.err_state = txn->req.msg_state;
4634 txn->req.msg_state = HTTP_MSG_ERROR;
4635 txn->status = 500;
4636 req->analysers &= AN_REQ_FLT_END;
4637 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_500));
4638
4639 if (!(s->flags & SF_ERR_MASK))
4640 s->flags |= SF_ERR_RESOURCE;
4641 if (!(s->flags & SF_FINST_MASK))
4642 s->flags |= SF_FINST_R;
4643
4644 return 0;
4645 }
4646
4647 path = http_get_path(txn);
4648 if (url2sa(req->buf->p + msg->sl.rq.u,
4649 path ? path - (req->buf->p + msg->sl.rq.u) : msg->sl.rq.u_l,
4650 &conn->addr.to, NULL) == -1)
4651 goto return_bad_req;
4652
4653 /* if the path was found, we have to remove everything between
4654 * req->buf->p + msg->sl.rq.u and path (excluded). If it was not
4655 * found, we need to replace from req->buf->p + msg->sl.rq.u for
4656 * u_l characters by a single "/".
4657 */
4658 if (path) {
4659 char *cur_ptr = req->buf->p;
4660 char *cur_end = cur_ptr + txn->req.sl.rq.l;
4661 int delta;
4662
4663 delta = buffer_replace2(req->buf, req->buf->p + msg->sl.rq.u, path, NULL, 0);
4664 http_msg_move_end(&txn->req, delta);
4665 cur_end += delta;
4666 if (http_parse_reqline(&txn->req, HTTP_MSG_RQMETH, cur_ptr, cur_end + 1, NULL, NULL) == NULL)
4667 goto return_bad_req;
4668 }
4669 else {
4670 char *cur_ptr = req->buf->p;
4671 char *cur_end = cur_ptr + txn->req.sl.rq.l;
4672 int delta;
4673
4674 delta = buffer_replace2(req->buf, req->buf->p + msg->sl.rq.u,
4675 req->buf->p + msg->sl.rq.u + msg->sl.rq.u_l, "/", 1);
4676 http_msg_move_end(&txn->req, delta);
4677 cur_end += delta;
4678 if (http_parse_reqline(&txn->req, HTTP_MSG_RQMETH, cur_ptr, cur_end + 1, NULL, NULL) == NULL)
4679 goto return_bad_req;
4680 }
4681 }
4682
4683 /*
4684 * 7: Now we can work with the cookies.
4685 * Note that doing so might move headers in the request, but
4686 * the fields will stay coherent and the URI will not move.
4687 * This should only be performed in the backend.
4688 */
4689 if (s->be->cookie_name || sess->fe->capture_name)
4690 manage_client_side_cookies(s, req);
4691
4692 /* add unique-id if "header-unique-id" is specified */
4693
4694 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
4695 if ((s->unique_id = pool_alloc2(pool2_uniqueid)) == NULL)
4696 goto return_bad_req;
4697 s->unique_id[0] = '\0';
4698 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
4699 }
4700
4701 if (sess->fe->header_unique_id && s->unique_id) {
4702 chunk_printf(&trash, "%s: %s", sess->fe->header_unique_id, s->unique_id);
4703 if (trash.len < 0)
4704 goto return_bad_req;
4705 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, trash.len) < 0))
4706 goto return_bad_req;
4707 }
4708
4709 /*
4710 * 9: add X-Forwarded-For if either the frontend or the backend
4711 * asks for it.
4712 */
4713 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
4714 struct hdr_ctx ctx = { .idx = 0 };
4715 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
4716 http_find_header2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
4717 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len,
4718 req->buf->p, &txn->hdr_idx, &ctx)) {
4719 /* The header is set to be added only if none is present
4720 * and we found it, so don't do anything.
4721 */
4722 }
4723 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
4724 /* Add an X-Forwarded-For header unless the source IP is
4725 * in the 'except' network range.
4726 */
4727 if ((!sess->fe->except_mask.s_addr ||
4728 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
4729 != sess->fe->except_net.s_addr) &&
4730 (!s->be->except_mask.s_addr ||
4731 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
4732 != s->be->except_net.s_addr)) {
4733 int len;
4734 unsigned char *pn;
4735 pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
4736
4737 /* Note: we rely on the backend to get the header name to be used for
4738 * x-forwarded-for, because the header is really meant for the backends.
4739 * However, if the backend did not specify any option, we have to rely
4740 * on the frontend's header name.
4741 */
4742 if (s->be->fwdfor_hdr_len) {
4743 len = s->be->fwdfor_hdr_len;
4744 memcpy(trash.str, s->be->fwdfor_hdr_name, len);
4745 } else {
4746 len = sess->fe->fwdfor_hdr_len;
4747 memcpy(trash.str, sess->fe->fwdfor_hdr_name, len);
4748 }
4749 len += snprintf(trash.str + len, trash.size - len, ": %d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
4750
4751 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, len) < 0))
4752 goto return_bad_req;
4753 }
4754 }
4755 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
4756 /* FIXME: for the sake of completeness, we should also support
4757 * 'except' here, although it is mostly useless in this case.
4758 */
4759 int len;
4760 char pn[INET6_ADDRSTRLEN];
4761 inet_ntop(AF_INET6,
4762 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
4763 pn, sizeof(pn));
4764
4765 /* Note: we rely on the backend to get the header name to be used for
4766 * x-forwarded-for, because the header is really meant for the backends.
4767 * However, if the backend did not specify any option, we have to rely
4768 * on the frontend's header name.
4769 */
4770 if (s->be->fwdfor_hdr_len) {
4771 len = s->be->fwdfor_hdr_len;
4772 memcpy(trash.str, s->be->fwdfor_hdr_name, len);
4773 } else {
4774 len = sess->fe->fwdfor_hdr_len;
4775 memcpy(trash.str, sess->fe->fwdfor_hdr_name, len);
4776 }
4777 len += snprintf(trash.str + len, trash.size - len, ": %s", pn);
4778
4779 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, len) < 0))
4780 goto return_bad_req;
4781 }
4782 }
4783
4784 /*
4785 * 10: add X-Original-To if either the frontend or the backend
4786 * asks for it.
4787 */
4788 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
4789
4790 /* FIXME: don't know if IPv6 can handle that case too. */
4791 if (cli_conn && cli_conn->addr.to.ss_family == AF_INET) {
4792 /* Add an X-Original-To header unless the destination IP is
4793 * in the 'except' network range.
4794 */
4795 conn_get_to_addr(cli_conn);
4796
4797 if (cli_conn->addr.to.ss_family == AF_INET &&
4798 ((!sess->fe->except_mask_to.s_addr ||
4799 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
4800 != sess->fe->except_to.s_addr) &&
4801 (!s->be->except_mask_to.s_addr ||
4802 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
4803 != s->be->except_to.s_addr))) {
4804 int len;
4805 unsigned char *pn;
4806 pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
4807
4808 /* Note: we rely on the backend to get the header name to be used for
4809 * x-original-to, because the header is really meant for the backends.
4810 * However, if the backend did not specify any option, we have to rely
4811 * on the frontend's header name.
4812 */
4813 if (s->be->orgto_hdr_len) {
4814 len = s->be->orgto_hdr_len;
4815 memcpy(trash.str, s->be->orgto_hdr_name, len);
4816 } else {
4817 len = sess->fe->orgto_hdr_len;
4818 memcpy(trash.str, sess->fe->orgto_hdr_name, len);
4819 }
4820 len += snprintf(trash.str + len, trash.size - len, ": %d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
4821
4822 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, len) < 0))
4823 goto return_bad_req;
4824 }
4825 }
4826 }
4827
4828 /* 11: add "Connection: close" or "Connection: keep-alive" if needed and not yet set.
4829 * If an "Upgrade" token is found, the header is left untouched in order not to have
4830 * to deal with some servers bugs : some of them fail an Upgrade if anything but
4831 * "Upgrade" is present in the Connection header.
4832 */
4833 if (!(txn->flags & TX_HDR_CONN_UPG) &&
4834 (((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN) ||
4835 ((sess->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||
4836 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL))) {
4837 unsigned int want_flags = 0;
4838
4839 if (msg->flags & HTTP_MSGF_VER_11) {
4840 if (((txn->flags & TX_CON_WANT_MSK) >= TX_CON_WANT_SCL ||
4841 ((sess->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||
4842 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL)) &&
4843 !((sess->fe->options2|s->be->options2) & PR_O2_FAKE_KA))
4844 want_flags |= TX_CON_CLO_SET;
4845 } else {
4846 if (((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL &&
4847 ((sess->fe->options & PR_O_HTTP_MODE) != PR_O_HTTP_PCL &&
4848 (s->be->options & PR_O_HTTP_MODE) != PR_O_HTTP_PCL)) ||
4849 ((sess->fe->options2|s->be->options2) & PR_O2_FAKE_KA))
4850 want_flags |= TX_CON_KAL_SET;
4851 }
4852
4853 if (want_flags != (txn->flags & (TX_CON_CLO_SET|TX_CON_KAL_SET)))
4854 http_change_connection_header(txn, msg, want_flags);
4855 }
4856
4857
4858 /* If we have no server assigned yet and we're balancing on url_param
4859 * with a POST request, we may be interested in checking the body for
4860 * that parameter. This will be done in another analyser.
4861 */
4862 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
4863 s->txn->meth == HTTP_METH_POST &&
4864 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH &&
4865 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
4866 channel_dont_connect(req);
4867 req->analysers |= AN_REQ_HTTP_BODY;
4868 }
4869
4870 if (msg->flags & HTTP_MSGF_XFER_LEN) {
4871 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
4872 req->analysers |= AN_REQ_HTTP_XFER_BODY;
4873 #ifdef TCP_QUICKACK
4874 /* We expect some data from the client. Unless we know for sure
4875 * we already have a full request, we have to re-enable quick-ack
4876 * in case we previously disabled it, otherwise we might cause
4877 * the client to delay further data.
4878 */
4879 if ((sess->listener->options & LI_O_NOQUICKACK) &&
4880 cli_conn && conn_ctrl_ready(cli_conn) &&
4881 ((msg->flags & HTTP_MSGF_TE_CHNK) ||
4882 (msg->body_len > req->buf->i - txn->req.eoh - 2)))
4883 setsockopt(cli_conn->t.sock.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
4884 #endif
4885 }
4886
4887 /*************************************************************
4888 * OK, that's finished for the headers. We have done what we *
4889 * could. Let's switch to the DATA state. *
4890 ************************************************************/
4891 req->analyse_exp = TICK_ETERNITY;
4892 req->analysers &= ~an_bit;
4893
4894 /* if the server closes the connection, we want to immediately react
4895 * and close the socket to save packets and syscalls.
4896 */
4897 if (!(req->analysers & AN_REQ_HTTP_XFER_BODY))
4898 s->si[1].flags |= SI_FL_NOHALF;
4899
4900 s->logs.tv_request = now;
4901 /* OK let's go on with the BODY now */
4902 return 1;
4903
4904 return_bad_req: /* let's centralize all bad requests */
4905 if (unlikely(msg->msg_state == HTTP_MSG_ERROR) || msg->err_pos >= 0) {
4906 /* we detected a parsing error. We want to archive this request
4907 * in the dedicated proxy area for later troubleshooting.
4908 */
4909 http_capture_bad_message(&sess->fe->invalid_req, s, msg, msg->err_state, sess->fe);
4910 }
4911
4912 txn->req.err_state = txn->req.msg_state;
4913 txn->req.msg_state = HTTP_MSG_ERROR;
4914 txn->status = 400;
4915 req->analysers &= AN_REQ_FLT_END;
4916 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_400));
4917
4918 sess->fe->fe_counters.failed_req++;
4919 if (sess->listener->counters)
4920 sess->listener->counters->failed_req++;
4921
4922 if (!(s->flags & SF_ERR_MASK))
4923 s->flags |= SF_ERR_PRXCOND;
4924 if (!(s->flags & SF_FINST_MASK))
4925 s->flags |= SF_FINST_R;
4926 return 0;
4927 }
4928
4929 /* This function is an analyser which processes the HTTP tarpit. It always
4930 * returns zero, at the beginning because it prevents any other processing
4931 * from occurring, and at the end because it terminates the request.
4932 */
http_process_tarpit(struct stream * s,struct channel * req,int an_bit)4933 int http_process_tarpit(struct stream *s, struct channel *req, int an_bit)
4934 {
4935 struct http_txn *txn = s->txn;
4936
4937 /* This connection is being tarpitted. The CLIENT side has
4938 * already set the connect expiration date to the right
4939 * timeout. We just have to check that the client is still
4940 * there and that the timeout has not expired.
4941 */
4942 channel_dont_connect(req);
4943 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
4944 !tick_is_expired(req->analyse_exp, now_ms))
4945 return 0;
4946
4947 /* We will set the queue timer to the time spent, just for
4948 * logging purposes. We fake a 500 server error, so that the
4949 * attacker will not suspect his connection has been tarpitted.
4950 * It will not cause trouble to the logs because we can exclude
4951 * the tarpitted connections by filtering on the 'PT' status flags.
4952 */
4953 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
4954
4955 txn->status = 500;
4956 if (!(req->flags & CF_READ_ERROR))
4957 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_500));
4958
4959 req->analysers &= AN_REQ_FLT_END;
4960 req->analyse_exp = TICK_ETERNITY;
4961
4962 if (!(s->flags & SF_ERR_MASK))
4963 s->flags |= SF_ERR_PRXCOND;
4964 if (!(s->flags & SF_FINST_MASK))
4965 s->flags |= SF_FINST_T;
4966 return 0;
4967 }
4968
4969 /* This function is an analyser which waits for the HTTP request body. It waits
4970 * for either the buffer to be full, or the full advertised contents to have
4971 * reached the buffer. It must only be called after the standard HTTP request
4972 * processing has occurred, because it expects the request to be parsed and will
4973 * look for the Expect header. It may send a 100-Continue interim response. It
4974 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
4975 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
4976 * needs to read more data, or 1 once it has completed its analysis.
4977 */
http_wait_for_request_body(struct stream * s,struct channel * req,int an_bit)4978 int http_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
4979 {
4980 struct session *sess = s->sess;
4981 struct http_txn *txn = s->txn;
4982 struct http_msg *msg = &s->txn->req;
4983
4984 /* We have to parse the HTTP request body to find any required data.
4985 * "balance url_param check_post" should have been the only way to get
4986 * into this. We were brought here after HTTP header analysis, so all
4987 * related structures are ready.
4988 */
4989
4990 if (msg->msg_state < HTTP_MSG_CHUNK_SIZE) {
4991 /* This is the first call */
4992 if (msg->msg_state < HTTP_MSG_BODY)
4993 goto missing_data;
4994
4995 if (msg->msg_state < HTTP_MSG_100_SENT) {
4996 /* If we have HTTP/1.1 and Expect: 100-continue, then we must
4997 * send an HTTP/1.1 100 Continue intermediate response.
4998 */
4999 if (msg->flags & HTTP_MSGF_VER_11) {
5000 struct hdr_ctx ctx;
5001 ctx.idx = 0;
5002 /* Expect is allowed in 1.1, look for it */
5003 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &ctx) &&
5004 unlikely(ctx.vlen == 12 && strncasecmp(ctx.line+ctx.val, "100-continue", 12) == 0)) {
5005 bo_inject(&s->res, http_100_chunk.str, http_100_chunk.len);
5006 http_remove_header2(&txn->req, &txn->hdr_idx, &ctx);
5007 }
5008 }
5009 msg->msg_state = HTTP_MSG_100_SENT;
5010 }
5011
5012 /* we have msg->sov which points to the first byte of message body.
5013 * req->buf->p still points to the beginning of the message. We
5014 * must save the body in msg->next because it survives buffer
5015 * re-alignments.
5016 */
5017 msg->next = msg->sov;
5018
5019 if (msg->flags & HTTP_MSGF_TE_CHNK)
5020 msg->msg_state = HTTP_MSG_CHUNK_SIZE;
5021 else
5022 msg->msg_state = HTTP_MSG_DATA;
5023 }
5024
5025 if (!(msg->flags & HTTP_MSGF_TE_CHNK)) {
5026 /* We're in content-length mode, we just have to wait for enough data. */
5027 if (http_body_bytes(msg) < msg->body_len)
5028 goto missing_data;
5029
5030 /* OK we have everything we need now */
5031 goto http_end;
5032 }
5033
5034 /* OK here we're parsing a chunked-encoded message */
5035
5036 if (msg->msg_state == HTTP_MSG_CHUNK_SIZE) {
5037 /* read the chunk size and assign it to ->chunk_len, then
5038 * set ->sov and ->next to point to the body and switch to DATA or
5039 * TRAILERS state.
5040 */
5041 int ret = http_parse_chunk_size(msg);
5042
5043 if (!ret)
5044 goto missing_data;
5045 else if (ret < 0) {
5046 stream_inc_http_err_ctr(s);
5047 goto return_bad_req;
5048 }
5049 msg->next += ret;
5050 msg->msg_state = msg->chunk_len ? HTTP_MSG_DATA : HTTP_MSG_TRAILERS;
5051 }
5052
5053 /* Now we're in HTTP_MSG_DATA or HTTP_MSG_TRAILERS state.
5054 * We have the first data byte is in msg->sov + msg->sol. We're waiting
5055 * for at least a whole chunk or the whole content length bytes after
5056 * msg->sov + msg->sol.
5057 */
5058 if (msg->msg_state == HTTP_MSG_TRAILERS)
5059 goto http_end;
5060
5061 if (http_body_bytes(msg) >= msg->body_len) /* we have enough bytes now */
5062 goto http_end;
5063
5064 missing_data:
5065 /* we get here if we need to wait for more data. If the buffer is full,
5066 * we have the maximum we can expect.
5067 */
5068 if (buffer_full(req->buf, global.tune.maxrewrite))
5069 goto http_end;
5070
5071 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
5072 txn->status = 408;
5073 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_408));
5074
5075 if (!(s->flags & SF_ERR_MASK))
5076 s->flags |= SF_ERR_CLITO;
5077 if (!(s->flags & SF_FINST_MASK))
5078 s->flags |= SF_FINST_D;
5079 goto return_err_msg;
5080 }
5081
5082 /* we get here if we need to wait for more data */
5083 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
5084 /* Not enough data. We'll re-use the http-request
5085 * timeout here. Ideally, we should set the timeout
5086 * relative to the accept() date. We just set the
5087 * request timeout once at the beginning of the
5088 * request.
5089 */
5090 channel_dont_connect(req);
5091 if (!tick_isset(req->analyse_exp))
5092 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
5093 return 0;
5094 }
5095
5096 http_end:
5097 /* The situation will not evolve, so let's give up on the analysis. */
5098 s->logs.tv_request = now; /* update the request timer to reflect full request */
5099 req->analysers &= ~an_bit;
5100 req->analyse_exp = TICK_ETERNITY;
5101 return 1;
5102
5103 return_bad_req: /* let's centralize all bad requests */
5104 txn->req.err_state = txn->req.msg_state;
5105 txn->req.msg_state = HTTP_MSG_ERROR;
5106 txn->status = 400;
5107 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_400));
5108
5109 if (!(s->flags & SF_ERR_MASK))
5110 s->flags |= SF_ERR_PRXCOND;
5111 if (!(s->flags & SF_FINST_MASK))
5112 s->flags |= SF_FINST_R;
5113
5114 return_err_msg:
5115 req->analysers &= AN_REQ_FLT_END;
5116 sess->fe->fe_counters.failed_req++;
5117 if (sess->listener->counters)
5118 sess->listener->counters->failed_req++;
5119 return 0;
5120 }
5121
5122 /* send a server's name with an outgoing request over an established connection.
5123 * Note: this function is designed to be called once the request has been scheduled
5124 * for being forwarded. This is the reason why it rewinds the buffer before
5125 * proceeding.
5126 */
http_send_name_header(struct http_txn * txn,struct proxy * be,const char * srv_name)5127 int http_send_name_header(struct http_txn *txn, struct proxy* be, const char* srv_name) {
5128
5129 struct hdr_ctx ctx;
5130
5131 char *hdr_name = be->server_id_hdr_name;
5132 int hdr_name_len = be->server_id_hdr_len;
5133 struct channel *chn = txn->req.chn;
5134 char *hdr_val;
5135 unsigned int old_o, old_i;
5136
5137 ctx.idx = 0;
5138
5139 old_o = http_hdr_rewind(&txn->req);
5140 if (old_o) {
5141 /* The request was already skipped, let's restore it */
5142 b_rew(chn->buf, old_o);
5143 txn->req.next += old_o;
5144 txn->req.sov += old_o;
5145 }
5146
5147 old_i = chn->buf->i;
5148 while (http_find_header2(hdr_name, hdr_name_len, txn->req.chn->buf->p, &txn->hdr_idx, &ctx)) {
5149 /* remove any existing values from the header */
5150 http_remove_header2(&txn->req, &txn->hdr_idx, &ctx);
5151 }
5152
5153 /* Add the new header requested with the server value */
5154 hdr_val = trash.str;
5155 memcpy(hdr_val, hdr_name, hdr_name_len);
5156 hdr_val += hdr_name_len;
5157 *hdr_val++ = ':';
5158 *hdr_val++ = ' ';
5159 hdr_val += strlcpy2(hdr_val, srv_name, trash.str + trash.size - hdr_val);
5160 http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, hdr_val - trash.str);
5161
5162 if (old_o) {
5163 /* If this was a forwarded request, we must readjust the amount of
5164 * data to be forwarded in order to take into account the size
5165 * variations. Note that the current state is >= HTTP_MSG_BODY,
5166 * so we don't have to adjust ->sol.
5167 */
5168 old_o += chn->buf->i - old_i;
5169 b_adv(chn->buf, old_o);
5170 txn->req.next -= old_o;
5171 txn->req.sov -= old_o;
5172 }
5173
5174 return 0;
5175 }
5176
5177 /* Terminate current transaction and prepare a new one. This is very tricky
5178 * right now but it works.
5179 */
http_end_txn_clean_session(struct stream * s)5180 void http_end_txn_clean_session(struct stream *s)
5181 {
5182 int prev_status = s->txn->status;
5183 struct proxy *fe = strm_fe(s);
5184 struct proxy *be = s->be;
5185 struct connection *srv_conn;
5186 struct server *srv;
5187 unsigned int prev_flags = s->txn->flags;
5188
5189 /* FIXME: We need a more portable way of releasing a backend's and a
5190 * server's connections. We need a safer way to reinitialize buffer
5191 * flags. We also need a more accurate method for computing per-request
5192 * data.
5193 */
5194 srv_conn = objt_conn(s->si[1].end);
5195
5196 /* unless we're doing keep-alive, we want to quickly close the connection
5197 * to the server.
5198 */
5199 if (((s->txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) ||
5200 !si_conn_ready(&s->si[1])) {
5201 s->si[1].flags |= SI_FL_NOLINGER | SI_FL_NOHALF;
5202 si_shutr(&s->si[1]);
5203 si_shutw(&s->si[1]);
5204 }
5205
5206 if (s->flags & SF_BE_ASSIGNED) {
5207 be->beconn--;
5208 if (unlikely(s->srv_conn))
5209 sess_change_server(s, NULL);
5210 }
5211
5212 s->logs.t_close = tv_ms_elapsed(&s->logs.tv_accept, &now);
5213 stream_process_counters(s);
5214
5215 if (s->txn->status) {
5216 int n;
5217
5218 n = s->txn->status / 100;
5219 if (n < 1 || n > 5)
5220 n = 0;
5221
5222 if (fe->mode == PR_MODE_HTTP) {
5223 fe->fe_counters.p.http.rsp[n]++;
5224 }
5225 if ((s->flags & SF_BE_ASSIGNED) &&
5226 (be->mode == PR_MODE_HTTP)) {
5227 be->be_counters.p.http.rsp[n]++;
5228 be->be_counters.p.http.cum_req++;
5229 }
5230 }
5231
5232 /* don't count other requests' data */
5233 s->logs.bytes_in -= s->req.buf->i;
5234 s->logs.bytes_out -= s->res.buf->i;
5235
5236 /* let's do a final log if we need it */
5237 if (!LIST_ISEMPTY(&fe->logformat) && s->logs.logwait &&
5238 !(s->flags & SF_MONITOR) &&
5239 (!(fe->options & PR_O_NULLNOLOG) || s->req.total)) {
5240 s->do_log(s);
5241 }
5242
5243 /* stop tracking content-based counters */
5244 stream_stop_content_counters(s);
5245 stream_update_time_stats(s);
5246
5247 s->logs.accept_date = date; /* user-visible date for logging */
5248 s->logs.tv_accept = now; /* corrected date for internal use */
5249 s->logs.t_handshake = 0; /* There are no handshake in keep alive connection. */
5250 s->logs.t_idle = -1;
5251 tv_zero(&s->logs.tv_request);
5252 s->logs.t_queue = -1;
5253 s->logs.t_connect = -1;
5254 s->logs.t_data = -1;
5255 s->logs.t_close = 0;
5256 s->logs.prx_queue_size = 0; /* we get the number of pending conns before us */
5257 s->logs.srv_queue_size = 0; /* we will get this number soon */
5258
5259 s->logs.bytes_in = s->req.total = s->req.buf->i;
5260 s->logs.bytes_out = s->res.total = s->res.buf->i;
5261
5262 if (s->pend_pos)
5263 pendconn_free(s->pend_pos);
5264
5265 if (objt_server(s->target)) {
5266 if (s->flags & SF_CURR_SESS) {
5267 s->flags &= ~SF_CURR_SESS;
5268 objt_server(s->target)->cur_sess--;
5269 }
5270 if (may_dequeue_tasks(objt_server(s->target), be))
5271 process_srv_queue(objt_server(s->target));
5272 }
5273
5274 s->target = NULL;
5275
5276 /* only release our endpoint if we don't intend to reuse the
5277 * connection.
5278 */
5279 if (((s->txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) ||
5280 !si_conn_ready(&s->si[1])) {
5281 si_release_endpoint(&s->si[1]);
5282 srv_conn = NULL;
5283 }
5284
5285 s->si[1].state = s->si[1].prev_state = SI_ST_INI;
5286 s->si[1].err_type = SI_ET_NONE;
5287 s->si[1].conn_retries = 0; /* used for logging too */
5288 s->si[1].exp = TICK_ETERNITY;
5289 s->si[1].flags &= SI_FL_ISBACK | SI_FL_DONT_WAKE; /* we're in the context of process_stream */
5290 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);
5291 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);
5292 s->flags &= ~(SF_DIRECT|SF_ASSIGNED|SF_ADDR_SET|SF_BE_ASSIGNED|SF_FORCE_PRST|SF_IGNORE_PRST);
5293 s->flags &= ~(SF_CURR_SESS|SF_REDIRECTABLE|SF_SRV_REUSED);
5294 s->flags &= ~(SF_ERR_MASK|SF_FINST_MASK|SF_REDISP);
5295
5296 hlua_ctx_destroy(&s->hlua);
5297
5298 /* cleanup and reinit capture arrays, if any */
5299 if (s->req_cap) {
5300 struct cap_hdr *h;
5301 for (h = fe->req_cap; h; h = h->next)
5302 pool_free2(h->pool, s->req_cap[h->index]);
5303 memset(s->req_cap, 0, fe->nb_req_cap * sizeof(void *));
5304 }
5305
5306 if (s->res_cap) {
5307 struct cap_hdr *h;
5308 for (h = fe->rsp_cap; h; h = h->next)
5309 pool_free2(h->pool, s->res_cap[h->index]);
5310 memset(s->res_cap, 0, fe->nb_rsp_cap * sizeof(void *));
5311 }
5312
5313 s->txn->meth = 0;
5314 http_reset_txn(s);
5315 s->txn->flags |= TX_NOT_FIRST | TX_WAIT_NEXT_RQ;
5316
5317 if (prev_status == 401 || prev_status == 407) {
5318 /* In HTTP keep-alive mode, if we receive a 401, we still have
5319 * a chance of being able to send the visitor again to the same
5320 * server over the same connection. This is required by some
5321 * broken protocols such as NTLM, and anyway whenever there is
5322 * an opportunity for sending the challenge to the proper place,
5323 * it's better to do it (at least it helps with debugging).
5324 */
5325 s->txn->flags |= TX_PREFER_LAST;
5326 if (srv_conn)
5327 srv_conn->flags |= CO_FL_PRIVATE;
5328 }
5329
5330 /* Never ever allow to reuse a connection from a non-reuse backend */
5331 if (srv_conn && (be->options & PR_O_REUSE_MASK) == PR_O_REUSE_NEVR)
5332 srv_conn->flags |= CO_FL_PRIVATE;
5333
5334 if (fe->options2 & PR_O2_INDEPSTR)
5335 s->si[1].flags |= SI_FL_INDEP_STR;
5336
5337 if (fe->options2 & PR_O2_NODELAY) {
5338 s->req.flags |= CF_NEVER_WAIT;
5339 s->res.flags |= CF_NEVER_WAIT;
5340 }
5341
5342 /* we're removing the analysers, we MUST re-enable events detection.
5343 * We don't enable close on the response channel since it's either
5344 * already closed, or in keep-alive with an idle connection handler.
5345 */
5346 channel_auto_read(&s->req);
5347 channel_auto_close(&s->req);
5348 channel_auto_read(&s->res);
5349
5350 /* we're in keep-alive with an idle connection, monitor it if not already done */
5351 if (srv_conn && LIST_ISEMPTY(&srv_conn->list)) {
5352 srv = objt_server(srv_conn->target);
5353 if (!srv)
5354 si_idle_conn(&s->si[1], NULL);
5355 else if (srv_conn->flags & CO_FL_PRIVATE)
5356 si_idle_conn(&s->si[1], &srv->priv_conns);
5357 else if (prev_flags & TX_NOT_FIRST)
5358 /* note: we check the request, not the connection, but
5359 * this is valid for strategies SAFE and AGGR, and in
5360 * case of ALWS, we don't care anyway.
5361 */
5362 si_idle_conn(&s->si[1], &srv->safe_conns);
5363 else
5364 si_idle_conn(&s->si[1], &srv->idle_conns);
5365 }
5366 s->req.analysers = strm_li(s) ? strm_li(s)->analysers : 0;
5367 s->res.analysers = 0;
5368 }
5369
5370
5371 /* This function updates the request state machine according to the response
5372 * state machine and buffer flags. It returns 1 if it changes anything (flag
5373 * or state), otherwise zero. It ignores any state before HTTP_MSG_DONE, as
5374 * it is only used to find when a request/response couple is complete. Both
5375 * this function and its equivalent should loop until both return zero. It
5376 * can set its own state to DONE, CLOSING, CLOSED, TUNNEL, ERROR.
5377 */
http_sync_req_state(struct stream * s)5378 int http_sync_req_state(struct stream *s)
5379 {
5380 struct channel *chn = &s->req;
5381 struct http_txn *txn = s->txn;
5382 unsigned int old_flags = chn->flags;
5383 unsigned int old_state = txn->req.msg_state;
5384
5385 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5386 return 0;
5387
5388 if (txn->req.msg_state == HTTP_MSG_DONE) {
5389 /* No need to read anymore, the request was completely parsed.
5390 * We can shut the read side unless we want to abort_on_close,
5391 * or we have a POST request. The issue with POST requests is
5392 * that some browsers still send a CRLF after the request, and
5393 * this CRLF must be read so that it does not remain in the kernel
5394 * buffers, otherwise a close could cause an RST on some systems
5395 * (eg: Linux).
5396 * Note that if we're using keep-alive on the client side, we'd
5397 * rather poll now and keep the polling enabled for the whole
5398 * stream's life than enabling/disabling it between each
5399 * response and next request.
5400 */
5401 if (((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_SCL) &&
5402 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) &&
5403 !(s->be->options & PR_O_ABRT_CLOSE) &&
5404 txn->meth != HTTP_METH_POST)
5405 channel_dont_read(chn);
5406
5407 /* if the server closes the connection, we want to immediately react
5408 * and close the socket to save packets and syscalls.
5409 */
5410 s->si[1].flags |= SI_FL_NOHALF;
5411
5412 /* In any case we've finished parsing the request so we must
5413 * disable Nagle when sending data because 1) we're not going
5414 * to shut this side, and 2) the server is waiting for us to
5415 * send pending data.
5416 */
5417 chn->flags |= CF_NEVER_WAIT;
5418
5419 if (txn->rsp.msg_state == HTTP_MSG_ERROR)
5420 goto wait_other_side;
5421
5422 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5423 /* The server has not finished to respond, so we
5424 * don't want to move in order not to upset it.
5425 */
5426 goto wait_other_side;
5427 }
5428
5429 /* When we get here, it means that both the request and the
5430 * response have finished receiving. Depending on the connection
5431 * mode, we'll have to wait for the last bytes to leave in either
5432 * direction, and sometimes for a close to be effective.
5433 */
5434
5435 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) {
5436 /* Server-close mode : queue a connection close to the server */
5437 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW)))
5438 channel_shutw_now(chn);
5439 }
5440 else if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_CLO) {
5441 /* Option forceclose is set, or either side wants to close,
5442 * let's enforce it now that we're not expecting any new
5443 * data to come. The caller knows the stream is complete
5444 * once both states are CLOSED.
5445 *
5446 * However, there is an exception if the response
5447 * length is undefined. In this case, we need to wait
5448 * the close from the server. The response will be
5449 * switched in TUNNEL mode until the end.
5450 */
5451 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5452 txn->rsp.msg_state != HTTP_MSG_CLOSED)
5453 goto check_channel_flags;
5454
5455 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5456 channel_shutr_now(chn);
5457 channel_shutw_now(chn);
5458 }
5459 }
5460 else {
5461 /* The last possible modes are keep-alive and tunnel. Tunnel mode
5462 * will not have any analyser so it needs to poll for reads.
5463 */
5464 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5465 channel_auto_read(chn);
5466 txn->req.msg_state = HTTP_MSG_TUNNEL;
5467 }
5468 }
5469
5470 goto check_channel_flags;
5471 }
5472
5473 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5474 http_msg_closing:
5475 /* nothing else to forward, just waiting for the output buffer
5476 * to be empty and for the shutw_now to take effect.
5477 */
5478 if (channel_is_empty(chn)) {
5479 txn->req.msg_state = HTTP_MSG_CLOSED;
5480 goto http_msg_closed;
5481 }
5482 else if (chn->flags & CF_SHUTW) {
5483 txn->req.err_state = txn->req.msg_state;
5484 txn->req.msg_state = HTTP_MSG_ERROR;
5485 }
5486 goto wait_other_side;
5487 }
5488
5489 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5490 http_msg_closed:
5491 /* if we don't know whether the server will close, we need to hard close */
5492 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5493 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
5494
5495 /* see above in MSG_DONE why we only do this in these states */
5496 if (((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_SCL) &&
5497 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) &&
5498 !(s->be->options & PR_O_ABRT_CLOSE))
5499 channel_dont_read(chn);
5500 goto wait_other_side;
5501 }
5502
5503 check_channel_flags:
5504 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5505 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5506 /* if we've just closed an output, let's switch */
5507 txn->req.msg_state = HTTP_MSG_CLOSING;
5508 goto http_msg_closing;
5509 }
5510
5511
5512 wait_other_side:
5513 return txn->req.msg_state != old_state || chn->flags != old_flags;
5514 }
5515
5516
5517 /* This function updates the response state machine according to the request
5518 * state machine and buffer flags. It returns 1 if it changes anything (flag
5519 * or state), otherwise zero. It ignores any state before HTTP_MSG_DONE, as
5520 * it is only used to find when a request/response couple is complete. Both
5521 * this function and its equivalent should loop until both return zero. It
5522 * can set its own state to DONE, CLOSING, CLOSED, TUNNEL, ERROR.
5523 */
http_sync_res_state(struct stream * s)5524 int http_sync_res_state(struct stream *s)
5525 {
5526 struct channel *chn = &s->res;
5527 struct http_txn *txn = s->txn;
5528 unsigned int old_flags = chn->flags;
5529 unsigned int old_state = txn->rsp.msg_state;
5530
5531 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5532 return 0;
5533
5534 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5535 /* In theory, we don't need to read anymore, but we must
5536 * still monitor the server connection for a possible close
5537 * while the request is being uploaded, so we don't disable
5538 * reading.
5539 */
5540 /* channel_dont_read(chn); */
5541
5542 if (txn->req.msg_state == HTTP_MSG_ERROR)
5543 goto wait_other_side;
5544
5545 if (txn->req.msg_state < HTTP_MSG_DONE) {
5546 /* The client seems to still be sending data, probably
5547 * because we got an error response during an upload.
5548 * We have the choice of either breaking the connection
5549 * or letting it pass through. Let's do the later.
5550 */
5551 goto wait_other_side;
5552 }
5553
5554 /* When we get here, it means that both the request and the
5555 * response have finished receiving. Depending on the connection
5556 * mode, we'll have to wait for the last bytes to leave in either
5557 * direction, and sometimes for a close to be effective.
5558 */
5559
5560 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) {
5561 /* Server-close mode : shut read and wait for the request
5562 * side to close its output buffer. The caller will detect
5563 * when we're in DONE and the other is in CLOSED and will
5564 * catch that for the final cleanup.
5565 */
5566 if (!(chn->flags & (CF_SHUTR|CF_SHUTR_NOW)))
5567 channel_shutr_now(chn);
5568 }
5569 else if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_CLO) {
5570 /* Option forceclose is set, or either side wants to close,
5571 * let's enforce it now that we're not expecting any new
5572 * data to come. The caller knows the stream is complete
5573 * once both states are CLOSED.
5574 */
5575 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5576 channel_shutr_now(chn);
5577 channel_shutw_now(chn);
5578 }
5579 }
5580 else {
5581 /* The last possible modes are keep-alive and tunnel. Tunnel will
5582 * need to forward remaining data. Keep-alive will need to monitor
5583 * for connection closing.
5584 */
5585 channel_auto_read(chn);
5586 chn->flags |= CF_NEVER_WAIT;
5587 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN)
5588 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5589 }
5590
5591 goto check_channel_flags;
5592 }
5593
5594 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5595 http_msg_closing:
5596 /* nothing else to forward, just waiting for the output buffer
5597 * to be empty and for the shutw_now to take effect.
5598 */
5599 if (channel_is_empty(chn)) {
5600 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5601 goto http_msg_closed;
5602 }
5603 else if (chn->flags & CF_SHUTW) {
5604 txn->rsp.err_state = txn->rsp.msg_state;
5605 txn->rsp.msg_state = HTTP_MSG_ERROR;
5606 s->be->be_counters.cli_aborts++;
5607 if (objt_server(s->target))
5608 objt_server(s->target)->counters.cli_aborts++;
5609 }
5610 goto wait_other_side;
5611 }
5612
5613 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5614 http_msg_closed:
5615 /* drop any pending data */
5616 channel_truncate(chn);
5617 channel_auto_close(chn);
5618 channel_auto_read(chn);
5619 goto wait_other_side;
5620 }
5621
5622 check_channel_flags:
5623 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5624 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5625 /* if we've just closed an output, let's switch */
5626 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5627 goto http_msg_closing;
5628 }
5629
5630 wait_other_side:
5631 /* We force the response to leave immediately if we're waiting for the
5632 * other side, since there is no pending shutdown to push it out.
5633 */
5634 if (!channel_is_empty(chn))
5635 chn->flags |= CF_SEND_DONTWAIT;
5636 return txn->rsp.msg_state != old_state || chn->flags != old_flags;
5637 }
5638
5639
5640 /* Resync the request and response state machines. Return 1 if either state
5641 * changes.
5642 */
http_resync_states(struct stream * s)5643 int http_resync_states(struct stream *s)
5644 {
5645 struct http_txn *txn = s->txn;
5646 int old_req_state = txn->req.msg_state;
5647 int old_res_state = txn->rsp.msg_state;
5648
5649 http_sync_req_state(s);
5650 while (1) {
5651 if (!http_sync_res_state(s))
5652 break;
5653 if (!http_sync_req_state(s))
5654 break;
5655 }
5656
5657 /* OK, both state machines agree on a compatible state.
5658 * There are a few cases we're interested in :
5659 * - HTTP_MSG_CLOSED on both sides means we've reached the end in both
5660 * directions, so let's simply disable both analysers.
5661 * - HTTP_MSG_CLOSED on the response only or HTTP_MSG_ERROR on either
5662 * means we must abort the request.
5663 * - HTTP_MSG_TUNNEL on either means we have to disable analyser on
5664 * corresponding channel.
5665 * - HTTP_MSG_DONE or HTTP_MSG_CLOSED on the request and HTTP_MSG_DONE
5666 * on the response with server-close mode means we've completed one
5667 * request and we must re-initialize the server connection.
5668 */
5669 if (txn->req.msg_state == HTTP_MSG_CLOSED &&
5670 txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5671 s->req.analysers &= AN_REQ_FLT_END;
5672 channel_auto_close(&s->req);
5673 channel_auto_read(&s->req);
5674 s->res.analysers &= AN_RES_FLT_END;
5675 channel_auto_close(&s->res);
5676 channel_auto_read(&s->res);
5677 }
5678 else if (txn->rsp.msg_state == HTTP_MSG_CLOSED ||
5679 txn->rsp.msg_state == HTTP_MSG_ERROR ||
5680 txn->req.msg_state == HTTP_MSG_ERROR) {
5681 s->res.analysers &= AN_RES_FLT_END;
5682 channel_auto_close(&s->res);
5683 channel_auto_read(&s->res);
5684 s->req.analysers &= AN_REQ_FLT_END;
5685 channel_abort(&s->req);
5686 channel_auto_close(&s->req);
5687 channel_auto_read(&s->req);
5688 channel_truncate(&s->req);
5689 }
5690 else if (txn->req.msg_state == HTTP_MSG_TUNNEL ||
5691 txn->rsp.msg_state == HTTP_MSG_TUNNEL) {
5692 if (txn->req.msg_state == HTTP_MSG_TUNNEL) {
5693 s->req.analysers &= AN_REQ_FLT_END;
5694 if (HAS_REQ_DATA_FILTERS(s))
5695 s->req.analysers |= AN_REQ_FLT_XFER_DATA;
5696 }
5697 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL) {
5698 s->res.analysers &= AN_RES_FLT_END;
5699 if (HAS_RSP_DATA_FILTERS(s))
5700 s->res.analysers |= AN_RES_FLT_XFER_DATA;
5701 }
5702 channel_auto_close(&s->req);
5703 channel_auto_read(&s->req);
5704 channel_auto_close(&s->res);
5705 channel_auto_read(&s->res);
5706 }
5707 else if ((txn->req.msg_state == HTTP_MSG_DONE ||
5708 txn->req.msg_state == HTTP_MSG_CLOSED) &&
5709 txn->rsp.msg_state == HTTP_MSG_DONE &&
5710 ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL ||
5711 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)) {
5712 /* server-close/keep-alive: terminate this transaction,
5713 * possibly killing the server connection and reinitialize
5714 * a fresh-new transaction, but only once we're sure there's
5715 * enough room in the request and response buffer to process
5716 * another request. They must not hold any pending output data
5717 * and the response buffer must realigned
5718 * (realign is done is http_end_txn_clean_session).
5719 */
5720 if (s->req.buf->o) {
5721 s->req.flags |= CF_WAKE_WRITE;
5722 return 0;
5723 }
5724 else if (s->res.buf->o) {
5725 s->res.flags |= CF_WAKE_WRITE;
5726 return 0;
5727 }
5728 s->req.analysers = AN_REQ_FLT_END;
5729 s->res.analysers = AN_RES_FLT_END;
5730 txn->flags |= TX_WAIT_CLEANUP;
5731 return 1;
5732 }
5733
5734 return txn->req.msg_state != old_req_state ||
5735 txn->rsp.msg_state != old_res_state;
5736 }
5737
5738 /* This function is an analyser which forwards request body (including chunk
5739 * sizes if any). It is called as soon as we must forward, even if we forward
5740 * zero byte. The only situation where it must not be called is when we're in
5741 * tunnel mode and we want to forward till the close. It's used both to forward
5742 * remaining data and to resync after end of body. It expects the msg_state to
5743 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
5744 * read more data, or 1 once we can go on with next request or end the stream.
5745 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
5746 * bytes of pending data + the headers if not already done.
5747 */
http_request_forward_body(struct stream * s,struct channel * req,int an_bit)5748 int http_request_forward_body(struct stream *s, struct channel *req, int an_bit)
5749 {
5750 struct session *sess = s->sess;
5751 struct http_txn *txn = s->txn;
5752 struct http_msg *msg = &s->txn->req;
5753 int ret;
5754
5755 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
5756 return 0;
5757
5758 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
5759 ((req->flags & CF_SHUTW) && (req->to_forward || req->buf->o))) {
5760 /* Output closed while we were sending data. We must abort and
5761 * wake the other side up.
5762 */
5763 msg->err_state = msg->msg_state;
5764 msg->msg_state = HTTP_MSG_ERROR;
5765 http_resync_states(s);
5766 return 1;
5767 }
5768
5769 /* Note that we don't have to send 100-continue back because we don't
5770 * need the data to complete our job, and it's up to the server to
5771 * decide whether to return 100, 417 or anything else in return of
5772 * an "Expect: 100-continue" header.
5773 */
5774 if (msg->msg_state == HTTP_MSG_BODY) {
5775 msg->msg_state = ((msg->flags & HTTP_MSGF_TE_CHNK)
5776 ? HTTP_MSG_CHUNK_SIZE
5777 : HTTP_MSG_DATA);
5778
5779 /* TODO/filters: when http-buffer-request option is set or if a
5780 * rule on url_param exists, the first chunk size could be
5781 * already parsed. In that case, msg->next is after the chunk
5782 * size (including the CRLF after the size). So this case should
5783 * be handled to */
5784 }
5785
5786 /* Some post-connect processing might want us to refrain from starting to
5787 * forward data. Currently, the only reason for this is "balance url_param"
5788 * whichs need to parse/process the request after we've enabled forwarding.
5789 */
5790 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
5791 if (!(s->res.flags & CF_READ_ATTACHED)) {
5792 channel_auto_connect(req);
5793 req->flags |= CF_WAKE_CONNECT;
5794 goto missing_data_or_waiting;
5795 }
5796 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
5797 }
5798
5799 /* in most states, we should abort in case of early close */
5800 channel_auto_close(req);
5801
5802 if (req->to_forward) {
5803 /* We can't process the buffer's contents yet */
5804 req->flags |= CF_WAKE_WRITE;
5805 goto missing_data_or_waiting;
5806 }
5807
5808 if (msg->msg_state < HTTP_MSG_DONE) {
5809 ret = ((msg->flags & HTTP_MSGF_TE_CHNK)
5810 ? http_msg_forward_chunked_body(s, msg)
5811 : http_msg_forward_body(s, msg));
5812 if (!ret)
5813 goto missing_data_or_waiting;
5814 if (ret < 0)
5815 goto return_bad_req;
5816 }
5817
5818 /* other states, DONE...TUNNEL */
5819 /* we don't want to forward closes on DONE except in tunnel mode. */
5820 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
5821 channel_dont_close(req);
5822
5823 if (http_resync_states(s)) {
5824 /* some state changes occurred, maybe the analyser
5825 * was disabled too. */
5826 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
5827 if (req->flags & CF_SHUTW) {
5828 /* request errors are most likely due to the
5829 * server aborting the transfer. */
5830 goto aborted_xfer;
5831 }
5832 if (msg->err_pos >= 0)
5833 http_capture_bad_message(&sess->fe->invalid_req, s, msg, msg->err_state, s->be);
5834 goto return_bad_req;
5835 }
5836 return 1;
5837 }
5838
5839 /* If "option abortonclose" is set on the backend, we want to monitor
5840 * the client's connection and forward any shutdown notification to the
5841 * server, which will decide whether to close or to go on processing the
5842 * request. We only do that in tunnel mode, and not in other modes since
5843 * it can be abused to exhaust source ports. */
5844 if (s->be->options & PR_O_ABRT_CLOSE) {
5845 channel_auto_read(req);
5846 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
5847 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
5848 s->si[1].flags |= SI_FL_NOLINGER;
5849 channel_auto_close(req);
5850 }
5851 else if (s->txn->meth == HTTP_METH_POST) {
5852 /* POST requests may require to read extra CRLF sent by broken
5853 * browsers and which could cause an RST to be sent upon close
5854 * on some systems (eg: Linux). */
5855 channel_auto_read(req);
5856 }
5857 return 0;
5858
5859 missing_data_or_waiting:
5860 /* stop waiting for data if the input is closed before the end */
5861 if (msg->msg_state < HTTP_MSG_ENDING && req->flags & CF_SHUTR) {
5862 if (!(s->flags & SF_ERR_MASK))
5863 s->flags |= SF_ERR_CLICL;
5864 if (!(s->flags & SF_FINST_MASK)) {
5865 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
5866 s->flags |= SF_FINST_H;
5867 else
5868 s->flags |= SF_FINST_D;
5869 }
5870
5871 sess->fe->fe_counters.cli_aborts++;
5872 s->be->be_counters.cli_aborts++;
5873 if (objt_server(s->target))
5874 objt_server(s->target)->counters.cli_aborts++;
5875
5876 goto return_bad_req_stats_ok;
5877 }
5878
5879 /* waiting for the last bits to leave the buffer */
5880 if (req->flags & CF_SHUTW)
5881 goto aborted_xfer;
5882
5883 /* When TE: chunked is used, we need to get there again to parse remaining
5884 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
5885 * And when content-length is used, we never want to let the possible
5886 * shutdown be forwarded to the other side, as the state machine will
5887 * take care of it once the client responds. It's also important to
5888 * prevent TIME_WAITs from accumulating on the backend side, and for
5889 * HTTP/2 where the last frame comes with a shutdown.
5890 */
5891 if (msg->flags & (HTTP_MSGF_TE_CHNK|HTTP_MSGF_CNT_LEN))
5892 channel_dont_close(req);
5893
5894 /* We know that more data are expected, but we couldn't send more that
5895 * what we did. So we always set the CF_EXPECT_MORE flag so that the
5896 * system knows it must not set a PUSH on this first part. Interactive
5897 * modes are already handled by the stream sock layer. We must not do
5898 * this in content-length mode because it could present the MSG_MORE
5899 * flag with the last block of forwarded data, which would cause an
5900 * additional delay to be observed by the receiver.
5901 */
5902 if (msg->flags & HTTP_MSGF_TE_CHNK)
5903 req->flags |= CF_EXPECT_MORE;
5904
5905 return 0;
5906
5907 return_bad_req: /* let's centralize all bad requests */
5908 sess->fe->fe_counters.failed_req++;
5909 if (sess->listener->counters)
5910 sess->listener->counters->failed_req++;
5911
5912 return_bad_req_stats_ok:
5913 txn->req.err_state = txn->req.msg_state;
5914 txn->req.msg_state = HTTP_MSG_ERROR;
5915 if (txn->status) {
5916 /* Note: we don't send any error if some data were already sent */
5917 http_reply_and_close(s, txn->status, NULL);
5918 } else {
5919 txn->status = 400;
5920 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_400));
5921 }
5922 req->analysers &= AN_REQ_FLT_END;
5923 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
5924
5925 if (!(s->flags & SF_ERR_MASK))
5926 s->flags |= SF_ERR_PRXCOND;
5927 if (!(s->flags & SF_FINST_MASK)) {
5928 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
5929 s->flags |= SF_FINST_H;
5930 else
5931 s->flags |= SF_FINST_D;
5932 }
5933 return 0;
5934
5935 aborted_xfer:
5936 txn->req.err_state = txn->req.msg_state;
5937 txn->req.msg_state = HTTP_MSG_ERROR;
5938 if (txn->status) {
5939 /* Note: we don't send any error if some data were already sent */
5940 http_reply_and_close(s, txn->status, NULL);
5941 } else {
5942 txn->status = 502;
5943 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_502));
5944 }
5945 req->analysers &= AN_REQ_FLT_END;
5946 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
5947
5948 sess->fe->fe_counters.srv_aborts++;
5949 s->be->be_counters.srv_aborts++;
5950 if (objt_server(s->target))
5951 objt_server(s->target)->counters.srv_aborts++;
5952
5953 if (!(s->flags & SF_ERR_MASK))
5954 s->flags |= SF_ERR_SRVCL;
5955 if (!(s->flags & SF_FINST_MASK)) {
5956 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
5957 s->flags |= SF_FINST_H;
5958 else
5959 s->flags |= SF_FINST_D;
5960 }
5961 return 0;
5962 }
5963
5964 /* This stream analyser waits for a complete HTTP response. It returns 1 if the
5965 * processing can continue on next analysers, or zero if it either needs more
5966 * data or wants to immediately abort the response (eg: timeout, error, ...). It
5967 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
5968 * when it has nothing left to do, and may remove any analyser when it wants to
5969 * abort.
5970 */
http_wait_for_response(struct stream * s,struct channel * rep,int an_bit)5971 int http_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
5972 {
5973 struct session *sess = s->sess;
5974 struct http_txn *txn = s->txn;
5975 struct http_msg *msg = &txn->rsp;
5976 struct hdr_ctx ctx;
5977 int use_close_only;
5978 int cur_idx;
5979 int n;
5980
5981 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n",
5982 now_ms, __FUNCTION__,
5983 s,
5984 rep,
5985 rep->rex, rep->wex,
5986 rep->flags,
5987 rep->buf->i,
5988 rep->analysers);
5989
5990 /*
5991 * Now parse the partial (or complete) lines.
5992 * We will check the response syntax, and also join multi-line
5993 * headers. An index of all the lines will be elaborated while
5994 * parsing.
5995 *
5996 * For the parsing, we use a 28 states FSM.
5997 *
5998 * Here is the information we currently have :
5999 * rep->buf->p = beginning of response
6000 * rep->buf->p + msg->eoh = end of processed headers / start of current one
6001 * rep->buf->p + rep->buf->i = end of input data
6002 * msg->eol = end of current header or line (LF or CRLF)
6003 * msg->next = first non-visited byte
6004 */
6005
6006 next_one:
6007 /* There's a protected area at the end of the buffer for rewriting
6008 * purposes. We don't want to start to parse the request if the
6009 * protected area is affected, because we may have to move processed
6010 * data later, which is much more complicated.
6011 */
6012 if (buffer_not_empty(rep->buf) && msg->msg_state < HTTP_MSG_ERROR) {
6013 if (unlikely(!channel_is_rewritable(rep) && rep->buf->o)) {
6014 /* some data has still not left the buffer, wake us once that's done */
6015 if (rep->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_WRITE_ERROR|CF_WRITE_TIMEOUT))
6016 goto abort_response;
6017 channel_dont_close(rep);
6018 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
6019 rep->flags |= CF_WAKE_WRITE;
6020 return 0;
6021 }
6022
6023 if (unlikely(bi_end(rep->buf) < b_ptr(rep->buf, msg->next) ||
6024 bi_end(rep->buf) > rep->buf->data + rep->buf->size - global.tune.maxrewrite))
6025 buffer_slow_realign(rep->buf);
6026
6027 if (likely(msg->next < rep->buf->i))
6028 http_msg_analyzer(msg, &txn->hdr_idx);
6029 }
6030
6031 /* 1: we might have to print this header in debug mode */
6032 if (unlikely((global.mode & MODE_DEBUG) &&
6033 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) &&
6034 msg->msg_state >= HTTP_MSG_BODY)) {
6035 char *eol, *sol;
6036
6037 sol = rep->buf->p;
6038 eol = sol + (msg->sl.st.l ? msg->sl.st.l : rep->buf->i);
6039 debug_hdr("srvrep", s, sol, eol);
6040
6041 sol += hdr_idx_first_pos(&txn->hdr_idx);
6042 cur_idx = hdr_idx_first_idx(&txn->hdr_idx);
6043
6044 while (cur_idx) {
6045 eol = sol + txn->hdr_idx.v[cur_idx].len;
6046 debug_hdr("srvhdr", s, sol, eol);
6047 sol = eol + txn->hdr_idx.v[cur_idx].cr + 1;
6048 cur_idx = txn->hdr_idx.v[cur_idx].next;
6049 }
6050 }
6051
6052 /*
6053 * Now we quickly check if we have found a full valid response.
6054 * If not so, we check the FD and buffer states before leaving.
6055 * A full response is indicated by the fact that we have seen
6056 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
6057 * responses are checked first.
6058 *
6059 * Depending on whether the client is still there or not, we
6060 * may send an error response back or not. Note that normally
6061 * we should only check for HTTP status there, and check I/O
6062 * errors somewhere else.
6063 */
6064
6065 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
6066 /* Invalid response */
6067 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
6068 /* we detected a parsing error. We want to archive this response
6069 * in the dedicated proxy area for later troubleshooting.
6070 */
6071 hdr_response_bad:
6072 if (msg->msg_state == HTTP_MSG_ERROR || msg->err_pos >= 0)
6073 http_capture_bad_message(&s->be->invalid_rep, s, msg, msg->err_state, sess->fe);
6074
6075 s->be->be_counters.failed_resp++;
6076 if (objt_server(s->target)) {
6077 objt_server(s->target)->counters.failed_resp++;
6078 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
6079 }
6080 abort_response:
6081 channel_auto_close(rep);
6082 rep->analysers &= AN_RES_FLT_END;
6083 s->req.analysers &= AN_REQ_FLT_END;
6084 rep->analyse_exp = TICK_ETERNITY;
6085 txn->status = 502;
6086 s->si[1].flags |= SI_FL_NOLINGER;
6087 channel_truncate(rep);
6088 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_502));
6089
6090 if (!(s->flags & SF_ERR_MASK))
6091 s->flags |= SF_ERR_PRXCOND;
6092 if (!(s->flags & SF_FINST_MASK))
6093 s->flags |= SF_FINST_H;
6094
6095 return 0;
6096 }
6097
6098 /* too large response does not fit in buffer. */
6099 else if (buffer_full(rep->buf, global.tune.maxrewrite)) {
6100 if (msg->err_pos < 0)
6101 msg->err_pos = rep->buf->i;
6102 goto hdr_response_bad;
6103 }
6104
6105 /* read error */
6106 else if (rep->flags & CF_READ_ERROR) {
6107 if (msg->err_pos >= 0)
6108 http_capture_bad_message(&s->be->invalid_rep, s, msg, msg->err_state, sess->fe);
6109 else if (txn->flags & TX_NOT_FIRST)
6110 goto abort_keep_alive;
6111
6112 s->be->be_counters.failed_resp++;
6113 if (objt_server(s->target)) {
6114 objt_server(s->target)->counters.failed_resp++;
6115 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
6116 }
6117
6118 channel_auto_close(rep);
6119 rep->analysers &= AN_RES_FLT_END;
6120 s->req.analysers &= AN_REQ_FLT_END;
6121 rep->analyse_exp = TICK_ETERNITY;
6122 txn->status = 502;
6123 s->si[1].flags |= SI_FL_NOLINGER;
6124 channel_truncate(rep);
6125 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_502));
6126
6127 if (!(s->flags & SF_ERR_MASK))
6128 s->flags |= SF_ERR_SRVCL;
6129 if (!(s->flags & SF_FINST_MASK))
6130 s->flags |= SF_FINST_H;
6131 return 0;
6132 }
6133
6134 /* read timeout : return a 504 to the client. */
6135 else if (rep->flags & CF_READ_TIMEOUT) {
6136 if (msg->err_pos >= 0)
6137 http_capture_bad_message(&s->be->invalid_rep, s, msg, msg->err_state, sess->fe);
6138
6139 s->be->be_counters.failed_resp++;
6140 if (objt_server(s->target)) {
6141 objt_server(s->target)->counters.failed_resp++;
6142 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
6143 }
6144
6145 channel_auto_close(rep);
6146 rep->analysers &= AN_RES_FLT_END;
6147 s->req.analysers &= AN_REQ_FLT_END;
6148 rep->analyse_exp = TICK_ETERNITY;
6149 txn->status = 504;
6150 s->si[1].flags |= SI_FL_NOLINGER;
6151 channel_truncate(rep);
6152 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_504));
6153
6154 if (!(s->flags & SF_ERR_MASK))
6155 s->flags |= SF_ERR_SRVTO;
6156 if (!(s->flags & SF_FINST_MASK))
6157 s->flags |= SF_FINST_H;
6158 return 0;
6159 }
6160
6161 /* client abort with an abortonclose */
6162 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
6163 sess->fe->fe_counters.cli_aborts++;
6164 s->be->be_counters.cli_aborts++;
6165 if (objt_server(s->target))
6166 objt_server(s->target)->counters.cli_aborts++;
6167
6168 rep->analysers &= AN_RES_FLT_END;
6169 s->req.analysers &= AN_REQ_FLT_END;
6170 rep->analyse_exp = TICK_ETERNITY;
6171 channel_auto_close(rep);
6172
6173 txn->status = 400;
6174 channel_truncate(rep);
6175 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_400));
6176
6177 if (!(s->flags & SF_ERR_MASK))
6178 s->flags |= SF_ERR_CLICL;
6179 if (!(s->flags & SF_FINST_MASK))
6180 s->flags |= SF_FINST_H;
6181
6182 /* process_stream() will take care of the error */
6183 return 0;
6184 }
6185
6186 /* close from server, capture the response if the server has started to respond */
6187 else if (rep->flags & CF_SHUTR) {
6188 if (msg->msg_state >= HTTP_MSG_RPVER || msg->err_pos >= 0)
6189 http_capture_bad_message(&s->be->invalid_rep, s, msg, msg->err_state, sess->fe);
6190 else if (txn->flags & TX_NOT_FIRST)
6191 goto abort_keep_alive;
6192
6193 s->be->be_counters.failed_resp++;
6194 if (objt_server(s->target)) {
6195 objt_server(s->target)->counters.failed_resp++;
6196 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
6197 }
6198
6199 channel_auto_close(rep);
6200 rep->analysers &= AN_RES_FLT_END;
6201 s->req.analysers &= AN_REQ_FLT_END;
6202 rep->analyse_exp = TICK_ETERNITY;
6203 txn->status = 502;
6204 s->si[1].flags |= SI_FL_NOLINGER;
6205 channel_truncate(rep);
6206 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_502));
6207
6208 if (!(s->flags & SF_ERR_MASK))
6209 s->flags |= SF_ERR_SRVCL;
6210 if (!(s->flags & SF_FINST_MASK))
6211 s->flags |= SF_FINST_H;
6212 return 0;
6213 }
6214
6215 /* write error to client (we don't send any message then) */
6216 else if (rep->flags & CF_WRITE_ERROR) {
6217 if (msg->err_pos >= 0)
6218 http_capture_bad_message(&s->be->invalid_rep, s, msg, msg->err_state, sess->fe);
6219 else if (txn->flags & TX_NOT_FIRST)
6220 goto abort_keep_alive;
6221
6222 s->be->be_counters.failed_resp++;
6223 rep->analysers &= AN_RES_FLT_END;
6224 s->req.analysers &= AN_REQ_FLT_END;
6225 rep->analyse_exp = TICK_ETERNITY;
6226 channel_auto_close(rep);
6227
6228 if (!(s->flags & SF_ERR_MASK))
6229 s->flags |= SF_ERR_CLICL;
6230 if (!(s->flags & SF_FINST_MASK))
6231 s->flags |= SF_FINST_H;
6232
6233 /* process_stream() will take care of the error */
6234 return 0;
6235 }
6236
6237 channel_dont_close(rep);
6238 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
6239 return 0;
6240 }
6241
6242 /* More interesting part now : we know that we have a complete
6243 * response which at least looks like HTTP. We have an indicator
6244 * of each header's length, so we can parse them quickly.
6245 */
6246
6247 if (unlikely(msg->err_pos >= 0))
6248 http_capture_bad_message(&s->be->invalid_rep, s, msg, msg->err_state, sess->fe);
6249
6250 /*
6251 * 1: get the status code
6252 */
6253 n = rep->buf->p[msg->sl.st.c] - '0';
6254 if (n < 1 || n > 5)
6255 n = 0;
6256 /* when the client triggers a 4xx from the server, it's most often due
6257 * to a missing object or permission. These events should be tracked
6258 * because if they happen often, it may indicate a brute force or a
6259 * vulnerability scan.
6260 */
6261 if (n == 4)
6262 stream_inc_http_err_ctr(s);
6263
6264 if (objt_server(s->target))
6265 objt_server(s->target)->counters.p.http.rsp[n]++;
6266
6267 /* RFC7230#2.6 has enforced the format of the HTTP version string to be
6268 * exactly one digit "." one digit. This check may be disabled using
6269 * option accept-invalid-http-response.
6270 */
6271 if (!(s->be->options2 & PR_O2_RSPBUG_OK)) {
6272 if (msg->sl.st.v_l != 8) {
6273 msg->err_pos = 0;
6274 goto hdr_response_bad;
6275 }
6276
6277 if (rep->buf->p[4] != '/' ||
6278 !isdigit((unsigned char)rep->buf->p[5]) ||
6279 rep->buf->p[6] != '.' ||
6280 !isdigit((unsigned char)rep->buf->p[7])) {
6281 msg->err_pos = 4;
6282 goto hdr_response_bad;
6283 }
6284 }
6285
6286 /* check if the response is HTTP/1.1 or above */
6287 if ((msg->sl.st.v_l == 8) &&
6288 ((rep->buf->p[5] > '1') ||
6289 ((rep->buf->p[5] == '1') && (rep->buf->p[7] >= '1'))))
6290 msg->flags |= HTTP_MSGF_VER_11;
6291
6292 /* "connection" has not been parsed yet */
6293 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);
6294
6295 /* transfer length unknown*/
6296 msg->flags &= ~HTTP_MSGF_XFER_LEN;
6297
6298 txn->status = strl2ui(rep->buf->p + msg->sl.st.c, msg->sl.st.c_l);
6299
6300 /* Adjust server's health based on status code. Note: status codes 501
6301 * and 505 are triggered on demand by client request, so we must not
6302 * count them as server failures.
6303 */
6304 if (objt_server(s->target)) {
6305 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
6306 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_OK);
6307 else
6308 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_STS);
6309 }
6310
6311 /*
6312 * We may be facing a 100-continue response, or any other informational
6313 * 1xx response which is non-final, in which case this is not the right
6314 * response, and we're waiting for the next one. Let's allow this response
6315 * to go to the client and wait for the next one. There's an exception for
6316 * 101 which is used later in the code to switch protocols.
6317 */
6318 if (txn->status < 200 &&
6319 (txn->status == 100 || txn->status >= 102)) {
6320 hdr_idx_init(&txn->hdr_idx);
6321 msg->next -= channel_forward(rep, msg->next);
6322 msg->msg_state = HTTP_MSG_RPBEFORE;
6323 txn->status = 0;
6324 s->logs.t_data = -1; /* was not a response yet */
6325 FLT_STRM_CB(s, flt_http_reset(s, msg));
6326 goto next_one;
6327 }
6328
6329 /*
6330 * 2: check for cacheability.
6331 */
6332
6333 switch (txn->status) {
6334 case 200:
6335 case 203:
6336 case 206:
6337 case 300:
6338 case 301:
6339 case 410:
6340 /* RFC2616 @13.4:
6341 * "A response received with a status code of
6342 * 200, 203, 206, 300, 301 or 410 MAY be stored
6343 * by a cache (...) unless a cache-control
6344 * directive prohibits caching."
6345 *
6346 * RFC2616 @9.5: POST method :
6347 * "Responses to this method are not cacheable,
6348 * unless the response includes appropriate
6349 * Cache-Control or Expires header fields."
6350 */
6351 if (likely(txn->meth != HTTP_METH_POST) &&
6352 ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC)))
6353 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
6354 break;
6355 default:
6356 break;
6357 }
6358
6359 /*
6360 * 3: we may need to capture headers
6361 */
6362 s->logs.logwait &= ~LW_RESP;
6363 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
6364 capture_headers(rep->buf->p, &txn->hdr_idx,
6365 s->res_cap, sess->fe->rsp_cap);
6366
6367 /* 4: determine the transfer-length according to RFC2616 #4.4, updated
6368 * by RFC7230#3.3.3 :
6369 *
6370 * The length of a message body is determined by one of the following
6371 * (in order of precedence):
6372 *
6373 * 1. Any 2xx (Successful) response to a CONNECT request implies that
6374 * the connection will become a tunnel immediately after the empty
6375 * line that concludes the header fields. A client MUST ignore
6376 * any Content-Length or Transfer-Encoding header fields received
6377 * in such a message. Any 101 response (Switching Protocols) is
6378 * managed in the same manner.
6379 *
6380 * 2. Any response to a HEAD request and any response with a 1xx
6381 * (Informational), 204 (No Content), or 304 (Not Modified) status
6382 * code is always terminated by the first empty line after the
6383 * header fields, regardless of the header fields present in the
6384 * message, and thus cannot contain a message body.
6385 *
6386 * 3. If a Transfer-Encoding header field is present and the chunked
6387 * transfer coding (Section 4.1) is the final encoding, the message
6388 * body length is determined by reading and decoding the chunked
6389 * data until the transfer coding indicates the data is complete.
6390 *
6391 * If a Transfer-Encoding header field is present in a response and
6392 * the chunked transfer coding is not the final encoding, the
6393 * message body length is determined by reading the connection until
6394 * it is closed by the server. If a Transfer-Encoding header field
6395 * is present in a request and the chunked transfer coding is not
6396 * the final encoding, the message body length cannot be determined
6397 * reliably; the server MUST respond with the 400 (Bad Request)
6398 * status code and then close the connection.
6399 *
6400 * If a message is received with both a Transfer-Encoding and a
6401 * Content-Length header field, the Transfer-Encoding overrides the
6402 * Content-Length. Such a message might indicate an attempt to
6403 * perform request smuggling (Section 9.5) or response splitting
6404 * (Section 9.4) and ought to be handled as an error. A sender MUST
6405 * remove the received Content-Length field prior to forwarding such
6406 * a message downstream.
6407 *
6408 * 4. If a message is received without Transfer-Encoding and with
6409 * either multiple Content-Length header fields having differing
6410 * field-values or a single Content-Length header field having an
6411 * invalid value, then the message framing is invalid and the
6412 * recipient MUST treat it as an unrecoverable error. If this is a
6413 * request message, the server MUST respond with a 400 (Bad Request)
6414 * status code and then close the connection. If this is a response
6415 * message received by a proxy, the proxy MUST close the connection
6416 * to the server, discard the received response, and send a 502 (Bad
6417 * Gateway) response to the client. If this is a response message
6418 * received by a user agent, the user agent MUST close the
6419 * connection to the server and discard the received response.
6420 *
6421 * 5. If a valid Content-Length header field is present without
6422 * Transfer-Encoding, its decimal value defines the expected message
6423 * body length in octets. If the sender closes the connection or
6424 * the recipient times out before the indicated number of octets are
6425 * received, the recipient MUST consider the message to be
6426 * incomplete and close the connection.
6427 *
6428 * 6. If this is a request message and none of the above are true, then
6429 * the message body length is zero (no message body is present).
6430 *
6431 * 7. Otherwise, this is a response message without a declared message
6432 * body length, so the message body length is determined by the
6433 * number of octets received prior to the server closing the
6434 * connection.
6435 */
6436
6437 /* Skip parsing if no content length is possible. The response flags
6438 * remain 0 as well as the chunk_len, which may or may not mirror
6439 * the real header value, and we note that we know the response's length.
6440 * FIXME: should we parse anyway and return an error on chunked encoding ?
6441 */
6442 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
6443 txn->status == 101)) {
6444 /* Either we've established an explicit tunnel, or we're
6445 * switching the protocol. In both cases, we're very unlikely
6446 * to understand the next protocols. We have to switch to tunnel
6447 * mode, so that we transfer the request and responses then let
6448 * this protocol pass unmodified. When we later implement specific
6449 * parsers for such protocols, we'll want to check the Upgrade
6450 * header which contains information about that protocol for
6451 * responses with status 101 (eg: see RFC2817 about TLS).
6452 */
6453 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
6454 msg->flags |= HTTP_MSGF_XFER_LEN;
6455 goto end;
6456 }
6457
6458 if (txn->meth == HTTP_METH_HEAD ||
6459 (txn->status >= 100 && txn->status < 200) ||
6460 txn->status == 204 || txn->status == 304) {
6461 msg->flags |= HTTP_MSGF_XFER_LEN;
6462 goto skip_content_length;
6463 }
6464
6465 use_close_only = 0;
6466 ctx.idx = 0;
6467 while (http_find_header2("Transfer-Encoding", 17, rep->buf->p, &txn->hdr_idx, &ctx)) {
6468 if (ctx.vlen == 7 && strncasecmp(ctx.line + ctx.val, "chunked", 7) == 0)
6469 msg->flags |= (HTTP_MSGF_TE_CHNK | HTTP_MSGF_XFER_LEN);
6470 else if (msg->flags & HTTP_MSGF_TE_CHNK) {
6471 /* bad transfer-encoding (chunked followed by something else) */
6472 use_close_only = 1;
6473 msg->flags &= ~(HTTP_MSGF_TE_CHNK | HTTP_MSGF_XFER_LEN);
6474 break;
6475 }
6476 }
6477
6478 /* "chunked" mandatory if transfer-encoding is used */
6479 if (ctx.idx && !(msg->flags & HTTP_MSGF_TE_CHNK)) {
6480 use_close_only = 1;
6481 msg->flags &= ~(HTTP_MSGF_TE_CHNK | HTTP_MSGF_XFER_LEN);
6482 }
6483
6484 /* Chunked responses must have their content-length removed */
6485 ctx.idx = 0;
6486 if (use_close_only || (msg->flags & HTTP_MSGF_TE_CHNK)) {
6487 while (http_find_header2("Content-Length", 14, rep->buf->p, &txn->hdr_idx, &ctx))
6488 http_remove_header2(msg, &txn->hdr_idx, &ctx);
6489 }
6490 else while (http_find_header2("Content-Length", 14, rep->buf->p, &txn->hdr_idx, &ctx)) {
6491 signed long long cl;
6492
6493 if (!ctx.vlen) {
6494 msg->err_pos = ctx.line + ctx.val - rep->buf->p;
6495 goto hdr_response_bad;
6496 }
6497
6498 if (strl2llrc(ctx.line + ctx.val, ctx.vlen, &cl)) {
6499 msg->err_pos = ctx.line + ctx.val - rep->buf->p;
6500 goto hdr_response_bad; /* parse failure */
6501 }
6502
6503 if (cl < 0) {
6504 msg->err_pos = ctx.line + ctx.val - rep->buf->p;
6505 goto hdr_response_bad;
6506 }
6507
6508 if ((msg->flags & HTTP_MSGF_CNT_LEN) && (msg->chunk_len != cl)) {
6509 msg->err_pos = ctx.line + ctx.val - rep->buf->p;
6510 goto hdr_response_bad; /* already specified, was different */
6511 }
6512
6513 msg->flags |= HTTP_MSGF_CNT_LEN | HTTP_MSGF_XFER_LEN;
6514 msg->body_len = msg->chunk_len = cl;
6515 }
6516
6517 skip_content_length:
6518 /* Now we have to check if we need to modify the Connection header.
6519 * This is more difficult on the response than it is on the request,
6520 * because we can have two different HTTP versions and we don't know
6521 * how the client will interprete a response. For instance, let's say
6522 * that the client sends a keep-alive request in HTTP/1.0 and gets an
6523 * HTTP/1.1 response without any header. Maybe it will bound itself to
6524 * HTTP/1.0 because it only knows about it, and will consider the lack
6525 * of header as a close, or maybe it knows HTTP/1.1 and can consider
6526 * the lack of header as a keep-alive. Thus we will use two flags
6527 * indicating how a request MAY be understood by the client. In case
6528 * of multiple possibilities, we'll fix the header to be explicit. If
6529 * ambiguous cases such as both close and keepalive are seen, then we
6530 * will fall back to explicit close. Note that we won't take risks with
6531 * HTTP/1.0 clients which may not necessarily understand keep-alive.
6532 * See doc/internals/connection-header.txt for the complete matrix.
6533 */
6534 if ((txn->status >= 200) && !(txn->flags & TX_HDR_CONN_PRS) &&
6535 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN ||
6536 ((sess->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||
6537 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL))) {
6538 int to_del = 0;
6539
6540 /* this situation happens when combining pretend-keepalive with httpclose. */
6541 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL &&
6542 ((sess->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||
6543 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL))
6544 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
6545
6546 /* on unknown transfer length, we must close */
6547 if (!(msg->flags & HTTP_MSGF_XFER_LEN) &&
6548 (txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
6549 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
6550
6551 /* now adjust header transformations depending on current state */
6552 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN ||
6553 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_CLO) {
6554 to_del |= 2; /* remove "keep-alive" on any response */
6555 if (!(msg->flags & HTTP_MSGF_VER_11))
6556 to_del |= 1; /* remove "close" for HTTP/1.0 responses */
6557 }
6558 else { /* SCL / KAL */
6559 to_del |= 1; /* remove "close" on any response */
6560 if (txn->req.flags & msg->flags & HTTP_MSGF_VER_11)
6561 to_del |= 2; /* remove "keep-alive" on pure 1.1 responses */
6562 }
6563
6564 /* Parse and remove some headers from the connection header */
6565 http_parse_connection_header(txn, msg, to_del);
6566
6567 /* Some keep-alive responses are converted to Server-close if
6568 * the server wants to close.
6569 */
6570 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL) {
6571 if ((txn->flags & TX_HDR_CONN_CLO) ||
6572 (!(txn->flags & TX_HDR_CONN_KAL) && !(msg->flags & HTTP_MSGF_VER_11)))
6573 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
6574 }
6575 }
6576
6577 end:
6578 /* we want to have the response time before we start processing it */
6579 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
6580
6581 /* end of job, return OK */
6582 rep->analysers &= ~an_bit;
6583 rep->analyse_exp = TICK_ETERNITY;
6584 channel_auto_close(rep);
6585 return 1;
6586
6587 abort_keep_alive:
6588 /* A keep-alive request to the server failed on a network error.
6589 * The client is required to retry. We need to close without returning
6590 * any other information so that the client retries.
6591 */
6592 txn->status = 0;
6593 rep->analysers &= AN_RES_FLT_END;
6594 s->req.analysers &= AN_REQ_FLT_END;
6595 rep->analyse_exp = TICK_ETERNITY;
6596 channel_auto_close(rep);
6597 s->logs.logwait = 0;
6598 s->logs.level = 0;
6599 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
6600 channel_truncate(rep);
6601 http_reply_and_close(s, txn->status, NULL);
6602 return 0;
6603 }
6604
6605 /* This function performs all the processing enabled for the current response.
6606 * It normally returns 1 unless it wants to break. It relies on buffers flags,
6607 * and updates s->res.analysers. It might make sense to explode it into several
6608 * other functions. It works like process_request (see indications above).
6609 */
http_process_res_common(struct stream * s,struct channel * rep,int an_bit,struct proxy * px)6610 int http_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
6611 {
6612 struct session *sess = s->sess;
6613 struct http_txn *txn = s->txn;
6614 struct http_msg *msg = &txn->rsp;
6615 struct proxy *cur_proxy;
6616 struct cond_wordlist *wl;
6617 enum rule_result ret = HTTP_RULE_RES_CONT;
6618
6619 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n",
6620 now_ms, __FUNCTION__,
6621 s,
6622 rep,
6623 rep->rex, rep->wex,
6624 rep->flags,
6625 rep->buf->i,
6626 rep->analysers);
6627
6628 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
6629 return 0;
6630
6631 /* The stats applet needs to adjust the Connection header but we don't
6632 * apply any filter there.
6633 */
6634 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
6635 rep->analysers &= ~an_bit;
6636 rep->analyse_exp = TICK_ETERNITY;
6637 goto skip_filters;
6638 }
6639
6640 /*
6641 * We will have to evaluate the filters.
6642 * As opposed to version 1.2, now they will be evaluated in the
6643 * filters order and not in the header order. This means that
6644 * each filter has to be validated among all headers.
6645 *
6646 * Filters are tried with ->be first, then with ->fe if it is
6647 * different from ->be.
6648 *
6649 * Maybe we are in resume condiion. In this case I choose the
6650 * "struct proxy" which contains the rule list matching the resume
6651 * pointer. If none of theses "struct proxy" match, I initialise
6652 * the process with the first one.
6653 *
6654 * In fact, I check only correspondance betwwen the current list
6655 * pointer and the ->fe rule list. If it doesn't match, I initialize
6656 * the loop with the ->be.
6657 */
6658 if (s->current_rule_list == &sess->fe->http_res_rules)
6659 cur_proxy = sess->fe;
6660 else
6661 cur_proxy = s->be;
6662 while (1) {
6663 struct proxy *rule_set = cur_proxy;
6664
6665 /* evaluate http-response rules */
6666 if (ret == HTTP_RULE_RES_CONT) {
6667 ret = http_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
6668
6669 if (ret == HTTP_RULE_RES_BADREQ)
6670 goto return_srv_prx_502;
6671
6672 if (ret == HTTP_RULE_RES_DONE) {
6673 rep->analysers &= ~an_bit;
6674 rep->analyse_exp = TICK_ETERNITY;
6675 return 1;
6676 }
6677 }
6678
6679 /* we need to be called again. */
6680 if (ret == HTTP_RULE_RES_YIELD) {
6681 channel_dont_close(rep);
6682 return 0;
6683 }
6684
6685 /* try headers filters */
6686 if (rule_set->rsp_exp != NULL) {
6687 if (apply_filters_to_response(s, rep, rule_set) < 0) {
6688 return_bad_resp:
6689 if (objt_server(s->target)) {
6690 objt_server(s->target)->counters.failed_resp++;
6691 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_RSP);
6692 }
6693 s->be->be_counters.failed_resp++;
6694 return_srv_prx_502:
6695 rep->analysers &= AN_RES_FLT_END;
6696 s->req.analysers &= AN_REQ_FLT_END;
6697 rep->analyse_exp = TICK_ETERNITY;
6698 txn->status = 502;
6699 s->logs.t_data = -1; /* was not a valid response */
6700 s->si[1].flags |= SI_FL_NOLINGER;
6701 channel_truncate(rep);
6702 http_reply_and_close(s, txn->status, http_error_message(s, HTTP_ERR_502));
6703 if (!(s->flags & SF_ERR_MASK))
6704 s->flags |= SF_ERR_PRXCOND;
6705 if (!(s->flags & SF_FINST_MASK))
6706 s->flags |= SF_FINST_H;
6707 return 0;
6708 }
6709 }
6710
6711 /* has the response been denied ? */
6712 if (txn->flags & TX_SVDENY) {
6713 if (objt_server(s->target))
6714 objt_server(s->target)->counters.failed_secu++;
6715
6716 s->be->be_counters.denied_resp++;
6717 sess->fe->fe_counters.denied_resp++;
6718 if (sess->listener->counters)
6719 sess->listener->counters->denied_resp++;
6720
6721 goto return_srv_prx_502;
6722 }
6723
6724 /* add response headers from the rule sets in the same order */
6725 list_for_each_entry(wl, &rule_set->rsp_add, list) {
6726 if (txn->status < 200 && txn->status != 101)
6727 break;
6728 if (wl->cond) {
6729 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
6730 ret = acl_pass(ret);
6731 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
6732 ret = !ret;
6733 if (!ret)
6734 continue;
6735 }
6736 if (unlikely(http_header_add_tail(&txn->rsp, &txn->hdr_idx, wl->s) < 0))
6737 goto return_bad_resp;
6738 }
6739
6740 /* check whether we're already working on the frontend */
6741 if (cur_proxy == sess->fe)
6742 break;
6743 cur_proxy = sess->fe;
6744 }
6745
6746 /* After this point, this anayzer can't return yield, so we can
6747 * remove the bit corresponding to this analyzer from the list.
6748 *
6749 * Note that the intermediate returns and goto found previously
6750 * reset the analyzers.
6751 */
6752 rep->analysers &= ~an_bit;
6753 rep->analyse_exp = TICK_ETERNITY;
6754
6755 /* OK that's all we can do for 1xx responses */
6756 if (unlikely(txn->status < 200 && txn->status != 101))
6757 goto skip_header_mangling;
6758
6759 /*
6760 * Now check for a server cookie.
6761 */
6762 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
6763 manage_server_side_cookies(s, rep);
6764
6765 /*
6766 * Check for cache-control or pragma headers if required.
6767 */
6768 if (((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC)) && txn->status != 101)
6769 check_response_for_cacheability(s, rep);
6770
6771 /*
6772 * Add server cookie in the response if needed
6773 */
6774 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
6775 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
6776 (!(s->flags & SF_DIRECT) ||
6777 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
6778 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
6779 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
6780 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
6781 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
6782 !(s->flags & SF_IGNORE_PRST)) {
6783 /* the server is known, it's not the one the client requested, or the
6784 * cookie's last seen date needs to be refreshed. We have to
6785 * insert a set-cookie here, except if we want to insert only on POST
6786 * requests and this one isn't. Note that servers which don't have cookies
6787 * (eg: some backup servers) will return a full cookie removal request.
6788 */
6789 if (!objt_server(s->target)->cookie) {
6790 chunk_printf(&trash,
6791 "Set-Cookie: %s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
6792 s->be->cookie_name);
6793 }
6794 else {
6795 chunk_printf(&trash, "Set-Cookie: %s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
6796
6797 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
6798 /* emit last_date, which is mandatory */
6799 trash.str[trash.len++] = COOKIE_DELIM_DATE;
6800 s30tob64((date.tv_sec+3) >> 2, trash.str + trash.len);
6801 trash.len += 5;
6802
6803 if (s->be->cookie_maxlife) {
6804 /* emit first_date, which is either the original one or
6805 * the current date.
6806 */
6807 trash.str[trash.len++] = COOKIE_DELIM_DATE;
6808 s30tob64(txn->cookie_first_date ?
6809 txn->cookie_first_date >> 2 :
6810 (date.tv_sec+3) >> 2, trash.str + trash.len);
6811 trash.len += 5;
6812 }
6813 }
6814 chunk_appendf(&trash, "; path=/");
6815 }
6816
6817 if (s->be->cookie_domain)
6818 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
6819
6820 if (s->be->ck_opts & PR_CK_HTTPONLY)
6821 chunk_appendf(&trash, "; HttpOnly");
6822
6823 if (s->be->ck_opts & PR_CK_SECURE)
6824 chunk_appendf(&trash, "; Secure");
6825
6826 if (s->be->cookie_attrs)
6827 chunk_appendf(&trash, "; %s", s->be->cookie_attrs);
6828
6829 if (unlikely(http_header_add_tail2(&txn->rsp, &txn->hdr_idx, trash.str, trash.len) < 0))
6830 goto return_bad_resp;
6831
6832 txn->flags &= ~TX_SCK_MASK;
6833 if (objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
6834 /* the server did not change, only the date was updated */
6835 txn->flags |= TX_SCK_UPDATED;
6836 else
6837 txn->flags |= TX_SCK_INSERTED;
6838
6839 /* Here, we will tell an eventual cache on the client side that we don't
6840 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
6841 * Some caches understand the correct form: 'no-cache="set-cookie"', but
6842 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
6843 */
6844 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
6845
6846 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
6847
6848 if (unlikely(http_header_add_tail2(&txn->rsp, &txn->hdr_idx,
6849 "Cache-control: private", 22) < 0))
6850 goto return_bad_resp;
6851 }
6852 }
6853
6854 /*
6855 * Check if result will be cacheable with a cookie.
6856 * We'll block the response if security checks have caught
6857 * nasty things such as a cacheable cookie.
6858 */
6859 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
6860 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
6861 (s->be->options & PR_O_CHK_CACHE)) {
6862 /* we're in presence of a cacheable response containing
6863 * a set-cookie header. We'll block it as requested by
6864 * the 'checkcache' option, and send an alert.
6865 */
6866 if (objt_server(s->target))
6867 objt_server(s->target)->counters.failed_secu++;
6868
6869 s->be->be_counters.denied_resp++;
6870 sess->fe->fe_counters.denied_resp++;
6871 if (sess->listener->counters)
6872 sess->listener->counters->denied_resp++;
6873
6874 Alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
6875 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
6876 send_log(s->be, LOG_ALERT,
6877 "Blocking cacheable cookie in response from instance %s, server %s.\n",
6878 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
6879 goto return_srv_prx_502;
6880 }
6881
6882 skip_filters:
6883 /*
6884 * Adjust "Connection: close" or "Connection: keep-alive" if needed.
6885 * If an "Upgrade" token is found, the header is left untouched in order
6886 * not to have to deal with some client bugs : some of them fail an upgrade
6887 * if anything but "Upgrade" is present in the Connection header. We don't
6888 * want to touch any 101 response either since it's switching to another
6889 * protocol.
6890 */
6891 if ((txn->status != 101) && !(txn->flags & TX_HDR_CONN_UPG) &&
6892 (((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN) ||
6893 ((sess->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||
6894 (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL))) {
6895 unsigned int want_flags = 0;
6896
6897 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL ||
6898 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) {
6899 /* we want a keep-alive response here. Keep-alive header
6900 * required if either side is not 1.1.
6901 */
6902 if (!(txn->req.flags & msg->flags & HTTP_MSGF_VER_11))
6903 want_flags |= TX_CON_KAL_SET;
6904 }
6905 else {
6906 /* we want a close response here. Close header required if
6907 * the server is 1.1, regardless of the client.
6908 */
6909 if (msg->flags & HTTP_MSGF_VER_11)
6910 want_flags |= TX_CON_CLO_SET;
6911 }
6912
6913 if (want_flags != (txn->flags & (TX_CON_CLO_SET|TX_CON_KAL_SET)))
6914 http_change_connection_header(txn, msg, want_flags);
6915 }
6916
6917 skip_header_mangling:
6918 /* Always enter in the body analyzer */
6919 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
6920 rep->analysers |= AN_RES_HTTP_XFER_BODY;
6921
6922 /* if the user wants to log as soon as possible, without counting
6923 * bytes from the server, then this is the right moment. We have
6924 * to temporarily assign bytes_out to log what we currently have.
6925 */
6926 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
6927 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
6928 s->logs.bytes_out = txn->rsp.eoh;
6929 s->do_log(s);
6930 s->logs.bytes_out = 0;
6931 }
6932 return 1;
6933 }
6934
6935 /* This function is an analyser which forwards response body (including chunk
6936 * sizes if any). It is called as soon as we must forward, even if we forward
6937 * zero byte. The only situation where it must not be called is when we're in
6938 * tunnel mode and we want to forward till the close. It's used both to forward
6939 * remaining data and to resync after end of body. It expects the msg_state to
6940 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
6941 * read more data, or 1 once we can go on with next request or end the stream.
6942 *
6943 * It is capable of compressing response data both in content-length mode and
6944 * in chunked mode. The state machines follows different flows depending on
6945 * whether content-length and chunked modes are used, since there are no
6946 * trailers in content-length :
6947 *
6948 * chk-mode cl-mode
6949 * ,----- BODY -----.
6950 * / \
6951 * V size > 0 V chk-mode
6952 * .--> SIZE -------------> DATA -------------> CRLF
6953 * | | size == 0 | last byte |
6954 * | v final crlf v inspected |
6955 * | TRAILERS -----------> DONE |
6956 * | |
6957 * `----------------------------------------------'
6958 *
6959 * Compression only happens in the DATA state, and must be flushed in final
6960 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
6961 * is performed at once on final states for all bytes parsed, or when leaving
6962 * on missing data.
6963 */
http_response_forward_body(struct stream * s,struct channel * res,int an_bit)6964 int http_response_forward_body(struct stream *s, struct channel *res, int an_bit)
6965 {
6966 struct session *sess = s->sess;
6967 struct http_txn *txn = s->txn;
6968 struct http_msg *msg = &s->txn->rsp;
6969 int ret;
6970
6971 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
6972 return 0;
6973
6974 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
6975 ((res->flags & CF_SHUTW) && (res->to_forward || res->buf->o)) ||
6976 !s->req.analysers) {
6977 /* Output closed while we were sending data. We must abort and
6978 * wake the other side up.
6979 */
6980 msg->err_state = msg->msg_state;
6981 msg->msg_state = HTTP_MSG_ERROR;
6982 http_resync_states(s);
6983 return 1;
6984 }
6985
6986 /* in most states, we should abort in case of early close */
6987 channel_auto_close(res);
6988
6989 if (msg->msg_state == HTTP_MSG_BODY) {
6990 msg->msg_state = ((msg->flags & HTTP_MSGF_TE_CHNK)
6991 ? HTTP_MSG_CHUNK_SIZE
6992 : HTTP_MSG_DATA);
6993 }
6994
6995 if (res->to_forward) {
6996 /* We can't process the buffer's contents yet */
6997 res->flags |= CF_WAKE_WRITE;
6998 goto missing_data_or_waiting;
6999 }
7000
7001 if (msg->msg_state < HTTP_MSG_DONE) {
7002 ret = ((msg->flags & HTTP_MSGF_TE_CHNK)
7003 ? http_msg_forward_chunked_body(s, msg)
7004 : http_msg_forward_body(s, msg));
7005 if (!ret)
7006 goto missing_data_or_waiting;
7007 if (ret < 0)
7008 goto return_bad_res;
7009 }
7010
7011 /* other states, DONE...TUNNEL */
7012 /* for keep-alive we don't want to forward closes on DONE */
7013 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL ||
7014 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL)
7015 channel_dont_close(res);
7016
7017 if (http_resync_states(s)) {
7018 /* some state changes occurred, maybe the analyser was disabled
7019 * too. */
7020 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
7021 if (res->flags & CF_SHUTW) {
7022 /* response errors are most likely due to the
7023 * client aborting the transfer. */
7024 goto aborted_xfer;
7025 }
7026 if (msg->err_pos >= 0)
7027 http_capture_bad_message(&s->be->invalid_rep, s, msg, msg->err_state, strm_fe(s));
7028 goto return_bad_res;
7029 }
7030 return 1;
7031 }
7032 return 0;
7033
7034 missing_data_or_waiting:
7035 if (res->flags & CF_SHUTW)
7036 goto aborted_xfer;
7037
7038 /* stop waiting for data if the input is closed before the end. If the
7039 * client side was already closed, it means that the client has aborted,
7040 * so we don't want to count this as a server abort. Otherwise it's a
7041 * server abort.
7042 */
7043 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
7044 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
7045 goto aborted_xfer;
7046 /* If we have some pending data, we continue the processing */
7047 if (!buffer_pending(res->buf)) {
7048 if (!(s->flags & SF_ERR_MASK))
7049 s->flags |= SF_ERR_SRVCL;
7050 sess->fe->fe_counters.srv_aborts++;
7051 s->be->be_counters.srv_aborts++;
7052 if (objt_server(s->target))
7053 objt_server(s->target)->counters.srv_aborts++;
7054 goto return_bad_res_stats_ok;
7055 }
7056 }
7057
7058 /* we need to obey the req analyser, so if it leaves, we must too */
7059 if (!s->req.analysers)
7060 goto return_bad_res;
7061
7062 /* When TE: chunked is used, we need to get there again to parse
7063 * remaining chunks even if the server has closed, so we don't want to
7064 * set CF_DONTCLOSE. Similarly, if keep-alive is set on the client side
7065 * or if there are filters registered on the stream, we don't want to
7066 * forward a close
7067 */
7068 if ((msg->flags & HTTP_MSGF_TE_CHNK) ||
7069 HAS_DATA_FILTERS(s, res) ||
7070 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL ||
7071 (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL)
7072 channel_dont_close(res);
7073
7074 /* We know that more data are expected, but we couldn't send more that
7075 * what we did. So we always set the CF_EXPECT_MORE flag so that the
7076 * system knows it must not set a PUSH on this first part. Interactive
7077 * modes are already handled by the stream sock layer. We must not do
7078 * this in content-length mode because it could present the MSG_MORE
7079 * flag with the last block of forwarded data, which would cause an
7080 * additional delay to be observed by the receiver.
7081 */
7082 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
7083 res->flags |= CF_EXPECT_MORE;
7084
7085 /* the stream handler will take care of timeouts and errors */
7086 return 0;
7087
7088 return_bad_res: /* let's centralize all bad responses */
7089 s->be->be_counters.failed_resp++;
7090 if (objt_server(s->target))
7091 objt_server(s->target)->counters.failed_resp++;
7092
7093 return_bad_res_stats_ok:
7094 txn->rsp.err_state = txn->rsp.msg_state;
7095 txn->rsp.msg_state = HTTP_MSG_ERROR;
7096 /* don't send any error message as we're in the body */
7097 http_reply_and_close(s, txn->status, NULL);
7098 res->analysers &= AN_RES_FLT_END;
7099 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
7100 if (objt_server(s->target))
7101 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
7102
7103 if (!(s->flags & SF_ERR_MASK))
7104 s->flags |= SF_ERR_PRXCOND;
7105 if (!(s->flags & SF_FINST_MASK))
7106 s->flags |= SF_FINST_D;
7107 return 0;
7108
7109 aborted_xfer:
7110 txn->rsp.err_state = txn->rsp.msg_state;
7111 txn->rsp.msg_state = HTTP_MSG_ERROR;
7112 /* don't send any error message as we're in the body */
7113 http_reply_and_close(s, txn->status, NULL);
7114 res->analysers &= AN_RES_FLT_END;
7115 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
7116
7117 sess->fe->fe_counters.cli_aborts++;
7118 s->be->be_counters.cli_aborts++;
7119 if (objt_server(s->target))
7120 objt_server(s->target)->counters.cli_aborts++;
7121
7122 if (!(s->flags & SF_ERR_MASK))
7123 s->flags |= SF_ERR_CLICL;
7124 if (!(s->flags & SF_FINST_MASK))
7125 s->flags |= SF_FINST_D;
7126 return 0;
7127 }
7128
7129
7130 static inline int
http_msg_forward_body(struct stream * s,struct http_msg * msg)7131 http_msg_forward_body(struct stream *s, struct http_msg *msg)
7132 {
7133 struct channel *chn = msg->chn;
7134 int ret;
7135
7136 /* Here we have the guarantee to be in HTTP_MSG_DATA or HTTP_MSG_ENDING state */
7137
7138 if (msg->msg_state == HTTP_MSG_ENDING)
7139 goto ending;
7140
7141 /* Neither content-length, nor transfer-encoding was found, so we must
7142 * read the body until the server connection is closed. In that case, we
7143 * eat data as they come. Of course, this happens for response only. */
7144 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
7145 unsigned long long len = (chn->buf->i - msg->next);
7146 msg->chunk_len += len;
7147 msg->body_len += len;
7148 }
7149 ret = FLT_STRM_DATA_CB(s, chn, flt_http_data(s, msg),
7150 /* default_ret */ MIN(msg->chunk_len, chn->buf->i - msg->next),
7151 /* on_error */ goto error);
7152 msg->next += ret;
7153 msg->chunk_len -= ret;
7154 if (msg->chunk_len) {
7155 /* input empty or output full */
7156 if (chn->buf->i > msg->next)
7157 chn->flags |= CF_WAKE_WRITE;
7158 goto missing_data_or_waiting;
7159 }
7160
7161 /* This check can only be true for a response. HTTP_MSGF_XFER_LEN is
7162 * always set for a request. */
7163 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
7164 /* The server still sending data that should be filtered */
7165 if (!(chn->flags & CF_SHUTR) && HAS_DATA_FILTERS(s, chn))
7166 goto missing_data_or_waiting;
7167 msg->msg_state = HTTP_MSG_TUNNEL;
7168 goto ending;
7169 }
7170
7171 msg->msg_state = HTTP_MSG_ENDING;
7172
7173 ending:
7174 /* we may have some pending data starting at res->buf->p such as a last
7175 * chunk of data or trailers. */
7176 ret = FLT_STRM_DATA_CB(s, chn, flt_http_forward_data(s, msg, msg->next),
7177 /* default_ret */ msg->next,
7178 /* on_error */ goto error);
7179 b_adv(chn->buf, ret);
7180 msg->next -= ret;
7181 if (unlikely(!(chn->flags & CF_WROTE_DATA) || msg->sov > 0))
7182 msg->sov -= ret;
7183 if (msg->next)
7184 goto waiting;
7185
7186 FLT_STRM_DATA_CB(s, chn, flt_http_end(s, msg),
7187 /* default_ret */ 1,
7188 /* on_error */ goto error,
7189 /* on_wait */ goto waiting);
7190 if (msg->msg_state == HTTP_MSG_ENDING)
7191 msg->msg_state = HTTP_MSG_DONE;
7192 return 1;
7193
7194 missing_data_or_waiting:
7195 /* we may have some pending data starting at chn->buf->p */
7196 ret = FLT_STRM_DATA_CB(s, chn, flt_http_forward_data(s, msg, msg->next),
7197 /* default_ret */ msg->next,
7198 /* on_error */ goto error);
7199 b_adv(chn->buf, ret);
7200 msg->next -= ret;
7201 if (!(chn->flags & CF_WROTE_DATA) || msg->sov > 0)
7202 msg->sov -= ret;
7203 if (!HAS_DATA_FILTERS(s, chn))
7204 msg->chunk_len -= channel_forward(chn, msg->chunk_len);
7205 waiting:
7206 return 0;
7207 error:
7208 return -1;
7209 }
7210
7211 static inline int
http_msg_forward_chunked_body(struct stream * s,struct http_msg * msg)7212 http_msg_forward_chunked_body(struct stream *s, struct http_msg *msg)
7213 {
7214 struct channel *chn = msg->chn;
7215 int ret;
7216
7217 /* Here we have the guarantee to be in one of the following state:
7218 * HTTP_MSG_DATA, HTTP_MSG_CHUNK_SIZE, HTTP_MSG_CHUNK_CRLF,
7219 * HTTP_MSG_TRAILERS or HTTP_MSG_ENDING. */
7220
7221 switch_states:
7222 switch (msg->msg_state) {
7223 case HTTP_MSG_DATA:
7224 ret = FLT_STRM_DATA_CB(s, chn, flt_http_data(s, msg),
7225 /* default_ret */ MIN(msg->chunk_len, chn->buf->i - msg->next),
7226 /* on_error */ goto error);
7227 msg->next += ret;
7228 msg->chunk_len -= ret;
7229 if (msg->chunk_len) {
7230 /* input empty or output full */
7231 if (chn->buf->i > msg->next)
7232 chn->flags |= CF_WAKE_WRITE;
7233 goto missing_data_or_waiting;
7234 }
7235
7236 /* nothing left to forward for this chunk*/
7237 msg->msg_state = HTTP_MSG_CHUNK_CRLF;
7238 /* fall through for HTTP_MSG_CHUNK_CRLF */
7239
7240 case HTTP_MSG_CHUNK_CRLF:
7241 /* we want the CRLF after the data */
7242 ret = http_skip_chunk_crlf(msg);
7243 if (ret == 0)
7244 goto missing_data_or_waiting;
7245 if (ret < 0)
7246 goto chunk_parsing_error;
7247 msg->next += ret;
7248 msg->msg_state = HTTP_MSG_CHUNK_SIZE;
7249 /* fall through for HTTP_MSG_CHUNK_SIZE */
7250
7251 case HTTP_MSG_CHUNK_SIZE:
7252 /* read the chunk size and assign it to ->chunk_len,
7253 * then set ->next to point to the body and switch to
7254 * DATA or TRAILERS state.
7255 */
7256 ret = http_parse_chunk_size(msg);
7257 if (ret == 0)
7258 goto missing_data_or_waiting;
7259 if (ret < 0)
7260 goto chunk_parsing_error;
7261 msg->next += ret;
7262 if (msg->chunk_len) {
7263 msg->msg_state = HTTP_MSG_DATA;
7264 goto switch_states;
7265 }
7266 msg->msg_state = HTTP_MSG_TRAILERS;
7267 /* fall through for HTTP_MSG_TRAILERS */
7268
7269 case HTTP_MSG_TRAILERS:
7270 ret = http_forward_trailers(msg);
7271 if (ret < 0)
7272 goto chunk_parsing_error;
7273 FLT_STRM_DATA_CB(s, chn, flt_http_chunk_trailers(s, msg),
7274 /* default_ret */ 1,
7275 /* on_error */ goto error);
7276 msg->next += msg->sol;
7277 if (!ret)
7278 goto missing_data_or_waiting;
7279 break;
7280
7281 case HTTP_MSG_ENDING:
7282 goto ending;
7283
7284 default:
7285 /* This should no happen in this function */
7286 goto error;
7287 }
7288
7289 msg->msg_state = HTTP_MSG_ENDING;
7290 ending:
7291 /* we may have some pending data starting at res->buf->p such as a last
7292 * chunk of data or trailers. */
7293 ret = FLT_STRM_DATA_CB(s, chn, flt_http_forward_data(s, msg, msg->next),
7294 /* default_ret */ msg->next,
7295 /* on_error */ goto error);
7296 b_adv(chn->buf, ret);
7297 msg->next -= ret;
7298 if (unlikely(!(chn->flags & CF_WROTE_DATA) || msg->sov > 0))
7299 msg->sov -= ret;
7300 if (msg->next)
7301 goto waiting;
7302
7303 FLT_STRM_DATA_CB(s, chn, flt_http_end(s, msg),
7304 /* default_ret */ 1,
7305 /* on_error */ goto error,
7306 /* on_wait */ goto waiting);
7307 msg->msg_state = HTTP_MSG_DONE;
7308 return 1;
7309
7310 missing_data_or_waiting:
7311 /* we may have some pending data starting at chn->buf->p */
7312 ret = FLT_STRM_DATA_CB(s, chn, flt_http_forward_data(s, msg, msg->next),
7313 /* default_ret */ msg->next,
7314 /* on_error */ goto error);
7315 b_adv(chn->buf, ret);
7316 msg->next -= ret;
7317 if (!(chn->flags & CF_WROTE_DATA) || msg->sov > 0)
7318 msg->sov -= ret;
7319 if (!HAS_DATA_FILTERS(s, chn))
7320 msg->chunk_len -= channel_forward(chn, msg->chunk_len);
7321 waiting:
7322 return 0;
7323
7324 chunk_parsing_error:
7325 if (msg->err_pos >= 0) {
7326 if (chn->flags & CF_ISRESP)
7327 http_capture_bad_message(&s->be->invalid_rep, s, msg,
7328 msg->msg_state, strm_fe(s));
7329 else
7330 http_capture_bad_message(&strm_fe(s)->invalid_req, s,
7331 msg, msg->msg_state, s->be);
7332 }
7333 error:
7334 return -1;
7335 }
7336
7337
7338 /* Iterate the same filter through all request headers.
7339 * Returns 1 if this filter can be stopped upon return, otherwise 0.
7340 * Since it can manage the switch to another backend, it updates the per-proxy
7341 * DENY stats.
7342 */
apply_filter_to_req_headers(struct stream * s,struct channel * req,struct hdr_exp * exp)7343 int apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
7344 {
7345 char *cur_ptr, *cur_end, *cur_next;
7346 int cur_idx, old_idx, last_hdr;
7347 struct http_txn *txn = s->txn;
7348 struct hdr_idx_elem *cur_hdr;
7349 int delta;
7350
7351 last_hdr = 0;
7352
7353 cur_next = req->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
7354 old_idx = 0;
7355
7356 while (!last_hdr) {
7357 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
7358 return 1;
7359 else if (unlikely(txn->flags & TX_CLALLOW) &&
7360 (exp->action == ACT_ALLOW ||
7361 exp->action == ACT_DENY ||
7362 exp->action == ACT_TARPIT))
7363 return 0;
7364
7365 cur_idx = txn->hdr_idx.v[old_idx].next;
7366 if (!cur_idx)
7367 break;
7368
7369 cur_hdr = &txn->hdr_idx.v[cur_idx];
7370 cur_ptr = cur_next;
7371 cur_end = cur_ptr + cur_hdr->len;
7372 cur_next = cur_end + cur_hdr->cr + 1;
7373
7374 /* Now we have one header between cur_ptr and cur_end,
7375 * and the next header starts at cur_next.
7376 */
7377
7378 if (regex_exec_match2(exp->preg, cur_ptr, cur_end-cur_ptr, MAX_MATCH, pmatch, 0)) {
7379 switch (exp->action) {
7380 case ACT_ALLOW:
7381 txn->flags |= TX_CLALLOW;
7382 last_hdr = 1;
7383 break;
7384
7385 case ACT_DENY:
7386 txn->flags |= TX_CLDENY;
7387 last_hdr = 1;
7388 break;
7389
7390 case ACT_TARPIT:
7391 txn->flags |= TX_CLTARPIT;
7392 last_hdr = 1;
7393 break;
7394
7395 case ACT_REPLACE:
7396 trash.len = exp_replace(trash.str, trash.size, cur_ptr, exp->replace, pmatch);
7397 if (trash.len < 0)
7398 return -1;
7399
7400 delta = buffer_replace2(req->buf, cur_ptr, cur_end, trash.str, trash.len);
7401 /* FIXME: if the user adds a newline in the replacement, the
7402 * index will not be recalculated for now, and the new line
7403 * will not be counted as a new header.
7404 */
7405
7406 cur_end += delta;
7407 cur_next += delta;
7408 cur_hdr->len += delta;
7409 http_msg_move_end(&txn->req, delta);
7410 break;
7411
7412 case ACT_REMOVE:
7413 delta = buffer_replace2(req->buf, cur_ptr, cur_next, NULL, 0);
7414 cur_next += delta;
7415
7416 http_msg_move_end(&txn->req, delta);
7417 txn->hdr_idx.v[old_idx].next = cur_hdr->next;
7418 txn->hdr_idx.used--;
7419 cur_hdr->len = 0;
7420 cur_end = NULL; /* null-term has been rewritten */
7421 cur_idx = old_idx;
7422 break;
7423
7424 }
7425 }
7426
7427 /* keep the link from this header to next one in case of later
7428 * removal of next header.
7429 */
7430 old_idx = cur_idx;
7431 }
7432 return 0;
7433 }
7434
7435
7436 /* Apply the filter to the request line.
7437 * Returns 0 if nothing has been done, 1 if the filter has been applied,
7438 * or -1 if a replacement resulted in an invalid request line.
7439 * Since it can manage the switch to another backend, it updates the per-proxy
7440 * DENY stats.
7441 */
apply_filter_to_req_line(struct stream * s,struct channel * req,struct hdr_exp * exp)7442 int apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
7443 {
7444 char *cur_ptr, *cur_end;
7445 int done;
7446 struct http_txn *txn = s->txn;
7447 int delta;
7448
7449 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
7450 return 1;
7451 else if (unlikely(txn->flags & TX_CLALLOW) &&
7452 (exp->action == ACT_ALLOW ||
7453 exp->action == ACT_DENY ||
7454 exp->action == ACT_TARPIT))
7455 return 0;
7456 else if (exp->action == ACT_REMOVE)
7457 return 0;
7458
7459 done = 0;
7460
7461 cur_ptr = req->buf->p;
7462 cur_end = cur_ptr + txn->req.sl.rq.l;
7463
7464 /* Now we have the request line between cur_ptr and cur_end */
7465
7466 if (regex_exec_match2(exp->preg, cur_ptr, cur_end-cur_ptr, MAX_MATCH, pmatch, 0)) {
7467 switch (exp->action) {
7468 case ACT_ALLOW:
7469 txn->flags |= TX_CLALLOW;
7470 done = 1;
7471 break;
7472
7473 case ACT_DENY:
7474 txn->flags |= TX_CLDENY;
7475 done = 1;
7476 break;
7477
7478 case ACT_TARPIT:
7479 txn->flags |= TX_CLTARPIT;
7480 done = 1;
7481 break;
7482
7483 case ACT_REPLACE:
7484 trash.len = exp_replace(trash.str, trash.size, cur_ptr, exp->replace, pmatch);
7485 if (trash.len < 0)
7486 return -1;
7487
7488 delta = buffer_replace2(req->buf, cur_ptr, cur_end, trash.str, trash.len);
7489 /* FIXME: if the user adds a newline in the replacement, the
7490 * index will not be recalculated for now, and the new line
7491 * will not be counted as a new header.
7492 */
7493
7494 http_msg_move_end(&txn->req, delta);
7495 cur_end += delta;
7496 cur_end = (char *)http_parse_reqline(&txn->req,
7497 HTTP_MSG_RQMETH,
7498 cur_ptr, cur_end + 1,
7499 NULL, NULL);
7500 if (unlikely(!cur_end))
7501 return -1;
7502
7503 /* we have a full request and we know that we have either a CR
7504 * or an LF at <ptr>.
7505 */
7506 txn->meth = find_http_meth(cur_ptr, txn->req.sl.rq.m_l);
7507 hdr_idx_set_start(&txn->hdr_idx, txn->req.sl.rq.l, *cur_end == '\r');
7508 /* there is no point trying this regex on headers */
7509 return 1;
7510 }
7511 }
7512 return done;
7513 }
7514
7515
7516
7517 /*
7518 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
7519 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
7520 * unparsable request. Since it can manage the switch to another backend, it
7521 * updates the per-proxy DENY stats.
7522 */
apply_filters_to_request(struct stream * s,struct channel * req,struct proxy * px)7523 int apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
7524 {
7525 struct session *sess = s->sess;
7526 struct http_txn *txn = s->txn;
7527 struct hdr_exp *exp;
7528
7529 for (exp = px->req_exp; exp; exp = exp->next) {
7530 int ret;
7531
7532 /*
7533 * The interleaving of transformations and verdicts
7534 * makes it difficult to decide to continue or stop
7535 * the evaluation.
7536 */
7537
7538 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
7539 break;
7540
7541 if ((txn->flags & TX_CLALLOW) &&
7542 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
7543 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
7544 continue;
7545
7546 /* if this filter had a condition, evaluate it now and skip to
7547 * next filter if the condition does not match.
7548 */
7549 if (exp->cond) {
7550 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
7551 ret = acl_pass(ret);
7552 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
7553 ret = !ret;
7554
7555 if (!ret)
7556 continue;
7557 }
7558
7559 /* Apply the filter to the request line. */
7560 ret = apply_filter_to_req_line(s, req, exp);
7561 if (unlikely(ret < 0))
7562 return -1;
7563
7564 if (likely(ret == 0)) {
7565 /* The filter did not match the request, it can be
7566 * iterated through all headers.
7567 */
7568 if (unlikely(apply_filter_to_req_headers(s, req, exp) < 0))
7569 return -1;
7570 }
7571 }
7572 return 0;
7573 }
7574
7575
7576 /* Find the end of a cookie value contained between <s> and <e>. It works the
7577 * same way as with headers above except that the semi-colon also ends a token.
7578 * See RFC2965 for more information. Note that it requires a valid header to
7579 * return a valid result.
7580 */
find_cookie_value_end(char * s,const char * e)7581 char *find_cookie_value_end(char *s, const char *e)
7582 {
7583 int quoted, qdpair;
7584
7585 quoted = qdpair = 0;
7586 for (; s < e; s++) {
7587 if (qdpair) qdpair = 0;
7588 else if (quoted) {
7589 if (*s == '\\') qdpair = 1;
7590 else if (*s == '"') quoted = 0;
7591 }
7592 else if (*s == '"') quoted = 1;
7593 else if (*s == ',' || *s == ';') return s;
7594 }
7595 return s;
7596 }
7597
7598 /* Delete a value in a header between delimiters <from> and <next> in buffer
7599 * <buf>. The number of characters displaced is returned, and the pointer to
7600 * the first delimiter is updated if required. The function tries as much as
7601 * possible to respect the following principles :
7602 * - replace <from> delimiter by the <next> one unless <from> points to a
7603 * colon, in which case <next> is simply removed
7604 * - set exactly one space character after the new first delimiter, unless
7605 * there are not enough characters in the block being moved to do so.
7606 * - remove unneeded spaces before the previous delimiter and after the new
7607 * one.
7608 *
7609 * It is the caller's responsibility to ensure that :
7610 * - <from> points to a valid delimiter or the colon ;
7611 * - <next> points to a valid delimiter or the final CR/LF ;
7612 * - there are non-space chars before <from> ;
7613 * - there is a CR/LF at or after <next>.
7614 */
del_hdr_value(struct buffer * buf,char ** from,char * next)7615 int del_hdr_value(struct buffer *buf, char **from, char *next)
7616 {
7617 char *prev = *from;
7618
7619 if (*prev == ':') {
7620 /* We're removing the first value, preserve the colon and add a
7621 * space if possible.
7622 */
7623 if (!HTTP_IS_CRLF(*next))
7624 next++;
7625 prev++;
7626 if (prev < next)
7627 *prev++ = ' ';
7628
7629 while (HTTP_IS_SPHT(*next))
7630 next++;
7631 } else {
7632 /* Remove useless spaces before the old delimiter. */
7633 while (HTTP_IS_SPHT(*(prev-1)))
7634 prev--;
7635 *from = prev;
7636
7637 /* copy the delimiter and if possible a space if we're
7638 * not at the end of the line.
7639 */
7640 if (!HTTP_IS_CRLF(*next)) {
7641 *prev++ = *next++;
7642 if (prev + 1 < next)
7643 *prev++ = ' ';
7644 while (HTTP_IS_SPHT(*next))
7645 next++;
7646 }
7647 }
7648 return buffer_replace2(buf, prev, next, NULL, 0);
7649 }
7650
7651 /*
7652 * Manage client-side cookie. It can impact performance by about 2% so it is
7653 * desirable to call it only when needed. This code is quite complex because
7654 * of the multiple very crappy and ambiguous syntaxes we have to support. it
7655 * highly recommended not to touch this part without a good reason !
7656 */
manage_client_side_cookies(struct stream * s,struct channel * req)7657 void manage_client_side_cookies(struct stream *s, struct channel *req)
7658 {
7659 struct http_txn *txn = s->txn;
7660 struct session *sess = s->sess;
7661 int preserve_hdr;
7662 int cur_idx, old_idx;
7663 char *hdr_beg, *hdr_end, *hdr_next, *del_from;
7664 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
7665
7666 /* Iterate through the headers, we start with the start line. */
7667 old_idx = 0;
7668 hdr_next = req->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
7669
7670 while ((cur_idx = txn->hdr_idx.v[old_idx].next)) {
7671 struct hdr_idx_elem *cur_hdr;
7672 int val;
7673
7674 cur_hdr = &txn->hdr_idx.v[cur_idx];
7675 hdr_beg = hdr_next;
7676 hdr_end = hdr_beg + cur_hdr->len;
7677 hdr_next = hdr_end + cur_hdr->cr + 1;
7678
7679 /* We have one full header between hdr_beg and hdr_end, and the
7680 * next header starts at hdr_next. We're only interested in
7681 * "Cookie:" headers.
7682 */
7683
7684 val = http_header_match2(hdr_beg, hdr_end, "Cookie", 6);
7685 if (!val) {
7686 old_idx = cur_idx;
7687 continue;
7688 }
7689
7690 del_from = NULL; /* nothing to be deleted */
7691 preserve_hdr = 0; /* assume we may kill the whole header */
7692
7693 /* Now look for cookies. Conforming to RFC2109, we have to support
7694 * attributes whose name begin with a '$', and associate them with
7695 * the right cookie, if we want to delete this cookie.
7696 * So there are 3 cases for each cookie read :
7697 * 1) it's a special attribute, beginning with a '$' : ignore it.
7698 * 2) it's a server id cookie that we *MAY* want to delete : save
7699 * some pointers on it (last semi-colon, beginning of cookie...)
7700 * 3) it's an application cookie : we *MAY* have to delete a previous
7701 * "special" cookie.
7702 * At the end of loop, if a "special" cookie remains, we may have to
7703 * remove it. If no application cookie persists in the header, we
7704 * *MUST* delete it.
7705 *
7706 * Note: RFC2965 is unclear about the processing of spaces around
7707 * the equal sign in the ATTR=VALUE form. A careful inspection of
7708 * the RFC explicitly allows spaces before it, and not within the
7709 * tokens (attrs or values). An inspection of RFC2109 allows that
7710 * too but section 10.1.3 lets one think that spaces may be allowed
7711 * after the equal sign too, resulting in some (rare) buggy
7712 * implementations trying to do that. So let's do what servers do.
7713 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
7714 * allowed quoted strings in values, with any possible character
7715 * after a backslash, including control chars and delimitors, which
7716 * causes parsing to become ambiguous. Browsers also allow spaces
7717 * within values even without quotes.
7718 *
7719 * We have to keep multiple pointers in order to support cookie
7720 * removal at the beginning, middle or end of header without
7721 * corrupting the header. All of these headers are valid :
7722 *
7723 * Cookie:NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3\r\n
7724 * Cookie:NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3\r\n
7725 * Cookie: NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3\r\n
7726 * | | | | | | | | |
7727 * | | | | | | | | hdr_end <--+
7728 * | | | | | | | +--> next
7729 * | | | | | | +----> val_end
7730 * | | | | | +-----------> val_beg
7731 * | | | | +--------------> equal
7732 * | | | +----------------> att_end
7733 * | | +---------------------> att_beg
7734 * | +--------------------------> prev
7735 * +--------------------------------> hdr_beg
7736 */
7737
7738 for (prev = hdr_beg + 6; prev < hdr_end; prev = next) {
7739 /* Iterate through all cookies on this line */
7740
7741 /* find att_beg */
7742 att_beg = prev + 1;
7743 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
7744 att_beg++;
7745
7746 /* find att_end : this is the first character after the last non
7747 * space before the equal. It may be equal to hdr_end.
7748 */
7749 equal = att_end = att_beg;
7750
7751 while (equal < hdr_end) {
7752 if (*equal == '=' || *equal == ',' || *equal == ';')
7753 break;
7754 if (HTTP_IS_SPHT(*equal++))
7755 continue;
7756 att_end = equal;
7757 }
7758
7759 /* here, <equal> points to '=', a delimitor or the end. <att_end>
7760 * is between <att_beg> and <equal>, both may be identical.
7761 */
7762
7763 /* look for end of cookie if there is an equal sign */
7764 if (equal < hdr_end && *equal == '=') {
7765 /* look for the beginning of the value */
7766 val_beg = equal + 1;
7767 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
7768 val_beg++;
7769
7770 /* find the end of the value, respecting quotes */
7771 next = find_cookie_value_end(val_beg, hdr_end);
7772
7773 /* make val_end point to the first white space or delimitor after the value */
7774 val_end = next;
7775 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
7776 val_end--;
7777 } else {
7778 val_beg = val_end = next = equal;
7779 }
7780
7781 /* We have nothing to do with attributes beginning with '$'. However,
7782 * they will automatically be removed if a header before them is removed,
7783 * since they're supposed to be linked together.
7784 */
7785 if (*att_beg == '$')
7786 continue;
7787
7788 /* Ignore cookies with no equal sign */
7789 if (equal == next) {
7790 /* This is not our cookie, so we must preserve it. But if we already
7791 * scheduled another cookie for removal, we cannot remove the
7792 * complete header, but we can remove the previous block itself.
7793 */
7794 preserve_hdr = 1;
7795 if (del_from != NULL) {
7796 int delta = del_hdr_value(req->buf, &del_from, prev);
7797 val_end += delta;
7798 next += delta;
7799 hdr_end += delta;
7800 hdr_next += delta;
7801 cur_hdr->len += delta;
7802 http_msg_move_end(&txn->req, delta);
7803 prev = del_from;
7804 del_from = NULL;
7805 }
7806 continue;
7807 }
7808
7809 /* if there are spaces around the equal sign, we need to
7810 * strip them otherwise we'll get trouble for cookie captures,
7811 * or even for rewrites. Since this happens extremely rarely,
7812 * it does not hurt performance.
7813 */
7814 if (unlikely(att_end != equal || val_beg > equal + 1)) {
7815 int stripped_before = 0;
7816 int stripped_after = 0;
7817
7818 if (att_end != equal) {
7819 stripped_before = buffer_replace2(req->buf, att_end, equal, NULL, 0);
7820 equal += stripped_before;
7821 val_beg += stripped_before;
7822 }
7823
7824 if (val_beg > equal + 1) {
7825 stripped_after = buffer_replace2(req->buf, equal + 1, val_beg, NULL, 0);
7826 val_beg += stripped_after;
7827 stripped_before += stripped_after;
7828 }
7829
7830 val_end += stripped_before;
7831 next += stripped_before;
7832 hdr_end += stripped_before;
7833 hdr_next += stripped_before;
7834 cur_hdr->len += stripped_before;
7835 http_msg_move_end(&txn->req, stripped_before);
7836 }
7837 /* now everything is as on the diagram above */
7838
7839 /* First, let's see if we want to capture this cookie. We check
7840 * that we don't already have a client side cookie, because we
7841 * can only capture one. Also as an optimisation, we ignore
7842 * cookies shorter than the declared name.
7843 */
7844 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
7845 (val_end - att_beg >= sess->fe->capture_namelen) &&
7846 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
7847 int log_len = val_end - att_beg;
7848
7849 if ((txn->cli_cookie = pool_alloc2(pool2_capture)) == NULL) {
7850 Alert("HTTP logging : out of memory.\n");
7851 } else {
7852 if (log_len > sess->fe->capture_len)
7853 log_len = sess->fe->capture_len;
7854 memcpy(txn->cli_cookie, att_beg, log_len);
7855 txn->cli_cookie[log_len] = 0;
7856 }
7857 }
7858
7859 /* Persistence cookies in passive, rewrite or insert mode have the
7860 * following form :
7861 *
7862 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
7863 *
7864 * For cookies in prefix mode, the form is :
7865 *
7866 * Cookie: NAME=SRV~VALUE
7867 */
7868 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
7869 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
7870 struct server *srv = s->be->srv;
7871 char *delim;
7872
7873 /* if we're in cookie prefix mode, we'll search the delimitor so that we
7874 * have the server ID between val_beg and delim, and the original cookie between
7875 * delim+1 and val_end. Otherwise, delim==val_end :
7876 *
7877 * Cookie: NAME=SRV; # in all but prefix modes
7878 * Cookie: NAME=SRV~OPAQUE ; # in prefix mode
7879 * | || || | |+-> next
7880 * | || || | +--> val_end
7881 * | || || +---------> delim
7882 * | || |+------------> val_beg
7883 * | || +-------------> att_end = equal
7884 * | |+-----------------> att_beg
7885 * | +------------------> prev
7886 * +-------------------------> hdr_beg
7887 */
7888
7889 if (s->be->ck_opts & PR_CK_PFX) {
7890 for (delim = val_beg; delim < val_end; delim++)
7891 if (*delim == COOKIE_DELIM)
7892 break;
7893 } else {
7894 char *vbar1;
7895 delim = val_end;
7896 /* Now check if the cookie contains a date field, which would
7897 * appear after a vertical bar ('|') just after the server name
7898 * and before the delimiter.
7899 */
7900 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
7901 if (vbar1) {
7902 /* OK, so left of the bar is the server's cookie and
7903 * right is the last seen date. It is a base64 encoded
7904 * 30-bit value representing the UNIX date since the
7905 * epoch in 4-second quantities.
7906 */
7907 int val;
7908 delim = vbar1++;
7909 if (val_end - vbar1 >= 5) {
7910 val = b64tos30(vbar1);
7911 if (val > 0)
7912 txn->cookie_last_date = val << 2;
7913 }
7914 /* look for a second vertical bar */
7915 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
7916 if (vbar1 && (val_end - vbar1 > 5)) {
7917 val = b64tos30(vbar1 + 1);
7918 if (val > 0)
7919 txn->cookie_first_date = val << 2;
7920 }
7921 }
7922 }
7923
7924 /* if the cookie has an expiration date and the proxy wants to check
7925 * it, then we do that now. We first check if the cookie is too old,
7926 * then only if it has expired. We detect strict overflow because the
7927 * time resolution here is not great (4 seconds). Cookies with dates
7928 * in the future are ignored if their offset is beyond one day. This
7929 * allows an admin to fix timezone issues without expiring everyone
7930 * and at the same time avoids keeping unwanted side effects for too
7931 * long.
7932 */
7933 if (txn->cookie_first_date && s->be->cookie_maxlife &&
7934 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
7935 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
7936 txn->flags &= ~TX_CK_MASK;
7937 txn->flags |= TX_CK_OLD;
7938 delim = val_beg; // let's pretend we have not found the cookie
7939 txn->cookie_first_date = 0;
7940 txn->cookie_last_date = 0;
7941 }
7942 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
7943 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
7944 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
7945 txn->flags &= ~TX_CK_MASK;
7946 txn->flags |= TX_CK_EXPIRED;
7947 delim = val_beg; // let's pretend we have not found the cookie
7948 txn->cookie_first_date = 0;
7949 txn->cookie_last_date = 0;
7950 }
7951
7952 /* Here, we'll look for the first running server which supports the cookie.
7953 * This allows to share a same cookie between several servers, for example
7954 * to dedicate backup servers to specific servers only.
7955 * However, to prevent clients from sticking to cookie-less backup server
7956 * when they have incidentely learned an empty cookie, we simply ignore
7957 * empty cookies and mark them as invalid.
7958 * The same behaviour is applied when persistence must be ignored.
7959 */
7960 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
7961 srv = NULL;
7962
7963 while (srv) {
7964 if (srv->cookie && (srv->cklen == delim - val_beg) &&
7965 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
7966 if ((srv->state != SRV_ST_STOPPED) ||
7967 (s->be->options & PR_O_PERSIST) ||
7968 (s->flags & SF_FORCE_PRST)) {
7969 /* we found the server and we can use it */
7970 txn->flags &= ~TX_CK_MASK;
7971 txn->flags |= (srv->state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
7972 s->flags |= SF_DIRECT | SF_ASSIGNED;
7973 s->target = &srv->obj_type;
7974 break;
7975 } else {
7976 /* we found a server, but it's down,
7977 * mark it as such and go on in case
7978 * another one is available.
7979 */
7980 txn->flags &= ~TX_CK_MASK;
7981 txn->flags |= TX_CK_DOWN;
7982 }
7983 }
7984 srv = srv->next;
7985 }
7986
7987 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
7988 /* no server matched this cookie or we deliberately skipped it */
7989 txn->flags &= ~TX_CK_MASK;
7990 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
7991 txn->flags |= TX_CK_UNUSED;
7992 else
7993 txn->flags |= TX_CK_INVALID;
7994 }
7995
7996 /* depending on the cookie mode, we may have to either :
7997 * - delete the complete cookie if we're in insert+indirect mode, so that
7998 * the server never sees it ;
7999 * - remove the server id from the cookie value, and tag the cookie as an
8000 * application cookie so that it does not get accidentely removed later,
8001 * if we're in cookie prefix mode
8002 */
8003 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
8004 int delta; /* negative */
8005
8006 delta = buffer_replace2(req->buf, val_beg, delim + 1, NULL, 0);
8007 val_end += delta;
8008 next += delta;
8009 hdr_end += delta;
8010 hdr_next += delta;
8011 cur_hdr->len += delta;
8012 http_msg_move_end(&txn->req, delta);
8013
8014 del_from = NULL;
8015 preserve_hdr = 1; /* we want to keep this cookie */
8016 }
8017 else if (del_from == NULL &&
8018 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
8019 del_from = prev;
8020 }
8021 } else {
8022 /* This is not our cookie, so we must preserve it. But if we already
8023 * scheduled another cookie for removal, we cannot remove the
8024 * complete header, but we can remove the previous block itself.
8025 */
8026 preserve_hdr = 1;
8027
8028 if (del_from != NULL) {
8029 int delta = del_hdr_value(req->buf, &del_from, prev);
8030 if (att_beg >= del_from)
8031 att_beg += delta;
8032 if (att_end >= del_from)
8033 att_end += delta;
8034 val_beg += delta;
8035 val_end += delta;
8036 next += delta;
8037 hdr_end += delta;
8038 hdr_next += delta;
8039 cur_hdr->len += delta;
8040 http_msg_move_end(&txn->req, delta);
8041 prev = del_from;
8042 del_from = NULL;
8043 }
8044 }
8045
8046 /* continue with next cookie on this header line */
8047 att_beg = next;
8048 } /* for each cookie */
8049
8050 /* There are no more cookies on this line.
8051 * We may still have one (or several) marked for deletion at the
8052 * end of the line. We must do this now in two ways :
8053 * - if some cookies must be preserved, we only delete from the
8054 * mark to the end of line ;
8055 * - if nothing needs to be preserved, simply delete the whole header
8056 */
8057 if (del_from) {
8058 int delta;
8059 if (preserve_hdr) {
8060 delta = del_hdr_value(req->buf, &del_from, hdr_end);
8061 hdr_end = del_from;
8062 cur_hdr->len += delta;
8063 } else {
8064 delta = buffer_replace2(req->buf, hdr_beg, hdr_next, NULL, 0);
8065
8066 /* FIXME: this should be a separate function */
8067 txn->hdr_idx.v[old_idx].next = cur_hdr->next;
8068 txn->hdr_idx.used--;
8069 cur_hdr->len = 0;
8070 cur_idx = old_idx;
8071 }
8072 hdr_next += delta;
8073 http_msg_move_end(&txn->req, delta);
8074 }
8075
8076 /* check next header */
8077 old_idx = cur_idx;
8078 }
8079 }
8080
8081
8082 /* Iterate the same filter through all response headers contained in <rtr>.
8083 * Returns 1 if this filter can be stopped upon return, otherwise 0.
8084 */
apply_filter_to_resp_headers(struct stream * s,struct channel * rtr,struct hdr_exp * exp)8085 int apply_filter_to_resp_headers(struct stream *s, struct channel *rtr, struct hdr_exp *exp)
8086 {
8087 char *cur_ptr, *cur_end, *cur_next;
8088 int cur_idx, old_idx, last_hdr;
8089 struct http_txn *txn = s->txn;
8090 struct hdr_idx_elem *cur_hdr;
8091 int delta;
8092
8093 last_hdr = 0;
8094
8095 cur_next = rtr->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
8096 old_idx = 0;
8097
8098 while (!last_hdr) {
8099 if (unlikely(txn->flags & TX_SVDENY))
8100 return 1;
8101 else if (unlikely(txn->flags & TX_SVALLOW) &&
8102 (exp->action == ACT_ALLOW ||
8103 exp->action == ACT_DENY))
8104 return 0;
8105
8106 cur_idx = txn->hdr_idx.v[old_idx].next;
8107 if (!cur_idx)
8108 break;
8109
8110 cur_hdr = &txn->hdr_idx.v[cur_idx];
8111 cur_ptr = cur_next;
8112 cur_end = cur_ptr + cur_hdr->len;
8113 cur_next = cur_end + cur_hdr->cr + 1;
8114
8115 /* Now we have one header between cur_ptr and cur_end,
8116 * and the next header starts at cur_next.
8117 */
8118
8119 if (regex_exec_match2(exp->preg, cur_ptr, cur_end-cur_ptr, MAX_MATCH, pmatch, 0)) {
8120 switch (exp->action) {
8121 case ACT_ALLOW:
8122 txn->flags |= TX_SVALLOW;
8123 last_hdr = 1;
8124 break;
8125
8126 case ACT_DENY:
8127 txn->flags |= TX_SVDENY;
8128 last_hdr = 1;
8129 break;
8130
8131 case ACT_REPLACE:
8132 trash.len = exp_replace(trash.str, trash.size, cur_ptr, exp->replace, pmatch);
8133 if (trash.len < 0)
8134 return -1;
8135
8136 delta = buffer_replace2(rtr->buf, cur_ptr, cur_end, trash.str, trash.len);
8137 /* FIXME: if the user adds a newline in the replacement, the
8138 * index will not be recalculated for now, and the new line
8139 * will not be counted as a new header.
8140 */
8141
8142 cur_end += delta;
8143 cur_next += delta;
8144 cur_hdr->len += delta;
8145 http_msg_move_end(&txn->rsp, delta);
8146 break;
8147
8148 case ACT_REMOVE:
8149 delta = buffer_replace2(rtr->buf, cur_ptr, cur_next, NULL, 0);
8150 cur_next += delta;
8151
8152 http_msg_move_end(&txn->rsp, delta);
8153 txn->hdr_idx.v[old_idx].next = cur_hdr->next;
8154 txn->hdr_idx.used--;
8155 cur_hdr->len = 0;
8156 cur_end = NULL; /* null-term has been rewritten */
8157 cur_idx = old_idx;
8158 break;
8159
8160 }
8161 }
8162
8163 /* keep the link from this header to next one in case of later
8164 * removal of next header.
8165 */
8166 old_idx = cur_idx;
8167 }
8168 return 0;
8169 }
8170
8171
8172 /* Apply the filter to the status line in the response buffer <rtr>.
8173 * Returns 0 if nothing has been done, 1 if the filter has been applied,
8174 * or -1 if a replacement resulted in an invalid status line.
8175 */
apply_filter_to_sts_line(struct stream * s,struct channel * rtr,struct hdr_exp * exp)8176 int apply_filter_to_sts_line(struct stream *s, struct channel *rtr, struct hdr_exp *exp)
8177 {
8178 char *cur_ptr, *cur_end;
8179 int done;
8180 struct http_txn *txn = s->txn;
8181 int delta;
8182
8183
8184 if (unlikely(txn->flags & TX_SVDENY))
8185 return 1;
8186 else if (unlikely(txn->flags & TX_SVALLOW) &&
8187 (exp->action == ACT_ALLOW ||
8188 exp->action == ACT_DENY))
8189 return 0;
8190 else if (exp->action == ACT_REMOVE)
8191 return 0;
8192
8193 done = 0;
8194
8195 cur_ptr = rtr->buf->p;
8196 cur_end = cur_ptr + txn->rsp.sl.st.l;
8197
8198 /* Now we have the status line between cur_ptr and cur_end */
8199
8200 if (regex_exec_match2(exp->preg, cur_ptr, cur_end-cur_ptr, MAX_MATCH, pmatch, 0)) {
8201 switch (exp->action) {
8202 case ACT_ALLOW:
8203 txn->flags |= TX_SVALLOW;
8204 done = 1;
8205 break;
8206
8207 case ACT_DENY:
8208 txn->flags |= TX_SVDENY;
8209 done = 1;
8210 break;
8211
8212 case ACT_REPLACE:
8213 trash.len = exp_replace(trash.str, trash.size, cur_ptr, exp->replace, pmatch);
8214 if (trash.len < 0)
8215 return -1;
8216
8217 delta = buffer_replace2(rtr->buf, cur_ptr, cur_end, trash.str, trash.len);
8218 /* FIXME: if the user adds a newline in the replacement, the
8219 * index will not be recalculated for now, and the new line
8220 * will not be counted as a new header.
8221 */
8222
8223 http_msg_move_end(&txn->rsp, delta);
8224 cur_end += delta;
8225 cur_end = (char *)http_parse_stsline(&txn->rsp,
8226 HTTP_MSG_RPVER,
8227 cur_ptr, cur_end + 1,
8228 NULL, NULL);
8229 if (unlikely(!cur_end))
8230 return -1;
8231
8232 /* we have a full respnse and we know that we have either a CR
8233 * or an LF at <ptr>.
8234 */
8235 txn->status = strl2ui(rtr->buf->p + txn->rsp.sl.st.c, txn->rsp.sl.st.c_l);
8236 hdr_idx_set_start(&txn->hdr_idx, txn->rsp.sl.st.l, *cur_end == '\r');
8237 /* there is no point trying this regex on headers */
8238 return 1;
8239 }
8240 }
8241 return done;
8242 }
8243
8244
8245
8246 /*
8247 * Apply all the resp filters of proxy <px> to all headers in buffer <rtr> of stream <s>.
8248 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
8249 * unparsable response.
8250 */
apply_filters_to_response(struct stream * s,struct channel * rtr,struct proxy * px)8251 int apply_filters_to_response(struct stream *s, struct channel *rtr, struct proxy *px)
8252 {
8253 struct session *sess = s->sess;
8254 struct http_txn *txn = s->txn;
8255 struct hdr_exp *exp;
8256
8257 for (exp = px->rsp_exp; exp; exp = exp->next) {
8258 int ret;
8259
8260 /*
8261 * The interleaving of transformations and verdicts
8262 * makes it difficult to decide to continue or stop
8263 * the evaluation.
8264 */
8265
8266 if (txn->flags & TX_SVDENY)
8267 break;
8268
8269 if ((txn->flags & TX_SVALLOW) &&
8270 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
8271 exp->action == ACT_PASS)) {
8272 exp = exp->next;
8273 continue;
8274 }
8275
8276 /* if this filter had a condition, evaluate it now and skip to
8277 * next filter if the condition does not match.
8278 */
8279 if (exp->cond) {
8280 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
8281 ret = acl_pass(ret);
8282 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
8283 ret = !ret;
8284 if (!ret)
8285 continue;
8286 }
8287
8288 /* Apply the filter to the status line. */
8289 ret = apply_filter_to_sts_line(s, rtr, exp);
8290 if (unlikely(ret < 0))
8291 return -1;
8292
8293 if (likely(ret == 0)) {
8294 /* The filter did not match the response, it can be
8295 * iterated through all headers.
8296 */
8297 if (unlikely(apply_filter_to_resp_headers(s, rtr, exp) < 0))
8298 return -1;
8299 }
8300 }
8301 return 0;
8302 }
8303
8304
8305 /*
8306 * Manage server-side cookies. It can impact performance by about 2% so it is
8307 * desirable to call it only when needed. This function is also used when we
8308 * just need to know if there is a cookie (eg: for check-cache).
8309 */
manage_server_side_cookies(struct stream * s,struct channel * res)8310 void manage_server_side_cookies(struct stream *s, struct channel *res)
8311 {
8312 struct http_txn *txn = s->txn;
8313 struct session *sess = s->sess;
8314 struct server *srv;
8315 int is_cookie2;
8316 int cur_idx, old_idx, delta;
8317 char *hdr_beg, *hdr_end, *hdr_next;
8318 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
8319
8320 /* Iterate through the headers.
8321 * we start with the start line.
8322 */
8323 old_idx = 0;
8324 hdr_next = res->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
8325
8326 while ((cur_idx = txn->hdr_idx.v[old_idx].next)) {
8327 struct hdr_idx_elem *cur_hdr;
8328 int val;
8329
8330 cur_hdr = &txn->hdr_idx.v[cur_idx];
8331 hdr_beg = hdr_next;
8332 hdr_end = hdr_beg + cur_hdr->len;
8333 hdr_next = hdr_end + cur_hdr->cr + 1;
8334
8335 /* We have one full header between hdr_beg and hdr_end, and the
8336 * next header starts at hdr_next. We're only interested in
8337 * "Set-Cookie" and "Set-Cookie2" headers.
8338 */
8339
8340 is_cookie2 = 0;
8341 prev = hdr_beg + 10;
8342 val = http_header_match2(hdr_beg, hdr_end, "Set-Cookie", 10);
8343 if (!val) {
8344 val = http_header_match2(hdr_beg, hdr_end, "Set-Cookie2", 11);
8345 if (!val) {
8346 old_idx = cur_idx;
8347 continue;
8348 }
8349 is_cookie2 = 1;
8350 prev = hdr_beg + 11;
8351 }
8352
8353 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
8354 * <prev> points to the colon.
8355 */
8356 txn->flags |= TX_SCK_PRESENT;
8357
8358 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
8359 * check-cache is enabled) and we are not interested in checking
8360 * them. Warning, the cookie capture is declared in the frontend.
8361 */
8362 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
8363 return;
8364
8365 /* OK so now we know we have to process this response cookie.
8366 * The format of the Set-Cookie header is slightly different
8367 * from the format of the Cookie header in that it does not
8368 * support the comma as a cookie delimiter (thus the header
8369 * cannot be folded) because the Expires attribute described in
8370 * the original Netscape's spec may contain an unquoted date
8371 * with a comma inside. We have to live with this because
8372 * many browsers don't support Max-Age and some browsers don't
8373 * support quoted strings. However the Set-Cookie2 header is
8374 * clean.
8375 *
8376 * We have to keep multiple pointers in order to support cookie
8377 * removal at the beginning, middle or end of header without
8378 * corrupting the header (in case of set-cookie2). A special
8379 * pointer, <scav> points to the beginning of the set-cookie-av
8380 * fields after the first semi-colon. The <next> pointer points
8381 * either to the end of line (set-cookie) or next unquoted comma
8382 * (set-cookie2). All of these headers are valid :
8383 *
8384 * Set-Cookie: NAME1 = VALUE 1 ; Secure; Path="/"\r\n
8385 * Set-Cookie:NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT\r\n
8386 * Set-Cookie: NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT\r\n
8387 * Set-Cookie2: NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard\r\n
8388 * | | | | | | | | | |
8389 * | | | | | | | | +-> next hdr_end <--+
8390 * | | | | | | | +------------> scav
8391 * | | | | | | +--------------> val_end
8392 * | | | | | +--------------------> val_beg
8393 * | | | | +----------------------> equal
8394 * | | | +------------------------> att_end
8395 * | | +----------------------------> att_beg
8396 * | +------------------------------> prev
8397 * +-----------------------------------------> hdr_beg
8398 */
8399
8400 for (; prev < hdr_end; prev = next) {
8401 /* Iterate through all cookies on this line */
8402
8403 /* find att_beg */
8404 att_beg = prev + 1;
8405 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
8406 att_beg++;
8407
8408 /* find att_end : this is the first character after the last non
8409 * space before the equal. It may be equal to hdr_end.
8410 */
8411 equal = att_end = att_beg;
8412
8413 while (equal < hdr_end) {
8414 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
8415 break;
8416 if (HTTP_IS_SPHT(*equal++))
8417 continue;
8418 att_end = equal;
8419 }
8420
8421 /* here, <equal> points to '=', a delimitor or the end. <att_end>
8422 * is between <att_beg> and <equal>, both may be identical.
8423 */
8424
8425 /* look for end of cookie if there is an equal sign */
8426 if (equal < hdr_end && *equal == '=') {
8427 /* look for the beginning of the value */
8428 val_beg = equal + 1;
8429 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
8430 val_beg++;
8431
8432 /* find the end of the value, respecting quotes */
8433 next = find_cookie_value_end(val_beg, hdr_end);
8434
8435 /* make val_end point to the first white space or delimitor after the value */
8436 val_end = next;
8437 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
8438 val_end--;
8439 } else {
8440 /* <equal> points to next comma, semi-colon or EOL */
8441 val_beg = val_end = next = equal;
8442 }
8443
8444 if (next < hdr_end) {
8445 /* Set-Cookie2 supports multiple cookies, and <next> points to
8446 * a colon or semi-colon before the end. So skip all attr-value
8447 * pairs and look for the next comma. For Set-Cookie, since
8448 * commas are permitted in values, skip to the end.
8449 */
8450 if (is_cookie2)
8451 next = find_hdr_value_end(next, hdr_end);
8452 else
8453 next = hdr_end;
8454 }
8455
8456 /* Now everything is as on the diagram above */
8457
8458 /* Ignore cookies with no equal sign */
8459 if (equal == val_end)
8460 continue;
8461
8462 /* If there are spaces around the equal sign, we need to
8463 * strip them otherwise we'll get trouble for cookie captures,
8464 * or even for rewrites. Since this happens extremely rarely,
8465 * it does not hurt performance.
8466 */
8467 if (unlikely(att_end != equal || val_beg > equal + 1)) {
8468 int stripped_before = 0;
8469 int stripped_after = 0;
8470
8471 if (att_end != equal) {
8472 stripped_before = buffer_replace2(res->buf, att_end, equal, NULL, 0);
8473 equal += stripped_before;
8474 val_beg += stripped_before;
8475 }
8476
8477 if (val_beg > equal + 1) {
8478 stripped_after = buffer_replace2(res->buf, equal + 1, val_beg, NULL, 0);
8479 val_beg += stripped_after;
8480 stripped_before += stripped_after;
8481 }
8482
8483 val_end += stripped_before;
8484 next += stripped_before;
8485 hdr_end += stripped_before;
8486 hdr_next += stripped_before;
8487 cur_hdr->len += stripped_before;
8488 http_msg_move_end(&txn->rsp, stripped_before);
8489 }
8490
8491 /* First, let's see if we want to capture this cookie. We check
8492 * that we don't already have a server side cookie, because we
8493 * can only capture one. Also as an optimisation, we ignore
8494 * cookies shorter than the declared name.
8495 */
8496 if (sess->fe->capture_name != NULL &&
8497 txn->srv_cookie == NULL &&
8498 (val_end - att_beg >= sess->fe->capture_namelen) &&
8499 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
8500 int log_len = val_end - att_beg;
8501 if ((txn->srv_cookie = pool_alloc2(pool2_capture)) == NULL) {
8502 Alert("HTTP logging : out of memory.\n");
8503 }
8504 else {
8505 if (log_len > sess->fe->capture_len)
8506 log_len = sess->fe->capture_len;
8507 memcpy(txn->srv_cookie, att_beg, log_len);
8508 txn->srv_cookie[log_len] = 0;
8509 }
8510 }
8511
8512 srv = objt_server(s->target);
8513 /* now check if we need to process it for persistence */
8514 if (!(s->flags & SF_IGNORE_PRST) &&
8515 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
8516 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
8517 /* assume passive cookie by default */
8518 txn->flags &= ~TX_SCK_MASK;
8519 txn->flags |= TX_SCK_FOUND;
8520
8521 /* If the cookie is in insert mode on a known server, we'll delete
8522 * this occurrence because we'll insert another one later.
8523 * We'll delete it too if the "indirect" option is set and we're in
8524 * a direct access.
8525 */
8526 if (s->be->ck_opts & PR_CK_PSV) {
8527 /* The "preserve" flag was set, we don't want to touch the
8528 * server's cookie.
8529 */
8530 }
8531 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
8532 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
8533 /* this cookie must be deleted */
8534 if (*prev == ':' && next == hdr_end) {
8535 /* whole header */
8536 delta = buffer_replace2(res->buf, hdr_beg, hdr_next, NULL, 0);
8537 txn->hdr_idx.v[old_idx].next = cur_hdr->next;
8538 txn->hdr_idx.used--;
8539 cur_hdr->len = 0;
8540 cur_idx = old_idx;
8541 hdr_next += delta;
8542 http_msg_move_end(&txn->rsp, delta);
8543 /* note: while both invalid now, <next> and <hdr_end>
8544 * are still equal, so the for() will stop as expected.
8545 */
8546 } else {
8547 /* just remove the value */
8548 int delta = del_hdr_value(res->buf, &prev, next);
8549 next = prev;
8550 hdr_end += delta;
8551 hdr_next += delta;
8552 cur_hdr->len += delta;
8553 http_msg_move_end(&txn->rsp, delta);
8554 }
8555 txn->flags &= ~TX_SCK_MASK;
8556 txn->flags |= TX_SCK_DELETED;
8557 /* and go on with next cookie */
8558 }
8559 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
8560 /* replace bytes val_beg->val_end with the cookie name associated
8561 * with this server since we know it.
8562 */
8563 delta = buffer_replace2(res->buf, val_beg, val_end, srv->cookie, srv->cklen);
8564 next += delta;
8565 hdr_end += delta;
8566 hdr_next += delta;
8567 cur_hdr->len += delta;
8568 http_msg_move_end(&txn->rsp, delta);
8569
8570 txn->flags &= ~TX_SCK_MASK;
8571 txn->flags |= TX_SCK_REPLACED;
8572 }
8573 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
8574 /* insert the cookie name associated with this server
8575 * before existing cookie, and insert a delimiter between them..
8576 */
8577 delta = buffer_replace2(res->buf, val_beg, val_beg, srv->cookie, srv->cklen + 1);
8578 next += delta;
8579 hdr_end += delta;
8580 hdr_next += delta;
8581 cur_hdr->len += delta;
8582 http_msg_move_end(&txn->rsp, delta);
8583
8584 val_beg[srv->cklen] = COOKIE_DELIM;
8585 txn->flags &= ~TX_SCK_MASK;
8586 txn->flags |= TX_SCK_REPLACED;
8587 }
8588 }
8589 /* that's done for this cookie, check the next one on the same
8590 * line when next != hdr_end (only if is_cookie2).
8591 */
8592 }
8593 /* check next header */
8594 old_idx = cur_idx;
8595 }
8596 }
8597
8598
8599 /*
8600 * Check if response is cacheable or not. Updates s->txn->flags.
8601 */
check_response_for_cacheability(struct stream * s,struct channel * rtr)8602 void check_response_for_cacheability(struct stream *s, struct channel *rtr)
8603 {
8604 struct http_txn *txn = s->txn;
8605 char *p1, *p2;
8606
8607 char *cur_ptr, *cur_end, *cur_next;
8608 int cur_idx;
8609
8610 if (!(txn->flags & TX_CACHEABLE))
8611 return;
8612
8613 /* Iterate through the headers.
8614 * we start with the start line.
8615 */
8616 cur_idx = 0;
8617 cur_next = rtr->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
8618
8619 while ((cur_idx = txn->hdr_idx.v[cur_idx].next)) {
8620 struct hdr_idx_elem *cur_hdr;
8621 int val;
8622
8623 cur_hdr = &txn->hdr_idx.v[cur_idx];
8624 cur_ptr = cur_next;
8625 cur_end = cur_ptr + cur_hdr->len;
8626 cur_next = cur_end + cur_hdr->cr + 1;
8627
8628 /* We have one full header between cur_ptr and cur_end, and the
8629 * next header starts at cur_next.
8630 */
8631
8632 val = http_header_match2(cur_ptr, cur_end, "Pragma", 6);
8633 if (val) {
8634 if ((cur_end - (cur_ptr + val) >= 8) &&
8635 strncasecmp(cur_ptr + val, "no-cache", 8) == 0) {
8636 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
8637 return;
8638 }
8639 }
8640
8641 val = http_header_match2(cur_ptr, cur_end, "Cache-control", 13);
8642 if (!val)
8643 continue;
8644
8645 /* OK, right now we know we have a cache-control header at cur_ptr */
8646
8647 p1 = cur_ptr + val; /* first non-space char after 'cache-control:' */
8648
8649 if (p1 >= cur_end) /* no more info */
8650 continue;
8651
8652 /* p1 is at the beginning of the value */
8653 p2 = p1;
8654
8655 while (p2 < cur_end && *p2 != '=' && *p2 != ',' && !isspace((unsigned char)*p2))
8656 p2++;
8657
8658 /* we have a complete value between p1 and p2 */
8659 if (p2 < cur_end && *p2 == '=') {
8660 if (((cur_end - p2) > 1 && (p2 - p1 == 7) && strncasecmp(p1, "max-age=0", 9) == 0) ||
8661 ((cur_end - p2) > 1 && (p2 - p1 == 8) && strncasecmp(p1, "s-maxage=0", 10) == 0)) {
8662 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
8663 continue;
8664 }
8665
8666 /* we have something of the form no-cache="set-cookie" */
8667 if ((cur_end - p1 >= 21) &&
8668 strncasecmp(p1, "no-cache=\"set-cookie", 20) == 0
8669 && (p1[20] == '"' || p1[20] == ','))
8670 txn->flags &= ~TX_CACHE_COOK;
8671 continue;
8672 }
8673
8674 /* OK, so we know that either p2 points to the end of string or to a comma */
8675 if (((p2 - p1 == 7) && strncasecmp(p1, "private", 7) == 0) ||
8676 ((p2 - p1 == 8) && strncasecmp(p1, "no-cache", 8) == 0) ||
8677 ((p2 - p1 == 8) && strncasecmp(p1, "no-store", 8) == 0)) {
8678 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
8679 return;
8680 }
8681
8682 if ((p2 - p1 == 6) && strncasecmp(p1, "public", 6) == 0) {
8683 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
8684 continue;
8685 }
8686 }
8687 }
8688
8689
8690 /*
8691 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
8692 * for the current backend.
8693 *
8694 * It is assumed that the request is either a HEAD, GET, or POST and that the
8695 * uri_auth field is valid.
8696 *
8697 * Returns 1 if stats should be provided, otherwise 0.
8698 */
stats_check_uri(struct stream_interface * si,struct http_txn * txn,struct proxy * backend)8699 int stats_check_uri(struct stream_interface *si, struct http_txn *txn, struct proxy *backend)
8700 {
8701 struct uri_auth *uri_auth = backend->uri_auth;
8702 struct http_msg *msg = &txn->req;
8703 const char *uri = msg->chn->buf->p+ msg->sl.rq.u;
8704
8705 if (!uri_auth)
8706 return 0;
8707
8708 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
8709 return 0;
8710
8711 /* check URI size */
8712 if (uri_auth->uri_len > msg->sl.rq.u_l)
8713 return 0;
8714
8715 if (memcmp(uri, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
8716 return 0;
8717
8718 return 1;
8719 }
8720
8721 /*
8722 * Capture a bad request or response and archive it in the proxy's structure.
8723 * By default it tries to report the error position as msg->err_pos. However if
8724 * this one is not set, it will then report msg->next, which is the last known
8725 * parsing point. The function is able to deal with wrapping buffers. It always
8726 * displays buffers as a contiguous area starting at buf->p.
8727 */
http_capture_bad_message(struct error_snapshot * es,struct stream * s,struct http_msg * msg,enum ht_state state,struct proxy * other_end)8728 void http_capture_bad_message(struct error_snapshot *es, struct stream *s,
8729 struct http_msg *msg,
8730 enum ht_state state, struct proxy *other_end)
8731 {
8732 struct session *sess = strm_sess(s);
8733 struct channel *chn = msg->chn;
8734 int len1, len2;
8735
8736 es->len = MIN(chn->buf->i, global.tune.bufsize);
8737 len1 = chn->buf->data + chn->buf->size - chn->buf->p;
8738 len1 = MIN(len1, es->len);
8739 len2 = es->len - len1; /* remaining data if buffer wraps */
8740
8741 if (!es->buf)
8742 es->buf = malloc(global.tune.bufsize);
8743
8744 if (es->buf) {
8745 memcpy(es->buf, chn->buf->p, len1);
8746 if (len2)
8747 memcpy(es->buf + len1, chn->buf->data, len2);
8748 }
8749
8750 if (msg->err_pos >= 0)
8751 es->pos = msg->err_pos;
8752 else
8753 es->pos = msg->next;
8754
8755 es->when = date; // user-visible date
8756 es->sid = s->uniq_id;
8757 es->srv = objt_server(s->target);
8758 es->oe = other_end;
8759 if (objt_conn(sess->origin))
8760 es->src = __objt_conn(sess->origin)->addr.from;
8761 else
8762 memset(&es->src, 0, sizeof(es->src));
8763
8764 es->state = state;
8765 es->ev_id = error_snapshot_id++;
8766 es->b_flags = chn->flags;
8767 es->s_flags = s->flags;
8768 es->t_flags = s->txn->flags;
8769 es->m_flags = msg->flags;
8770 es->b_out = chn->buf->o;
8771 es->b_wrap = chn->buf->data + chn->buf->size - chn->buf->p;
8772 es->b_tot = chn->total;
8773 es->m_clen = msg->chunk_len;
8774 es->m_blen = msg->body_len;
8775 }
8776
8777 /* Return in <vptr> and <vlen> the pointer and length of occurrence <occ> of
8778 * header whose name is <hname> of length <hlen>. If <ctx> is null, lookup is
8779 * performed over the whole headers. Otherwise it must contain a valid header
8780 * context, initialised with ctx->idx=0 for the first lookup in a series. If
8781 * <occ> is positive or null, occurrence #occ from the beginning (or last ctx)
8782 * is returned. Occ #0 and #1 are equivalent. If <occ> is negative (and no less
8783 * than -MAX_HDR_HISTORY), the occurrence is counted from the last one which is
8784 * -1. The value fetch stops at commas, so this function is suited for use with
8785 * list headers.
8786 * The return value is 0 if nothing was found, or non-zero otherwise.
8787 */
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)8788 unsigned int http_get_hdr(const struct http_msg *msg, const char *hname, int hlen,
8789 struct hdr_idx *idx, int occ,
8790 struct hdr_ctx *ctx, char **vptr, int *vlen)
8791 {
8792 struct hdr_ctx local_ctx;
8793 char *ptr_hist[MAX_HDR_HISTORY];
8794 int len_hist[MAX_HDR_HISTORY];
8795 unsigned int hist_ptr;
8796 int found;
8797
8798 if (!ctx) {
8799 local_ctx.idx = 0;
8800 ctx = &local_ctx;
8801 }
8802
8803 if (occ >= 0) {
8804 /* search from the beginning */
8805 while (http_find_header2(hname, hlen, msg->chn->buf->p, idx, ctx)) {
8806 occ--;
8807 if (occ <= 0) {
8808 *vptr = ctx->line + ctx->val;
8809 *vlen = ctx->vlen;
8810 return 1;
8811 }
8812 }
8813 return 0;
8814 }
8815
8816 /* negative occurrence, we scan all the list then walk back */
8817 if (-occ > MAX_HDR_HISTORY)
8818 return 0;
8819
8820 found = hist_ptr = 0;
8821 while (http_find_header2(hname, hlen, msg->chn->buf->p, idx, ctx)) {
8822 ptr_hist[hist_ptr] = ctx->line + ctx->val;
8823 len_hist[hist_ptr] = ctx->vlen;
8824 if (++hist_ptr >= MAX_HDR_HISTORY)
8825 hist_ptr = 0;
8826 found++;
8827 }
8828 if (-occ > found)
8829 return 0;
8830 /* OK now we have the last occurrence in [hist_ptr-1], and we need to
8831 * find occurrence -occ. 0 <= hist_ptr < MAX_HDR_HISTORY, and we have
8832 * -10 <= occ <= -1. So we have to check [hist_ptr%MAX_HDR_HISTORY+occ]
8833 * to remain in the 0..9 range.
8834 */
8835 hist_ptr += occ + MAX_HDR_HISTORY;
8836 if (hist_ptr >= MAX_HDR_HISTORY)
8837 hist_ptr -= MAX_HDR_HISTORY;
8838 *vptr = ptr_hist[hist_ptr];
8839 *vlen = len_hist[hist_ptr];
8840 return 1;
8841 }
8842
8843 /* Return in <vptr> and <vlen> the pointer and length of occurrence <occ> of
8844 * header whose name is <hname> of length <hlen>. If <ctx> is null, lookup is
8845 * performed over the whole headers. Otherwise it must contain a valid header
8846 * context, initialised with ctx->idx=0 for the first lookup in a series. If
8847 * <occ> is positive or null, occurrence #occ from the beginning (or last ctx)
8848 * is returned. Occ #0 and #1 are equivalent. If <occ> is negative (and no less
8849 * than -MAX_HDR_HISTORY), the occurrence is counted from the last one which is
8850 * -1. This function differs from http_get_hdr() in that it only returns full
8851 * line header values and does not stop at commas.
8852 * The return value is 0 if nothing was found, or non-zero otherwise.
8853 */
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)8854 unsigned int http_get_fhdr(const struct http_msg *msg, const char *hname, int hlen,
8855 struct hdr_idx *idx, int occ,
8856 struct hdr_ctx *ctx, char **vptr, int *vlen)
8857 {
8858 struct hdr_ctx local_ctx;
8859 char *ptr_hist[MAX_HDR_HISTORY];
8860 int len_hist[MAX_HDR_HISTORY];
8861 unsigned int hist_ptr;
8862 int found;
8863
8864 if (!ctx) {
8865 local_ctx.idx = 0;
8866 ctx = &local_ctx;
8867 }
8868
8869 if (occ >= 0) {
8870 /* search from the beginning */
8871 while (http_find_full_header2(hname, hlen, msg->chn->buf->p, idx, ctx)) {
8872 occ--;
8873 if (occ <= 0) {
8874 *vptr = ctx->line + ctx->val;
8875 *vlen = ctx->vlen;
8876 return 1;
8877 }
8878 }
8879 return 0;
8880 }
8881
8882 /* negative occurrence, we scan all the list then walk back */
8883 if (-occ > MAX_HDR_HISTORY)
8884 return 0;
8885
8886 found = hist_ptr = 0;
8887 while (http_find_full_header2(hname, hlen, msg->chn->buf->p, idx, ctx)) {
8888 ptr_hist[hist_ptr] = ctx->line + ctx->val;
8889 len_hist[hist_ptr] = ctx->vlen;
8890 if (++hist_ptr >= MAX_HDR_HISTORY)
8891 hist_ptr = 0;
8892 found++;
8893 }
8894 if (-occ > found)
8895 return 0;
8896
8897 /* OK now we have the last occurrence in [hist_ptr-1], and we need to
8898 * find occurrence -occ. 0 <= hist_ptr < MAX_HDR_HISTORY, and we have
8899 * -10 <= occ <= -1. So we have to check [hist_ptr%MAX_HDR_HISTORY+occ]
8900 * to remain in the 0..9 range.
8901 */
8902 hist_ptr += occ + MAX_HDR_HISTORY;
8903 if (hist_ptr >= MAX_HDR_HISTORY)
8904 hist_ptr -= MAX_HDR_HISTORY;
8905 *vptr = ptr_hist[hist_ptr];
8906 *vlen = len_hist[hist_ptr];
8907 return 1;
8908 }
8909
8910 /*
8911 * Print a debug line with a header. Always stop at the first CR or LF char,
8912 * so it is safe to pass it a full buffer if needed. If <err> is not NULL, an
8913 * arrow is printed after the line which contains the pointer.
8914 */
debug_hdr(const char * dir,struct stream * s,const char * start,const char * end)8915 void debug_hdr(const char *dir, struct stream *s, const char *start, const char *end)
8916 {
8917 struct session *sess = strm_sess(s);
8918 int max;
8919
8920 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
8921 dir,
8922 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->t.sock.fd : -1,
8923 objt_conn(s->si[1].end) ? (unsigned short)objt_conn(s->si[1].end)->t.sock.fd : -1);
8924
8925 for (max = 0; start + max < end; max++)
8926 if (start[max] == '\r' || start[max] == '\n')
8927 break;
8928
8929 UBOUND(max, trash.size - trash.len - 3);
8930 trash.len += strlcpy2(trash.str + trash.len, start, max + 1);
8931 trash.str[trash.len++] = '\n';
8932 shut_your_big_mouth_gcc(write(1, trash.str, trash.len));
8933 }
8934
8935
8936 /* Allocate a new HTTP transaction for stream <s> unless there is one already.
8937 * The hdr_idx is allocated as well. In case of allocation failure, everything
8938 * allocated is freed and NULL is returned. Otherwise the new transaction is
8939 * assigned to the stream and returned.
8940 */
http_alloc_txn(struct stream * s)8941 struct http_txn *http_alloc_txn(struct stream *s)
8942 {
8943 struct http_txn *txn = s->txn;
8944
8945 if (txn)
8946 return txn;
8947
8948 txn = pool_alloc2(pool2_http_txn);
8949 if (!txn)
8950 return txn;
8951
8952 txn->hdr_idx.size = global.tune.max_http_hdr;
8953 txn->hdr_idx.v = pool_alloc2(pool2_hdr_idx);
8954 if (!txn->hdr_idx.v) {
8955 pool_free2(pool2_http_txn, txn);
8956 return NULL;
8957 }
8958
8959 s->txn = txn;
8960 return txn;
8961 }
8962
http_txn_reset_req(struct http_txn * txn)8963 void http_txn_reset_req(struct http_txn *txn)
8964 {
8965 txn->req.flags = 0;
8966 txn->req.sol = txn->req.eol = txn->req.eoh = 0; /* relative to the buffer */
8967 txn->req.next = 0;
8968 txn->req.chunk_len = 0LL;
8969 txn->req.body_len = 0LL;
8970 txn->req.msg_state = HTTP_MSG_RQBEFORE; /* at the very beginning of the request */
8971 }
8972
http_txn_reset_res(struct http_txn * txn)8973 void http_txn_reset_res(struct http_txn *txn)
8974 {
8975 txn->rsp.flags = 0;
8976 txn->rsp.sol = txn->rsp.eol = txn->rsp.eoh = 0; /* relative to the buffer */
8977 txn->rsp.next = 0;
8978 txn->rsp.chunk_len = 0LL;
8979 txn->rsp.body_len = 0LL;
8980 txn->rsp.msg_state = HTTP_MSG_RPBEFORE; /* at the very beginning of the response */
8981 }
8982
8983 /*
8984 * Initialize a new HTTP transaction for stream <s>. It is assumed that all
8985 * the required fields are properly allocated and that we only need to (re)init
8986 * them. This should be used before processing any new request.
8987 */
http_init_txn(struct stream * s)8988 void http_init_txn(struct stream *s)
8989 {
8990 struct http_txn *txn = s->txn;
8991 struct proxy *fe = strm_fe(s);
8992
8993 txn->flags = 0;
8994 txn->status = -1;
8995
8996 txn->cookie_first_date = 0;
8997 txn->cookie_last_date = 0;
8998
8999 txn->srv_cookie = NULL;
9000 txn->cli_cookie = NULL;
9001 txn->uri = NULL;
9002
9003 http_txn_reset_req(txn);
9004 http_txn_reset_res(txn);
9005
9006 txn->req.chn = &s->req;
9007 txn->rsp.chn = &s->res;
9008
9009 txn->auth.method = HTTP_AUTH_UNKNOWN;
9010
9011 txn->req.err_pos = txn->rsp.err_pos = -2; /* block buggy requests/responses */
9012 if (fe->options2 & PR_O2_REQBUG_OK)
9013 txn->req.err_pos = -1; /* let buggy requests pass */
9014
9015 if (txn->hdr_idx.v)
9016 hdr_idx_init(&txn->hdr_idx);
9017
9018 vars_init(&s->vars_txn, SCOPE_TXN);
9019 vars_init(&s->vars_reqres, SCOPE_REQ);
9020 }
9021
9022 /* to be used at the end of a transaction */
http_end_txn(struct stream * s)9023 void http_end_txn(struct stream *s)
9024 {
9025 struct http_txn *txn = s->txn;
9026
9027 /* these ones will have been dynamically allocated */
9028 pool_free2(pool2_requri, txn->uri);
9029 pool_free2(pool2_capture, txn->cli_cookie);
9030 pool_free2(pool2_capture, txn->srv_cookie);
9031 pool_free2(pool2_uniqueid, s->unique_id);
9032
9033 s->unique_id = NULL;
9034 txn->uri = NULL;
9035 txn->srv_cookie = NULL;
9036 txn->cli_cookie = NULL;
9037
9038 vars_prune(&s->vars_txn, s->sess, s);
9039 vars_prune(&s->vars_reqres, s->sess, s);
9040 }
9041
9042 /* to be used at the end of a transaction to prepare a new one */
http_reset_txn(struct stream * s)9043 void http_reset_txn(struct stream *s)
9044 {
9045 http_end_txn(s);
9046 http_init_txn(s);
9047
9048 /* reinitialise the current rule list pointer to NULL. We are sure that
9049 * any rulelist match the NULL pointer.
9050 */
9051 s->current_rule_list = NULL;
9052
9053 s->be = strm_fe(s);
9054 s->logs.logwait = strm_fe(s)->to_log;
9055 s->logs.level = 0;
9056 stream_del_srv_conn(s);
9057 s->target = NULL;
9058 /* re-init store persistence */
9059 s->store_count = 0;
9060 s->uniq_id = global.req_count++;
9061
9062 s->pend_pos = NULL;
9063
9064 s->req.flags |= CF_READ_DONTWAIT; /* one read is usually enough */
9065
9066 /* We must trim any excess data from the response buffer, because we
9067 * may have blocked an invalid response from a server that we don't
9068 * want to accidentely forward once we disable the analysers, nor do
9069 * we want those data to come along with next response. A typical
9070 * example of such data would be from a buggy server responding to
9071 * a HEAD with some data, or sending more than the advertised
9072 * content-length.
9073 */
9074 if (unlikely(s->res.buf->i))
9075 s->res.buf->i = 0;
9076
9077 /* Now we can realign the response buffer */
9078 buffer_realign(s->res.buf);
9079
9080 s->req.rto = strm_fe(s)->timeout.client;
9081 s->req.wto = TICK_ETERNITY;
9082
9083 s->res.rto = TICK_ETERNITY;
9084 s->res.wto = strm_fe(s)->timeout.client;
9085
9086 s->req.rex = TICK_ETERNITY;
9087 s->req.wex = TICK_ETERNITY;
9088 s->req.analyse_exp = TICK_ETERNITY;
9089 s->res.rex = TICK_ETERNITY;
9090 s->res.wex = TICK_ETERNITY;
9091 s->res.analyse_exp = TICK_ETERNITY;
9092 s->si[1].hcto = TICK_ETERNITY;
9093 }
9094
9095 /* parse an "http-request" rule */
parse_http_req_cond(const char ** args,const char * file,int linenum,struct proxy * proxy)9096 struct act_rule *parse_http_req_cond(const char **args, const char *file, int linenum, struct proxy *proxy)
9097 {
9098 struct act_rule *rule;
9099 struct action_kw *custom = NULL;
9100 int cur_arg;
9101 char *error;
9102
9103 rule = calloc(1, sizeof(*rule));
9104 if (!rule) {
9105 Alert("parsing [%s:%d]: out of memory.\n", file, linenum);
9106 goto out_err;
9107 }
9108
9109 rule->deny_status = HTTP_ERR_403;
9110 if (!strcmp(args[0], "allow")) {
9111 rule->action = ACT_ACTION_ALLOW;
9112 cur_arg = 1;
9113 } else if (!strcmp(args[0], "deny") || !strcmp(args[0], "block")) {
9114 int code;
9115 int hc;
9116
9117 rule->action = ACT_ACTION_DENY;
9118 cur_arg = 1;
9119 if (strcmp(args[cur_arg], "deny_status") == 0) {
9120 cur_arg++;
9121 if (!args[cur_arg]) {
9122 Alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-request %s' rule : missing status code.\n",
9123 file, linenum, proxy_type_str(proxy), proxy->id, args[0]);
9124 goto out_err;
9125 }
9126
9127 code = atol(args[cur_arg]);
9128 cur_arg++;
9129 for (hc = 0; hc < HTTP_ERR_SIZE; hc++) {
9130 if (http_err_codes[hc] == code) {
9131 rule->deny_status = hc;
9132 break;
9133 }
9134 }
9135
9136 if (hc >= HTTP_ERR_SIZE) {
9137 Warning("parsing [%s:%d] : status code %d not handled, using default code 403.\n",
9138 file, linenum, code);
9139 }
9140 }
9141 } else if (!strcmp(args[0], "tarpit")) {
9142 rule->action = ACT_HTTP_REQ_TARPIT;
9143 cur_arg = 1;
9144 } else if (!strcmp(args[0], "auth")) {
9145 rule->action = ACT_HTTP_REQ_AUTH;
9146 cur_arg = 1;
9147
9148 while(*args[cur_arg]) {
9149 if (!strcmp(args[cur_arg], "realm")) {
9150 rule->arg.auth.realm = strdup(args[cur_arg + 1]);
9151 cur_arg+=2;
9152 continue;
9153 } else
9154 break;
9155 }
9156 } else if (!strcmp(args[0], "set-nice")) {
9157 rule->action = ACT_HTTP_SET_NICE;
9158 cur_arg = 1;
9159
9160 if (!*args[cur_arg] ||
9161 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
9162 Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument (integer value).\n",
9163 file, linenum, args[0]);
9164 goto out_err;
9165 }
9166 rule->arg.nice = atoi(args[cur_arg]);
9167 if (rule->arg.nice < -1024)
9168 rule->arg.nice = -1024;
9169 else if (rule->arg.nice > 1024)
9170 rule->arg.nice = 1024;
9171 cur_arg++;
9172 } else if (!strcmp(args[0], "set-tos")) {
9173 #ifdef IP_TOS
9174 char *err;
9175 rule->action = ACT_HTTP_SET_TOS;
9176 cur_arg = 1;
9177
9178 if (!*args[cur_arg] ||
9179 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
9180 Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument (integer/hex value).\n",
9181 file, linenum, args[0]);
9182 goto out_err;
9183 }
9184
9185 rule->arg.tos = strtol(args[cur_arg], &err, 0);
9186 if (err && *err != '\0') {
9187 Alert("parsing [%s:%d]: invalid character starting at '%s' in 'http-request %s' (integer/hex value expected).\n",
9188 file, linenum, err, args[0]);
9189 goto out_err;
9190 }
9191 cur_arg++;
9192 #else
9193 Alert("parsing [%s:%d]: 'http-request %s' is not supported on this platform (IP_TOS undefined).\n", file, linenum, args[0]);
9194 goto out_err;
9195 #endif
9196 } else if (!strcmp(args[0], "set-mark")) {
9197 #ifdef SO_MARK
9198 char *err;
9199 rule->action = ACT_HTTP_SET_MARK;
9200 cur_arg = 1;
9201
9202 if (!*args[cur_arg] ||
9203 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
9204 Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument (integer/hex value).\n",
9205 file, linenum, args[0]);
9206 goto out_err;
9207 }
9208
9209 rule->arg.mark = strtoul(args[cur_arg], &err, 0);
9210 if (err && *err != '\0') {
9211 Alert("parsing [%s:%d]: invalid character starting at '%s' in 'http-request %s' (integer/hex value expected).\n",
9212 file, linenum, err, args[0]);
9213 goto out_err;
9214 }
9215 cur_arg++;
9216 global.last_checks |= LSTCHK_NETADM;
9217 #else
9218 Alert("parsing [%s:%d]: 'http-request %s' is not supported on this platform (SO_MARK undefined).\n", file, linenum, args[0]);
9219 goto out_err;
9220 #endif
9221 } else if (!strcmp(args[0], "set-log-level")) {
9222 rule->action = ACT_HTTP_SET_LOGL;
9223 cur_arg = 1;
9224
9225 if (!*args[cur_arg] ||
9226 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
9227 bad_log_level:
9228 Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument (log level name or 'silent').\n",
9229 file, linenum, args[0]);
9230 goto out_err;
9231 }
9232 if (strcmp(args[cur_arg], "silent") == 0)
9233 rule->arg.loglevel = -1;
9234 else if ((rule->arg.loglevel = get_log_level(args[cur_arg]) + 1) == 0)
9235 goto bad_log_level;
9236 cur_arg++;
9237 } else if (strcmp(args[0], "add-header") == 0 || strcmp(args[0], "set-header") == 0) {
9238 rule->action = *args[0] == 'a' ? ACT_HTTP_ADD_HDR : ACT_HTTP_SET_HDR;
9239 cur_arg = 1;
9240
9241 if (!*args[cur_arg] || !*args[cur_arg+1] ||
9242 (*args[cur_arg+2] && strcmp(args[cur_arg+2], "if") != 0 && strcmp(args[cur_arg+2], "unless") != 0)) {
9243 Alert("parsing [%s:%d]: 'http-request %s' expects exactly 2 arguments.\n",
9244 file, linenum, args[0]);
9245 goto out_err;
9246 }
9247
9248 rule->arg.hdr_add.name = strdup(args[cur_arg]);
9249 rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name);
9250 LIST_INIT(&rule->arg.hdr_add.fmt);
9251
9252 proxy->conf.args.ctx = ARGC_HRQ;
9253 error = NULL;
9254 if (!parse_logformat_string(args[cur_arg + 1], proxy, &rule->arg.hdr_add.fmt, LOG_OPT_HTTP,
9255 (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, &error)) {
9256 Alert("parsing [%s:%d]: 'http-request %s': %s.\n",
9257 file, linenum, args[0], error);
9258 free(error);
9259 goto out_err;
9260 }
9261 free(proxy->conf.lfs_file);
9262 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9263 proxy->conf.lfs_line = proxy->conf.args.line;
9264 cur_arg += 2;
9265 } else if (strcmp(args[0], "replace-header") == 0 || strcmp(args[0], "replace-value") == 0) {
9266 rule->action = args[0][8] == 'h' ? ACT_HTTP_REPLACE_HDR : ACT_HTTP_REPLACE_VAL;
9267 cur_arg = 1;
9268
9269 if (!*args[cur_arg] || !*args[cur_arg+1] || !*args[cur_arg+2] ||
9270 (*args[cur_arg+3] && strcmp(args[cur_arg+3], "if") != 0 && strcmp(args[cur_arg+3], "unless") != 0)) {
9271 Alert("parsing [%s:%d]: 'http-request %s' expects exactly 3 arguments.\n",
9272 file, linenum, args[0]);
9273 goto out_err;
9274 }
9275
9276 rule->arg.hdr_add.name = strdup(args[cur_arg]);
9277 rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name);
9278 LIST_INIT(&rule->arg.hdr_add.fmt);
9279
9280 error = NULL;
9281 if (!regex_comp(args[cur_arg + 1], &rule->arg.hdr_add.re, 1, 1, &error)) {
9282 Alert("parsing [%s:%d] : '%s' : %s.\n", file, linenum,
9283 args[cur_arg + 1], error);
9284 free(error);
9285 goto out_err;
9286 }
9287
9288 proxy->conf.args.ctx = ARGC_HRQ;
9289 error = NULL;
9290 if (!parse_logformat_string(args[cur_arg + 2], proxy, &rule->arg.hdr_add.fmt, LOG_OPT_HTTP,
9291 (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, &error)) {
9292 Alert("parsing [%s:%d]: 'http-request %s': %s.\n",
9293 file, linenum, args[0], error);
9294 free(error);
9295 goto out_err;
9296 }
9297
9298 free(proxy->conf.lfs_file);
9299 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9300 proxy->conf.lfs_line = proxy->conf.args.line;
9301 cur_arg += 3;
9302 } else if (strcmp(args[0], "del-header") == 0) {
9303 rule->action = ACT_HTTP_DEL_HDR;
9304 cur_arg = 1;
9305
9306 if (!*args[cur_arg] ||
9307 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
9308 Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument.\n",
9309 file, linenum, args[0]);
9310 goto out_err;
9311 }
9312
9313 rule->arg.hdr_add.name = strdup(args[cur_arg]);
9314 rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name);
9315
9316 proxy->conf.args.ctx = ARGC_HRQ;
9317 free(proxy->conf.lfs_file);
9318 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9319 proxy->conf.lfs_line = proxy->conf.args.line;
9320 cur_arg += 1;
9321 } else if (strncmp(args[0], "track-sc", 8) == 0 &&
9322 args[0][9] == '\0' && args[0][8] >= '0' &&
9323 args[0][8] < '0' + MAX_SESS_STKCTR) { /* track-sc 0..9 */
9324 struct sample_expr *expr;
9325 unsigned int where;
9326 char *err = NULL;
9327
9328 cur_arg = 1;
9329 proxy->conf.args.ctx = ARGC_TRK;
9330
9331 expr = sample_parse_expr((char **)args, &cur_arg, file, linenum, &err, &proxy->conf.args);
9332 if (!expr) {
9333 Alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-request %s' rule : %s.\n",
9334 file, linenum, proxy_type_str(proxy), proxy->id, args[0], err);
9335 free(err);
9336 goto out_err;
9337 }
9338
9339 where = 0;
9340 if (proxy->cap & PR_CAP_FE)
9341 where |= SMP_VAL_FE_HRQ_HDR;
9342 if (proxy->cap & PR_CAP_BE)
9343 where |= SMP_VAL_BE_HRQ_HDR;
9344
9345 if (!(expr->fetch->val & where)) {
9346 Alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-request %s' rule :"
9347 " fetch method '%s' extracts information from '%s', none of which is available here.\n",
9348 file, linenum, proxy_type_str(proxy), proxy->id, args[0],
9349 args[cur_arg-1], sample_src_names(expr->fetch->use));
9350 free(expr);
9351 goto out_err;
9352 }
9353
9354 if (strcmp(args[cur_arg], "table") == 0) {
9355 cur_arg++;
9356 if (!args[cur_arg]) {
9357 Alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-request %s' rule : missing table name.\n",
9358 file, linenum, proxy_type_str(proxy), proxy->id, args[0]);
9359 free(expr);
9360 goto out_err;
9361 }
9362 /* we copy the table name for now, it will be resolved later */
9363 rule->arg.trk_ctr.table.n = strdup(args[cur_arg]);
9364 cur_arg++;
9365 }
9366 rule->arg.trk_ctr.expr = expr;
9367 rule->action = ACT_ACTION_TRK_SC0 + args[0][8] - '0';
9368 } else if (strcmp(args[0], "redirect") == 0) {
9369 struct redirect_rule *redir;
9370 char *errmsg = NULL;
9371
9372 if ((redir = http_parse_redirect_rule(file, linenum, proxy, (const char **)args + 1, &errmsg, 1, 0)) == NULL) {
9373 Alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-request %s' rule : %s.\n",
9374 file, linenum, proxy_type_str(proxy), proxy->id, args[0], errmsg);
9375 goto out_err;
9376 }
9377
9378 /* this redirect rule might already contain a parsed condition which
9379 * we'll pass to the http-request rule.
9380 */
9381 rule->action = ACT_HTTP_REDIR;
9382 rule->arg.redir = redir;
9383 rule->cond = redir->cond;
9384 redir->cond = NULL;
9385 cur_arg = 2;
9386 return rule;
9387 } else if (strncmp(args[0], "add-acl", 7) == 0) {
9388 /* http-request add-acl(<reference (acl name)>) <key pattern> */
9389 rule->action = ACT_HTTP_ADD_ACL;
9390 /*
9391 * '+ 8' for 'add-acl('
9392 * '- 9' for 'add-acl(' + trailing ')'
9393 */
9394 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
9395
9396 cur_arg = 1;
9397
9398 if (!*args[cur_arg] ||
9399 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
9400 Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument.\n",
9401 file, linenum, args[0]);
9402 goto out_err;
9403 }
9404
9405 LIST_INIT(&rule->arg.map.key);
9406 proxy->conf.args.ctx = ARGC_HRQ;
9407 error = NULL;
9408 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
9409 (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, &error)) {
9410 Alert("parsing [%s:%d]: 'http-request %s': %s.\n",
9411 file, linenum, args[0], error);
9412 free(error);
9413 goto out_err;
9414 }
9415 free(proxy->conf.lfs_file);
9416 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9417 proxy->conf.lfs_line = proxy->conf.args.line;
9418 cur_arg += 1;
9419 } else if (strncmp(args[0], "del-acl", 7) == 0) {
9420 /* http-request del-acl(<reference (acl name)>) <key pattern> */
9421 rule->action = ACT_HTTP_DEL_ACL;
9422 /*
9423 * '+ 8' for 'del-acl('
9424 * '- 9' for 'del-acl(' + trailing ')'
9425 */
9426 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
9427
9428 cur_arg = 1;
9429
9430 if (!*args[cur_arg] ||
9431 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
9432 Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument.\n",
9433 file, linenum, args[0]);
9434 goto out_err;
9435 }
9436
9437 LIST_INIT(&rule->arg.map.key);
9438 proxy->conf.args.ctx = ARGC_HRQ;
9439 error = NULL;
9440 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
9441 (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, &error)) {
9442 Alert("parsing [%s:%d]: 'http-request %s': %s.\n",
9443 file, linenum, args[0], error);
9444 free(error);
9445 goto out_err;
9446 }
9447 free(proxy->conf.lfs_file);
9448 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9449 proxy->conf.lfs_line = proxy->conf.args.line;
9450 cur_arg += 1;
9451 } else if (strncmp(args[0], "del-map", 7) == 0) {
9452 /* http-request del-map(<reference (map name)>) <key pattern> */
9453 rule->action = ACT_HTTP_DEL_MAP;
9454 /*
9455 * '+ 8' for 'del-map('
9456 * '- 9' for 'del-map(' + trailing ')'
9457 */
9458 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
9459
9460 cur_arg = 1;
9461
9462 if (!*args[cur_arg] ||
9463 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
9464 Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument.\n",
9465 file, linenum, args[0]);
9466 goto out_err;
9467 }
9468
9469 LIST_INIT(&rule->arg.map.key);
9470 proxy->conf.args.ctx = ARGC_HRQ;
9471 error = NULL;
9472 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
9473 (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, &error)) {
9474 Alert("parsing [%s:%d]: 'http-request %s': %s.\n",
9475 file, linenum, args[0], error);
9476 free(error);
9477 goto out_err;
9478 }
9479 free(proxy->conf.lfs_file);
9480 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9481 proxy->conf.lfs_line = proxy->conf.args.line;
9482 cur_arg += 1;
9483 } else if (strncmp(args[0], "set-map", 7) == 0) {
9484 /* http-request set-map(<reference (map name)>) <key pattern> <value pattern> */
9485 rule->action = ACT_HTTP_SET_MAP;
9486 /*
9487 * '+ 8' for 'set-map('
9488 * '- 9' for 'set-map(' + trailing ')'
9489 */
9490 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
9491
9492 cur_arg = 1;
9493
9494 if (!*args[cur_arg] || !*args[cur_arg+1] ||
9495 (*args[cur_arg+2] && strcmp(args[cur_arg+2], "if") != 0 && strcmp(args[cur_arg+2], "unless") != 0)) {
9496 Alert("parsing [%s:%d]: 'http-request %s' expects exactly 2 arguments.\n",
9497 file, linenum, args[0]);
9498 goto out_err;
9499 }
9500
9501 LIST_INIT(&rule->arg.map.key);
9502 LIST_INIT(&rule->arg.map.value);
9503 proxy->conf.args.ctx = ARGC_HRQ;
9504
9505 /* key pattern */
9506 error = NULL;
9507 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
9508 (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, &error)) {
9509 Alert("parsing [%s:%d]: 'http-request %s' key: %s.\n",
9510 file, linenum, args[0], error);
9511 free(error);
9512 goto out_err;
9513 }
9514
9515 /* value pattern */
9516 error = NULL;
9517 if (!parse_logformat_string(args[cur_arg + 1], proxy, &rule->arg.map.value, LOG_OPT_HTTP,
9518 (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, &error)) {
9519 Alert("parsing [%s:%d]: 'http-request %s' pattern: %s.\n",
9520 file, linenum, args[0], error);
9521 free(error);
9522 goto out_err;
9523 }
9524 free(proxy->conf.lfs_file);
9525 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9526 proxy->conf.lfs_line = proxy->conf.args.line;
9527
9528 cur_arg += 2;
9529 } else if (((custom = action_http_req_custom(args[0])) != NULL)) {
9530 char *errmsg = NULL;
9531 cur_arg = 1;
9532 /* try in the module list */
9533 rule->from = ACT_F_HTTP_REQ;
9534 rule->kw = custom;
9535 if (custom->parse(args, &cur_arg, proxy, rule, &errmsg) == ACT_RET_PRS_ERR) {
9536 Alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-request %s' rule : %s.\n",
9537 file, linenum, proxy_type_str(proxy), proxy->id, args[0], errmsg);
9538 free(errmsg);
9539 goto out_err;
9540 }
9541 } else {
9542 action_build_list(&http_req_keywords.list, &trash);
9543 Alert("parsing [%s:%d]: 'http-request' expects 'allow', 'deny', 'auth', 'redirect', "
9544 "'tarpit', 'add-header', 'set-header', 'replace-header', 'replace-value', 'set-nice', "
9545 "'set-tos', 'set-mark', 'set-log-level', 'add-acl', 'del-acl', 'del-map', 'set-map', 'track-sc*'"
9546 "%s%s, but got '%s'%s.\n",
9547 file, linenum, *trash.str ? ", " : "", trash.str, args[0], *args[0] ? "" : " (missing argument)");
9548 goto out_err;
9549 }
9550
9551 if (strcmp(args[cur_arg], "if") == 0 || strcmp(args[cur_arg], "unless") == 0) {
9552 struct acl_cond *cond;
9553 char *errmsg = NULL;
9554
9555 if ((cond = build_acl_cond(file, linenum, proxy, args+cur_arg, &errmsg)) == NULL) {
9556 Alert("parsing [%s:%d] : error detected while parsing an 'http-request %s' condition : %s.\n",
9557 file, linenum, args[0], errmsg);
9558 free(errmsg);
9559 goto out_err;
9560 }
9561 rule->cond = cond;
9562 }
9563 else if (*args[cur_arg]) {
9564 Alert("parsing [%s:%d]: 'http-request %s' expects 'realm' for 'auth',"
9565 " 'deny_status' for 'deny', or"
9566 " either 'if' or 'unless' followed by a condition but found '%s'.\n",
9567 file, linenum, args[0], args[cur_arg]);
9568 goto out_err;
9569 }
9570
9571 return rule;
9572 out_err:
9573 free(rule);
9574 return NULL;
9575 }
9576
9577 /* parse an "http-respose" rule */
parse_http_res_cond(const char ** args,const char * file,int linenum,struct proxy * proxy)9578 struct act_rule *parse_http_res_cond(const char **args, const char *file, int linenum, struct proxy *proxy)
9579 {
9580 struct act_rule *rule;
9581 struct action_kw *custom = NULL;
9582 int cur_arg;
9583 char *error;
9584
9585 rule = calloc(1, sizeof(*rule));
9586 if (!rule) {
9587 Alert("parsing [%s:%d]: out of memory.\n", file, linenum);
9588 goto out_err;
9589 }
9590
9591 if (!strcmp(args[0], "allow")) {
9592 rule->action = ACT_ACTION_ALLOW;
9593 cur_arg = 1;
9594 } else if (!strcmp(args[0], "deny")) {
9595 rule->action = ACT_ACTION_DENY;
9596 cur_arg = 1;
9597 } else if (!strcmp(args[0], "set-nice")) {
9598 rule->action = ACT_HTTP_SET_NICE;
9599 cur_arg = 1;
9600
9601 if (!*args[cur_arg] ||
9602 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
9603 Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument (integer value).\n",
9604 file, linenum, args[0]);
9605 goto out_err;
9606 }
9607 rule->arg.nice = atoi(args[cur_arg]);
9608 if (rule->arg.nice < -1024)
9609 rule->arg.nice = -1024;
9610 else if (rule->arg.nice > 1024)
9611 rule->arg.nice = 1024;
9612 cur_arg++;
9613 } else if (!strcmp(args[0], "set-tos")) {
9614 #ifdef IP_TOS
9615 char *err;
9616 rule->action = ACT_HTTP_SET_TOS;
9617 cur_arg = 1;
9618
9619 if (!*args[cur_arg] ||
9620 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
9621 Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument (integer/hex value).\n",
9622 file, linenum, args[0]);
9623 goto out_err;
9624 }
9625
9626 rule->arg.tos = strtol(args[cur_arg], &err, 0);
9627 if (err && *err != '\0') {
9628 Alert("parsing [%s:%d]: invalid character starting at '%s' in 'http-response %s' (integer/hex value expected).\n",
9629 file, linenum, err, args[0]);
9630 goto out_err;
9631 }
9632 cur_arg++;
9633 #else
9634 Alert("parsing [%s:%d]: 'http-response %s' is not supported on this platform (IP_TOS undefined).\n", file, linenum, args[0]);
9635 goto out_err;
9636 #endif
9637 } else if (!strcmp(args[0], "set-mark")) {
9638 #ifdef SO_MARK
9639 char *err;
9640 rule->action = ACT_HTTP_SET_MARK;
9641 cur_arg = 1;
9642
9643 if (!*args[cur_arg] ||
9644 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
9645 Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument (integer/hex value).\n",
9646 file, linenum, args[0]);
9647 goto out_err;
9648 }
9649
9650 rule->arg.mark = strtoul(args[cur_arg], &err, 0);
9651 if (err && *err != '\0') {
9652 Alert("parsing [%s:%d]: invalid character starting at '%s' in 'http-response %s' (integer/hex value expected).\n",
9653 file, linenum, err, args[0]);
9654 goto out_err;
9655 }
9656 cur_arg++;
9657 global.last_checks |= LSTCHK_NETADM;
9658 #else
9659 Alert("parsing [%s:%d]: 'http-response %s' is not supported on this platform (SO_MARK undefined).\n", file, linenum, args[0]);
9660 goto out_err;
9661 #endif
9662 } else if (!strcmp(args[0], "set-log-level")) {
9663 rule->action = ACT_HTTP_SET_LOGL;
9664 cur_arg = 1;
9665
9666 if (!*args[cur_arg] ||
9667 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
9668 bad_log_level:
9669 Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument (log level name or 'silent').\n",
9670 file, linenum, args[0]);
9671 goto out_err;
9672 }
9673 if (strcmp(args[cur_arg], "silent") == 0)
9674 rule->arg.loglevel = -1;
9675 else if ((rule->arg.loglevel = get_log_level(args[cur_arg]) + 1) == 0)
9676 goto bad_log_level;
9677 cur_arg++;
9678 } else if (strcmp(args[0], "add-header") == 0 || strcmp(args[0], "set-header") == 0) {
9679 rule->action = *args[0] == 'a' ? ACT_HTTP_ADD_HDR : ACT_HTTP_SET_HDR;
9680 cur_arg = 1;
9681
9682 if (!*args[cur_arg] || !*args[cur_arg+1] ||
9683 (*args[cur_arg+2] && strcmp(args[cur_arg+2], "if") != 0 && strcmp(args[cur_arg+2], "unless") != 0)) {
9684 Alert("parsing [%s:%d]: 'http-response %s' expects exactly 2 arguments.\n",
9685 file, linenum, args[0]);
9686 goto out_err;
9687 }
9688
9689 rule->arg.hdr_add.name = strdup(args[cur_arg]);
9690 rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name);
9691 LIST_INIT(&rule->arg.hdr_add.fmt);
9692
9693 proxy->conf.args.ctx = ARGC_HRS;
9694 error = NULL;
9695 if (!parse_logformat_string(args[cur_arg + 1], proxy, &rule->arg.hdr_add.fmt, LOG_OPT_HTTP,
9696 (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, &error)) {
9697 Alert("parsing [%s:%d]: 'http-response %s': %s.\n",
9698 file, linenum, args[0], error);
9699 free(error);
9700 goto out_err;
9701 }
9702 free(proxy->conf.lfs_file);
9703 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9704 proxy->conf.lfs_line = proxy->conf.args.line;
9705 cur_arg += 2;
9706 } else if (strcmp(args[0], "replace-header") == 0 || strcmp(args[0], "replace-value") == 0) {
9707 rule->action = args[0][8] == 'h' ? ACT_HTTP_REPLACE_HDR : ACT_HTTP_REPLACE_VAL;
9708 cur_arg = 1;
9709
9710 if (!*args[cur_arg] || !*args[cur_arg+1] || !*args[cur_arg+2] ||
9711 (*args[cur_arg+3] && strcmp(args[cur_arg+3], "if") != 0 && strcmp(args[cur_arg+3], "unless") != 0)) {
9712 Alert("parsing [%s:%d]: 'http-response %s' expects exactly 3 arguments.\n",
9713 file, linenum, args[0]);
9714 goto out_err;
9715 }
9716
9717 rule->arg.hdr_add.name = strdup(args[cur_arg]);
9718 rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name);
9719 LIST_INIT(&rule->arg.hdr_add.fmt);
9720
9721 error = NULL;
9722 if (!regex_comp(args[cur_arg + 1], &rule->arg.hdr_add.re, 1, 1, &error)) {
9723 Alert("parsing [%s:%d] : '%s' : %s.\n", file, linenum,
9724 args[cur_arg + 1], error);
9725 free(error);
9726 goto out_err;
9727 }
9728
9729 proxy->conf.args.ctx = ARGC_HRQ;
9730 error = NULL;
9731 if (!parse_logformat_string(args[cur_arg + 2], proxy, &rule->arg.hdr_add.fmt, LOG_OPT_HTTP,
9732 (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, &error)) {
9733 Alert("parsing [%s:%d]: 'http-response %s': %s.\n",
9734 file, linenum, args[0], error);
9735 free(error);
9736 goto out_err;
9737 }
9738
9739 free(proxy->conf.lfs_file);
9740 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9741 proxy->conf.lfs_line = proxy->conf.args.line;
9742 cur_arg += 3;
9743 } else if (strcmp(args[0], "del-header") == 0) {
9744 rule->action = ACT_HTTP_DEL_HDR;
9745 cur_arg = 1;
9746
9747 if (!*args[cur_arg] ||
9748 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
9749 Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument.\n",
9750 file, linenum, args[0]);
9751 goto out_err;
9752 }
9753
9754 rule->arg.hdr_add.name = strdup(args[cur_arg]);
9755 rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name);
9756
9757 proxy->conf.args.ctx = ARGC_HRS;
9758 free(proxy->conf.lfs_file);
9759 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9760 proxy->conf.lfs_line = proxy->conf.args.line;
9761 cur_arg += 1;
9762 } else if (strncmp(args[0], "add-acl", 7) == 0) {
9763 /* http-request add-acl(<reference (acl name)>) <key pattern> */
9764 rule->action = ACT_HTTP_ADD_ACL;
9765 /*
9766 * '+ 8' for 'add-acl('
9767 * '- 9' for 'add-acl(' + trailing ')'
9768 */
9769 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
9770
9771 cur_arg = 1;
9772
9773 if (!*args[cur_arg] ||
9774 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
9775 Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument.\n",
9776 file, linenum, args[0]);
9777 goto out_err;
9778 }
9779
9780 LIST_INIT(&rule->arg.map.key);
9781 proxy->conf.args.ctx = ARGC_HRS;
9782 error = NULL;
9783 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
9784 (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, &error)) {
9785 Alert("parsing [%s:%d]: 'http-response %s': %s.\n",
9786 file, linenum, args[0], error);
9787 free(error);
9788 goto out_err;
9789 }
9790 free(proxy->conf.lfs_file);
9791 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9792 proxy->conf.lfs_line = proxy->conf.args.line;
9793
9794 cur_arg += 1;
9795 } else if (strncmp(args[0], "del-acl", 7) == 0) {
9796 /* http-response del-acl(<reference (acl name)>) <key pattern> */
9797 rule->action = ACT_HTTP_DEL_ACL;
9798 /*
9799 * '+ 8' for 'del-acl('
9800 * '- 9' for 'del-acl(' + trailing ')'
9801 */
9802 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
9803
9804 cur_arg = 1;
9805
9806 if (!*args[cur_arg] ||
9807 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
9808 Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument.\n",
9809 file, linenum, args[0]);
9810 goto out_err;
9811 }
9812
9813 LIST_INIT(&rule->arg.map.key);
9814 proxy->conf.args.ctx = ARGC_HRS;
9815 error = NULL;
9816 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
9817 (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, &error)) {
9818 Alert("parsing [%s:%d]: 'http-response %s': %s.\n",
9819 file, linenum, args[0], error);
9820 free(error);
9821 goto out_err;
9822 }
9823 free(proxy->conf.lfs_file);
9824 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9825 proxy->conf.lfs_line = proxy->conf.args.line;
9826 cur_arg += 1;
9827 } else if (strncmp(args[0], "del-map", 7) == 0) {
9828 /* http-response del-map(<reference (map name)>) <key pattern> */
9829 rule->action = ACT_HTTP_DEL_MAP;
9830 /*
9831 * '+ 8' for 'del-map('
9832 * '- 9' for 'del-map(' + trailing ')'
9833 */
9834 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
9835
9836 cur_arg = 1;
9837
9838 if (!*args[cur_arg] ||
9839 (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) {
9840 Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument.\n",
9841 file, linenum, args[0]);
9842 goto out_err;
9843 }
9844
9845 LIST_INIT(&rule->arg.map.key);
9846 proxy->conf.args.ctx = ARGC_HRS;
9847 error = NULL;
9848 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
9849 (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, &error)) {
9850 Alert("parsing [%s:%d]: 'http-response %s' %s.\n",
9851 file, linenum, args[0], error);
9852 free(error);
9853 goto out_err;
9854 }
9855 free(proxy->conf.lfs_file);
9856 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9857 proxy->conf.lfs_line = proxy->conf.args.line;
9858 cur_arg += 1;
9859 } else if (strncmp(args[0], "set-map", 7) == 0) {
9860 /* http-response set-map(<reference (map name)>) <key pattern> <value pattern> */
9861 rule->action = ACT_HTTP_SET_MAP;
9862 /*
9863 * '+ 8' for 'set-map('
9864 * '- 9' for 'set-map(' + trailing ')'
9865 */
9866 rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9);
9867
9868 cur_arg = 1;
9869
9870 if (!*args[cur_arg] || !*args[cur_arg+1] ||
9871 (*args[cur_arg+2] && strcmp(args[cur_arg+2], "if") != 0 && strcmp(args[cur_arg+2], "unless") != 0)) {
9872 Alert("parsing [%s:%d]: 'http-response %s' expects exactly 2 arguments.\n",
9873 file, linenum, args[0]);
9874 goto out_err;
9875 }
9876
9877 LIST_INIT(&rule->arg.map.key);
9878 LIST_INIT(&rule->arg.map.value);
9879
9880 proxy->conf.args.ctx = ARGC_HRS;
9881
9882 /* key pattern */
9883 error = NULL;
9884 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP,
9885 (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, &error)) {
9886 Alert("parsing [%s:%d]: 'http-response %s' name: %s.\n",
9887 file, linenum, args[0], error);
9888 free(error);
9889 goto out_err;
9890 }
9891
9892 /* value pattern */
9893 error = NULL;
9894 if (!parse_logformat_string(args[cur_arg + 1], proxy, &rule->arg.map.value, LOG_OPT_HTTP,
9895 (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, &error)) {
9896 Alert("parsing [%s:%d]: 'http-response %s' value: %s.\n",
9897 file, linenum, args[0], error);
9898 free(error);
9899 goto out_err;
9900 }
9901
9902 free(proxy->conf.lfs_file);
9903 proxy->conf.lfs_file = strdup(proxy->conf.args.file);
9904 proxy->conf.lfs_line = proxy->conf.args.line;
9905
9906 cur_arg += 2;
9907 } else if (strcmp(args[0], "redirect") == 0) {
9908 struct redirect_rule *redir;
9909 char *errmsg = NULL;
9910
9911 if ((redir = http_parse_redirect_rule(file, linenum, proxy, (const char **)args + 1, &errmsg, 1, 1)) == NULL) {
9912 Alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-response %s' rule : %s.\n",
9913 file, linenum, proxy_type_str(proxy), proxy->id, args[0], errmsg);
9914 goto out_err;
9915 }
9916
9917 /* this redirect rule might already contain a parsed condition which
9918 * we'll pass to the http-request rule.
9919 */
9920 rule->action = ACT_HTTP_REDIR;
9921 rule->arg.redir = redir;
9922 rule->cond = redir->cond;
9923 redir->cond = NULL;
9924 cur_arg = 2;
9925 return rule;
9926 } else if (strncmp(args[0], "track-sc", 8) == 0 &&
9927 args[0][9] == '\0' && args[0][8] >= '0' &&
9928 args[0][8] < '0' + MAX_SESS_STKCTR) { /* track-sc 0..9 */
9929 struct sample_expr *expr;
9930 unsigned int where;
9931 char *err = NULL;
9932
9933 cur_arg = 1;
9934 proxy->conf.args.ctx = ARGC_TRK;
9935
9936 expr = sample_parse_expr((char **)args, &cur_arg, file, linenum, &err, &proxy->conf.args);
9937 if (!expr) {
9938 Alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-response %s' rule : %s.\n",
9939 file, linenum, proxy_type_str(proxy), proxy->id, args[0], err);
9940 free(err);
9941 goto out_err;
9942 }
9943
9944 where = 0;
9945 if (proxy->cap & PR_CAP_FE)
9946 where |= SMP_VAL_FE_HRS_HDR;
9947 if (proxy->cap & PR_CAP_BE)
9948 where |= SMP_VAL_BE_HRS_HDR;
9949
9950 if (!(expr->fetch->val & where)) {
9951 Alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-response %s' rule :"
9952 " fetch method '%s' extracts information from '%s', none of which is available here.\n",
9953 file, linenum, proxy_type_str(proxy), proxy->id, args[0],
9954 args[cur_arg-1], sample_src_names(expr->fetch->use));
9955 free(expr);
9956 goto out_err;
9957 }
9958
9959 if (strcmp(args[cur_arg], "table") == 0) {
9960 cur_arg++;
9961 if (!args[cur_arg]) {
9962 Alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-response %s' rule : missing table name.\n",
9963 file, linenum, proxy_type_str(proxy), proxy->id, args[0]);
9964 free(expr);
9965 goto out_err;
9966 }
9967 /* we copy the table name for now, it will be resolved later */
9968 rule->arg.trk_ctr.table.n = strdup(args[cur_arg]);
9969 cur_arg++;
9970 }
9971 rule->arg.trk_ctr.expr = expr;
9972 rule->action = ACT_ACTION_TRK_SC0 + args[0][8] - '0';
9973 } else if (((custom = action_http_res_custom(args[0])) != NULL)) {
9974 char *errmsg = NULL;
9975 cur_arg = 1;
9976 /* try in the module list */
9977 rule->from = ACT_F_HTTP_RES;
9978 rule->kw = custom;
9979 if (custom->parse(args, &cur_arg, proxy, rule, &errmsg) == ACT_RET_PRS_ERR) {
9980 Alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-response %s' rule : %s.\n",
9981 file, linenum, proxy_type_str(proxy), proxy->id, args[0], errmsg);
9982 free(errmsg);
9983 goto out_err;
9984 }
9985 } else {
9986 action_build_list(&http_res_keywords.list, &trash);
9987 Alert("parsing [%s:%d]: 'http-response' expects 'allow', 'deny', 'redirect', "
9988 "'add-header', 'del-header', 'set-header', 'replace-header', 'replace-value', 'set-nice', "
9989 "'set-tos', 'set-mark', 'set-log-level', 'add-acl', 'del-acl', 'del-map', 'set-map', 'track-sc*'"
9990 "%s%s, but got '%s'%s.\n",
9991 file, linenum, *trash.str ? ", " : "", trash.str, args[0], *args[0] ? "" : " (missing argument)");
9992 goto out_err;
9993 }
9994
9995 if (strcmp(args[cur_arg], "if") == 0 || strcmp(args[cur_arg], "unless") == 0) {
9996 struct acl_cond *cond;
9997 char *errmsg = NULL;
9998
9999 if ((cond = build_acl_cond(file, linenum, proxy, args+cur_arg, &errmsg)) == NULL) {
10000 Alert("parsing [%s:%d] : error detected while parsing an 'http-response %s' condition : %s.\n",
10001 file, linenum, args[0], errmsg);
10002 free(errmsg);
10003 goto out_err;
10004 }
10005 rule->cond = cond;
10006 }
10007 else if (*args[cur_arg]) {
10008 Alert("parsing [%s:%d]: 'http-response %s' expects"
10009 " either 'if' or 'unless' followed by a condition but found '%s'.\n",
10010 file, linenum, args[0], args[cur_arg]);
10011 goto out_err;
10012 }
10013
10014 return rule;
10015 out_err:
10016 free(rule);
10017 return NULL;
10018 }
10019
10020 /* Parses a redirect rule. Returns the redirect rule on success or NULL on error,
10021 * with <err> filled with the error message. If <use_fmt> is not null, builds a
10022 * dynamic log-format rule instead of a static string. Parameter <dir> indicates
10023 * the direction of the rule, and equals 0 for request, non-zero for responses.
10024 */
http_parse_redirect_rule(const char * file,int linenum,struct proxy * curproxy,const char ** args,char ** errmsg,int use_fmt,int dir)10025 struct redirect_rule *http_parse_redirect_rule(const char *file, int linenum, struct proxy *curproxy,
10026 const char **args, char **errmsg, int use_fmt, int dir)
10027 {
10028 struct redirect_rule *rule;
10029 int cur_arg;
10030 int type = REDIRECT_TYPE_NONE;
10031 int code = 302;
10032 const char *destination = NULL;
10033 const char *cookie = NULL;
10034 int cookie_set = 0;
10035 unsigned int flags = (!dir ? REDIRECT_FLAG_FROM_REQ : REDIRECT_FLAG_NONE);
10036 struct acl_cond *cond = NULL;
10037
10038 cur_arg = 0;
10039 while (*(args[cur_arg])) {
10040 if (strcmp(args[cur_arg], "location") == 0) {
10041 if (!*args[cur_arg + 1])
10042 goto missing_arg;
10043
10044 type = REDIRECT_TYPE_LOCATION;
10045 cur_arg++;
10046 destination = args[cur_arg];
10047 }
10048 else if (strcmp(args[cur_arg], "prefix") == 0) {
10049 if (!*args[cur_arg + 1])
10050 goto missing_arg;
10051 type = REDIRECT_TYPE_PREFIX;
10052 cur_arg++;
10053 destination = args[cur_arg];
10054 }
10055 else if (strcmp(args[cur_arg], "scheme") == 0) {
10056 if (!*args[cur_arg + 1])
10057 goto missing_arg;
10058
10059 type = REDIRECT_TYPE_SCHEME;
10060 cur_arg++;
10061 destination = args[cur_arg];
10062 }
10063 else if (strcmp(args[cur_arg], "set-cookie") == 0) {
10064 if (!*args[cur_arg + 1])
10065 goto missing_arg;
10066
10067 cur_arg++;
10068 cookie = args[cur_arg];
10069 cookie_set = 1;
10070 }
10071 else if (strcmp(args[cur_arg], "clear-cookie") == 0) {
10072 if (!*args[cur_arg + 1])
10073 goto missing_arg;
10074
10075 cur_arg++;
10076 cookie = args[cur_arg];
10077 cookie_set = 0;
10078 }
10079 else if (strcmp(args[cur_arg], "code") == 0) {
10080 if (!*args[cur_arg + 1])
10081 goto missing_arg;
10082
10083 cur_arg++;
10084 code = atol(args[cur_arg]);
10085 if (code < 301 || code > 308 || (code > 303 && code < 307)) {
10086 memprintf(errmsg,
10087 "'%s': unsupported HTTP code '%s' (must be one of 301, 302, 303, 307 or 308)",
10088 args[cur_arg - 1], args[cur_arg]);
10089 return NULL;
10090 }
10091 }
10092 else if (!strcmp(args[cur_arg],"drop-query")) {
10093 flags |= REDIRECT_FLAG_DROP_QS;
10094 }
10095 else if (!strcmp(args[cur_arg],"append-slash")) {
10096 flags |= REDIRECT_FLAG_APPEND_SLASH;
10097 }
10098 else if (strcmp(args[cur_arg], "if") == 0 ||
10099 strcmp(args[cur_arg], "unless") == 0) {
10100 cond = build_acl_cond(file, linenum, curproxy, (const char **)args + cur_arg, errmsg);
10101 if (!cond) {
10102 memprintf(errmsg, "error in condition: %s", *errmsg);
10103 return NULL;
10104 }
10105 break;
10106 }
10107 else {
10108 memprintf(errmsg,
10109 "expects 'code', 'prefix', 'location', 'scheme', 'set-cookie', 'clear-cookie', 'drop-query' or 'append-slash' (was '%s')",
10110 args[cur_arg]);
10111 return NULL;
10112 }
10113 cur_arg++;
10114 }
10115
10116 if (type == REDIRECT_TYPE_NONE) {
10117 memprintf(errmsg, "redirection type expected ('prefix', 'location', or 'scheme')");
10118 return NULL;
10119 }
10120
10121 if (dir && type != REDIRECT_TYPE_LOCATION) {
10122 memprintf(errmsg, "response only supports redirect type 'location'");
10123 return NULL;
10124 }
10125
10126 rule = calloc(1, sizeof(*rule));
10127 rule->cond = cond;
10128 LIST_INIT(&rule->rdr_fmt);
10129
10130 if (!use_fmt) {
10131 /* old-style static redirect rule */
10132 rule->rdr_str = strdup(destination);
10133 rule->rdr_len = strlen(destination);
10134 }
10135 else {
10136 /* log-format based redirect rule */
10137
10138 /* Parse destination. Note that in the REDIRECT_TYPE_PREFIX case,
10139 * if prefix == "/", we don't want to add anything, otherwise it
10140 * makes it hard for the user to configure a self-redirection.
10141 */
10142 curproxy->conf.args.ctx = ARGC_RDR;
10143 if (!(type == REDIRECT_TYPE_PREFIX && destination[0] == '/' && destination[1] == '\0')) {
10144 if (!parse_logformat_string(destination, curproxy, &rule->rdr_fmt, LOG_OPT_HTTP,
10145 dir ? (curproxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRS_HDR : SMP_VAL_BE_HRS_HDR
10146 : (curproxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR,
10147 errmsg)) {
10148 return NULL;
10149 }
10150 free(curproxy->conf.lfs_file);
10151 curproxy->conf.lfs_file = strdup(curproxy->conf.args.file);
10152 curproxy->conf.lfs_line = curproxy->conf.args.line;
10153 }
10154 }
10155
10156 if (cookie) {
10157 /* depending on cookie_set, either we want to set the cookie, or to clear it.
10158 * a clear consists in appending "; path=/; Max-Age=0;" at the end.
10159 */
10160 rule->cookie_len = strlen(cookie);
10161 if (cookie_set) {
10162 rule->cookie_str = malloc(rule->cookie_len + 10);
10163 memcpy(rule->cookie_str, cookie, rule->cookie_len);
10164 memcpy(rule->cookie_str + rule->cookie_len, "; path=/;", 10);
10165 rule->cookie_len += 9;
10166 } else {
10167 rule->cookie_str = malloc(rule->cookie_len + 21);
10168 memcpy(rule->cookie_str, cookie, rule->cookie_len);
10169 memcpy(rule->cookie_str + rule->cookie_len, "; path=/; Max-Age=0;", 21);
10170 rule->cookie_len += 20;
10171 }
10172 }
10173 rule->type = type;
10174 rule->code = code;
10175 rule->flags = flags;
10176 LIST_INIT(&rule->list);
10177 return rule;
10178
10179 missing_arg:
10180 memprintf(errmsg, "missing argument for '%s'", args[cur_arg]);
10181 return NULL;
10182 }
10183
10184 /************************************************************************/
10185 /* The code below is dedicated to ACL parsing and matching */
10186 /************************************************************************/
10187
10188
10189 /* This function ensures that the prerequisites for an L7 fetch are ready,
10190 * which means that a request or response is ready. If some data is missing,
10191 * a parsing attempt is made. This is useful in TCP-based ACLs which are able
10192 * to extract data from L7. If <req_vol> is non-null during a request prefetch,
10193 * another test is made to ensure the required information is not gone.
10194 *
10195 * The function returns :
10196 * 0 with SMP_F_MAY_CHANGE in the sample flags if some data is missing to
10197 * decide whether or not an HTTP message is present ;
10198 * 0 if the requested data cannot be fetched or if it is certain that
10199 * we'll never have any HTTP message there ;
10200 * 1 if an HTTP message is ready
10201 */
smp_prefetch_http(struct proxy * px,struct stream * s,unsigned int opt,const struct arg * args,struct sample * smp,int req_vol)10202 int smp_prefetch_http(struct proxy *px, struct stream *s, unsigned int opt,
10203 const struct arg *args, struct sample *smp, int req_vol)
10204 {
10205 struct http_txn *txn;
10206 struct http_msg *msg;
10207
10208 /* Note: it is possible that <s> is NULL when called before stream
10209 * initialization (eg: tcp-request connection), so this function is the
10210 * one responsible for guarding against this case for all HTTP users.
10211 */
10212 if (!s)
10213 return 0;
10214
10215 if (!s->txn) {
10216 if (unlikely(!http_alloc_txn(s)))
10217 return 0; /* not enough memory */
10218 http_init_txn(s);
10219 }
10220 txn = s->txn;
10221 msg = &txn->req;
10222
10223 /* Check for a dependency on a request */
10224 smp->data.type = SMP_T_BOOL;
10225
10226 if ((opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) {
10227 /* If the buffer does not leave enough free space at the end,
10228 * we must first realign it.
10229 */
10230 if (s->req.buf->p > s->req.buf->data &&
10231 s->req.buf->i + s->req.buf->p > s->req.buf->data + s->req.buf->size - global.tune.maxrewrite)
10232 buffer_slow_realign(s->req.buf);
10233
10234 if (unlikely(txn->req.msg_state < HTTP_MSG_BODY)) {
10235 if (msg->msg_state == HTTP_MSG_ERROR)
10236 return 0;
10237
10238 /* Try to decode HTTP request */
10239 if (likely(msg->next < s->req.buf->i))
10240 http_msg_analyzer(msg, &txn->hdr_idx);
10241
10242 /* Still no valid request ? */
10243 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
10244 if ((msg->msg_state == HTTP_MSG_ERROR) ||
10245 buffer_full(s->req.buf, global.tune.maxrewrite)) {
10246 return 0;
10247 }
10248 /* wait for final state */
10249 smp->flags |= SMP_F_MAY_CHANGE;
10250 return 0;
10251 }
10252
10253 /* OK we just got a valid HTTP request. We have some minor
10254 * preparation to perform so that further checks can rely
10255 * on HTTP tests.
10256 */
10257
10258 /* If the request was parsed but was too large, we must absolutely
10259 * return an error so that it is not processed. At the moment this
10260 * cannot happen, but if the parsers are to change in the future,
10261 * we want this check to be maintained.
10262 */
10263 if (unlikely(s->req.buf->i + s->req.buf->p >
10264 s->req.buf->data + s->req.buf->size - global.tune.maxrewrite)) {
10265 msg->err_state = msg->msg_state;
10266 msg->msg_state = HTTP_MSG_ERROR;
10267 smp->data.u.sint = 1;
10268 return 1;
10269 }
10270
10271 txn->meth = find_http_meth(msg->chn->buf->p, msg->sl.rq.m_l);
10272 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
10273 s->flags |= SF_REDIRECTABLE;
10274
10275 if (unlikely(msg->sl.rq.v_l == 0) && !http_upgrade_v09_to_v10(txn))
10276 return 0;
10277 }
10278
10279 if (req_vol && txn->rsp.msg_state != HTTP_MSG_RPBEFORE) {
10280 return 0; /* data might have moved and indexes changed */
10281 }
10282
10283 /* otherwise everything's ready for the request */
10284 }
10285 else {
10286 /* Check for a dependency on a response */
10287 if (txn->rsp.msg_state < HTTP_MSG_BODY) {
10288 smp->flags |= SMP_F_MAY_CHANGE;
10289 return 0;
10290 }
10291 }
10292
10293 /* everything's OK */
10294 smp->data.u.sint = 1;
10295 return 1;
10296 }
10297
10298 /* 1. Check on METHOD
10299 * We use the pre-parsed method if it is known, and store its number as an
10300 * integer. If it is unknown, we use the pointer and the length.
10301 */
pat_parse_meth(const char * text,struct pattern * pattern,int mflags,char ** err)10302 static int pat_parse_meth(const char *text, struct pattern *pattern, int mflags, char **err)
10303 {
10304 int len, meth;
10305
10306 len = strlen(text);
10307 meth = find_http_meth(text, len);
10308
10309 pattern->val.i = meth;
10310 if (meth == HTTP_METH_OTHER) {
10311 pattern->ptr.str = (char *)text;
10312 pattern->len = len;
10313 }
10314 else {
10315 pattern->ptr.str = NULL;
10316 pattern->len = 0;
10317 }
10318 return 1;
10319 }
10320
10321 /* This function fetches the method of current HTTP request and stores
10322 * it in the global pattern struct as a chunk. There are two possibilities :
10323 * - if the method is known (not HTTP_METH_OTHER), its identifier is stored
10324 * in <len> and <ptr> is NULL ;
10325 * - if the method is unknown (HTTP_METH_OTHER), <ptr> points to the text and
10326 * <len> to its length.
10327 * This is intended to be used with pat_match_meth() only.
10328 */
10329 static int
smp_fetch_meth(const struct arg * args,struct sample * smp,const char * kw,void * private)10330 smp_fetch_meth(const struct arg *args, struct sample *smp, const char *kw, void *private)
10331 {
10332 int meth;
10333 struct http_txn *txn;
10334
10335 CHECK_HTTP_MESSAGE_FIRST_PERM();
10336
10337 txn = smp->strm->txn;
10338 meth = txn->meth;
10339 smp->data.type = SMP_T_METH;
10340 smp->data.u.meth.meth = meth;
10341 if (meth == HTTP_METH_OTHER) {
10342 if (txn->rsp.msg_state != HTTP_MSG_RPBEFORE)
10343 /* ensure the indexes are not affected */
10344 return 0;
10345 smp->flags |= SMP_F_CONST;
10346 smp->data.u.meth.str.len = txn->req.sl.rq.m_l;
10347 smp->data.u.meth.str.str = txn->req.chn->buf->p;
10348 }
10349 smp->flags |= SMP_F_VOL_1ST;
10350 return 1;
10351 }
10352
10353 /* See above how the method is stored in the global pattern */
pat_match_meth(struct sample * smp,struct pattern_expr * expr,int fill)10354 static struct pattern *pat_match_meth(struct sample *smp, struct pattern_expr *expr, int fill)
10355 {
10356 int icase;
10357 struct pattern_list *lst;
10358 struct pattern *pattern;
10359
10360 list_for_each_entry(lst, &expr->patterns, list) {
10361 pattern = &lst->pat;
10362
10363 /* well-known method */
10364 if (pattern->val.i != HTTP_METH_OTHER) {
10365 if (smp->data.u.meth.meth == pattern->val.i)
10366 return pattern;
10367 else
10368 continue;
10369 }
10370
10371 /* Other method, we must compare the strings */
10372 if (pattern->len != smp->data.u.meth.str.len)
10373 continue;
10374
10375 icase = expr->mflags & PAT_MF_IGNORE_CASE;
10376 if ((icase && strncasecmp(pattern->ptr.str, smp->data.u.meth.str.str, smp->data.u.meth.str.len) == 0) ||
10377 (!icase && strncmp(pattern->ptr.str, smp->data.u.meth.str.str, smp->data.u.meth.str.len) == 0))
10378 return pattern;
10379 }
10380 return NULL;
10381 }
10382
10383 static int
smp_fetch_rqver(const struct arg * args,struct sample * smp,const char * kw,void * private)10384 smp_fetch_rqver(const struct arg *args, struct sample *smp, const char *kw, void *private)
10385 {
10386 struct http_txn *txn;
10387 char *ptr;
10388 int len;
10389
10390 CHECK_HTTP_MESSAGE_FIRST();
10391
10392 txn = smp->strm->txn;
10393 len = txn->req.sl.rq.v_l;
10394 ptr = txn->req.chn->buf->p + txn->req.sl.rq.v;
10395
10396 while ((len-- > 0) && (*ptr++ != '/'));
10397 if (len <= 0)
10398 return 0;
10399
10400 smp->data.type = SMP_T_STR;
10401 smp->data.u.str.str = ptr;
10402 smp->data.u.str.len = len;
10403
10404 smp->flags = SMP_F_VOL_1ST | SMP_F_CONST;
10405 return 1;
10406 }
10407
10408 static int
smp_fetch_stver(const struct arg * args,struct sample * smp,const char * kw,void * private)10409 smp_fetch_stver(const struct arg *args, struct sample *smp, const char *kw, void *private)
10410 {
10411 struct http_txn *txn;
10412 char *ptr;
10413 int len;
10414
10415 CHECK_HTTP_MESSAGE_FIRST();
10416
10417 txn = smp->strm->txn;
10418 if (txn->rsp.msg_state < HTTP_MSG_BODY)
10419 return 0;
10420
10421 len = txn->rsp.sl.st.v_l;
10422 ptr = txn->rsp.chn->buf->p;
10423
10424 while ((len-- > 0) && (*ptr++ != '/'));
10425 if (len <= 0)
10426 return 0;
10427
10428 smp->data.type = SMP_T_STR;
10429 smp->data.u.str.str = ptr;
10430 smp->data.u.str.len = len;
10431
10432 smp->flags = SMP_F_VOL_1ST | SMP_F_CONST;
10433 return 1;
10434 }
10435
10436 /* 3. Check on Status Code. We manipulate integers here. */
10437 static int
smp_fetch_stcode(const struct arg * args,struct sample * smp,const char * kw,void * private)10438 smp_fetch_stcode(const struct arg *args, struct sample *smp, const char *kw, void *private)
10439 {
10440 struct http_txn *txn;
10441 char *ptr;
10442 int len;
10443
10444 CHECK_HTTP_MESSAGE_FIRST();
10445
10446 txn = smp->strm->txn;
10447 if (txn->rsp.msg_state < HTTP_MSG_BODY)
10448 return 0;
10449
10450 len = txn->rsp.sl.st.c_l;
10451 ptr = txn->rsp.chn->buf->p + txn->rsp.sl.st.c;
10452
10453 smp->data.type = SMP_T_SINT;
10454 smp->data.u.sint = __strl2ui(ptr, len);
10455 smp->flags = SMP_F_VOL_1ST;
10456 return 1;
10457 }
10458
10459 static int
smp_fetch_uniqueid(const struct arg * args,struct sample * smp,const char * kw,void * private)10460 smp_fetch_uniqueid(const struct arg *args, struct sample *smp, const char *kw, void *private)
10461 {
10462 if (LIST_ISEMPTY(&smp->sess->fe->format_unique_id))
10463 return 0;
10464
10465 if (!smp->strm)
10466 return 0;
10467
10468 if (!smp->strm->unique_id) {
10469 if ((smp->strm->unique_id = pool_alloc2(pool2_uniqueid)) == NULL)
10470 return 0;
10471 smp->strm->unique_id[0] = '\0';
10472 build_logline(smp->strm, smp->strm->unique_id,
10473 UNIQUEID_LEN, &smp->sess->fe->format_unique_id);
10474 }
10475 smp->data.u.str.len = strlen(smp->strm->unique_id);
10476 smp->data.type = SMP_T_STR;
10477 smp->data.u.str.str = smp->strm->unique_id;
10478 smp->flags = SMP_F_CONST;
10479 return 1;
10480 }
10481
10482 /* returns the longest available part of the body. This requires that the body
10483 * has been waited for using http-buffer-request.
10484 */
10485 static int
smp_fetch_body(const struct arg * args,struct sample * smp,const char * kw,void * private)10486 smp_fetch_body(const struct arg *args, struct sample *smp, const char *kw, void *private)
10487 {
10488 struct http_msg *msg;
10489 unsigned long len;
10490 unsigned long block1;
10491 char *body;
10492 struct chunk *temp;
10493
10494 CHECK_HTTP_MESSAGE_FIRST();
10495
10496 if ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ)
10497 msg = &smp->strm->txn->req;
10498 else
10499 msg = &smp->strm->txn->rsp;
10500
10501 len = http_body_bytes(msg);
10502 body = b_ptr(msg->chn->buf, -http_data_rewind(msg));
10503
10504 block1 = len;
10505 if (block1 > msg->chn->buf->data + msg->chn->buf->size - body)
10506 block1 = msg->chn->buf->data + msg->chn->buf->size - body;
10507
10508 if (block1 == len) {
10509 /* buffer is not wrapped (or empty) */
10510 smp->data.type = SMP_T_BIN;
10511 smp->data.u.str.str = body;
10512 smp->data.u.str.len = len;
10513 smp->flags = SMP_F_VOL_TEST | SMP_F_CONST;
10514 }
10515 else {
10516 /* buffer is wrapped, we need to defragment it */
10517 temp = get_trash_chunk();
10518 memcpy(temp->str, body, block1);
10519 memcpy(temp->str + block1, msg->chn->buf->data, len - block1);
10520 smp->data.type = SMP_T_BIN;
10521 smp->data.u.str.str = temp->str;
10522 smp->data.u.str.len = len;
10523 smp->flags = SMP_F_VOL_TEST;
10524 }
10525 return 1;
10526 }
10527
10528
10529 /* returns the available length of the body. This requires that the body
10530 * has been waited for using http-buffer-request.
10531 */
10532 static int
smp_fetch_body_len(const struct arg * args,struct sample * smp,const char * kw,void * private)10533 smp_fetch_body_len(const struct arg *args, struct sample *smp, const char *kw, void *private)
10534 {
10535 struct http_msg *msg;
10536
10537 CHECK_HTTP_MESSAGE_FIRST();
10538
10539 if ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ)
10540 msg = &smp->strm->txn->req;
10541 else
10542 msg = &smp->strm->txn->rsp;
10543
10544 smp->data.type = SMP_T_SINT;
10545 smp->data.u.sint = http_body_bytes(msg);
10546
10547 smp->flags = SMP_F_VOL_TEST;
10548 return 1;
10549 }
10550
10551
10552 /* returns the advertised length of the body, or the advertised size of the
10553 * chunks available in the buffer. This requires that the body has been waited
10554 * for using http-buffer-request.
10555 */
10556 static int
smp_fetch_body_size(const struct arg * args,struct sample * smp,const char * kw,void * private)10557 smp_fetch_body_size(const struct arg *args, struct sample *smp, const char *kw, void *private)
10558 {
10559 struct http_msg *msg;
10560
10561 CHECK_HTTP_MESSAGE_FIRST();
10562
10563 if ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ)
10564 msg = &smp->strm->txn->req;
10565 else
10566 msg = &smp->strm->txn->rsp;
10567
10568 smp->data.type = SMP_T_SINT;
10569 smp->data.u.sint = msg->body_len;
10570
10571 smp->flags = SMP_F_VOL_TEST;
10572 return 1;
10573 }
10574
10575
10576 /* 4. Check on URL/URI. A pointer to the URI is stored. */
10577 static int
smp_fetch_url(const struct arg * args,struct sample * smp,const char * kw,void * private)10578 smp_fetch_url(const struct arg *args, struct sample *smp, const char *kw, void *private)
10579 {
10580 struct http_txn *txn;
10581
10582 CHECK_HTTP_MESSAGE_FIRST();
10583
10584 txn = smp->strm->txn;
10585 smp->data.type = SMP_T_STR;
10586 smp->data.u.str.len = txn->req.sl.rq.u_l;
10587 smp->data.u.str.str = txn->req.chn->buf->p + txn->req.sl.rq.u;
10588 smp->flags = SMP_F_VOL_1ST | SMP_F_CONST;
10589 return 1;
10590 }
10591
10592 static int
smp_fetch_url_ip(const struct arg * args,struct sample * smp,const char * kw,void * private)10593 smp_fetch_url_ip(const struct arg *args, struct sample *smp, const char *kw, void *private)
10594 {
10595 struct http_txn *txn;
10596 struct sockaddr_storage addr;
10597
10598 CHECK_HTTP_MESSAGE_FIRST();
10599
10600 txn = smp->strm->txn;
10601 url2sa(txn->req.chn->buf->p + txn->req.sl.rq.u, txn->req.sl.rq.u_l, &addr, NULL);
10602 if (((struct sockaddr_in *)&addr)->sin_family != AF_INET)
10603 return 0;
10604
10605 smp->data.type = SMP_T_IPV4;
10606 smp->data.u.ipv4 = ((struct sockaddr_in *)&addr)->sin_addr;
10607 smp->flags = 0;
10608 return 1;
10609 }
10610
10611 static int
smp_fetch_url_port(const struct arg * args,struct sample * smp,const char * kw,void * private)10612 smp_fetch_url_port(const struct arg *args, struct sample *smp, const char *kw, void *private)
10613 {
10614 struct http_txn *txn;
10615 struct sockaddr_storage addr;
10616
10617 CHECK_HTTP_MESSAGE_FIRST();
10618
10619 txn = smp->strm->txn;
10620 url2sa(txn->req.chn->buf->p + txn->req.sl.rq.u, txn->req.sl.rq.u_l, &addr, NULL);
10621 if (((struct sockaddr_in *)&addr)->sin_family != AF_INET)
10622 return 0;
10623
10624 smp->data.type = SMP_T_SINT;
10625 smp->data.u.sint = ntohs(((struct sockaddr_in *)&addr)->sin_port);
10626 smp->flags = 0;
10627 return 1;
10628 }
10629
10630 /* Fetch an HTTP header. A pointer to the beginning of the value is returned.
10631 * Accepts an optional argument of type string containing the header field name,
10632 * and an optional argument of type signed or unsigned integer to request an
10633 * explicit occurrence of the header. Note that in the event of a missing name,
10634 * headers are considered from the first one. It does not stop on commas and
10635 * returns full lines instead (useful for User-Agent or Date for example).
10636 */
10637 static int
smp_fetch_fhdr(const struct arg * args,struct sample * smp,const char * kw,void * private)10638 smp_fetch_fhdr(const struct arg *args, struct sample *smp, const char *kw, void *private)
10639 {
10640 struct hdr_idx *idx;
10641 struct hdr_ctx *ctx = smp->ctx.a[0];
10642 const struct http_msg *msg;
10643 int occ = 0;
10644 const char *name_str = NULL;
10645 int name_len = 0;
10646
10647 if (!ctx) {
10648 /* first call */
10649 ctx = &static_hdr_ctx;
10650 ctx->idx = 0;
10651 smp->ctx.a[0] = ctx;
10652 }
10653
10654 if (args) {
10655 if (args[0].type != ARGT_STR)
10656 return 0;
10657 name_str = args[0].data.str.str;
10658 name_len = args[0].data.str.len;
10659
10660 if (args[1].type == ARGT_SINT)
10661 occ = args[1].data.sint;
10662 }
10663
10664 CHECK_HTTP_MESSAGE_FIRST();
10665
10666 idx = &smp->strm->txn->hdr_idx;
10667 msg = ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) ? &smp->strm->txn->req : &smp->strm->txn->rsp;
10668
10669 if (ctx && !(smp->flags & SMP_F_NOT_LAST))
10670 /* search for header from the beginning */
10671 ctx->idx = 0;
10672
10673 if (!occ && !(smp->opt & SMP_OPT_ITERATE))
10674 /* no explicit occurrence and single fetch => last header by default */
10675 occ = -1;
10676
10677 if (!occ)
10678 /* prepare to report multiple occurrences for ACL fetches */
10679 smp->flags |= SMP_F_NOT_LAST;
10680
10681 smp->data.type = SMP_T_STR;
10682 smp->flags |= SMP_F_VOL_HDR | SMP_F_CONST;
10683 if (http_get_fhdr(msg, name_str, name_len, idx, occ, ctx, &smp->data.u.str.str, &smp->data.u.str.len))
10684 return 1;
10685
10686 smp->flags &= ~SMP_F_NOT_LAST;
10687 return 0;
10688 }
10689
10690 /* 6. Check on HTTP header count. The number of occurrences is returned.
10691 * Accepts exactly 1 argument of type string. It does not stop on commas and
10692 * returns full lines instead (useful for User-Agent or Date for example).
10693 */
10694 static int
smp_fetch_fhdr_cnt(const struct arg * args,struct sample * smp,const char * kw,void * private)10695 smp_fetch_fhdr_cnt(const struct arg *args, struct sample *smp, const char *kw, void *private)
10696 {
10697 struct hdr_idx *idx;
10698 struct hdr_ctx ctx;
10699 const struct http_msg *msg;
10700 int cnt;
10701 const char *name = NULL;
10702 int len = 0;
10703
10704 if (args && args->type == ARGT_STR) {
10705 name = args->data.str.str;
10706 len = args->data.str.len;
10707 }
10708
10709 CHECK_HTTP_MESSAGE_FIRST();
10710
10711 idx = &smp->strm->txn->hdr_idx;
10712 msg = ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) ? &smp->strm->txn->req : &smp->strm->txn->rsp;
10713
10714 ctx.idx = 0;
10715 cnt = 0;
10716 while (http_find_full_header2(name, len, msg->chn->buf->p, idx, &ctx))
10717 cnt++;
10718
10719 smp->data.type = SMP_T_SINT;
10720 smp->data.u.sint = cnt;
10721 smp->flags = SMP_F_VOL_HDR;
10722 return 1;
10723 }
10724
10725 static int
smp_fetch_hdr_names(const struct arg * args,struct sample * smp,const char * kw,void * private)10726 smp_fetch_hdr_names(const struct arg *args, struct sample *smp, const char *kw, void *private)
10727 {
10728 struct hdr_idx *idx;
10729 struct hdr_ctx ctx;
10730 const struct http_msg *msg;
10731 struct chunk *temp;
10732 char del = ',';
10733
10734 if (args && args->type == ARGT_STR)
10735 del = *args[0].data.str.str;
10736
10737 CHECK_HTTP_MESSAGE_FIRST();
10738
10739 idx = &smp->strm->txn->hdr_idx;
10740 msg = ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) ? &smp->strm->txn->req : &smp->strm->txn->rsp;
10741
10742 temp = get_trash_chunk();
10743
10744 ctx.idx = 0;
10745 while (http_find_next_header(msg->chn->buf->p, idx, &ctx)) {
10746 if (temp->len)
10747 temp->str[temp->len++] = del;
10748 memcpy(temp->str + temp->len, ctx.line, ctx.del);
10749 temp->len += ctx.del;
10750 }
10751
10752 smp->data.type = SMP_T_STR;
10753 smp->data.u.str.str = temp->str;
10754 smp->data.u.str.len = temp->len;
10755 smp->flags = SMP_F_VOL_HDR;
10756 return 1;
10757 }
10758
10759 /* Fetch an HTTP header. A pointer to the beginning of the value is returned.
10760 * Accepts an optional argument of type string containing the header field name,
10761 * and an optional argument of type signed or unsigned integer to request an
10762 * explicit occurrence of the header. Note that in the event of a missing name,
10763 * headers are considered from the first one.
10764 */
10765 static int
smp_fetch_hdr(const struct arg * args,struct sample * smp,const char * kw,void * private)10766 smp_fetch_hdr(const struct arg *args, struct sample *smp, const char *kw, void *private)
10767 {
10768 struct hdr_idx *idx;
10769 struct hdr_ctx *ctx = smp->ctx.a[0];
10770 const struct http_msg *msg;
10771 int occ = 0;
10772 const char *name_str = NULL;
10773 int name_len = 0;
10774
10775 if (!ctx) {
10776 /* first call */
10777 ctx = &static_hdr_ctx;
10778 ctx->idx = 0;
10779 smp->ctx.a[0] = ctx;
10780 }
10781
10782 if (args) {
10783 if (args[0].type != ARGT_STR)
10784 return 0;
10785 name_str = args[0].data.str.str;
10786 name_len = args[0].data.str.len;
10787
10788 if (args[1].type == ARGT_SINT)
10789 occ = args[1].data.sint;
10790 }
10791
10792 CHECK_HTTP_MESSAGE_FIRST();
10793
10794 idx = &smp->strm->txn->hdr_idx;
10795 msg = ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) ? &smp->strm->txn->req : &smp->strm->txn->rsp;
10796
10797 if (ctx && !(smp->flags & SMP_F_NOT_LAST))
10798 /* search for header from the beginning */
10799 ctx->idx = 0;
10800
10801 if (!occ && !(smp->opt & SMP_OPT_ITERATE))
10802 /* no explicit occurrence and single fetch => last header by default */
10803 occ = -1;
10804
10805 if (!occ)
10806 /* prepare to report multiple occurrences for ACL fetches */
10807 smp->flags |= SMP_F_NOT_LAST;
10808
10809 smp->data.type = SMP_T_STR;
10810 smp->flags |= SMP_F_VOL_HDR | SMP_F_CONST;
10811 if (http_get_hdr(msg, name_str, name_len, idx, occ, ctx, &smp->data.u.str.str, &smp->data.u.str.len))
10812 return 1;
10813
10814 smp->flags &= ~SMP_F_NOT_LAST;
10815 return 0;
10816 }
10817
10818 /* 6. Check on HTTP header count. The number of occurrences is returned.
10819 * Accepts exactly 1 argument of type string.
10820 */
10821 static int
smp_fetch_hdr_cnt(const struct arg * args,struct sample * smp,const char * kw,void * private)10822 smp_fetch_hdr_cnt(const struct arg *args, struct sample *smp, const char *kw, void *private)
10823 {
10824 struct hdr_idx *idx;
10825 struct hdr_ctx ctx;
10826 const struct http_msg *msg;
10827 int cnt;
10828 const char *name = NULL;
10829 int len = 0;
10830
10831 if (args && args->type == ARGT_STR) {
10832 name = args->data.str.str;
10833 len = args->data.str.len;
10834 }
10835
10836 CHECK_HTTP_MESSAGE_FIRST();
10837
10838 idx = &smp->strm->txn->hdr_idx;
10839 msg = ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) ? &smp->strm->txn->req : &smp->strm->txn->rsp;
10840
10841 ctx.idx = 0;
10842 cnt = 0;
10843 while (http_find_header2(name, len, msg->chn->buf->p, idx, &ctx))
10844 cnt++;
10845
10846 smp->data.type = SMP_T_SINT;
10847 smp->data.u.sint = cnt;
10848 smp->flags = SMP_F_VOL_HDR;
10849 return 1;
10850 }
10851
10852 /* Fetch an HTTP header's integer value. The integer value is returned. It
10853 * takes a mandatory argument of type string and an optional one of type int
10854 * to designate a specific occurrence. It returns an unsigned integer, which
10855 * may or may not be appropriate for everything.
10856 */
10857 static int
smp_fetch_hdr_val(const struct arg * args,struct sample * smp,const char * kw,void * private)10858 smp_fetch_hdr_val(const struct arg *args, struct sample *smp, const char *kw, void *private)
10859 {
10860 int ret = smp_fetch_hdr(args, smp, kw, private);
10861
10862 if (ret > 0) {
10863 smp->data.type = SMP_T_SINT;
10864 smp->data.u.sint = strl2ic(smp->data.u.str.str, smp->data.u.str.len);
10865 }
10866
10867 return ret;
10868 }
10869
10870 /* Fetch an HTTP header's IP value. takes a mandatory argument of type string
10871 * and an optional one of type int to designate a specific occurrence.
10872 * It returns an IPv4 or IPv6 address. Addresses surrounded by invalid chars
10873 * are rejected. However IPv4 addresses may be followed with a colon and a
10874 * valid port number.
10875 */
10876 static int
smp_fetch_hdr_ip(const struct arg * args,struct sample * smp,const char * kw,void * private)10877 smp_fetch_hdr_ip(const struct arg *args, struct sample *smp, const char *kw, void *private)
10878 {
10879 struct chunk *temp = get_trash_chunk();
10880 int ret, len;
10881 int port;
10882
10883 while ((ret = smp_fetch_hdr(args, smp, kw, private)) > 0) {
10884 if (smp->data.u.str.len < temp->size - 1) {
10885 memcpy(temp->str, smp->data.u.str.str,
10886 smp->data.u.str.len);
10887 temp->str[smp->data.u.str.len] = '\0';
10888 len = url2ipv4((char *) temp->str, &smp->data.u.ipv4);
10889 if (len > 0 && len == smp->data.u.str.len) {
10890 /* plain IPv4 address */
10891 smp->data.type = SMP_T_IPV4;
10892 break;
10893 } else if (len > 0 && temp->str[len] == ':' &&
10894 strl2irc(temp->str + len + 1, smp->data.u.str.len - len - 1, &port) == 0 &&
10895 port >= 0 && port <= 65535) {
10896 /* IPv4 address suffixed with ':' followed by a valid port number */
10897 smp->data.type = SMP_T_IPV4;
10898 break;
10899 } else if (inet_pton(AF_INET6, temp->str, &smp->data.u.ipv6)) {
10900 smp->data.type = SMP_T_IPV6;
10901 break;
10902 }
10903 }
10904
10905 /* if the header doesn't match an IP address, fetch next one */
10906 if (!(smp->flags & SMP_F_NOT_LAST))
10907 return 0;
10908 }
10909 return ret;
10910 }
10911
10912 /* 8. Check on URI PATH. A pointer to the PATH is stored. The path starts at
10913 * the first '/' after the possible hostname, and ends before the possible '?'.
10914 */
10915 static int
smp_fetch_path(const struct arg * args,struct sample * smp,const char * kw,void * private)10916 smp_fetch_path(const struct arg *args, struct sample *smp, const char *kw, void *private)
10917 {
10918 struct http_txn *txn;
10919 char *ptr, *end;
10920
10921 CHECK_HTTP_MESSAGE_FIRST();
10922
10923 txn = smp->strm->txn;
10924 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
10925 ptr = http_get_path(txn);
10926 if (!ptr)
10927 return 0;
10928
10929 /* OK, we got the '/' ! */
10930 smp->data.type = SMP_T_STR;
10931 smp->data.u.str.str = ptr;
10932
10933 while (ptr < end && *ptr != '?')
10934 ptr++;
10935
10936 smp->data.u.str.len = ptr - smp->data.u.str.str;
10937 smp->flags = SMP_F_VOL_1ST | SMP_F_CONST;
10938 return 1;
10939 }
10940
10941 /* This produces a concatenation of the first occurrence of the Host header
10942 * followed by the path component if it begins with a slash ('/'). This means
10943 * that '*' will not be added, resulting in exactly the first Host entry.
10944 * If no Host header is found, then the path is returned as-is. The returned
10945 * value is stored in the trash so it does not need to be marked constant.
10946 * The returned sample is of type string.
10947 */
10948 static int
smp_fetch_base(const struct arg * args,struct sample * smp,const char * kw,void * private)10949 smp_fetch_base(const struct arg *args, struct sample *smp, const char *kw, void *private)
10950 {
10951 struct http_txn *txn;
10952 char *ptr, *end, *beg;
10953 struct hdr_ctx ctx;
10954 struct chunk *temp;
10955
10956 CHECK_HTTP_MESSAGE_FIRST();
10957
10958 txn = smp->strm->txn;
10959 ctx.idx = 0;
10960 if (!http_find_header2("Host", 4, txn->req.chn->buf->p, &txn->hdr_idx, &ctx) || !ctx.vlen)
10961 return smp_fetch_path(args, smp, kw, private);
10962
10963 /* OK we have the header value in ctx.line+ctx.val for ctx.vlen bytes */
10964 temp = get_trash_chunk();
10965 memcpy(temp->str, ctx.line + ctx.val, ctx.vlen);
10966 smp->data.type = SMP_T_STR;
10967 smp->data.u.str.str = temp->str;
10968 smp->data.u.str.len = ctx.vlen;
10969
10970 /* now retrieve the path */
10971 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
10972 beg = http_get_path(txn);
10973 if (!beg)
10974 beg = end;
10975
10976 for (ptr = beg; ptr < end && *ptr != '?'; ptr++);
10977
10978 if (beg < ptr && *beg == '/') {
10979 memcpy(smp->data.u.str.str + smp->data.u.str.len, beg, ptr - beg);
10980 smp->data.u.str.len += ptr - beg;
10981 }
10982
10983 smp->flags = SMP_F_VOL_1ST;
10984 return 1;
10985 }
10986
10987 /* This produces a 32-bit hash of the concatenation of the first occurrence of
10988 * the Host header followed by the path component if it begins with a slash ('/').
10989 * This means that '*' will not be added, resulting in exactly the first Host
10990 * entry. If no Host header is found, then the path is used. The resulting value
10991 * is hashed using the path hash followed by a full avalanche hash and provides a
10992 * 32-bit integer value. This fetch is useful for tracking per-path activity on
10993 * high-traffic sites without having to store whole paths.
10994 */
10995 int
smp_fetch_base32(const struct arg * args,struct sample * smp,const char * kw,void * private)10996 smp_fetch_base32(const struct arg *args, struct sample *smp, const char *kw, void *private)
10997 {
10998 struct http_txn *txn;
10999 struct hdr_ctx ctx;
11000 unsigned int hash = 0;
11001 char *ptr, *beg, *end;
11002 int len;
11003
11004 CHECK_HTTP_MESSAGE_FIRST();
11005
11006 txn = smp->strm->txn;
11007 ctx.idx = 0;
11008 if (http_find_header2("Host", 4, txn->req.chn->buf->p, &txn->hdr_idx, &ctx)) {
11009 /* OK we have the header value in ctx.line+ctx.val for ctx.vlen bytes */
11010 ptr = ctx.line + ctx.val;
11011 len = ctx.vlen;
11012 while (len--)
11013 hash = *(ptr++) + (hash << 6) + (hash << 16) - hash;
11014 }
11015
11016 /* now retrieve the path */
11017 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
11018 beg = http_get_path(txn);
11019 if (!beg)
11020 beg = end;
11021
11022 for (ptr = beg; ptr < end && *ptr != '?'; ptr++);
11023
11024 if (beg < ptr && *beg == '/') {
11025 while (beg < ptr)
11026 hash = *(beg++) + (hash << 6) + (hash << 16) - hash;
11027 }
11028 hash = full_hash(hash);
11029
11030 smp->data.type = SMP_T_SINT;
11031 smp->data.u.sint = hash;
11032 smp->flags = SMP_F_VOL_1ST;
11033 return 1;
11034 }
11035
11036 /* This concatenates the source address with the 32-bit hash of the Host and
11037 * path as returned by smp_fetch_base32(). The idea is to have per-source and
11038 * per-path counters. The result is a binary block from 8 to 20 bytes depending
11039 * on the source address length. The path hash is stored before the address so
11040 * that in environments where IPv6 is insignificant, truncating the output to
11041 * 8 bytes would still work.
11042 */
11043 static int
smp_fetch_base32_src(const struct arg * args,struct sample * smp,const char * kw,void * private)11044 smp_fetch_base32_src(const struct arg *args, struct sample *smp, const char *kw, void *private)
11045 {
11046 struct chunk *temp;
11047 struct connection *cli_conn = objt_conn(smp->sess->origin);
11048
11049 if (!cli_conn)
11050 return 0;
11051
11052 if (!smp_fetch_base32(args, smp, kw, private))
11053 return 0;
11054
11055 temp = get_trash_chunk();
11056 *(unsigned int *)temp->str = htonl(smp->data.u.sint);
11057 temp->len += sizeof(unsigned int);
11058
11059 switch (cli_conn->addr.from.ss_family) {
11060 case AF_INET:
11061 memcpy(temp->str + temp->len, &((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr, 4);
11062 temp->len += 4;
11063 break;
11064 case AF_INET6:
11065 memcpy(temp->str + temp->len, &((struct sockaddr_in6 *)&cli_conn->addr.from)->sin6_addr, 16);
11066 temp->len += 16;
11067 break;
11068 default:
11069 return 0;
11070 }
11071
11072 smp->data.u.str = *temp;
11073 smp->data.type = SMP_T_BIN;
11074 return 1;
11075 }
11076
11077 /* Extracts the query string, which comes after the question mark '?'. If no
11078 * question mark is found, nothing is returned. Otherwise it returns a sample
11079 * of type string carrying the whole query string.
11080 */
11081 static int
smp_fetch_query(const struct arg * args,struct sample * smp,const char * kw,void * private)11082 smp_fetch_query(const struct arg *args, struct sample *smp, const char *kw, void *private)
11083 {
11084 struct http_txn *txn;
11085 char *ptr, *end;
11086
11087 CHECK_HTTP_MESSAGE_FIRST();
11088
11089 txn = smp->strm->txn;
11090 ptr = txn->req.chn->buf->p + txn->req.sl.rq.u;
11091 end = ptr + txn->req.sl.rq.u_l;
11092
11093 /* look up the '?' */
11094 do {
11095 if (ptr == end)
11096 return 0;
11097 } while (*ptr++ != '?');
11098
11099 smp->data.type = SMP_T_STR;
11100 smp->data.u.str.str = ptr;
11101 smp->data.u.str.len = end - ptr;
11102 smp->flags = SMP_F_VOL_1ST | SMP_F_CONST;
11103 return 1;
11104 }
11105
11106 static int
smp_fetch_proto_http(const struct arg * args,struct sample * smp,const char * kw,void * private)11107 smp_fetch_proto_http(const struct arg *args, struct sample *smp, const char *kw, void *private)
11108 {
11109 /* Note: hdr_idx.v cannot be NULL in this ACL because the ACL is tagged
11110 * as a layer7 ACL, which involves automatic allocation of hdr_idx.
11111 */
11112
11113 CHECK_HTTP_MESSAGE_FIRST_PERM();
11114
11115 smp->data.type = SMP_T_BOOL;
11116 smp->data.u.sint = 1;
11117 return 1;
11118 }
11119
11120 /* return a valid test if the current request is the first one on the connection */
11121 static int
smp_fetch_http_first_req(const struct arg * args,struct sample * smp,const char * kw,void * private)11122 smp_fetch_http_first_req(const struct arg *args, struct sample *smp, const char *kw, void *private)
11123 {
11124 if (!smp->strm)
11125 return 0;
11126
11127 smp->data.type = SMP_T_BOOL;
11128 smp->data.u.sint = !(smp->strm->txn->flags & TX_NOT_FIRST);
11129 return 1;
11130 }
11131
11132 /* Accepts exactly 1 argument of type userlist */
11133 static int
smp_fetch_http_auth(const struct arg * args,struct sample * smp,const char * kw,void * private)11134 smp_fetch_http_auth(const struct arg *args, struct sample *smp, const char *kw, void *private)
11135 {
11136
11137 if (!args || args->type != ARGT_USR)
11138 return 0;
11139
11140 CHECK_HTTP_MESSAGE_FIRST();
11141
11142 if (!get_http_auth(smp->strm))
11143 return 0;
11144
11145 smp->data.type = SMP_T_BOOL;
11146 smp->data.u.sint = check_user(args->data.usr, smp->strm->txn->auth.user,
11147 smp->strm->txn->auth.pass);
11148 return 1;
11149 }
11150
11151 /* Accepts exactly 1 argument of type userlist */
11152 static int
smp_fetch_http_auth_grp(const struct arg * args,struct sample * smp,const char * kw,void * private)11153 smp_fetch_http_auth_grp(const struct arg *args, struct sample *smp, const char *kw, void *private)
11154 {
11155 if (!args || args->type != ARGT_USR)
11156 return 0;
11157
11158 CHECK_HTTP_MESSAGE_FIRST();
11159
11160 if (!get_http_auth(smp->strm))
11161 return 0;
11162
11163 /* if the user does not belong to the userlist or has a wrong password,
11164 * report that it unconditionally does not match. Otherwise we return
11165 * a string containing the username.
11166 */
11167 if (!check_user(args->data.usr, smp->strm->txn->auth.user,
11168 smp->strm->txn->auth.pass))
11169 return 0;
11170
11171 /* pat_match_auth() will need the user list */
11172 smp->ctx.a[0] = args->data.usr;
11173
11174 smp->data.type = SMP_T_STR;
11175 smp->flags = SMP_F_CONST;
11176 smp->data.u.str.str = smp->strm->txn->auth.user;
11177 smp->data.u.str.len = strlen(smp->strm->txn->auth.user);
11178
11179 return 1;
11180 }
11181
11182 /* Try to find the next occurrence of a cookie name in a cookie header value.
11183 * To match on any cookie name, <cookie_name_l> must be set to 0.
11184 * The lookup begins at <hdr>. The pointer and size of the next occurrence of
11185 * the cookie value is returned into *value and *value_l, and the function
11186 * returns a pointer to the next pointer to search from if the value was found.
11187 * Otherwise if the cookie was not found, NULL is returned and neither value
11188 * nor value_l are touched. The input <hdr> string should first point to the
11189 * header's value, and the <hdr_end> pointer must point to the first character
11190 * not part of the value. <list> must be non-zero if value may represent a list
11191 * of values (cookie headers). This makes it faster to abort parsing when no
11192 * list is expected.
11193 */
11194 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)11195 extract_cookie_value(char *hdr, const char *hdr_end,
11196 char *cookie_name, size_t cookie_name_l, int list,
11197 char **value, int *value_l)
11198 {
11199 char *equal, *att_end, *att_beg, *val_beg, *val_end;
11200 char *next;
11201
11202 /* we search at least a cookie name followed by an equal, and more
11203 * generally something like this :
11204 * Cookie: NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3\r\n
11205 */
11206 for (att_beg = hdr; att_beg + cookie_name_l + 1 < hdr_end; att_beg = next + 1) {
11207 /* Iterate through all cookies on this line */
11208
11209 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
11210 att_beg++;
11211
11212 /* find att_end : this is the first character after the last non
11213 * space before the equal. It may be equal to hdr_end.
11214 */
11215 equal = att_end = att_beg;
11216
11217 while (equal < hdr_end) {
11218 if (*equal == '=' || *equal == ';' || (list && *equal == ','))
11219 break;
11220 if (HTTP_IS_SPHT(*equal++))
11221 continue;
11222 att_end = equal;
11223 }
11224
11225 /* here, <equal> points to '=', a delimitor or the end. <att_end>
11226 * is between <att_beg> and <equal>, both may be identical.
11227 */
11228
11229 /* look for end of cookie if there is an equal sign */
11230 if (equal < hdr_end && *equal == '=') {
11231 /* look for the beginning of the value */
11232 val_beg = equal + 1;
11233 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
11234 val_beg++;
11235
11236 /* find the end of the value, respecting quotes */
11237 next = find_cookie_value_end(val_beg, hdr_end);
11238
11239 /* make val_end point to the first white space or delimitor after the value */
11240 val_end = next;
11241 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
11242 val_end--;
11243 } else {
11244 val_beg = val_end = next = equal;
11245 }
11246
11247 /* We have nothing to do with attributes beginning with '$'. However,
11248 * they will automatically be removed if a header before them is removed,
11249 * since they're supposed to be linked together.
11250 */
11251 if (*att_beg == '$')
11252 continue;
11253
11254 /* Ignore cookies with no equal sign */
11255 if (equal == next)
11256 continue;
11257
11258 /* Now we have the cookie name between att_beg and att_end, and
11259 * its value between val_beg and val_end.
11260 */
11261
11262 if (cookie_name_l == 0 || (att_end - att_beg == cookie_name_l &&
11263 memcmp(att_beg, cookie_name, cookie_name_l) == 0)) {
11264 /* let's return this value and indicate where to go on from */
11265 *value = val_beg;
11266 *value_l = val_end - val_beg;
11267 return next + 1;
11268 }
11269
11270 /* Set-Cookie headers only have the name in the first attr=value part */
11271 if (!list)
11272 break;
11273 }
11274
11275 return NULL;
11276 }
11277
11278 /* Fetch a captured HTTP request header. The index is the position of
11279 * the "capture" option in the configuration file
11280 */
11281 static int
smp_fetch_capture_header_req(const struct arg * args,struct sample * smp,const char * kw,void * private)11282 smp_fetch_capture_header_req(const struct arg *args, struct sample *smp, const char *kw, void *private)
11283 {
11284 struct proxy *fe;
11285 int idx;
11286
11287 if (!args || args->type != ARGT_SINT)
11288 return 0;
11289
11290 if (!smp->strm)
11291 return 0;
11292
11293 fe = strm_fe(smp->strm);
11294 idx = args->data.sint;
11295
11296 if (idx > (fe->nb_req_cap - 1) || smp->strm->req_cap == NULL || smp->strm->req_cap[idx] == NULL)
11297 return 0;
11298
11299 smp->data.type = SMP_T_STR;
11300 smp->flags |= SMP_F_CONST;
11301 smp->data.u.str.str = smp->strm->req_cap[idx];
11302 smp->data.u.str.len = strlen(smp->strm->req_cap[idx]);
11303
11304 return 1;
11305 }
11306
11307 /* Fetch a captured HTTP response header. The index is the position of
11308 * the "capture" option in the configuration file
11309 */
11310 static int
smp_fetch_capture_header_res(const struct arg * args,struct sample * smp,const char * kw,void * private)11311 smp_fetch_capture_header_res(const struct arg *args, struct sample *smp, const char *kw, void *private)
11312 {
11313 struct proxy *fe;
11314 int idx;
11315
11316 if (!args || args->type != ARGT_SINT)
11317 return 0;
11318
11319 if (!smp->strm)
11320 return 0;
11321
11322 fe = strm_fe(smp->strm);
11323 idx = args->data.sint;
11324
11325 if (idx > (fe->nb_rsp_cap - 1) || smp->strm->res_cap == NULL || smp->strm->res_cap[idx] == NULL)
11326 return 0;
11327
11328 smp->data.type = SMP_T_STR;
11329 smp->flags |= SMP_F_CONST;
11330 smp->data.u.str.str = smp->strm->res_cap[idx];
11331 smp->data.u.str.len = strlen(smp->strm->res_cap[idx]);
11332
11333 return 1;
11334 }
11335
11336 /* Extracts the METHOD in the HTTP request, the txn->uri should be filled before the call */
11337 static int
smp_fetch_capture_req_method(const struct arg * args,struct sample * smp,const char * kw,void * private)11338 smp_fetch_capture_req_method(const struct arg *args, struct sample *smp, const char *kw, void *private)
11339 {
11340 struct chunk *temp;
11341 struct http_txn *txn;
11342 char *ptr;
11343
11344 if (!smp->strm)
11345 return 0;
11346
11347 txn = smp->strm->txn;
11348 if (!txn || !txn->uri)
11349 return 0;
11350
11351 ptr = txn->uri;
11352
11353 while (*ptr != ' ' && *ptr != '\0') /* find first space */
11354 ptr++;
11355
11356 temp = get_trash_chunk();
11357 temp->str = txn->uri;
11358 temp->len = ptr - txn->uri;
11359 smp->data.u.str = *temp;
11360 smp->data.type = SMP_T_STR;
11361 smp->flags = SMP_F_CONST;
11362
11363 return 1;
11364
11365 }
11366
11367 /* Extracts the path in the HTTP request, the txn->uri should be filled before the call */
11368 static int
smp_fetch_capture_req_uri(const struct arg * args,struct sample * smp,const char * kw,void * private)11369 smp_fetch_capture_req_uri(const struct arg *args, struct sample *smp, const char *kw, void *private)
11370 {
11371 struct chunk *temp;
11372 struct http_txn *txn;
11373 char *ptr;
11374
11375 if (!smp->strm)
11376 return 0;
11377
11378 txn = smp->strm->txn;
11379 if (!txn || !txn->uri)
11380 return 0;
11381
11382 ptr = txn->uri;
11383
11384 while (*ptr != ' ' && *ptr != '\0') /* find first space */
11385 ptr++;
11386
11387 if (!*ptr)
11388 return 0;
11389
11390 ptr++; /* skip the space */
11391
11392 temp = get_trash_chunk();
11393 ptr = temp->str = http_get_path_from_string(ptr);
11394 if (!ptr)
11395 return 0;
11396 while (*ptr != ' ' && *ptr != '\0') /* find space after URI */
11397 ptr++;
11398
11399 smp->data.u.str = *temp;
11400 smp->data.u.str.len = ptr - temp->str;
11401 smp->data.type = SMP_T_STR;
11402 smp->flags = SMP_F_CONST;
11403
11404 return 1;
11405 }
11406
11407 /* Retrieves the HTTP version from the request (either 1.0 or 1.1) and emits it
11408 * as a string (either "HTTP/1.0" or "HTTP/1.1").
11409 */
11410 static int
smp_fetch_capture_req_ver(const struct arg * args,struct sample * smp,const char * kw,void * private)11411 smp_fetch_capture_req_ver(const struct arg *args, struct sample *smp, const char *kw, void *private)
11412 {
11413 struct http_txn *txn;
11414
11415 if (!smp->strm)
11416 return 0;
11417
11418 txn = smp->strm->txn;
11419 if (!txn || txn->req.msg_state < HTTP_MSG_HDR_FIRST)
11420 return 0;
11421
11422 if (txn->req.flags & HTTP_MSGF_VER_11)
11423 smp->data.u.str.str = "HTTP/1.1";
11424 else
11425 smp->data.u.str.str = "HTTP/1.0";
11426
11427 smp->data.u.str.len = 8;
11428 smp->data.type = SMP_T_STR;
11429 smp->flags = SMP_F_CONST;
11430 return 1;
11431
11432 }
11433
11434 /* Retrieves the HTTP version from the response (either 1.0 or 1.1) and emits it
11435 * as a string (either "HTTP/1.0" or "HTTP/1.1").
11436 */
11437 static int
smp_fetch_capture_res_ver(const struct arg * args,struct sample * smp,const char * kw,void * private)11438 smp_fetch_capture_res_ver(const struct arg *args, struct sample *smp, const char *kw, void *private)
11439 {
11440 struct http_txn *txn;
11441
11442 if (!smp->strm)
11443 return 0;
11444
11445 txn = smp->strm->txn;
11446 if (!txn || txn->rsp.msg_state < HTTP_MSG_HDR_FIRST)
11447 return 0;
11448
11449 if (txn->rsp.flags & HTTP_MSGF_VER_11)
11450 smp->data.u.str.str = "HTTP/1.1";
11451 else
11452 smp->data.u.str.str = "HTTP/1.0";
11453
11454 smp->data.u.str.len = 8;
11455 smp->data.type = SMP_T_STR;
11456 smp->flags = SMP_F_CONST;
11457 return 1;
11458
11459 }
11460
11461
11462 /* Iterate over all cookies present in a message. The context is stored in
11463 * smp->ctx.a[0] for the in-header position, smp->ctx.a[1] for the
11464 * end-of-header-value, and smp->ctx.a[2] for the hdr_ctx. Depending on
11465 * the direction, multiple cookies may be parsed on the same line or not.
11466 * If provided, the searched cookie name is in args, in args->data.str. If
11467 * the input options indicate that no iterating is desired, then only last
11468 * value is fetched if any. If no cookie name is provided, the first cookie
11469 * value found is fetched. The returned sample is of type CSTR. Can be used
11470 * to parse cookies in other files.
11471 */
smp_fetch_cookie(const struct arg * args,struct sample * smp,const char * kw,void * private)11472 int smp_fetch_cookie(const struct arg *args, struct sample *smp, const char *kw, void *private)
11473 {
11474 struct http_txn *txn;
11475 char *cook = NULL;
11476 size_t cook_l = 0;
11477 struct hdr_idx *idx;
11478 struct hdr_ctx *ctx = smp->ctx.a[2];
11479 const struct http_msg *msg;
11480 const char *hdr_name;
11481 int hdr_name_len;
11482 char *sol;
11483 int found = 0;
11484
11485 if (args && args->type == ARGT_STR) {
11486 cook = args->data.str.str;
11487 cook_l = args->data.str.len;
11488 }
11489
11490 if (!ctx) {
11491 /* first call */
11492 ctx = &static_hdr_ctx;
11493 ctx->idx = 0;
11494 smp->ctx.a[2] = ctx;
11495 }
11496
11497 CHECK_HTTP_MESSAGE_FIRST();
11498
11499 txn = smp->strm->txn;
11500 idx = &smp->strm->txn->hdr_idx;
11501
11502 if ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) {
11503 msg = &txn->req;
11504 hdr_name = "Cookie";
11505 hdr_name_len = 6;
11506 } else {
11507 msg = &txn->rsp;
11508 hdr_name = "Set-Cookie";
11509 hdr_name_len = 10;
11510 }
11511
11512 /* OK so basically here, either we want only one value or we want to
11513 * iterate over all of them and we fetch the next one. In this last case
11514 * SMP_OPT_ITERATE option is set.
11515 */
11516
11517 sol = msg->chn->buf->p;
11518 if (!(smp->flags & SMP_F_NOT_LAST)) {
11519 /* search for the header from the beginning, we must first initialize
11520 * the search parameters.
11521 */
11522 smp->ctx.a[0] = NULL;
11523 ctx->idx = 0;
11524 }
11525
11526 smp->flags |= SMP_F_VOL_HDR;
11527
11528 while (1) {
11529 /* Note: smp->ctx.a[0] == NULL every time we need to fetch a new header */
11530 if (!smp->ctx.a[0]) {
11531 if (!http_find_header2(hdr_name, hdr_name_len, sol, idx, ctx))
11532 goto out;
11533
11534 if (ctx->vlen < cook_l + 1)
11535 continue;
11536
11537 smp->ctx.a[0] = ctx->line + ctx->val;
11538 smp->ctx.a[1] = smp->ctx.a[0] + ctx->vlen;
11539 }
11540
11541 smp->data.type = SMP_T_STR;
11542 smp->flags |= SMP_F_CONST;
11543 smp->ctx.a[0] = extract_cookie_value(smp->ctx.a[0], smp->ctx.a[1],
11544 cook, cook_l,
11545 (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ,
11546 &smp->data.u.str.str,
11547 &smp->data.u.str.len);
11548 if (smp->ctx.a[0]) {
11549 found = 1;
11550 if (smp->opt & SMP_OPT_ITERATE) {
11551 /* iterate on cookie value */
11552 smp->flags |= SMP_F_NOT_LAST;
11553 return 1;
11554 }
11555 if (args->data.str.len == 0) {
11556 /* No cookie name, first occurrence returned */
11557 break;
11558 }
11559 }
11560 /* if we're looking for last occurrence, let's loop */
11561 }
11562 /* all cookie headers and values were scanned. If we're looking for the
11563 * last occurrence, we may return it now.
11564 */
11565 out:
11566 smp->flags &= ~SMP_F_NOT_LAST;
11567 return found;
11568 }
11569
11570 /* Iterate over all cookies present in a request to count how many occurrences
11571 * match the name in args and args->data.str.len. If <multi> is non-null, then
11572 * multiple cookies may be parsed on the same line. The returned sample is of
11573 * type UINT. Accepts exactly 1 argument of type string.
11574 */
11575 static int
smp_fetch_cookie_cnt(const struct arg * args,struct sample * smp,const char * kw,void * private)11576 smp_fetch_cookie_cnt(const struct arg *args, struct sample *smp, const char *kw, void *private)
11577 {
11578 struct http_txn *txn;
11579 struct hdr_idx *idx;
11580 struct hdr_ctx ctx;
11581 const struct http_msg *msg;
11582 const char *hdr_name;
11583 int hdr_name_len;
11584 int cnt;
11585 char *val_beg, *val_end;
11586 char *cook = NULL;
11587 size_t cook_l = 0;
11588 char *sol;
11589
11590 if (args && args->type == ARGT_STR){
11591 cook = args->data.str.str;
11592 cook_l = args->data.str.len;
11593 }
11594
11595 CHECK_HTTP_MESSAGE_FIRST();
11596
11597 txn = smp->strm->txn;
11598 idx = &smp->strm->txn->hdr_idx;
11599
11600 if ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) {
11601 msg = &txn->req;
11602 hdr_name = "Cookie";
11603 hdr_name_len = 6;
11604 } else {
11605 msg = &txn->rsp;
11606 hdr_name = "Set-Cookie";
11607 hdr_name_len = 10;
11608 }
11609
11610 sol = msg->chn->buf->p;
11611 val_end = val_beg = NULL;
11612 ctx.idx = 0;
11613 cnt = 0;
11614
11615 while (1) {
11616 /* Note: val_beg == NULL every time we need to fetch a new header */
11617 if (!val_beg) {
11618 if (!http_find_header2(hdr_name, hdr_name_len, sol, idx, &ctx))
11619 break;
11620
11621 if (ctx.vlen < cook_l + 1)
11622 continue;
11623
11624 val_beg = ctx.line + ctx.val;
11625 val_end = val_beg + ctx.vlen;
11626 }
11627
11628 smp->data.type = SMP_T_STR;
11629 smp->flags |= SMP_F_CONST;
11630 while ((val_beg = extract_cookie_value(val_beg, val_end,
11631 cook, cook_l,
11632 (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ,
11633 &smp->data.u.str.str,
11634 &smp->data.u.str.len))) {
11635 cnt++;
11636 }
11637 }
11638
11639 smp->data.type = SMP_T_SINT;
11640 smp->data.u.sint = cnt;
11641 smp->flags |= SMP_F_VOL_HDR;
11642 return 1;
11643 }
11644
11645 /* Fetch an cookie's integer value. The integer value is returned. It
11646 * takes a mandatory argument of type string. It relies on smp_fetch_cookie().
11647 */
11648 static int
smp_fetch_cookie_val(const struct arg * args,struct sample * smp,const char * kw,void * private)11649 smp_fetch_cookie_val(const struct arg *args, struct sample *smp, const char *kw, void *private)
11650 {
11651 int ret = smp_fetch_cookie(args, smp, kw, private);
11652
11653 if (ret > 0) {
11654 smp->data.type = SMP_T_SINT;
11655 smp->data.u.sint = strl2ic(smp->data.u.str.str, smp->data.u.str.len);
11656 }
11657
11658 return ret;
11659 }
11660
11661 /************************************************************************/
11662 /* The code below is dedicated to sample fetches */
11663 /************************************************************************/
11664
11665 /*
11666 * Given a path string and its length, find the position of beginning of the
11667 * query string. Returns NULL if no query string is found in the path.
11668 *
11669 * Example: if path = "/foo/bar/fubar?yo=mama;ye=daddy", and n = 22:
11670 *
11671 * find_query_string(path, n, '?') points to "yo=mama;ye=daddy" string.
11672 */
find_param_list(char * path,size_t path_l,char delim)11673 static inline char *find_param_list(char *path, size_t path_l, char delim)
11674 {
11675 char *p;
11676
11677 p = memchr(path, delim, path_l);
11678 return p ? p + 1 : NULL;
11679 }
11680
is_param_delimiter(char c,char delim)11681 static inline int is_param_delimiter(char c, char delim)
11682 {
11683 return c == '&' || c == ';' || c == delim;
11684 }
11685
11686 /* after increasing a pointer value, it can exceed the first buffer
11687 * size. This function transform the value of <ptr> according with
11688 * the expected position. <chunks> is an array of the one or two
11689 * avalaible chunks. The first value is the start of the first chunk,
11690 * the second value if the end+1 of the first chunks. The third value
11691 * is NULL or the start of the second chunk and the fourth value is
11692 * the end+1 of the second chunk. The function returns 1 if does a
11693 * wrap, else returns 0.
11694 */
fix_pointer_if_wrap(const char ** chunks,const char ** ptr)11695 static inline int fix_pointer_if_wrap(const char **chunks, const char **ptr)
11696 {
11697 if (*ptr < chunks[1])
11698 return 0;
11699 if (!chunks[2])
11700 return 0;
11701 *ptr = chunks[2] + ( *ptr - chunks[1] );
11702 return 1;
11703 }
11704
11705 /*
11706 * Given a url parameter, find the starting position of the first occurence,
11707 * or NULL if the parameter is not found.
11708 *
11709 * Example: if query_string is "yo=mama;ye=daddy" and url_param_name is "ye",
11710 * the function will return query_string+8.
11711 *
11712 * Warning: this function returns a pointer that can point to the first chunk
11713 * or the second chunk. The caller must be check the position before using the
11714 * result.
11715 */
11716 static const char *
find_url_param_pos(const char ** chunks,const char * url_param_name,size_t url_param_name_l,char delim)11717 find_url_param_pos(const char **chunks,
11718 const char* url_param_name, size_t url_param_name_l,
11719 char delim)
11720 {
11721 const char *pos, *last, *equal;
11722 const char **bufs = chunks;
11723 int l1, l2;
11724
11725
11726 pos = bufs[0];
11727 last = bufs[1];
11728 while (pos < last) {
11729 /* Check the equal. */
11730 equal = pos + url_param_name_l;
11731 if (fix_pointer_if_wrap(chunks, &equal)) {
11732 if (equal >= chunks[3])
11733 return NULL;
11734 } else {
11735 if (equal >= chunks[1])
11736 return NULL;
11737 }
11738 if (*equal == '=') {
11739 if (pos + url_param_name_l > last) {
11740 /* process wrap case, we detect a wrap. In this case, the
11741 * comparison is performed in two parts.
11742 */
11743
11744 /* This is the end, we dont have any other chunk. */
11745 if (bufs != chunks || !bufs[2])
11746 return NULL;
11747
11748 /* Compute the length of each part of the comparison. */
11749 l1 = last - pos;
11750 l2 = url_param_name_l - l1;
11751
11752 /* The second buffer is too short to contain the compared string. */
11753 if (bufs[2] + l2 > bufs[3])
11754 return NULL;
11755
11756 if (memcmp(pos, url_param_name, l1) == 0 &&
11757 memcmp(bufs[2], url_param_name+l1, l2) == 0)
11758 return pos;
11759
11760 /* Perform wrapping and jump the string who fail the comparison. */
11761 bufs += 2;
11762 pos = bufs[0] + l2;
11763 last = bufs[1];
11764
11765 } else {
11766 /* process a simple comparison. */
11767 if (memcmp(pos, url_param_name, url_param_name_l) == 0)
11768 return pos;
11769 pos += url_param_name_l + 1;
11770 if (fix_pointer_if_wrap(chunks, &pos))
11771 last = bufs[2];
11772 }
11773 }
11774
11775 while (1) {
11776 /* Look for the next delimiter. */
11777 while (pos < last && !is_param_delimiter(*pos, delim))
11778 pos++;
11779 if (pos < last)
11780 break;
11781 /* process buffer wrapping. */
11782 if (bufs != chunks || !bufs[2])
11783 return NULL;
11784 bufs += 2;
11785 pos = bufs[0];
11786 last = bufs[1];
11787 }
11788 pos++;
11789 }
11790 return NULL;
11791 }
11792
11793 /*
11794 * Given a url parameter name and a query string, find the next value.
11795 * An empty url_param_name matches the first available parameter.
11796 * If the parameter is found, 1 is returned and *vstart / *vend are updated to
11797 * respectively provide a pointer to the value and its end.
11798 * Otherwise, 0 is returned and vstart/vend are not modified.
11799 */
11800 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)11801 find_next_url_param(const char **chunks,
11802 const char* url_param_name, size_t url_param_name_l,
11803 const char **vstart, const char **vend, char delim)
11804 {
11805 const char *arg_start, *qs_end;
11806 const char *value_start, *value_end;
11807
11808 arg_start = chunks[0];
11809 qs_end = chunks[1];
11810 if (url_param_name_l) {
11811 /* Looks for an argument name. */
11812 arg_start = find_url_param_pos(chunks,
11813 url_param_name, url_param_name_l,
11814 delim);
11815 /* Check for wrapping. */
11816 if (arg_start >= qs_end)
11817 qs_end = chunks[3];
11818 }
11819 if (!arg_start)
11820 return 0;
11821
11822 if (!url_param_name_l) {
11823 while (1) {
11824 /* looks for the first argument. */
11825 value_start = memchr(arg_start, '=', qs_end - arg_start);
11826 if (!value_start) {
11827 /* Check for wrapping. */
11828 if (arg_start >= chunks[0] &&
11829 arg_start < chunks[1] &&
11830 chunks[2]) {
11831 arg_start = chunks[2];
11832 qs_end = chunks[3];
11833 continue;
11834 }
11835 return 0;
11836 }
11837 break;
11838 }
11839 value_start++;
11840 }
11841 else {
11842 /* Jump the argument length. */
11843 value_start = arg_start + url_param_name_l + 1;
11844
11845 /* Check for pointer wrapping. */
11846 if (fix_pointer_if_wrap(chunks, &value_start)) {
11847 /* Update the end pointer. */
11848 qs_end = chunks[3];
11849
11850 /* Check for overflow. */
11851 if (value_start >= qs_end)
11852 return 0;
11853 }
11854 }
11855
11856 value_end = value_start;
11857
11858 while (1) {
11859 while ((value_end < qs_end) && !is_param_delimiter(*value_end, delim))
11860 value_end++;
11861 if (value_end < qs_end)
11862 break;
11863 /* process buffer wrapping. */
11864 if (value_end >= chunks[0] &&
11865 value_end < chunks[1] &&
11866 chunks[2]) {
11867 value_end = chunks[2];
11868 qs_end = chunks[3];
11869 continue;
11870 }
11871 break;
11872 }
11873
11874 *vstart = value_start;
11875 *vend = value_end;
11876 return 1;
11877 }
11878
11879 /* This scans a URL-encoded query string. It takes an optionally wrapping
11880 * string whose first contigous chunk has its beginning in ctx->a[0] and end
11881 * in ctx->a[1], and the optional second part in (ctx->a[2]..ctx->a[3]). The
11882 * pointers are updated for next iteration before leaving.
11883 */
11884 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)11885 smp_fetch_param(char delim, const char *name, int name_len, const struct arg *args, struct sample *smp, const char *kw, void *private)
11886 {
11887 const char *vstart, *vend;
11888 struct chunk *temp;
11889 const char **chunks = (const char **)smp->ctx.a;
11890
11891 if (!find_next_url_param(chunks,
11892 name, name_len,
11893 &vstart, &vend,
11894 delim))
11895 return 0;
11896
11897 /* Create sample. If the value is contiguous, return the pointer as CONST,
11898 * if the value is wrapped, copy-it in a buffer.
11899 */
11900 smp->data.type = SMP_T_STR;
11901 if (chunks[2] &&
11902 vstart >= chunks[0] && vstart <= chunks[1] &&
11903 vend >= chunks[2] && vend <= chunks[3]) {
11904 /* Wrapped case. */
11905 temp = get_trash_chunk();
11906 memcpy(temp->str, vstart, chunks[1] - vstart);
11907 memcpy(temp->str + ( chunks[1] - vstart ), chunks[2], vend - chunks[2]);
11908 smp->data.u.str.str = temp->str;
11909 smp->data.u.str.len = ( chunks[1] - vstart ) + ( vend - chunks[2] );
11910 } else {
11911 /* Contiguous case. */
11912 smp->data.u.str.str = (char *)vstart;
11913 smp->data.u.str.len = vend - vstart;
11914 smp->flags = SMP_F_VOL_1ST | SMP_F_CONST;
11915 }
11916
11917 /* Update context, check wrapping. */
11918 chunks[0] = vend;
11919 if (chunks[2] && vend >= chunks[2] && vend <= chunks[3]) {
11920 chunks[1] = chunks[3];
11921 chunks[2] = NULL;
11922 }
11923
11924 if (chunks[0] < chunks[1])
11925 smp->flags |= SMP_F_NOT_LAST;
11926
11927 return 1;
11928 }
11929
11930 /* This function iterates over each parameter of the query string. It uses
11931 * ctx->a[0] and ctx->a[1] to store the beginning and end of the current
11932 * parameter. Since it uses smp_fetch_param(), ctx->a[2..3] are both NULL.
11933 * An optional parameter name is passed in args[0], otherwise any parameter is
11934 * considered. It supports an optional delimiter argument for the beginning of
11935 * the string in args[1], which defaults to "?".
11936 */
11937 static int
smp_fetch_url_param(const struct arg * args,struct sample * smp,const char * kw,void * private)11938 smp_fetch_url_param(const struct arg *args, struct sample *smp, const char *kw, void *private)
11939 {
11940 struct http_msg *msg;
11941 char delim = '?';
11942 const char *name;
11943 int name_len;
11944
11945 if (!args ||
11946 (args[0].type && args[0].type != ARGT_STR) ||
11947 (args[1].type && args[1].type != ARGT_STR))
11948 return 0;
11949
11950 name = "";
11951 name_len = 0;
11952 if (args->type == ARGT_STR) {
11953 name = args->data.str.str;
11954 name_len = args->data.str.len;
11955 }
11956
11957 if (args[1].type)
11958 delim = *args[1].data.str.str;
11959
11960 if (!smp->ctx.a[0]) { // first call, find the query string
11961 CHECK_HTTP_MESSAGE_FIRST();
11962
11963 msg = &smp->strm->txn->req;
11964
11965 smp->ctx.a[0] = find_param_list(msg->chn->buf->p + msg->sl.rq.u,
11966 msg->sl.rq.u_l, delim);
11967 if (!smp->ctx.a[0])
11968 return 0;
11969
11970 smp->ctx.a[1] = msg->chn->buf->p + msg->sl.rq.u + msg->sl.rq.u_l;
11971
11972 /* Assume that the context is filled with NULL pointer
11973 * before the first call.
11974 * smp->ctx.a[2] = NULL;
11975 * smp->ctx.a[3] = NULL;
11976 */
11977 }
11978
11979 return smp_fetch_param(delim, name, name_len, args, smp, kw, private);
11980 }
11981
11982 /* This function iterates over each parameter of the body. This requires
11983 * that the body has been waited for using http-buffer-request. It uses
11984 * ctx->a[0] and ctx->a[1] to store the beginning and end of the first
11985 * contigous part of the body, and optionally ctx->a[2..3] to reference the
11986 * optional second part if the body wraps at the end of the buffer. An optional
11987 * parameter name is passed in args[0], otherwise any parameter is considered.
11988 */
11989 static int
smp_fetch_body_param(const struct arg * args,struct sample * smp,const char * kw,void * private)11990 smp_fetch_body_param(const struct arg *args, struct sample *smp, const char *kw, void *private)
11991 {
11992 struct http_msg *msg;
11993 unsigned long len;
11994 unsigned long block1;
11995 char *body;
11996 const char *name;
11997 int name_len;
11998
11999 if (!args || (args[0].type && args[0].type != ARGT_STR))
12000 return 0;
12001
12002 name = "";
12003 name_len = 0;
12004 if (args[0].type == ARGT_STR) {
12005 name = args[0].data.str.str;
12006 name_len = args[0].data.str.len;
12007 }
12008
12009 if (!smp->ctx.a[0]) { // first call, find the query string
12010 CHECK_HTTP_MESSAGE_FIRST();
12011
12012 if ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ)
12013 msg = &smp->strm->txn->req;
12014 else
12015 msg = &smp->strm->txn->rsp;
12016
12017 len = http_body_bytes(msg);
12018 body = b_ptr(msg->chn->buf, -http_data_rewind(msg));
12019
12020 block1 = len;
12021 if (block1 > msg->chn->buf->data + msg->chn->buf->size - body)
12022 block1 = msg->chn->buf->data + msg->chn->buf->size - body;
12023
12024 if (block1 == len) {
12025 /* buffer is not wrapped (or empty) */
12026 smp->ctx.a[0] = body;
12027 smp->ctx.a[1] = body + len;
12028
12029 /* Assume that the context is filled with NULL pointer
12030 * before the first call.
12031 * smp->ctx.a[2] = NULL;
12032 * smp->ctx.a[3] = NULL;
12033 */
12034 }
12035 else {
12036 /* buffer is wrapped, we need to defragment it */
12037 smp->ctx.a[0] = body;
12038 smp->ctx.a[1] = body + block1;
12039 smp->ctx.a[2] = msg->chn->buf->data;
12040 smp->ctx.a[3] = msg->chn->buf->data + ( len - block1 );
12041 }
12042 }
12043 return smp_fetch_param('&', name, name_len, args, smp, kw, private);
12044 }
12045
12046 /* Return the signed integer value for the specified url parameter (see url_param
12047 * above).
12048 */
12049 static int
smp_fetch_url_param_val(const struct arg * args,struct sample * smp,const char * kw,void * private)12050 smp_fetch_url_param_val(const struct arg *args, struct sample *smp, const char *kw, void *private)
12051 {
12052 int ret = smp_fetch_url_param(args, smp, kw, private);
12053
12054 if (ret > 0) {
12055 smp->data.type = SMP_T_SINT;
12056 smp->data.u.sint = strl2ic(smp->data.u.str.str, smp->data.u.str.len);
12057 }
12058
12059 return ret;
12060 }
12061
12062 /* This produces a 32-bit hash of the concatenation of the first occurrence of
12063 * the Host header followed by the path component if it begins with a slash ('/').
12064 * This means that '*' will not be added, resulting in exactly the first Host
12065 * entry. If no Host header is found, then the path is used. The resulting value
12066 * is hashed using the url hash followed by a full avalanche hash and provides a
12067 * 32-bit integer value. This fetch is useful for tracking per-URL activity on
12068 * high-traffic sites without having to store whole paths.
12069 * this differs from the base32 functions in that it includes the url parameters
12070 * as well as the path
12071 */
12072 static int
smp_fetch_url32(const struct arg * args,struct sample * smp,const char * kw,void * private)12073 smp_fetch_url32(const struct arg *args, struct sample *smp, const char *kw, void *private)
12074 {
12075 struct http_txn *txn;
12076 struct hdr_ctx ctx;
12077 unsigned int hash = 0;
12078 char *ptr, *beg, *end;
12079 int len;
12080
12081 CHECK_HTTP_MESSAGE_FIRST();
12082
12083 txn = smp->strm->txn;
12084 ctx.idx = 0;
12085 if (http_find_header2("Host", 4, txn->req.chn->buf->p, &txn->hdr_idx, &ctx)) {
12086 /* OK we have the header value in ctx.line+ctx.val for ctx.vlen bytes */
12087 ptr = ctx.line + ctx.val;
12088 len = ctx.vlen;
12089 while (len--)
12090 hash = *(ptr++) + (hash << 6) + (hash << 16) - hash;
12091 }
12092
12093 /* now retrieve the path */
12094 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
12095 beg = http_get_path(txn);
12096 if (!beg)
12097 beg = end;
12098
12099 for (ptr = beg; ptr < end ; ptr++);
12100
12101 if (beg < ptr && *beg == '/') {
12102 while (beg < ptr)
12103 hash = *(beg++) + (hash << 6) + (hash << 16) - hash;
12104 }
12105 hash = full_hash(hash);
12106
12107 smp->data.type = SMP_T_SINT;
12108 smp->data.u.sint = hash;
12109 smp->flags = SMP_F_VOL_1ST;
12110 return 1;
12111 }
12112
12113 /* This concatenates the source address with the 32-bit hash of the Host and
12114 * URL as returned by smp_fetch_base32(). The idea is to have per-source and
12115 * per-url counters. The result is a binary block from 8 to 20 bytes depending
12116 * on the source address length. The URL hash is stored before the address so
12117 * that in environments where IPv6 is insignificant, truncating the output to
12118 * 8 bytes would still work.
12119 */
12120 static int
smp_fetch_url32_src(const struct arg * args,struct sample * smp,const char * kw,void * private)12121 smp_fetch_url32_src(const struct arg *args, struct sample *smp, const char *kw, void *private)
12122 {
12123 struct chunk *temp;
12124 struct connection *cli_conn = objt_conn(smp->sess->origin);
12125
12126 if (!cli_conn)
12127 return 0;
12128
12129 if (!smp_fetch_url32(args, smp, kw, private))
12130 return 0;
12131
12132 temp = get_trash_chunk();
12133 *(unsigned int *)temp->str = htonl(smp->data.u.sint);
12134 temp->len += sizeof(unsigned int);
12135
12136 switch (cli_conn->addr.from.ss_family) {
12137 case AF_INET:
12138 memcpy(temp->str + temp->len, &((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr, 4);
12139 temp->len += 4;
12140 break;
12141 case AF_INET6:
12142 memcpy(temp->str + temp->len, &((struct sockaddr_in6 *)&cli_conn->addr.from)->sin6_addr, 16);
12143 temp->len += 16;
12144 break;
12145 default:
12146 return 0;
12147 }
12148
12149 smp->data.u.str = *temp;
12150 smp->data.type = SMP_T_BIN;
12151 return 1;
12152 }
12153
12154 /* This function is used to validate the arguments passed to any "hdr" fetch
12155 * keyword. These keywords support an optional positive or negative occurrence
12156 * number. We must ensure that the number is greater than -MAX_HDR_HISTORY. It
12157 * is assumed that the types are already the correct ones. Returns 0 on error,
12158 * non-zero if OK. If <err> is not NULL, it will be filled with a pointer to an
12159 * error message in case of error, that the caller is responsible for freeing.
12160 * The initial location must either be freeable or NULL.
12161 */
val_hdr(struct arg * arg,char ** err_msg)12162 int val_hdr(struct arg *arg, char **err_msg)
12163 {
12164 if (arg && arg[1].type == ARGT_SINT && arg[1].data.sint < -MAX_HDR_HISTORY) {
12165 memprintf(err_msg, "header occurrence must be >= %d", -MAX_HDR_HISTORY);
12166 return 0;
12167 }
12168 return 1;
12169 }
12170
12171 /* takes an UINT value on input supposed to represent the time since EPOCH,
12172 * adds an optional offset found in args[0] and emits a string representing
12173 * the date in RFC-1123/5322 format.
12174 */
sample_conv_http_date(const struct arg * args,struct sample * smp,void * private)12175 static int sample_conv_http_date(const struct arg *args, struct sample *smp, void *private)
12176 {
12177 const char day[7][4] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
12178 const char mon[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
12179 struct chunk *temp;
12180 struct tm *tm;
12181 /* With high numbers, the date returned can be negative, the 55 bits mask prevent this. */
12182 time_t curr_date = smp->data.u.sint & 0x007fffffffffffffLL;
12183
12184 /* add offset */
12185 if (args && (args[0].type == ARGT_SINT))
12186 curr_date += args[0].data.sint;
12187
12188 tm = gmtime(&curr_date);
12189 if (!tm)
12190 return 0;
12191
12192 temp = get_trash_chunk();
12193 temp->len = snprintf(temp->str, temp->size - temp->len,
12194 "%s, %02d %s %04d %02d:%02d:%02d GMT",
12195 day[tm->tm_wday], tm->tm_mday, mon[tm->tm_mon], 1900+tm->tm_year,
12196 tm->tm_hour, tm->tm_min, tm->tm_sec);
12197
12198 smp->data.u.str = *temp;
12199 smp->data.type = SMP_T_STR;
12200 return 1;
12201 }
12202
12203 /* Match language range with language tag. RFC2616 14.4:
12204 *
12205 * A language-range matches a language-tag if it exactly equals
12206 * the tag, or if it exactly equals a prefix of the tag such
12207 * that the first tag character following the prefix is "-".
12208 *
12209 * Return 1 if the strings match, else return 0.
12210 */
language_range_match(const char * range,int range_len,const char * tag,int tag_len)12211 static inline int language_range_match(const char *range, int range_len,
12212 const char *tag, int tag_len)
12213 {
12214 const char *end = range + range_len;
12215 const char *tend = tag + tag_len;
12216 while (range < end) {
12217 if (*range == '-' && tag == tend)
12218 return 1;
12219 if (*range != *tag || tag == tend)
12220 return 0;
12221 range++;
12222 tag++;
12223 }
12224 /* Return true only if the last char of the tag is matched. */
12225 return tag == tend;
12226 }
12227
12228 /* 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)12229 static int sample_conv_q_prefered(const struct arg *args, struct sample *smp, void *private)
12230 {
12231 const char *al = smp->data.u.str.str;
12232 const char *end = al + smp->data.u.str.len;
12233 const char *token;
12234 int toklen;
12235 int qvalue;
12236 const char *str;
12237 const char *w;
12238 int best_q = 0;
12239
12240 /* Set the constant to the sample, because the output of the
12241 * function will be peek in the constant configuration string.
12242 */
12243 smp->flags |= SMP_F_CONST;
12244 smp->data.u.str.size = 0;
12245 smp->data.u.str.str = "";
12246 smp->data.u.str.len = 0;
12247
12248 /* Parse the accept language */
12249 while (1) {
12250
12251 /* Jump spaces, quit if the end is detected. */
12252 while (al < end && isspace((unsigned char)*al))
12253 al++;
12254 if (al >= end)
12255 break;
12256
12257 /* Start of the fisrt word. */
12258 token = al;
12259
12260 /* Look for separator: isspace(), ',' or ';'. Next value if 0 length word. */
12261 while (al < end && *al != ';' && *al != ',' && !isspace((unsigned char)*al))
12262 al++;
12263 if (al == token)
12264 goto expect_comma;
12265
12266 /* Length of the token. */
12267 toklen = al - token;
12268 qvalue = 1000;
12269
12270 /* Check if the token exists in the list. If the token not exists,
12271 * jump to the next token.
12272 */
12273 str = args[0].data.str.str;
12274 w = str;
12275 while (1) {
12276 if (*str == ';' || *str == '\0') {
12277 if (language_range_match(token, toklen, w, str-w))
12278 goto look_for_q;
12279 if (*str == '\0')
12280 goto expect_comma;
12281 w = str + 1;
12282 }
12283 str++;
12284 }
12285 goto expect_comma;
12286
12287 look_for_q:
12288
12289 /* Jump spaces, quit if the end is detected. */
12290 while (al < end && isspace((unsigned char)*al))
12291 al++;
12292 if (al >= end)
12293 goto process_value;
12294
12295 /* If ',' is found, process the result */
12296 if (*al == ',')
12297 goto process_value;
12298
12299 /* If the character is different from ';', look
12300 * for the end of the header part in best effort.
12301 */
12302 if (*al != ';')
12303 goto expect_comma;
12304
12305 /* Assumes that the char is ';', now expect "q=". */
12306 al++;
12307
12308 /* Jump spaces, process value if the end is detected. */
12309 while (al < end && isspace((unsigned char)*al))
12310 al++;
12311 if (al >= end)
12312 goto process_value;
12313
12314 /* Expect 'q'. If no 'q', continue in best effort */
12315 if (*al != 'q')
12316 goto process_value;
12317 al++;
12318
12319 /* Jump spaces, process value if the end is detected. */
12320 while (al < end && isspace((unsigned char)*al))
12321 al++;
12322 if (al >= end)
12323 goto process_value;
12324
12325 /* Expect '='. If no '=', continue in best effort */
12326 if (*al != '=')
12327 goto process_value;
12328 al++;
12329
12330 /* Jump spaces, process value if the end is detected. */
12331 while (al < end && isspace((unsigned char)*al))
12332 al++;
12333 if (al >= end)
12334 goto process_value;
12335
12336 /* Parse the q value. */
12337 qvalue = parse_qvalue(al, &al);
12338
12339 process_value:
12340
12341 /* If the new q value is the best q value, then store the associated
12342 * language in the response. If qvalue is the biggest value (1000),
12343 * break the process.
12344 */
12345 if (qvalue > best_q) {
12346 smp->data.u.str.str = (char *)w;
12347 smp->data.u.str.len = str - w;
12348 if (qvalue >= 1000)
12349 break;
12350 best_q = qvalue;
12351 }
12352
12353 expect_comma:
12354
12355 /* Expect comma or end. If the end is detected, quit the loop. */
12356 while (al < end && *al != ',')
12357 al++;
12358 if (al >= end)
12359 break;
12360
12361 /* Comma is found, jump it and restart the analyzer. */
12362 al++;
12363 }
12364
12365 /* Set default value if required. */
12366 if (smp->data.u.str.len == 0 && args[1].type == ARGT_STR) {
12367 smp->data.u.str.str = args[1].data.str.str;
12368 smp->data.u.str.len = args[1].data.str.len;
12369 }
12370
12371 /* Return true only if a matching language was found. */
12372 return smp->data.u.str.len != 0;
12373 }
12374
12375 /* This fetch url-decode any input string. */
sample_conv_url_dec(const struct arg * args,struct sample * smp,void * private)12376 static int sample_conv_url_dec(const struct arg *args, struct sample *smp, void *private)
12377 {
12378 /* If the constant flag is set or if not size is avalaible at
12379 * the end of the buffer, copy the string in other buffer
12380 * before decoding.
12381 */
12382 if (smp->flags & SMP_F_CONST || smp->data.u.str.size <= smp->data.u.str.len) {
12383 struct chunk *str = get_trash_chunk();
12384 memcpy(str->str, smp->data.u.str.str, smp->data.u.str.len);
12385 smp->data.u.str.str = str->str;
12386 smp->data.u.str.size = str->size;
12387 smp->flags &= ~SMP_F_CONST;
12388 }
12389
12390 /* Add final \0 required by url_decode(), and convert the input string. */
12391 smp->data.u.str.str[smp->data.u.str.len] = '\0';
12392 smp->data.u.str.len = url_decode(smp->data.u.str.str);
12393 return (smp->data.u.str.len >= 0);
12394 }
12395
smp_conv_req_capture(const struct arg * args,struct sample * smp,void * private)12396 static int smp_conv_req_capture(const struct arg *args, struct sample *smp, void *private)
12397 {
12398 struct proxy *fe;
12399 int idx, i;
12400 struct cap_hdr *hdr;
12401 int len;
12402
12403 if (!args || args->type != ARGT_SINT)
12404 return 0;
12405
12406 if (!smp->strm)
12407 return 0;
12408
12409 fe = strm_fe(smp->strm);
12410 idx = args->data.sint;
12411
12412 /* Check the availibity of the capture id. */
12413 if (idx > fe->nb_req_cap - 1)
12414 return 0;
12415
12416 /* Look for the original configuration. */
12417 for (hdr = fe->req_cap, i = fe->nb_req_cap - 1;
12418 hdr != NULL && i != idx ;
12419 i--, hdr = hdr->next);
12420 if (!hdr)
12421 return 0;
12422
12423 /* check for the memory allocation */
12424 if (smp->strm->req_cap[hdr->index] == NULL)
12425 smp->strm->req_cap[hdr->index] = pool_alloc2(hdr->pool);
12426 if (smp->strm->req_cap[hdr->index] == NULL)
12427 return 0;
12428
12429 /* Check length. */
12430 len = smp->data.u.str.len;
12431 if (len > hdr->len)
12432 len = hdr->len;
12433
12434 /* Capture input data. */
12435 memcpy(smp->strm->req_cap[idx], smp->data.u.str.str, len);
12436 smp->strm->req_cap[idx][len] = '\0';
12437
12438 return 1;
12439 }
12440
smp_conv_res_capture(const struct arg * args,struct sample * smp,void * private)12441 static int smp_conv_res_capture(const struct arg *args, struct sample *smp, void *private)
12442 {
12443 struct proxy *fe;
12444 int idx, i;
12445 struct cap_hdr *hdr;
12446 int len;
12447
12448 if (!args || args->type != ARGT_SINT)
12449 return 0;
12450
12451 if (!smp->strm)
12452 return 0;
12453
12454 fe = strm_fe(smp->strm);
12455 idx = args->data.sint;
12456
12457 /* Check the availibity of the capture id. */
12458 if (idx > fe->nb_rsp_cap - 1)
12459 return 0;
12460
12461 /* Look for the original configuration. */
12462 for (hdr = fe->rsp_cap, i = fe->nb_rsp_cap - 1;
12463 hdr != NULL && i != idx ;
12464 i--, hdr = hdr->next);
12465 if (!hdr)
12466 return 0;
12467
12468 /* check for the memory allocation */
12469 if (smp->strm->res_cap[hdr->index] == NULL)
12470 smp->strm->res_cap[hdr->index] = pool_alloc2(hdr->pool);
12471 if (smp->strm->res_cap[hdr->index] == NULL)
12472 return 0;
12473
12474 /* Check length. */
12475 len = smp->data.u.str.len;
12476 if (len > hdr->len)
12477 len = hdr->len;
12478
12479 /* Capture input data. */
12480 memcpy(smp->strm->res_cap[idx], smp->data.u.str.str, len);
12481 smp->strm->res_cap[idx][len] = '\0';
12482
12483 return 1;
12484 }
12485
12486 /* This function executes one of the set-{method,path,query,uri} actions. It
12487 * takes the string from the variable 'replace' with length 'len', then modifies
12488 * the relevant part of the request line accordingly. Then it updates various
12489 * pointers to the next elements which were moved, and the total buffer length.
12490 * It finds the action to be performed in p[2], previously filled by function
12491 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
12492 * error, though this can be revisited when this code is finally exploited.
12493 *
12494 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
12495 * query string and 3 to replace uri.
12496 *
12497 * In query string case, the mark question '?' must be set at the start of the
12498 * string by the caller, event if the replacement query string is empty.
12499 */
http_replace_req_line(int action,const char * replace,int len,struct proxy * px,struct stream * s)12500 int http_replace_req_line(int action, const char *replace, int len,
12501 struct proxy *px, struct stream *s)
12502 {
12503 struct http_txn *txn = s->txn;
12504 char *cur_ptr, *cur_end;
12505 int offset = 0;
12506 int delta;
12507
12508 switch (action) {
12509 case 0: // method
12510 cur_ptr = s->req.buf->p;
12511 cur_end = cur_ptr + txn->req.sl.rq.m_l;
12512
12513 /* adjust req line offsets and lengths */
12514 delta = len - offset - (cur_end - cur_ptr);
12515 txn->req.sl.rq.m_l += delta;
12516 txn->req.sl.rq.u += delta;
12517 txn->req.sl.rq.v += delta;
12518 break;
12519
12520 case 1: // path
12521 cur_ptr = http_get_path(txn);
12522 if (!cur_ptr)
12523 cur_ptr = s->req.buf->p + txn->req.sl.rq.u;
12524
12525 cur_end = cur_ptr;
12526 while (cur_end < s->req.buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l && *cur_end != '?')
12527 cur_end++;
12528
12529 /* adjust req line offsets and lengths */
12530 delta = len - offset - (cur_end - cur_ptr);
12531 txn->req.sl.rq.u_l += delta;
12532 txn->req.sl.rq.v += delta;
12533 break;
12534
12535 case 2: // query
12536 offset = 1;
12537 cur_ptr = s->req.buf->p + txn->req.sl.rq.u;
12538 cur_end = cur_ptr + txn->req.sl.rq.u_l;
12539 while (cur_ptr < cur_end && *cur_ptr != '?')
12540 cur_ptr++;
12541
12542 /* skip the question mark or indicate that we must insert it
12543 * (but only if the format string is not empty then).
12544 */
12545 if (cur_ptr < cur_end)
12546 cur_ptr++;
12547 else if (len > 1)
12548 offset = 0;
12549
12550 /* adjust req line offsets and lengths */
12551 delta = len - offset - (cur_end - cur_ptr);
12552 txn->req.sl.rq.u_l += delta;
12553 txn->req.sl.rq.v += delta;
12554 break;
12555
12556 case 3: // uri
12557 cur_ptr = s->req.buf->p + txn->req.sl.rq.u;
12558 cur_end = cur_ptr + txn->req.sl.rq.u_l;
12559
12560 /* adjust req line offsets and lengths */
12561 delta = len - offset - (cur_end - cur_ptr);
12562 txn->req.sl.rq.u_l += delta;
12563 txn->req.sl.rq.v += delta;
12564 break;
12565
12566 default:
12567 return -1;
12568 }
12569
12570 /* commit changes and adjust end of message */
12571 delta = buffer_replace2(s->req.buf, cur_ptr, cur_end, replace + offset, len - offset);
12572 txn->req.sl.rq.l += delta;
12573 txn->hdr_idx.v[0].len += delta;
12574 http_msg_move_end(&txn->req, delta);
12575 return 0;
12576 }
12577
12578 /* This function replace the HTTP status code and the associated message. The
12579 * variable <status> contains the new status code. This function never fails.
12580 */
http_set_status(unsigned int status,const char * reason,struct stream * s)12581 void http_set_status(unsigned int status, const char *reason, struct stream *s)
12582 {
12583 struct http_txn *txn = s->txn;
12584 char *cur_ptr, *cur_end;
12585 int delta;
12586 char *res;
12587 int c_l;
12588 const char *msg = reason;
12589 int msg_len;
12590
12591 chunk_reset(&trash);
12592
12593 res = ultoa_o(status, trash.str, trash.size);
12594 c_l = res - trash.str;
12595
12596 trash.str[c_l] = ' ';
12597 trash.len = c_l + 1;
12598
12599 /* Do we have a custom reason format string? */
12600 if (msg == NULL)
12601 msg = get_reason(status);
12602 msg_len = strlen(msg);
12603 strncpy(&trash.str[trash.len], msg, trash.size - trash.len);
12604 trash.len += msg_len;
12605
12606 cur_ptr = s->res.buf->p + txn->rsp.sl.st.c;
12607 cur_end = s->res.buf->p + txn->rsp.sl.st.r + txn->rsp.sl.st.r_l;
12608
12609 /* commit changes and adjust message */
12610 delta = buffer_replace2(s->res.buf, cur_ptr, cur_end, trash.str, trash.len);
12611
12612 /* adjust res line offsets and lengths */
12613 txn->rsp.sl.st.r += c_l - txn->rsp.sl.st.c_l;
12614 txn->rsp.sl.st.c_l = c_l;
12615 txn->rsp.sl.st.r_l = msg_len;
12616
12617 delta = trash.len - (cur_end - cur_ptr);
12618 txn->rsp.sl.st.l += delta;
12619 txn->hdr_idx.v[0].len += delta;
12620 http_msg_move_end(&txn->rsp, delta);
12621 }
12622
12623 /* This function executes one of the set-{method,path,query,uri} actions. It
12624 * builds a string in the trash from the specified format string. It finds
12625 * the action to be performed in <http.action>, previously filled by function
12626 * parse_set_req_line(). The replacement action is excuted by the function
12627 * http_action_set_req_line(). It always returns ACT_RET_CONT. If an error
12628 * occurs the action is canceled, but the rule processing continue.
12629 */
http_action_set_req_line(struct act_rule * rule,struct proxy * px,struct session * sess,struct stream * s,int flags)12630 enum act_return http_action_set_req_line(struct act_rule *rule, struct proxy *px,
12631 struct session *sess, struct stream *s, int flags)
12632 {
12633 struct chunk *replace;
12634 enum act_return ret = ACT_RET_ERR;
12635
12636 replace = alloc_trash_chunk();
12637 if (!replace)
12638 goto leave;
12639
12640 /* If we have to create a query string, prepare a '?'. */
12641 if (rule->arg.http.action == 2)
12642 replace->str[replace->len++] = '?';
12643 replace->len += build_logline(s, replace->str + replace->len, replace->size - replace->len,
12644 &rule->arg.http.logfmt);
12645
12646 http_replace_req_line(rule->arg.http.action, replace->str, replace->len, px, s);
12647
12648 ret = ACT_RET_CONT;
12649
12650 leave:
12651 free_trash_chunk(replace);
12652 return ret;
12653 }
12654
12655 /* 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)12656 enum act_return action_http_set_status(struct act_rule *rule, struct proxy *px,
12657 struct session *sess, struct stream *s, int flags)
12658 {
12659 http_set_status(rule->arg.status.code, rule->arg.status.reason, s);
12660 return ACT_RET_CONT;
12661 }
12662
12663 /* parse an http-request action among :
12664 * set-method
12665 * set-path
12666 * set-query
12667 * set-uri
12668 *
12669 * All of them accept a single argument of type string representing a log-format.
12670 * The resulting rule makes use of arg->act.p[0..1] to store the log-format list
12671 * head, and p[2] to store the action as an int (0=method, 1=path, 2=query, 3=uri).
12672 * It returns ACT_RET_PRS_OK on success, ACT_RET_PRS_ERR on error.
12673 */
parse_set_req_line(const char ** args,int * orig_arg,struct proxy * px,struct act_rule * rule,char ** err)12674 enum act_parse_ret parse_set_req_line(const char **args, int *orig_arg, struct proxy *px,
12675 struct act_rule *rule, char **err)
12676 {
12677 int cur_arg = *orig_arg;
12678
12679 rule->action = ACT_CUSTOM;
12680
12681 switch (args[0][4]) {
12682 case 'm' :
12683 rule->arg.http.action = 0;
12684 rule->action_ptr = http_action_set_req_line;
12685 break;
12686 case 'p' :
12687 rule->arg.http.action = 1;
12688 rule->action_ptr = http_action_set_req_line;
12689 break;
12690 case 'q' :
12691 rule->arg.http.action = 2;
12692 rule->action_ptr = http_action_set_req_line;
12693 break;
12694 case 'u' :
12695 rule->arg.http.action = 3;
12696 rule->action_ptr = http_action_set_req_line;
12697 break;
12698 default:
12699 memprintf(err, "internal error: unhandled action '%s'", args[0]);
12700 return ACT_RET_PRS_ERR;
12701 }
12702
12703 if (!*args[cur_arg] ||
12704 (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) {
12705 memprintf(err, "expects exactly 1 argument <format>");
12706 return ACT_RET_PRS_ERR;
12707 }
12708
12709 LIST_INIT(&rule->arg.http.logfmt);
12710 proxy->conf.args.ctx = ARGC_HRQ;
12711 if (!parse_logformat_string(args[cur_arg], proxy, &rule->arg.http.logfmt, LOG_OPT_HTTP,
12712 (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, err)) {
12713 return ACT_RET_PRS_ERR;
12714 }
12715
12716 (*orig_arg)++;
12717 return ACT_RET_PRS_OK;
12718 }
12719
12720 /* parse set-status action:
12721 * This action accepts a single argument of type int representing
12722 * an http status code. It returns ACT_RET_PRS_OK on success,
12723 * ACT_RET_PRS_ERR on error.
12724 */
parse_http_set_status(const char ** args,int * orig_arg,struct proxy * px,struct act_rule * rule,char ** err)12725 enum act_parse_ret parse_http_set_status(const char **args, int *orig_arg, struct proxy *px,
12726 struct act_rule *rule, char **err)
12727 {
12728 char *error;
12729
12730 rule->action = ACT_CUSTOM;
12731 rule->action_ptr = action_http_set_status;
12732
12733 /* Check if an argument is available */
12734 if (!*args[*orig_arg]) {
12735 memprintf(err, "expects 1 argument: <status>; or 3 arguments: <status> reason <fmt>");
12736 return ACT_RET_PRS_ERR;
12737 }
12738
12739 /* convert status code as integer */
12740 rule->arg.status.code = strtol(args[*orig_arg], &error, 10);
12741 if (*error != '\0' || rule->arg.status.code < 100 || rule->arg.status.code > 999) {
12742 memprintf(err, "expects an integer status code between 100 and 999");
12743 return ACT_RET_PRS_ERR;
12744 }
12745
12746 (*orig_arg)++;
12747
12748 /* scustom reason string */
12749 rule->arg.status.reason = NULL; // If null, we use the default reason for the status code.
12750 if (*args[*orig_arg] && strcmp(args[*orig_arg], "reason") == 0 &&
12751 (*args[*orig_arg + 1] && strcmp(args[*orig_arg + 1], "if") != 0 && strcmp(args[*orig_arg + 1], "unless") != 0)) {
12752 (*orig_arg)++;
12753 rule->arg.status.reason = strdup(args[*orig_arg]);
12754 (*orig_arg)++;
12755 }
12756
12757 return ACT_RET_PRS_OK;
12758 }
12759
12760 /* This function executes the "capture" action. It executes a fetch expression,
12761 * turns the result into a string and puts it in a capture slot. It always
12762 * returns 1. If an error occurs the action is cancelled, but the rule
12763 * processing continues.
12764 */
http_action_req_capture(struct act_rule * rule,struct proxy * px,struct session * sess,struct stream * s,int flags)12765 enum act_return http_action_req_capture(struct act_rule *rule, struct proxy *px,
12766 struct session *sess, struct stream *s, int flags)
12767 {
12768 struct sample *key;
12769 struct cap_hdr *h = rule->arg.cap.hdr;
12770 char **cap = s->req_cap;
12771 int len;
12772
12773 key = sample_fetch_as_type(s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.cap.expr, SMP_T_STR);
12774 if (!key)
12775 return ACT_RET_CONT;
12776
12777 if (cap[h->index] == NULL)
12778 cap[h->index] = pool_alloc2(h->pool);
12779
12780 if (cap[h->index] == NULL) /* no more capture memory */
12781 return ACT_RET_CONT;
12782
12783 len = key->data.u.str.len;
12784 if (len > h->len)
12785 len = h->len;
12786
12787 memcpy(cap[h->index], key->data.u.str.str, len);
12788 cap[h->index][len] = 0;
12789 return ACT_RET_CONT;
12790 }
12791
12792 /* This function executes the "capture" action and store the result in a
12793 * capture slot if exists. It executes a fetch expression, turns the result
12794 * into a string and puts it in a capture slot. It always returns 1. If an
12795 * error occurs the action is cancelled, but the rule processing continues.
12796 */
http_action_req_capture_by_id(struct act_rule * rule,struct proxy * px,struct session * sess,struct stream * s,int flags)12797 enum act_return http_action_req_capture_by_id(struct act_rule *rule, struct proxy *px,
12798 struct session *sess, struct stream *s, int flags)
12799 {
12800 struct sample *key;
12801 struct cap_hdr *h;
12802 char **cap = s->req_cap;
12803 struct proxy *fe = strm_fe(s);
12804 int len;
12805 int i;
12806
12807 /* Look for the original configuration. */
12808 for (h = fe->req_cap, i = fe->nb_req_cap - 1;
12809 h != NULL && i != rule->arg.capid.idx ;
12810 i--, h = h->next);
12811 if (!h)
12812 return ACT_RET_CONT;
12813
12814 key = sample_fetch_as_type(s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.capid.expr, SMP_T_STR);
12815 if (!key)
12816 return ACT_RET_CONT;
12817
12818 if (cap[h->index] == NULL)
12819 cap[h->index] = pool_alloc2(h->pool);
12820
12821 if (cap[h->index] == NULL) /* no more capture memory */
12822 return ACT_RET_CONT;
12823
12824 len = key->data.u.str.len;
12825 if (len > h->len)
12826 len = h->len;
12827
12828 memcpy(cap[h->index], key->data.u.str.str, len);
12829 cap[h->index][len] = 0;
12830 return ACT_RET_CONT;
12831 }
12832
12833 /* parse an "http-request capture" action. It takes a single argument which is
12834 * a sample fetch expression. It stores the expression into arg->act.p[0] and
12835 * the allocated hdr_cap struct or the preallocated "id" into arg->act.p[1].
12836 * It returns ACT_RET_PRS_OK on success, ACT_RET_PRS_ERR on error.
12837 */
parse_http_req_capture(const char ** args,int * orig_arg,struct proxy * px,struct act_rule * rule,char ** err)12838 enum act_parse_ret parse_http_req_capture(const char **args, int *orig_arg, struct proxy *px,
12839 struct act_rule *rule, char **err)
12840 {
12841 struct sample_expr *expr;
12842 struct cap_hdr *hdr;
12843 int cur_arg;
12844 int len = 0;
12845
12846 for (cur_arg = *orig_arg; cur_arg < *orig_arg + 3 && *args[cur_arg]; cur_arg++)
12847 if (strcmp(args[cur_arg], "if") == 0 ||
12848 strcmp(args[cur_arg], "unless") == 0)
12849 break;
12850
12851 if (cur_arg < *orig_arg + 3) {
12852 memprintf(err, "expects <expression> [ 'len' <length> | id <idx> ]");
12853 return ACT_RET_PRS_ERR;
12854 }
12855
12856 cur_arg = *orig_arg;
12857 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args);
12858 if (!expr)
12859 return ACT_RET_PRS_ERR;
12860
12861 if (!(expr->fetch->val & SMP_VAL_FE_HRQ_HDR)) {
12862 memprintf(err,
12863 "fetch method '%s' extracts information from '%s', none of which is available here",
12864 args[cur_arg-1], sample_src_names(expr->fetch->use));
12865 free(expr);
12866 return ACT_RET_PRS_ERR;
12867 }
12868
12869 if (!args[cur_arg] || !*args[cur_arg]) {
12870 memprintf(err, "expects 'len or 'id'");
12871 free(expr);
12872 return ACT_RET_PRS_ERR;
12873 }
12874
12875 if (strcmp(args[cur_arg], "len") == 0) {
12876 cur_arg++;
12877
12878 if (!(px->cap & PR_CAP_FE)) {
12879 memprintf(err, "proxy '%s' has no frontend capability", px->id);
12880 return ACT_RET_PRS_ERR;
12881 }
12882
12883 proxy->conf.args.ctx = ARGC_CAP;
12884
12885 if (!args[cur_arg]) {
12886 memprintf(err, "missing length value");
12887 free(expr);
12888 return ACT_RET_PRS_ERR;
12889 }
12890 /* we copy the table name for now, it will be resolved later */
12891 len = atoi(args[cur_arg]);
12892 if (len <= 0) {
12893 memprintf(err, "length must be > 0");
12894 free(expr);
12895 return ACT_RET_PRS_ERR;
12896 }
12897 cur_arg++;
12898
12899 if (!len) {
12900 memprintf(err, "a positive 'len' argument is mandatory");
12901 free(expr);
12902 return ACT_RET_PRS_ERR;
12903 }
12904
12905 hdr = calloc(1, sizeof(*hdr));
12906 hdr->next = px->req_cap;
12907 hdr->name = NULL; /* not a header capture */
12908 hdr->namelen = 0;
12909 hdr->len = len;
12910 hdr->pool = create_pool("caphdr", hdr->len + 1, MEM_F_SHARED);
12911 hdr->index = px->nb_req_cap++;
12912
12913 px->req_cap = hdr;
12914 px->to_log |= LW_REQHDR;
12915
12916 rule->action = ACT_CUSTOM;
12917 rule->action_ptr = http_action_req_capture;
12918 rule->arg.cap.expr = expr;
12919 rule->arg.cap.hdr = hdr;
12920 }
12921
12922 else if (strcmp(args[cur_arg], "id") == 0) {
12923 int id;
12924 char *error;
12925
12926 cur_arg++;
12927
12928 if (!args[cur_arg]) {
12929 memprintf(err, "missing id value");
12930 free(expr);
12931 return ACT_RET_PRS_ERR;
12932 }
12933
12934 id = strtol(args[cur_arg], &error, 10);
12935 if (*error != '\0') {
12936 memprintf(err, "cannot parse id '%s'", args[cur_arg]);
12937 free(expr);
12938 return ACT_RET_PRS_ERR;
12939 }
12940 cur_arg++;
12941
12942 proxy->conf.args.ctx = ARGC_CAP;
12943
12944 rule->action = ACT_CUSTOM;
12945 rule->action_ptr = http_action_req_capture_by_id;
12946 rule->arg.capid.expr = expr;
12947 rule->arg.capid.idx = id;
12948 }
12949
12950 else {
12951 memprintf(err, "expects 'len' or 'id', found '%s'", args[cur_arg]);
12952 free(expr);
12953 return ACT_RET_PRS_ERR;
12954 }
12955
12956 *orig_arg = cur_arg;
12957 return ACT_RET_PRS_OK;
12958 }
12959
12960 /* This function executes the "capture" action and store the result in a
12961 * capture slot if exists. It executes a fetch expression, turns the result
12962 * into a string and puts it in a capture slot. It always returns 1. If an
12963 * error occurs the action is cancelled, but the rule processing continues.
12964 */
http_action_res_capture_by_id(struct act_rule * rule,struct proxy * px,struct session * sess,struct stream * s,int flags)12965 enum act_return http_action_res_capture_by_id(struct act_rule *rule, struct proxy *px,
12966 struct session *sess, struct stream *s, int flags)
12967 {
12968 struct sample *key;
12969 struct cap_hdr *h;
12970 char **cap = s->res_cap;
12971 struct proxy *fe = strm_fe(s);
12972 int len;
12973 int i;
12974
12975 /* Look for the original configuration. */
12976 for (h = fe->rsp_cap, i = fe->nb_rsp_cap - 1;
12977 h != NULL && i != rule->arg.capid.idx ;
12978 i--, h = h->next);
12979 if (!h)
12980 return ACT_RET_CONT;
12981
12982 key = sample_fetch_as_type(s->be, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL, rule->arg.capid.expr, SMP_T_STR);
12983 if (!key)
12984 return ACT_RET_CONT;
12985
12986 if (cap[h->index] == NULL)
12987 cap[h->index] = pool_alloc2(h->pool);
12988
12989 if (cap[h->index] == NULL) /* no more capture memory */
12990 return ACT_RET_CONT;
12991
12992 len = key->data.u.str.len;
12993 if (len > h->len)
12994 len = h->len;
12995
12996 memcpy(cap[h->index], key->data.u.str.str, len);
12997 cap[h->index][len] = 0;
12998 return ACT_RET_CONT;
12999 }
13000
13001
13002 /* parse an "http-response capture" action. It takes a single argument which is
13003 * a sample fetch expression. It stores the expression into arg->act.p[0] and
13004 * the allocated hdr_cap struct od the preallocated id into arg->act.p[1].
13005 * It returns ACT_RET_PRS_OK on success, ACT_RET_PRS_ERR on error.
13006 */
parse_http_res_capture(const char ** args,int * orig_arg,struct proxy * px,struct act_rule * rule,char ** err)13007 enum act_parse_ret parse_http_res_capture(const char **args, int *orig_arg, struct proxy *px,
13008 struct act_rule *rule, char **err)
13009 {
13010 struct sample_expr *expr;
13011 int cur_arg;
13012 int id;
13013 char *error;
13014
13015 for (cur_arg = *orig_arg; cur_arg < *orig_arg + 3 && *args[cur_arg]; cur_arg++)
13016 if (strcmp(args[cur_arg], "if") == 0 ||
13017 strcmp(args[cur_arg], "unless") == 0)
13018 break;
13019
13020 if (cur_arg < *orig_arg + 3) {
13021 memprintf(err, "expects <expression> id <idx>");
13022 return ACT_RET_PRS_ERR;
13023 }
13024
13025 cur_arg = *orig_arg;
13026 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args);
13027 if (!expr)
13028 return ACT_RET_PRS_ERR;
13029
13030 if (!(expr->fetch->val & SMP_VAL_FE_HRS_HDR)) {
13031 memprintf(err,
13032 "fetch method '%s' extracts information from '%s', none of which is available here",
13033 args[cur_arg-1], sample_src_names(expr->fetch->use));
13034 free(expr);
13035 return ACT_RET_PRS_ERR;
13036 }
13037
13038 if (!args[cur_arg] || !*args[cur_arg]) {
13039 memprintf(err, "expects 'id'");
13040 free(expr);
13041 return ACT_RET_PRS_ERR;
13042 }
13043
13044 if (strcmp(args[cur_arg], "id") != 0) {
13045 memprintf(err, "expects 'id', found '%s'", args[cur_arg]);
13046 free(expr);
13047 return ACT_RET_PRS_ERR;
13048 }
13049
13050 cur_arg++;
13051
13052 if (!args[cur_arg]) {
13053 memprintf(err, "missing id value");
13054 free(expr);
13055 return ACT_RET_PRS_ERR;
13056 }
13057
13058 id = strtol(args[cur_arg], &error, 10);
13059 if (*error != '\0') {
13060 memprintf(err, "cannot parse id '%s'", args[cur_arg]);
13061 free(expr);
13062 return ACT_RET_PRS_ERR;
13063 }
13064 cur_arg++;
13065
13066 proxy->conf.args.ctx = ARGC_CAP;
13067
13068 rule->action = ACT_CUSTOM;
13069 rule->action_ptr = http_action_res_capture_by_id;
13070 rule->arg.capid.expr = expr;
13071 rule->arg.capid.idx = id;
13072
13073 *orig_arg = cur_arg;
13074 return ACT_RET_PRS_OK;
13075 }
13076
13077 /*
13078 * Return the struct http_req_action_kw associated to a keyword.
13079 */
action_http_req_custom(const char * kw)13080 struct action_kw *action_http_req_custom(const char *kw)
13081 {
13082 return action_lookup(&http_req_keywords.list, kw);
13083 }
13084
13085 /*
13086 * Return the struct http_res_action_kw associated to a keyword.
13087 */
action_http_res_custom(const char * kw)13088 struct action_kw *action_http_res_custom(const char *kw)
13089 {
13090 return action_lookup(&http_res_keywords.list, kw);
13091 }
13092
13093
13094 /* "show errors" handler for the CLI. Returns 0 if wants to continue, 1 to stop
13095 * now.
13096 */
cli_parse_show_errors(char ** args,struct appctx * appctx,void * private)13097 static int cli_parse_show_errors(char **args, struct appctx *appctx, void *private)
13098 {
13099 if (!cli_has_level(appctx, ACCESS_LVL_OPER))
13100 return 1;
13101
13102 if (*args[2]) {
13103 struct proxy *px;
13104
13105 px = proxy_find_by_name(args[2], 0, 0);
13106 if (px)
13107 appctx->ctx.errors.iid = px->uuid;
13108 else
13109 appctx->ctx.errors.iid = atoi(args[2]);
13110
13111 if (!appctx->ctx.errors.iid) {
13112 appctx->ctx.cli.msg = "No such proxy.\n";
13113 appctx->st0 = CLI_ST_PRINT;
13114 return 1;
13115 }
13116 }
13117 else
13118 appctx->ctx.errors.iid = -1; // dump all proxies
13119
13120 appctx->ctx.errors.flag = 0;
13121 if (strcmp(args[3], "request") == 0)
13122 appctx->ctx.errors.flag |= 4; // ignore response
13123 else if (strcmp(args[3], "response") == 0)
13124 appctx->ctx.errors.flag |= 2; // ignore request
13125 appctx->ctx.errors.px = NULL;
13126 return 0;
13127 }
13128
13129 /* This function dumps all captured errors onto the stream interface's
13130 * read buffer. It returns 0 if the output buffer is full and it needs
13131 * to be called again, otherwise non-zero.
13132 */
cli_io_handler_show_errors(struct appctx * appctx)13133 static int cli_io_handler_show_errors(struct appctx *appctx)
13134 {
13135 struct stream_interface *si = appctx->owner;
13136 extern const char *monthname[12];
13137
13138 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
13139 return 1;
13140
13141 chunk_reset(&trash);
13142
13143 if (!appctx->ctx.errors.px) {
13144 /* the function had not been called yet, let's prepare the
13145 * buffer for a response.
13146 */
13147 struct tm tm;
13148
13149 get_localtime(date.tv_sec, &tm);
13150 chunk_appendf(&trash, "Total events captured on [%02d/%s/%04d:%02d:%02d:%02d.%03d] : %u\n",
13151 tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
13152 tm.tm_hour, tm.tm_min, tm.tm_sec, (int)(date.tv_usec/1000),
13153 error_snapshot_id);
13154
13155 if (bi_putchk(si_ic(si), &trash) == -1) {
13156 /* Socket buffer full. Let's try again later from the same point */
13157 si_applet_cant_put(si);
13158 return 0;
13159 }
13160
13161 appctx->ctx.errors.px = proxy;
13162 appctx->ctx.errors.bol = 0;
13163 appctx->ctx.errors.ptr = -1;
13164 }
13165
13166 /* we have two inner loops here, one for the proxy, the other one for
13167 * the buffer.
13168 */
13169 while (appctx->ctx.errors.px) {
13170 struct error_snapshot *es;
13171
13172 if ((appctx->ctx.errors.flag & 1) == 0) {
13173 es = &appctx->ctx.errors.px->invalid_req;
13174 if (appctx->ctx.errors.flag & 2) // skip req
13175 goto next;
13176 }
13177 else {
13178 es = &appctx->ctx.errors.px->invalid_rep;
13179 if (appctx->ctx.errors.flag & 4) // skip resp
13180 goto next;
13181 }
13182
13183 if (!es->when.tv_sec)
13184 goto next;
13185
13186 if (appctx->ctx.errors.iid >= 0 &&
13187 appctx->ctx.errors.px->uuid != appctx->ctx.errors.iid &&
13188 es->oe->uuid != appctx->ctx.errors.iid)
13189 goto next;
13190
13191 if (appctx->ctx.errors.ptr < 0) {
13192 /* just print headers now */
13193
13194 char pn[INET6_ADDRSTRLEN];
13195 struct tm tm;
13196 int port;
13197
13198 get_localtime(es->when.tv_sec, &tm);
13199 chunk_appendf(&trash, " \n[%02d/%s/%04d:%02d:%02d:%02d.%03d]",
13200 tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
13201 tm.tm_hour, tm.tm_min, tm.tm_sec, (int)(es->when.tv_usec/1000));
13202
13203 switch (addr_to_str(&es->src, pn, sizeof(pn))) {
13204 case AF_INET:
13205 case AF_INET6:
13206 port = get_host_port(&es->src);
13207 break;
13208 default:
13209 port = 0;
13210 }
13211
13212 switch (appctx->ctx.errors.flag & 1) {
13213 case 0:
13214 chunk_appendf(&trash,
13215 " frontend %s (#%d): invalid request\n"
13216 " backend %s (#%d)",
13217 appctx->ctx.errors.px->id, appctx->ctx.errors.px->uuid,
13218 (es->oe->cap & PR_CAP_BE) ? es->oe->id : "<NONE>",
13219 (es->oe->cap & PR_CAP_BE) ? es->oe->uuid : -1);
13220 break;
13221 case 1:
13222 chunk_appendf(&trash,
13223 " backend %s (#%d): invalid response\n"
13224 " frontend %s (#%d)",
13225 appctx->ctx.errors.px->id, appctx->ctx.errors.px->uuid,
13226 es->oe->id, es->oe->uuid);
13227 break;
13228 }
13229
13230 chunk_appendf(&trash,
13231 ", server %s (#%d), event #%u\n"
13232 " src %s:%d, session #%d, session flags 0x%08x\n"
13233 " HTTP msg state %s(%d), msg flags 0x%08x, tx flags 0x%08x\n"
13234 " HTTP chunk len %lld bytes, HTTP body len %lld bytes\n"
13235 " buffer flags 0x%08x, out %d bytes, total %lld bytes\n"
13236 " pending %d bytes, wrapping at %d, error at position %d:\n \n",
13237 es->srv ? es->srv->id : "<NONE>", es->srv ? es->srv->puid : -1,
13238 es->ev_id,
13239 pn, port, es->sid, es->s_flags,
13240 http_msg_state_str(es->state), es->state, es->m_flags, es->t_flags,
13241 es->m_clen, es->m_blen,
13242 es->b_flags, es->b_out, es->b_tot,
13243 es->len, es->b_wrap, es->pos);
13244
13245 if (bi_putchk(si_ic(si), &trash) == -1) {
13246 /* Socket buffer full. Let's try again later from the same point */
13247 si_applet_cant_put(si);
13248 return 0;
13249 }
13250 appctx->ctx.errors.ptr = 0;
13251 appctx->ctx.errors.sid = es->sid;
13252 }
13253
13254 if (appctx->ctx.errors.sid != es->sid) {
13255 /* the snapshot changed while we were dumping it */
13256 chunk_appendf(&trash,
13257 " WARNING! update detected on this snapshot, dump interrupted. Please re-check!\n");
13258 if (bi_putchk(si_ic(si), &trash) == -1) {
13259 si_applet_cant_put(si);
13260 return 0;
13261 }
13262 goto next;
13263 }
13264
13265 /* OK, ptr >= 0, so we have to dump the current line */
13266 while (es->buf && appctx->ctx.errors.ptr < es->len && appctx->ctx.errors.ptr < global.tune.bufsize) {
13267 int newptr;
13268 int newline;
13269
13270 newline = appctx->ctx.errors.bol;
13271 newptr = dump_text_line(&trash, es->buf, global.tune.bufsize, es->len, &newline, appctx->ctx.errors.ptr);
13272 if (newptr == appctx->ctx.errors.ptr)
13273 return 0;
13274
13275 if (bi_putchk(si_ic(si), &trash) == -1) {
13276 /* Socket buffer full. Let's try again later from the same point */
13277 si_applet_cant_put(si);
13278 return 0;
13279 }
13280 appctx->ctx.errors.ptr = newptr;
13281 appctx->ctx.errors.bol = newline;
13282 };
13283 next:
13284 appctx->ctx.errors.bol = 0;
13285 appctx->ctx.errors.ptr = -1;
13286 appctx->ctx.errors.flag ^= 1;
13287 if (!(appctx->ctx.errors.flag & 1))
13288 appctx->ctx.errors.px = appctx->ctx.errors.px->next;
13289 }
13290
13291 /* dump complete */
13292 return 1;
13293 }
13294
13295 /* register cli keywords */
13296 static struct cli_kw_list cli_kws = {{ },{
13297 { { "show", "errors", NULL },
13298 "show errors : report last request and response errors for each proxy",
13299 cli_parse_show_errors, cli_io_handler_show_errors, NULL,
13300 },
13301 {{},}
13302 }};
13303
13304 /************************************************************************/
13305 /* All supported ACL keywords must be declared here. */
13306 /************************************************************************/
13307
13308 /* Note: must not be declared <const> as its list will be overwritten.
13309 * Please take care of keeping this list alphabetically sorted.
13310 */
13311 static struct acl_kw_list acl_kws = {ILH, {
13312 { "base", "base", PAT_MATCH_STR },
13313 { "base_beg", "base", PAT_MATCH_BEG },
13314 { "base_dir", "base", PAT_MATCH_DIR },
13315 { "base_dom", "base", PAT_MATCH_DOM },
13316 { "base_end", "base", PAT_MATCH_END },
13317 { "base_len", "base", PAT_MATCH_LEN },
13318 { "base_reg", "base", PAT_MATCH_REG },
13319 { "base_sub", "base", PAT_MATCH_SUB },
13320
13321 { "cook", "req.cook", PAT_MATCH_STR },
13322 { "cook_beg", "req.cook", PAT_MATCH_BEG },
13323 { "cook_dir", "req.cook", PAT_MATCH_DIR },
13324 { "cook_dom", "req.cook", PAT_MATCH_DOM },
13325 { "cook_end", "req.cook", PAT_MATCH_END },
13326 { "cook_len", "req.cook", PAT_MATCH_LEN },
13327 { "cook_reg", "req.cook", PAT_MATCH_REG },
13328 { "cook_sub", "req.cook", PAT_MATCH_SUB },
13329
13330 { "hdr", "req.hdr", PAT_MATCH_STR },
13331 { "hdr_beg", "req.hdr", PAT_MATCH_BEG },
13332 { "hdr_dir", "req.hdr", PAT_MATCH_DIR },
13333 { "hdr_dom", "req.hdr", PAT_MATCH_DOM },
13334 { "hdr_end", "req.hdr", PAT_MATCH_END },
13335 { "hdr_len", "req.hdr", PAT_MATCH_LEN },
13336 { "hdr_reg", "req.hdr", PAT_MATCH_REG },
13337 { "hdr_sub", "req.hdr", PAT_MATCH_SUB },
13338
13339 /* these two declarations uses strings with list storage (in place
13340 * of tree storage). The basic match is PAT_MATCH_STR, but the indexation
13341 * and delete functions are relative to the list management. The parse
13342 * and match method are related to the corresponding fetch methods. This
13343 * is very particular ACL declaration mode.
13344 */
13345 { "http_auth_group", NULL, PAT_MATCH_STR, NULL, pat_idx_list_str, pat_del_list_ptr, NULL, pat_match_auth },
13346 { "method", NULL, PAT_MATCH_STR, pat_parse_meth, pat_idx_list_str, pat_del_list_ptr, NULL, pat_match_meth },
13347
13348 { "path", "path", PAT_MATCH_STR },
13349 { "path_beg", "path", PAT_MATCH_BEG },
13350 { "path_dir", "path", PAT_MATCH_DIR },
13351 { "path_dom", "path", PAT_MATCH_DOM },
13352 { "path_end", "path", PAT_MATCH_END },
13353 { "path_len", "path", PAT_MATCH_LEN },
13354 { "path_reg", "path", PAT_MATCH_REG },
13355 { "path_sub", "path", PAT_MATCH_SUB },
13356
13357 { "req_ver", "req.ver", PAT_MATCH_STR },
13358 { "resp_ver", "res.ver", PAT_MATCH_STR },
13359
13360 { "scook", "res.cook", PAT_MATCH_STR },
13361 { "scook_beg", "res.cook", PAT_MATCH_BEG },
13362 { "scook_dir", "res.cook", PAT_MATCH_DIR },
13363 { "scook_dom", "res.cook", PAT_MATCH_DOM },
13364 { "scook_end", "res.cook", PAT_MATCH_END },
13365 { "scook_len", "res.cook", PAT_MATCH_LEN },
13366 { "scook_reg", "res.cook", PAT_MATCH_REG },
13367 { "scook_sub", "res.cook", PAT_MATCH_SUB },
13368
13369 { "shdr", "res.hdr", PAT_MATCH_STR },
13370 { "shdr_beg", "res.hdr", PAT_MATCH_BEG },
13371 { "shdr_dir", "res.hdr", PAT_MATCH_DIR },
13372 { "shdr_dom", "res.hdr", PAT_MATCH_DOM },
13373 { "shdr_end", "res.hdr", PAT_MATCH_END },
13374 { "shdr_len", "res.hdr", PAT_MATCH_LEN },
13375 { "shdr_reg", "res.hdr", PAT_MATCH_REG },
13376 { "shdr_sub", "res.hdr", PAT_MATCH_SUB },
13377
13378 { "url", "url", PAT_MATCH_STR },
13379 { "url_beg", "url", PAT_MATCH_BEG },
13380 { "url_dir", "url", PAT_MATCH_DIR },
13381 { "url_dom", "url", PAT_MATCH_DOM },
13382 { "url_end", "url", PAT_MATCH_END },
13383 { "url_len", "url", PAT_MATCH_LEN },
13384 { "url_reg", "url", PAT_MATCH_REG },
13385 { "url_sub", "url", PAT_MATCH_SUB },
13386
13387 { "urlp", "urlp", PAT_MATCH_STR },
13388 { "urlp_beg", "urlp", PAT_MATCH_BEG },
13389 { "urlp_dir", "urlp", PAT_MATCH_DIR },
13390 { "urlp_dom", "urlp", PAT_MATCH_DOM },
13391 { "urlp_end", "urlp", PAT_MATCH_END },
13392 { "urlp_len", "urlp", PAT_MATCH_LEN },
13393 { "urlp_reg", "urlp", PAT_MATCH_REG },
13394 { "urlp_sub", "urlp", PAT_MATCH_SUB },
13395
13396 { /* END */ },
13397 }};
13398
13399 /************************************************************************/
13400 /* All supported pattern keywords must be declared here. */
13401 /************************************************************************/
13402 /* Note: must not be declared <const> as its list will be overwritten */
13403 static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, {
13404 { "base", smp_fetch_base, 0, NULL, SMP_T_STR, SMP_USE_HRQHV },
13405 { "base32", smp_fetch_base32, 0, NULL, SMP_T_SINT, SMP_USE_HRQHV },
13406 { "base32+src", smp_fetch_base32_src, 0, NULL, SMP_T_BIN, SMP_USE_HRQHV },
13407
13408 /* capture are allocated and are permanent in the stream */
13409 { "capture.req.hdr", smp_fetch_capture_header_req, ARG1(1,SINT), NULL, SMP_T_STR, SMP_USE_HRQHP },
13410
13411 /* retrieve these captures from the HTTP logs */
13412 { "capture.req.method", smp_fetch_capture_req_method, 0, NULL, SMP_T_STR, SMP_USE_HRQHP },
13413 { "capture.req.uri", smp_fetch_capture_req_uri, 0, NULL, SMP_T_STR, SMP_USE_HRQHP },
13414 { "capture.req.ver", smp_fetch_capture_req_ver, 0, NULL, SMP_T_STR, SMP_USE_HRQHP },
13415
13416 { "capture.res.hdr", smp_fetch_capture_header_res, ARG1(1,SINT), NULL, SMP_T_STR, SMP_USE_HRSHP },
13417 { "capture.res.ver", smp_fetch_capture_res_ver, 0, NULL, SMP_T_STR, SMP_USE_HRQHP },
13418
13419 /* cookie is valid in both directions (eg: for "stick ...") but cook*
13420 * are only here to match the ACL's name, are request-only and are used
13421 * for ACL compatibility only.
13422 */
13423 { "cook", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRQHV },
13424 { "cookie", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRQHV|SMP_USE_HRSHV },
13425 { "cook_cnt", smp_fetch_cookie_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
13426 { "cook_val", smp_fetch_cookie_val, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
13427
13428 /* hdr is valid in both directions (eg: for "stick ...") but hdr_* are
13429 * only here to match the ACL's name, are request-only and are used for
13430 * ACL compatibility only.
13431 */
13432 { "hdr", smp_fetch_hdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRQHV|SMP_USE_HRSHV },
13433 { "hdr_cnt", smp_fetch_hdr_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
13434 { "hdr_ip", smp_fetch_hdr_ip, ARG2(0,STR,SINT), val_hdr, SMP_T_IPV4, SMP_USE_HRQHV },
13435 { "hdr_val", smp_fetch_hdr_val, ARG2(0,STR,SINT), val_hdr, SMP_T_SINT, SMP_USE_HRQHV },
13436
13437 { "http_auth", smp_fetch_http_auth, ARG1(1,USR), NULL, SMP_T_BOOL, SMP_USE_HRQHV },
13438 { "http_auth_group", smp_fetch_http_auth_grp, ARG1(1,USR), NULL, SMP_T_STR, SMP_USE_HRQHV },
13439 { "http_first_req", smp_fetch_http_first_req, 0, NULL, SMP_T_BOOL, SMP_USE_HRQHP },
13440 { "method", smp_fetch_meth, 0, NULL, SMP_T_METH, SMP_USE_HRQHP },
13441 { "path", smp_fetch_path, 0, NULL, SMP_T_STR, SMP_USE_HRQHV },
13442 { "query", smp_fetch_query, 0, NULL, SMP_T_STR, SMP_USE_HRQHV },
13443
13444 /* HTTP protocol on the request path */
13445 { "req.proto_http", smp_fetch_proto_http, 0, NULL, SMP_T_BOOL, SMP_USE_HRQHP },
13446 { "req_proto_http", smp_fetch_proto_http, 0, NULL, SMP_T_BOOL, SMP_USE_HRQHP },
13447
13448 /* HTTP version on the request path */
13449 { "req.ver", smp_fetch_rqver, 0, NULL, SMP_T_STR, SMP_USE_HRQHV },
13450 { "req_ver", smp_fetch_rqver, 0, NULL, SMP_T_STR, SMP_USE_HRQHV },
13451
13452 { "req.body", smp_fetch_body, 0, NULL, SMP_T_BIN, SMP_USE_HRQHV },
13453 { "req.body_len", smp_fetch_body_len, 0, NULL, SMP_T_SINT, SMP_USE_HRQHV },
13454 { "req.body_size", smp_fetch_body_size, 0, NULL, SMP_T_SINT, SMP_USE_HRQHV },
13455 { "req.body_param", smp_fetch_body_param, ARG1(0,STR), NULL, SMP_T_BIN, SMP_USE_HRQHV },
13456
13457 /* HTTP version on the response path */
13458 { "res.ver", smp_fetch_stver, 0, NULL, SMP_T_STR, SMP_USE_HRSHV },
13459 { "resp_ver", smp_fetch_stver, 0, NULL, SMP_T_STR, SMP_USE_HRSHV },
13460
13461 /* explicit req.{cook,hdr} are used to force the fetch direction to be request-only */
13462 { "req.cook", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRQHV },
13463 { "req.cook_cnt", smp_fetch_cookie_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
13464 { "req.cook_val", smp_fetch_cookie_val, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
13465
13466 { "req.fhdr", smp_fetch_fhdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRQHV },
13467 { "req.fhdr_cnt", smp_fetch_fhdr_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
13468 { "req.hdr", smp_fetch_hdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRQHV },
13469 { "req.hdr_cnt", smp_fetch_hdr_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
13470 { "req.hdr_ip", smp_fetch_hdr_ip, ARG2(0,STR,SINT), val_hdr, SMP_T_IPV4, SMP_USE_HRQHV },
13471 { "req.hdr_names", smp_fetch_hdr_names, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRQHV },
13472 { "req.hdr_val", smp_fetch_hdr_val, ARG2(0,STR,SINT), val_hdr, SMP_T_SINT, SMP_USE_HRQHV },
13473
13474 /* explicit req.{cook,hdr} are used to force the fetch direction to be response-only */
13475 { "res.cook", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRSHV },
13476 { "res.cook_cnt", smp_fetch_cookie_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRSHV },
13477 { "res.cook_val", smp_fetch_cookie_val, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRSHV },
13478
13479 { "res.fhdr", smp_fetch_fhdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRSHV },
13480 { "res.fhdr_cnt", smp_fetch_fhdr_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRSHV },
13481 { "res.hdr", smp_fetch_hdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRSHV },
13482 { "res.hdr_cnt", smp_fetch_hdr_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRSHV },
13483 { "res.hdr_ip", smp_fetch_hdr_ip, ARG2(0,STR,SINT), val_hdr, SMP_T_IPV4, SMP_USE_HRSHV },
13484 { "res.hdr_names", smp_fetch_hdr_names, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRSHV },
13485 { "res.hdr_val", smp_fetch_hdr_val, ARG2(0,STR,SINT), val_hdr, SMP_T_SINT, SMP_USE_HRSHV },
13486
13487 /* scook is valid only on the response and is used for ACL compatibility */
13488 { "scook", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRSHV },
13489 { "scook_cnt", smp_fetch_cookie_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRSHV },
13490 { "scook_val", smp_fetch_cookie_val, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRSHV },
13491 { "set-cookie", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRSHV }, /* deprecated */
13492
13493 /* shdr is valid only on the response and is used for ACL compatibility */
13494 { "shdr", smp_fetch_hdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRSHV },
13495 { "shdr_cnt", smp_fetch_hdr_cnt, ARG1(0,STR), NULL, SMP_T_SINT, SMP_USE_HRSHV },
13496 { "shdr_ip", smp_fetch_hdr_ip, ARG2(0,STR,SINT), val_hdr, SMP_T_IPV4, SMP_USE_HRSHV },
13497 { "shdr_val", smp_fetch_hdr_val, ARG2(0,STR,SINT), val_hdr, SMP_T_SINT, SMP_USE_HRSHV },
13498
13499 { "status", smp_fetch_stcode, 0, NULL, SMP_T_SINT, SMP_USE_HRSHP },
13500 { "unique-id", smp_fetch_uniqueid, 0, NULL, SMP_T_STR, SMP_SRC_L4SRV },
13501 { "url", smp_fetch_url, 0, NULL, SMP_T_STR, SMP_USE_HRQHV },
13502 { "url32", smp_fetch_url32, 0, NULL, SMP_T_SINT, SMP_USE_HRQHV },
13503 { "url32+src", smp_fetch_url32_src, 0, NULL, SMP_T_BIN, SMP_USE_HRQHV },
13504 { "url_ip", smp_fetch_url_ip, 0, NULL, SMP_T_IPV4, SMP_USE_HRQHV },
13505 { "url_port", smp_fetch_url_port, 0, NULL, SMP_T_SINT, SMP_USE_HRQHV },
13506 { "url_param", smp_fetch_url_param, ARG2(0,STR,STR), NULL, SMP_T_STR, SMP_USE_HRQHV },
13507 { "urlp" , smp_fetch_url_param, ARG2(0,STR,STR), NULL, SMP_T_STR, SMP_USE_HRQHV },
13508 { "urlp_val", smp_fetch_url_param_val, ARG2(0,STR,STR), NULL, SMP_T_SINT, SMP_USE_HRQHV },
13509 { /* END */ },
13510 }};
13511
13512
13513 /************************************************************************/
13514 /* All supported converter keywords must be declared here. */
13515 /************************************************************************/
13516 /* Note: must not be declared <const> as its list will be overwritten */
13517 static struct sample_conv_kw_list sample_conv_kws = {ILH, {
13518 { "http_date", sample_conv_http_date, ARG1(0,SINT), NULL, SMP_T_SINT, SMP_T_STR},
13519 { "language", sample_conv_q_prefered, ARG2(1,STR,STR), NULL, SMP_T_STR, SMP_T_STR},
13520 { "capture-req", smp_conv_req_capture, ARG1(1,SINT), NULL, SMP_T_STR, SMP_T_STR},
13521 { "capture-res", smp_conv_res_capture, ARG1(1,SINT), NULL, SMP_T_STR, SMP_T_STR},
13522 { "url_dec", sample_conv_url_dec, 0, NULL, SMP_T_STR, SMP_T_STR},
13523 { NULL, NULL, 0, 0, 0 },
13524 }};
13525
13526
13527 /************************************************************************/
13528 /* All supported http-request action keywords must be declared here. */
13529 /************************************************************************/
13530 struct action_kw_list http_req_actions = {
13531 .kw = {
13532 { "capture", parse_http_req_capture },
13533 { "set-method", parse_set_req_line },
13534 { "set-path", parse_set_req_line },
13535 { "set-query", parse_set_req_line },
13536 { "set-uri", parse_set_req_line },
13537 { NULL, NULL }
13538 }
13539 };
13540
13541 struct action_kw_list http_res_actions = {
13542 .kw = {
13543 { "capture", parse_http_res_capture },
13544 { "set-status", parse_http_set_status },
13545 { NULL, NULL }
13546 }
13547 };
13548
13549 __attribute__((constructor))
__http_protocol_init(void)13550 static void __http_protocol_init(void)
13551 {
13552 acl_register_keywords(&acl_kws);
13553 sample_register_fetches(&sample_fetch_keywords);
13554 sample_register_convs(&sample_conv_kws);
13555 http_req_keywords_register(&http_req_actions);
13556 http_res_keywords_register(&http_res_actions);
13557 cli_register_kw(&cli_kws);
13558 }
13559
13560
13561 /*
13562 * Local variables:
13563 * c-indent-level: 8
13564 * c-basic-offset: 8
13565 * End:
13566 */
13567