]> git.ipfire.org Git - thirdparty/squid.git/blob - src/HttpHeader.cc
e7e8da3d5a49ece6e981eb97cf694e8eae0235c9
[thirdparty/squid.git] / src / HttpHeader.cc
1
2 /*
3 * $Id$
4 *
5 * DEBUG: section 55 HTTP Header
6 * AUTHOR: Alex Rousskov
7 *
8 * SQUID Web Proxy Cache http://www.squid-cache.org/
9 * ----------------------------------------------------------
10 *
11 * Squid is the result of efforts by numerous individuals from
12 * the Internet community; see the CONTRIBUTORS file for full
13 * details. Many organizations have provided support for Squid's
14 * development; see the SPONSORS file for full details. Squid is
15 * Copyrighted (C) 2001 by the Regents of the University of
16 * California; see the COPYRIGHT file for full details. Squid
17 * incorporates software developed and/or copyrighted by other
18 * sources; see the CREDITS file for full details.
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
33 *
34 */
35
36 #include "squid.h"
37 #include "base64.h"
38 #include "HttpHdrContRange.h"
39 #include "HttpHdrCc.h"
40 #include "HttpHdrSc.h"
41 #include "HttpHeader.h"
42 #include "HttpHeaderStat.h"
43 #include "MemBuf.h"
44 #include "mgr/Registration.h"
45 #include "rfc1123.h"
46 #include "StatHist.h"
47 #include "Store.h"
48 #include "TimeOrTag.h"
49
50 /*
51 * On naming conventions:
52 *
53 * HTTP/1.1 defines message-header as
54 *
55 * message-header = field-name ":" [ field-value ] CRLF
56 * field-name = token
57 * field-value = *( field-content | LWS )
58 *
59 * HTTP/1.1 does not give a name name a group of all message-headers in a message.
60 * Squid 1.1 seems to refer to that group _plus_ start-line as "headers".
61 *
62 * HttpHeader is an object that represents all message-headers in a message.
63 * HttpHeader does not manage start-line.
64 *
65 * HttpHeader is implemented as a collection of header "entries".
66 * An entry is a (field_id, field_name, field_value) triplet.
67 */
68
69
70 /*
71 * local constants and vars
72 */
73
74 /*
75 * A table with major attributes for every known field.
76 * We calculate name lengths and reorganize this array on start up.
77 * After reorganization, field id can be used as an index to the table.
78 */
79 static const HttpHeaderFieldAttrs HeadersAttrs[] = {
80 {"Accept", HDR_ACCEPT, ftStr},
81
82 {"Accept-Charset", HDR_ACCEPT_CHARSET, ftStr},
83 {"Accept-Encoding", HDR_ACCEPT_ENCODING, ftStr},
84 {"Accept-Language", HDR_ACCEPT_LANGUAGE, ftStr},
85 {"Accept-Ranges", HDR_ACCEPT_RANGES, ftStr},
86 {"Age", HDR_AGE, ftInt},
87 {"Allow", HDR_ALLOW, ftStr},
88 {"Authorization", HDR_AUTHORIZATION, ftStr}, /* for now */
89 {"Cache-Control", HDR_CACHE_CONTROL, ftPCc},
90 {"Connection", HDR_CONNECTION, ftStr},
91 {"Content-Base", HDR_CONTENT_BASE, ftStr},
92 {"Content-Disposition", HDR_CONTENT_DISPOSITION, ftStr}, /* for now */
93 {"Content-Encoding", HDR_CONTENT_ENCODING, ftStr},
94 {"Content-Language", HDR_CONTENT_LANGUAGE, ftStr},
95 {"Content-Length", HDR_CONTENT_LENGTH, ftInt64},
96 {"Content-Location", HDR_CONTENT_LOCATION, ftStr},
97 {"Content-MD5", HDR_CONTENT_MD5, ftStr}, /* for now */
98 {"Content-Range", HDR_CONTENT_RANGE, ftPContRange},
99 {"Content-Type", HDR_CONTENT_TYPE, ftStr},
100 {"Cookie", HDR_COOKIE, ftStr},
101 {"Cookie2", HDR_COOKIE2, ftStr},
102 {"Date", HDR_DATE, ftDate_1123},
103 {"ETag", HDR_ETAG, ftETag},
104 {"Expect", HDR_EXPECT, ftStr},
105 {"Expires", HDR_EXPIRES, ftDate_1123},
106 {"From", HDR_FROM, ftStr},
107 {"Host", HDR_HOST, ftStr},
108 {"If-Match", HDR_IF_MATCH, ftStr}, /* for now */
109 {"If-Modified-Since", HDR_IF_MODIFIED_SINCE, ftDate_1123},
110 {"If-None-Match", HDR_IF_NONE_MATCH, ftStr}, /* for now */
111 {"If-Range", HDR_IF_RANGE, ftDate_1123_or_ETag},
112 {"Keep-Alive", HDR_KEEP_ALIVE, ftStr},
113 {"Last-Modified", HDR_LAST_MODIFIED, ftDate_1123},
114 {"Link", HDR_LINK, ftStr},
115 {"Location", HDR_LOCATION, ftStr},
116 {"Max-Forwards", HDR_MAX_FORWARDS, ftInt64},
117 {"Mime-Version", HDR_MIME_VERSION, ftStr}, /* for now */
118 {"Negotiate", HDR_NEGOTIATE, ftStr},
119 {"Origin", HDR_ORIGIN, ftStr},
120 {"Pragma", HDR_PRAGMA, ftStr},
121 {"Proxy-Authenticate", HDR_PROXY_AUTHENTICATE, ftStr},
122 {"Proxy-Authentication-Info", HDR_PROXY_AUTHENTICATION_INFO, ftStr},
123 {"Proxy-Authorization", HDR_PROXY_AUTHORIZATION, ftStr},
124 {"Proxy-Connection", HDR_PROXY_CONNECTION, ftStr},
125 {"Proxy-support", HDR_PROXY_SUPPORT, ftStr},
126 {"Public", HDR_PUBLIC, ftStr},
127 {"Range", HDR_RANGE, ftPRange},
128 {"Referer", HDR_REFERER, ftStr},
129 {"Request-Range", HDR_REQUEST_RANGE, ftPRange}, /* usually matches HDR_RANGE */
130 {"Retry-After", HDR_RETRY_AFTER, ftStr}, /* for now (ftDate_1123 or ftInt!) */
131 {"Server", HDR_SERVER, ftStr},
132 {"Set-Cookie", HDR_SET_COOKIE, ftStr},
133 {"Set-Cookie2", HDR_SET_COOKIE2, ftStr},
134 {"TE", HDR_TE, ftStr},
135 {"Title", HDR_TITLE, ftStr},
136 {"Trailer", HDR_TRAILER, ftStr},
137 {"Transfer-Encoding", HDR_TRANSFER_ENCODING, ftStr},
138 {"Translate", HDR_TRANSLATE, ftStr}, /* for now. may need to crop */
139 {"Unless-Modified-Since", HDR_UNLESS_MODIFIED_SINCE, ftStr}, /* for now ignore. may need to crop */
140 {"Upgrade", HDR_UPGRADE, ftStr}, /* for now */
141 {"User-Agent", HDR_USER_AGENT, ftStr},
142 {"Vary", HDR_VARY, ftStr}, /* for now */
143 {"Via", HDR_VIA, ftStr}, /* for now */
144 {"Warning", HDR_WARNING, ftStr}, /* for now */
145 {"WWW-Authenticate", HDR_WWW_AUTHENTICATE, ftStr},
146 {"Authentication-Info", HDR_AUTHENTICATION_INFO, ftStr},
147 {"X-Cache", HDR_X_CACHE, ftStr},
148 {"X-Cache-Lookup", HDR_X_CACHE_LOOKUP, ftStr},
149 {"X-Forwarded-For", HDR_X_FORWARDED_FOR, ftStr},
150 {"X-Request-URI", HDR_X_REQUEST_URI, ftStr},
151 {"X-Squid-Error", HDR_X_SQUID_ERROR, ftStr},
152 #if X_ACCELERATOR_VARY
153 {"X-Accelerator-Vary", HDR_X_ACCELERATOR_VARY, ftStr},
154 #endif
155 #if USE_ADAPTATION
156 {"X-Next-Services", HDR_X_NEXT_SERVICES, ftStr},
157 #endif
158 {"Surrogate-Capability", HDR_SURROGATE_CAPABILITY, ftStr},
159 {"Surrogate-Control", HDR_SURROGATE_CONTROL, ftPSc},
160 {"Front-End-Https", HDR_FRONT_END_HTTPS, ftStr},
161 {"Other:", HDR_OTHER, ftStr} /* ':' will not allow matches */
162 };
163
164 static HttpHeaderFieldInfo *Headers = NULL;
165
166 http_hdr_type &operator++ (http_hdr_type &aHeader)
167 {
168 int tmp = (int)aHeader;
169 aHeader = (http_hdr_type)(++tmp);
170 return aHeader;
171 }
172
173
174 /*
175 * headers with field values defined as #(values) in HTTP/1.1
176 * Headers that are currently not recognized, are commented out.
177 */
178 static HttpHeaderMask ListHeadersMask; /* set run-time using ListHeadersArr */
179 static http_hdr_type ListHeadersArr[] = {
180 HDR_ACCEPT,
181 HDR_ACCEPT_CHARSET, HDR_ACCEPT_ENCODING, HDR_ACCEPT_LANGUAGE,
182 HDR_ACCEPT_RANGES, HDR_ALLOW,
183 HDR_CACHE_CONTROL,
184 HDR_CONTENT_ENCODING,
185 HDR_CONTENT_LANGUAGE,
186 HDR_CONNECTION,
187 HDR_EXPECT,
188 HDR_IF_MATCH, HDR_IF_NONE_MATCH,
189 HDR_LINK, HDR_PRAGMA,
190 HDR_PROXY_CONNECTION,
191 HDR_PROXY_SUPPORT,
192 HDR_TRANSFER_ENCODING,
193 HDR_UPGRADE,
194 HDR_VARY,
195 HDR_VIA,
196 HDR_WARNING,
197 HDR_WWW_AUTHENTICATE,
198 HDR_AUTHENTICATION_INFO,
199 HDR_PROXY_AUTHENTICATION_INFO,
200 /* HDR_TE, HDR_TRAILER */
201 #if X_ACCELERATOR_VARY
202 HDR_X_ACCELERATOR_VARY,
203 #endif
204 #if USE_ADAPTATION
205 HDR_X_NEXT_SERVICES,
206 #endif
207 HDR_SURROGATE_CAPABILITY,
208 HDR_SURROGATE_CONTROL,
209 HDR_X_FORWARDED_FOR
210 };
211
212 /* general-headers */
213 static http_hdr_type GeneralHeadersArr[] = {
214 HDR_CACHE_CONTROL, HDR_CONNECTION, HDR_DATE, HDR_PRAGMA,
215 HDR_TRANSFER_ENCODING,
216 HDR_UPGRADE,
217 /* HDR_TRAILER, */
218 HDR_VIA,
219 };
220
221 /* entity-headers */
222 static http_hdr_type EntityHeadersArr[] = {
223 HDR_ALLOW, HDR_CONTENT_BASE, HDR_CONTENT_ENCODING, HDR_CONTENT_LANGUAGE,
224 HDR_CONTENT_LENGTH, HDR_CONTENT_LOCATION, HDR_CONTENT_MD5,
225 HDR_CONTENT_RANGE, HDR_CONTENT_TYPE, HDR_ETAG, HDR_EXPIRES, HDR_LAST_MODIFIED, HDR_LINK,
226 HDR_OTHER
227 };
228
229 static HttpHeaderMask ReplyHeadersMask; /* set run-time using ReplyHeaders */
230 static http_hdr_type ReplyHeadersArr[] = {
231 HDR_ACCEPT, HDR_ACCEPT_CHARSET, HDR_ACCEPT_ENCODING, HDR_ACCEPT_LANGUAGE,
232 HDR_ACCEPT_RANGES, HDR_AGE,
233 HDR_LOCATION, HDR_MAX_FORWARDS,
234 HDR_MIME_VERSION, HDR_PUBLIC, HDR_RETRY_AFTER, HDR_SERVER, HDR_SET_COOKIE, HDR_SET_COOKIE2,
235 HDR_ORIGIN,
236 HDR_VARY,
237 HDR_WARNING, HDR_PROXY_CONNECTION, HDR_X_CACHE,
238 HDR_X_CACHE_LOOKUP,
239 HDR_X_REQUEST_URI,
240 #if X_ACCELERATOR_VARY
241 HDR_X_ACCELERATOR_VARY,
242 #endif
243 #if USE_ADAPTATION
244 HDR_X_NEXT_SERVICES,
245 #endif
246 HDR_X_SQUID_ERROR,
247 HDR_SURROGATE_CONTROL
248 };
249
250 static HttpHeaderMask RequestHeadersMask; /* set run-time using RequestHeaders */
251 static http_hdr_type RequestHeadersArr[] = {
252 HDR_AUTHORIZATION, HDR_FROM, HDR_HOST,
253 HDR_IF_MATCH, HDR_IF_MODIFIED_SINCE, HDR_IF_NONE_MATCH,
254 HDR_IF_RANGE, HDR_MAX_FORWARDS,
255 HDR_ORIGIN,
256 HDR_PROXY_CONNECTION,
257 HDR_PROXY_AUTHORIZATION, HDR_RANGE, HDR_REFERER, HDR_REQUEST_RANGE,
258 HDR_USER_AGENT, HDR_X_FORWARDED_FOR, HDR_SURROGATE_CAPABILITY
259 };
260
261 static HttpHeaderMask HopByHopHeadersMask;
262 static http_hdr_type HopByHopHeadersArr[] = {
263 HDR_CONNECTION, HDR_KEEP_ALIVE, /*HDR_PROXY_AUTHENTICATE,*/ HDR_PROXY_AUTHORIZATION,
264 HDR_TE, HDR_TRAILER, HDR_TRANSFER_ENCODING, HDR_UPGRADE, HDR_PROXY_CONNECTION
265 };
266
267 /* header accounting */
268 static HttpHeaderStat HttpHeaderStats[] = {
269 {"all"},
270 #if USE_HTCP
271 {"HTCP reply"},
272 #endif
273 {"request"},
274 {"reply"}
275 };
276 static int HttpHeaderStatCount = countof(HttpHeaderStats);
277
278 static int HeaderEntryParsedCount = 0;
279
280 /*
281 * local routines
282 */
283
284 #define assert_eid(id) assert((id) >= 0 && (id) < HDR_ENUM_END)
285
286 static void httpHeaderNoteParsedEntry(http_hdr_type id, String const &value, int error);
287
288 static void httpHeaderStatInit(HttpHeaderStat * hs, const char *label);
289 static void httpHeaderStatDump(const HttpHeaderStat * hs, StoreEntry * e);
290
291 /*
292 * Module initialization routines
293 */
294
295 static void
296 httpHeaderRegisterWithCacheManager(void)
297 {
298 Mgr::RegisterAction("http_headers",
299 "HTTP Header Statistics",
300 httpHeaderStoreReport, 0, 1);
301 }
302
303 void
304 httpHeaderInitModule(void)
305 {
306 int i;
307 /* check that we have enough space for masks */
308 assert(8 * sizeof(HttpHeaderMask) >= HDR_ENUM_END);
309 /* all headers must be described */
310 assert(countof(HeadersAttrs) == HDR_ENUM_END);
311
312 if (!Headers)
313 Headers = httpHeaderBuildFieldsInfo(HeadersAttrs, HDR_ENUM_END);
314
315 /* create masks */
316 httpHeaderMaskInit(&ListHeadersMask, 0);
317
318 httpHeaderCalcMask(&ListHeadersMask, ListHeadersArr, countof(ListHeadersArr));
319
320 httpHeaderMaskInit(&ReplyHeadersMask, 0);
321
322 httpHeaderCalcMask(&ReplyHeadersMask, ReplyHeadersArr, countof(ReplyHeadersArr));
323
324 httpHeaderCalcMask(&ReplyHeadersMask, GeneralHeadersArr, countof(GeneralHeadersArr));
325
326 httpHeaderCalcMask(&ReplyHeadersMask, EntityHeadersArr, countof(EntityHeadersArr));
327
328 httpHeaderMaskInit(&RequestHeadersMask, 0);
329
330 httpHeaderCalcMask(&RequestHeadersMask, RequestHeadersArr, countof(RequestHeadersArr));
331
332 httpHeaderCalcMask(&RequestHeadersMask, GeneralHeadersArr, countof(GeneralHeadersArr));
333
334 httpHeaderCalcMask(&RequestHeadersMask, EntityHeadersArr, countof(EntityHeadersArr));
335
336 httpHeaderMaskInit(&HopByHopHeadersMask, 0);
337
338 httpHeaderCalcMask(&HopByHopHeadersMask, HopByHopHeadersArr, countof(HopByHopHeadersArr));
339
340 /* init header stats */
341 assert(HttpHeaderStatCount == hoReply + 1);
342
343 for (i = 0; i < HttpHeaderStatCount; i++)
344 httpHeaderStatInit(HttpHeaderStats + i, HttpHeaderStats[i].label);
345
346 HttpHeaderStats[hoRequest].owner_mask = &RequestHeadersMask;
347
348 HttpHeaderStats[hoReply].owner_mask = &ReplyHeadersMask;
349
350 #if USE_HTCP
351
352 HttpHeaderStats[hoHtcpReply].owner_mask = &ReplyHeadersMask;
353
354 #endif
355 /* init dependent modules */
356 httpHdrCcInitModule();
357
358 httpHdrScInitModule();
359
360 httpHeaderRegisterWithCacheManager();
361 }
362
363 void
364 httpHeaderCleanModule(void)
365 {
366 httpHeaderDestroyFieldsInfo(Headers, HDR_ENUM_END);
367 Headers = NULL;
368 httpHdrCcCleanModule();
369 httpHdrScCleanModule();
370 }
371
372 static void
373 httpHeaderStatInit(HttpHeaderStat * hs, const char *label)
374 {
375 assert(hs);
376 assert(label);
377 memset(hs, 0, sizeof(HttpHeaderStat));
378 hs->label = label;
379 hs->hdrUCountDistr.enumInit(32); /* not a real enum */
380 hs->fieldTypeDistr.enumInit(HDR_ENUM_END);
381 hs->ccTypeDistr.enumInit(CC_ENUM_END);
382 hs->scTypeDistr.enumInit(SC_ENUM_END);
383 }
384
385 /*
386 * HttpHeader Implementation
387 */
388
389 HttpHeader::HttpHeader() : owner (hoNone), len (0)
390 {
391 httpHeaderMaskInit(&mask, 0);
392 }
393
394 HttpHeader::HttpHeader(const http_hdr_owner_type anOwner): owner(anOwner), len(0)
395 {
396 assert(anOwner > hoNone && anOwner < hoEnd);
397 debugs(55, 7, "init-ing hdr: " << this << " owner: " << owner);
398 httpHeaderMaskInit(&mask, 0);
399 }
400
401 HttpHeader::HttpHeader(const HttpHeader &other): owner(other.owner), len(other.len)
402 {
403 httpHeaderMaskInit(&mask, 0);
404 update(&other, NULL); // will update the mask as well
405 }
406
407 HttpHeader::~HttpHeader()
408 {
409 clean();
410 }
411
412 HttpHeader &
413 HttpHeader::operator =(const HttpHeader &other)
414 {
415 if (this != &other) {
416 // we do not really care, but the caller probably does
417 assert(owner == other.owner);
418 clean();
419 update(&other, NULL); // will update the mask as well
420 len = other.len;
421 }
422 return *this;
423 }
424
425 void
426 HttpHeader::clean()
427 {
428 HttpHeaderPos pos = HttpHeaderInitPos;
429 HttpHeaderEntry *e;
430
431 assert(owner > hoNone && owner < hoEnd);
432 debugs(55, 7, "cleaning hdr: " << this << " owner: " << owner);
433
434 PROF_start(HttpHeaderClean);
435
436 /*
437 * An unfortunate bug. The entries array is initialized
438 * such that count is set to zero. httpHeaderClean() seems to
439 * be called both when 'hdr' is created, and destroyed. Thus,
440 * we accumulate a large number of zero counts for 'hdr' before
441 * it is ever used. Can't think of a good way to fix it, except
442 * adding a state variable that indicates whether or not 'hdr'
443 * has been used. As a hack, just never count zero-sized header
444 * arrays.
445 */
446
447 if (owner <= hoReply) {
448 if (0 != entries.count)
449 HttpHeaderStats[owner].hdrUCountDistr.count(entries.count);
450
451 HttpHeaderStats[owner].destroyedCount++;
452
453 HttpHeaderStats[owner].busyDestroyedCount += entries.count > 0;
454
455 while ((e = getEntry(&pos))) {
456 /* tmp hack to try to avoid coredumps */
457
458 if (e->id < 0 || e->id >= HDR_ENUM_END) {
459 debugs(55, 0, "HttpHeader::clean BUG: entry[" << pos << "] is invalid (" << e->id << "). Ignored.");
460 } else {
461 HttpHeaderStats[owner].fieldTypeDistr.count(e->id);
462 /* yes, this deletion leaves us in an inconsistent state */
463 delete e;
464 }
465 }
466 } // if (owner <= hoReply)
467 entries.clean();
468 httpHeaderMaskInit(&mask, 0);
469 len = 0;
470 PROF_stop(HttpHeaderClean);
471 }
472
473 /* append entries (also see httpHeaderUpdate) */
474 void
475 HttpHeader::append(const HttpHeader * src)
476 {
477 const HttpHeaderEntry *e;
478 HttpHeaderPos pos = HttpHeaderInitPos;
479 assert(src);
480 assert(src != this);
481 debugs(55, 7, "appending hdr: " << this << " += " << src);
482
483 while ((e = src->getEntry(&pos))) {
484 addEntry(e->clone());
485 }
486 }
487
488 /* use fresh entries to replace old ones */
489 void
490 httpHeaderUpdate(HttpHeader * old, const HttpHeader * fresh, const HttpHeaderMask * denied_mask)
491 {
492 assert (old);
493 old->update (fresh, denied_mask);
494 }
495
496 void
497 HttpHeader::update (HttpHeader const *fresh, HttpHeaderMask const *denied_mask)
498 {
499 const HttpHeaderEntry *e;
500 HttpHeaderPos pos = HttpHeaderInitPos;
501 assert(fresh);
502 assert(this != fresh);
503
504 while ((e = fresh->getEntry(&pos))) {
505 /* deny bad guys (ok to check for HDR_OTHER) here */
506
507 if (denied_mask && CBIT_TEST(*denied_mask, e->id))
508 continue;
509
510 if (e->id != HDR_OTHER)
511 delById(e->id);
512 else
513 delByName(e->name.termedBuf());
514 }
515
516 pos = HttpHeaderInitPos;
517 while ((e = fresh->getEntry(&pos))) {
518 /* deny bad guys (ok to check for HDR_OTHER) here */
519
520 if (denied_mask && CBIT_TEST(*denied_mask, e->id))
521 continue;
522
523 debugs(55, 7, "Updating header '" << HeadersAttrs[e->id].name << "' in cached entry");
524
525 addEntry(e->clone());
526 }
527 }
528
529 /* just handy in parsing: resets and returns false */
530 int
531 HttpHeader::reset()
532 {
533 clean();
534 return 0;
535 }
536
537 int
538 HttpHeader::parse(const char *header_start, const char *header_end)
539 {
540 const char *field_ptr = header_start;
541 HttpHeaderEntry *e, *e2;
542
543 PROF_start(HttpHeaderParse);
544
545 assert(header_start && header_end);
546 debugs(55, 7, "parsing hdr: (" << this << ")" << std::endl << getStringPrefix(header_start, header_end));
547 HttpHeaderStats[owner].parsedCount++;
548
549 char *nulpos;
550 if ((nulpos = (char*)memchr(header_start, '\0', header_end - header_start))) {
551 debugs(55, 1, "WARNING: HTTP header contains NULL characters {" <<
552 getStringPrefix(header_start, nulpos) << "}\nNULL\n{" << getStringPrefix(nulpos+1, header_end));
553 goto reset;
554 }
555
556 /* common format headers are "<name>:[ws]<value>" lines delimited by <CRLF>.
557 * continuation lines start with a (single) space or tab */
558 while (field_ptr < header_end) {
559 const char *field_start = field_ptr;
560 const char *field_end;
561
562 do {
563 const char *this_line = field_ptr;
564 field_ptr = (const char *)memchr(field_ptr, '\n', header_end - field_ptr);
565
566 if (!field_ptr)
567 goto reset; /* missing <LF> */
568
569 field_end = field_ptr;
570
571 field_ptr++; /* Move to next line */
572
573 if (field_end > this_line && field_end[-1] == '\r') {
574 field_end--; /* Ignore CR LF */
575
576 if (owner == hoRequest && field_end > this_line) {
577 bool cr_only = true;
578 for (const char *p = this_line; p < field_end && cr_only; ++p) {
579 if (*p != '\r')
580 cr_only = false;
581 }
582 if (cr_only) {
583 debugs(55, 1, "WARNING: Rejecting HTTP request with a CR+ "
584 "header field to prevent request smuggling attacks: {" <<
585 getStringPrefix(header_start, header_end) << "}");
586 goto reset;
587 }
588 }
589 }
590
591 /* Barf on stray CR characters */
592 if (memchr(this_line, '\r', field_end - this_line)) {
593 debugs(55, 1, "WARNING: suspicious CR characters in HTTP header {" <<
594 getStringPrefix(field_start, field_end) << "}");
595
596 if (Config.onoff.relaxed_header_parser) {
597 char *p = (char *) this_line; /* XXX Warning! This destroys original header content and violates specifications somewhat */
598
599 while ((p = (char *)memchr(p, '\r', field_end - p)) != NULL)
600 *p++ = ' ';
601 } else
602 goto reset;
603 }
604
605 if (this_line + 1 == field_end && this_line > field_start) {
606 debugs(55, 1, "WARNING: Blank continuation line in HTTP header {" <<
607 getStringPrefix(header_start, header_end) << "}");
608 goto reset;
609 }
610 } while (field_ptr < header_end && (*field_ptr == ' ' || *field_ptr == '\t'));
611
612 if (field_start == field_end) {
613 if (field_ptr < header_end) {
614 debugs(55, 1, "WARNING: unparseable HTTP header field near {" <<
615 getStringPrefix(field_start, header_end) << "}");
616 goto reset;
617 }
618
619 break; /* terminating blank line */
620 }
621
622 if ((e = HttpHeaderEntry::parse(field_start, field_end)) == NULL) {
623 debugs(55, 1, "WARNING: unparseable HTTP header field {" <<
624 getStringPrefix(field_start, field_end) << "}");
625 debugs(55, Config.onoff.relaxed_header_parser <= 0 ? 1 : 2,
626 " in {" << getStringPrefix(header_start, header_end) << "}");
627
628 if (Config.onoff.relaxed_header_parser)
629 continue;
630 else
631 goto reset;
632 }
633
634 if (e->id == HDR_CONTENT_LENGTH && (e2 = findEntry(e->id)) != NULL) {
635 // if (e->value.cmp(e2->value.termedBuf()) != 0) {
636 if (e->value != e2->value) {
637 int64_t l1, l2;
638 debugs(55, Config.onoff.relaxed_header_parser <= 0 ? 1 : 2,
639 "WARNING: found two conflicting content-length headers in {" << getStringPrefix(header_start, header_end) << "}");
640
641 if (!Config.onoff.relaxed_header_parser) {
642 delete e;
643 goto reset;
644 }
645
646 if (!httpHeaderParseOffset(e->value.termedBuf(), &l1)) {
647 debugs(55, 1, "WARNING: Unparseable content-length '" << e->value << "'");
648 delete e;
649 continue;
650 } else if (!httpHeaderParseOffset(e2->value.termedBuf(), &l2)) {
651 debugs(55, 1, "WARNING: Unparseable content-length '" << e2->value << "'");
652 delById(e2->id);
653 } else if (l1 > l2) {
654 delById(e2->id);
655 } else {
656 delete e;
657 continue;
658 }
659 } else {
660 debugs(55, Config.onoff.relaxed_header_parser <= 0 ? 1 : 2,
661 "NOTICE: found double content-length header");
662
663 if (Config.onoff.relaxed_header_parser) {
664 delete e;
665 continue;
666 } else {
667 delete e;
668 goto reset;
669 }
670 }
671 }
672
673 if (e->id == HDR_OTHER && stringHasWhitespace(e->name.termedBuf())) {
674 debugs(55, Config.onoff.relaxed_header_parser <= 0 ? 1 : 2,
675 "WARNING: found whitespace in HTTP header name {" <<
676 getStringPrefix(field_start, field_end) << "}");
677
678 if (!Config.onoff.relaxed_header_parser) {
679 delete e;
680 goto reset;
681 }
682 }
683
684 addEntry(e);
685 }
686
687 if (chunked()) {
688 // RFC 2616 section 4.4: ignore Content-Length with Transfer-Encoding
689 delById(HDR_CONTENT_LENGTH);
690 }
691
692 PROF_stop(HttpHeaderParse);
693 return 1; /* even if no fields where found, it is a valid header */
694 reset:
695 PROF_stop(HttpHeaderParse);
696 return reset();
697 }
698
699 /* packs all the entries using supplied packer */
700 void
701 HttpHeader::packInto(Packer * p) const
702 {
703 HttpHeaderPos pos = HttpHeaderInitPos;
704 const HttpHeaderEntry *e;
705 assert(p);
706 debugs(55, 7, "packing hdr: (" << this << ")");
707 /* pack all entries one by one */
708 while ((e = getEntry(&pos)))
709 e->packInto(p);
710
711 /* Pack in the "special" entries */
712
713 /* Cache-Control */
714 }
715
716 /* returns next valid entry */
717 HttpHeaderEntry *
718 HttpHeader::getEntry(HttpHeaderPos * pos) const
719 {
720 assert(pos);
721 assert(*pos >= HttpHeaderInitPos && *pos < (ssize_t)entries.count);
722
723 for ((*pos)++; *pos < (ssize_t)entries.count; (*pos)++) {
724 if (entries.items[*pos])
725 return (HttpHeaderEntry*)entries.items[*pos];
726 }
727
728 return NULL;
729 }
730
731 /*
732 * returns a pointer to a specified entry if any
733 * note that we return one entry so it does not make much sense to ask for
734 * "list" headers
735 */
736 HttpHeaderEntry *
737 HttpHeader::findEntry(http_hdr_type id) const
738 {
739 HttpHeaderPos pos = HttpHeaderInitPos;
740 HttpHeaderEntry *e;
741 assert_eid(id);
742 assert(!CBIT_TEST(ListHeadersMask, id));
743
744 /* check mask first */
745
746 if (!CBIT_TEST(mask, id))
747 return NULL;
748
749 /* looks like we must have it, do linear search */
750 while ((e = getEntry(&pos))) {
751 if (e->id == id)
752 return e;
753 }
754
755 /* hm.. we thought it was there, but it was not found */
756 assert(0);
757
758 return NULL; /* not reached */
759 }
760
761 /*
762 * same as httpHeaderFindEntry
763 */
764 HttpHeaderEntry *
765 HttpHeader::findLastEntry(http_hdr_type id) const
766 {
767 HttpHeaderPos pos = HttpHeaderInitPos;
768 HttpHeaderEntry *e;
769 HttpHeaderEntry *result = NULL;
770 assert_eid(id);
771 assert(!CBIT_TEST(ListHeadersMask, id));
772
773 /* check mask first */
774
775 if (!CBIT_TEST(mask, id))
776 return NULL;
777
778 /* looks like we must have it, do linear search */
779 while ((e = getEntry(&pos))) {
780 if (e->id == id)
781 result = e;
782 }
783
784 assert(result); /* must be there! */
785 return result;
786 }
787
788 /*
789 * deletes all fields with a given name if any, returns #fields deleted;
790 */
791 int
792 HttpHeader::delByName(const char *name)
793 {
794 int count = 0;
795 HttpHeaderPos pos = HttpHeaderInitPos;
796 HttpHeaderEntry *e;
797 httpHeaderMaskInit(&mask, 0); /* temporal inconsistency */
798 debugs(55, 9, "deleting '" << name << "' fields in hdr " << this);
799
800 while ((e = getEntry(&pos))) {
801 if (!e->name.caseCmp(name))
802 delAt(pos, count);
803 else
804 CBIT_SET(mask, e->id);
805 }
806
807 return count;
808 }
809
810 /* deletes all entries with a given id, returns the #entries deleted */
811 int
812 HttpHeader::delById(http_hdr_type id)
813 {
814 int count = 0;
815 HttpHeaderPos pos = HttpHeaderInitPos;
816 HttpHeaderEntry *e;
817 debugs(55, 8, this << " del-by-id " << id);
818 assert_eid(id);
819 assert(id != HDR_OTHER); /* does not make sense */
820
821 if (!CBIT_TEST(mask, id))
822 return 0;
823
824 while ((e = getEntry(&pos))) {
825 if (e->id == id)
826 delAt(pos, count);
827 }
828
829 CBIT_CLR(mask, id);
830 assert(count);
831 return count;
832 }
833
834 /*
835 * deletes an entry at pos and leaves a gap; leaving a gap makes it
836 * possible to iterate(search) and delete fields at the same time
837 * NOTE: Does not update the header mask. Caller must follow up with
838 * a call to refreshMask() if headers_deleted was incremented.
839 */
840 void
841 HttpHeader::delAt(HttpHeaderPos pos, int &headers_deleted)
842 {
843 HttpHeaderEntry *e;
844 assert(pos >= HttpHeaderInitPos && pos < (ssize_t)entries.count);
845 e = (HttpHeaderEntry*)entries.items[pos];
846 entries.items[pos] = NULL;
847 /* decrement header length, allow for ": " and crlf */
848 len -= e->name.size() + 2 + e->value.size() + 2;
849 assert(len >= 0);
850 delete e;
851 ++headers_deleted;
852 }
853
854 /*
855 * Compacts the header storage
856 */
857 void
858 HttpHeader::compact()
859 {
860 entries.prune(NULL);
861 }
862
863 /*
864 * Refreshes the header mask. Required after delAt() calls.
865 */
866 void
867 HttpHeader::refreshMask()
868 {
869 httpHeaderMaskInit(&mask, 0);
870 debugs(55, 7, "refreshing the mask in hdr " << this);
871 HttpHeaderPos pos = HttpHeaderInitPos;
872 while (HttpHeaderEntry *e = getEntry(&pos)) {
873 CBIT_SET(mask, e->id);
874 }
875 }
876
877 /* appends an entry;
878 * does not call e->clone() so one should not reuse "*e"
879 */
880 void
881 HttpHeader::addEntry(HttpHeaderEntry * e)
882 {
883 assert(e);
884 assert_eid(e->id);
885 assert(e->name.size());
886
887 debugs(55, 7, HERE << this << " adding entry: " << e->id << " at " << entries.count);
888
889 if (CBIT_TEST(mask, e->id))
890 Headers[e->id].stat.repCount++;
891 else
892 CBIT_SET(mask, e->id);
893
894 entries.push_back(e);
895
896 /* increment header length, allow for ": " and crlf */
897 len += e->name.size() + 2 + e->value.size() + 2;
898 }
899
900 /* inserts an entry;
901 * does not call e->clone() so one should not reuse "*e"
902 */
903 void
904 HttpHeader::insertEntry(HttpHeaderEntry * e)
905 {
906 assert(e);
907 assert_eid(e->id);
908
909 debugs(55, 7, HERE << this << " adding entry: " << e->id << " at " << entries.count);
910
911 if (CBIT_TEST(mask, e->id))
912 Headers[e->id].stat.repCount++;
913 else
914 CBIT_SET(mask, e->id);
915
916 entries.insert(e);
917
918 /* increment header length, allow for ": " and crlf */
919 len += e->name.size() + 2 + e->value.size() + 2;
920 }
921
922 bool
923 HttpHeader::getList(http_hdr_type id, String *s) const
924 {
925 HttpHeaderEntry *e;
926 HttpHeaderPos pos = HttpHeaderInitPos;
927 debugs(55, 9, this << " joining for id " << id);
928 /* only fields from ListHeaders array can be "listed" */
929 assert(CBIT_TEST(ListHeadersMask, id));
930
931 if (!CBIT_TEST(mask, id))
932 return false;
933
934 while ((e = getEntry(&pos))) {
935 if (e->id == id)
936 strListAdd(s, e->value.termedBuf(), ',');
937 }
938
939 /*
940 * note: we might get an empty (size==0) string if there was an "empty"
941 * header. This results in an empty length String, which may have a NULL
942 * buffer.
943 */
944 /* temporary warning: remove it? (Is it useful for diagnostics ?) */
945 if (!s->size())
946 debugs(55, 3, "empty list header: " << Headers[id].name << "(" << id << ")");
947 else
948 debugs(55, 6, this << ": joined for id " << id << ": " << s);
949
950 return true;
951 }
952
953 /* return a list of entries with the same id separated by ',' and ws */
954 String
955 HttpHeader::getList(http_hdr_type id) const
956 {
957 HttpHeaderEntry *e;
958 HttpHeaderPos pos = HttpHeaderInitPos;
959 debugs(55, 9, this << "joining for id " << id);
960 /* only fields from ListHeaders array can be "listed" */
961 assert(CBIT_TEST(ListHeadersMask, id));
962
963 if (!CBIT_TEST(mask, id))
964 return String();
965
966 String s;
967
968 while ((e = getEntry(&pos))) {
969 if (e->id == id)
970 strListAdd(&s, e->value.termedBuf(), ',');
971 }
972
973 /*
974 * note: we might get an empty (size==0) string if there was an "empty"
975 * header. This results in an empty length String, which may have a NULL
976 * buffer.
977 */
978 /* temporary warning: remove it? (Is it useful for diagnostics ?) */
979 if (!s.size())
980 debugs(55, 3, "empty list header: " << Headers[id].name << "(" << id << ")");
981 else
982 debugs(55, 6, this << ": joined for id " << id << ": " << s);
983
984 return s;
985 }
986
987 /* return a string or list of entries with the same id separated by ',' and ws */
988 String
989 HttpHeader::getStrOrList(http_hdr_type id) const
990 {
991 HttpHeaderEntry *e;
992
993 if (CBIT_TEST(ListHeadersMask, id))
994 return getList(id);
995
996 if ((e = findEntry(id)))
997 return e->value;
998
999 return String();
1000 }
1001
1002 /*
1003 * Returns the value of the specified header.
1004 */
1005 String
1006 HttpHeader::getByName(const char *name) const
1007 {
1008 http_hdr_type id;
1009 HttpHeaderPos pos = HttpHeaderInitPos;
1010 HttpHeaderEntry *e;
1011
1012 assert(name);
1013
1014 /* First try the quick path */
1015 id = httpHeaderIdByNameDef(name, strlen(name));
1016
1017 if (id != -1)
1018 return getStrOrList(id);
1019
1020 String result;
1021
1022 /* Sorry, an unknown header name. Do linear search */
1023 while ((e = getEntry(&pos))) {
1024 if (e->id == HDR_OTHER && e->name.caseCmp(name) == 0) {
1025 strListAdd(&result, e->value.termedBuf(), ',');
1026 }
1027 }
1028
1029 return result;
1030 }
1031
1032 /*
1033 * Returns a the value of the specified list member, if any.
1034 */
1035 String
1036 HttpHeader::getByNameListMember(const char *name, const char *member, const char separator) const
1037 {
1038 String header;
1039 const char *pos = NULL;
1040 const char *item;
1041 int ilen;
1042 int mlen = strlen(member);
1043
1044 assert(name);
1045
1046 header = getByName(name);
1047
1048 String result;
1049
1050 while (strListGetItem(&header, separator, &item, &ilen, &pos)) {
1051 if (strncmp(item, member, mlen) == 0 && item[mlen] == '=') {
1052 result.append(item + mlen + 1, ilen - mlen - 1);
1053 break;
1054 }
1055 }
1056
1057 return result;
1058 }
1059
1060 /*
1061 * returns a the value of the specified list member, if any.
1062 */
1063 String
1064 HttpHeader::getListMember(http_hdr_type id, const char *member, const char separator) const
1065 {
1066 String header;
1067 const char *pos = NULL;
1068 const char *item;
1069 int ilen;
1070 int mlen = strlen(member);
1071
1072 assert(id >= 0);
1073
1074 header = getStrOrList(id);
1075 String result;
1076
1077 while (strListGetItem(&header, separator, &item, &ilen, &pos)) {
1078 if (strncmp(item, member, mlen) == 0 && item[mlen] == '=') {
1079 result.append(item + mlen + 1, ilen - mlen - 1);
1080 break;
1081 }
1082 }
1083
1084 header.clean();
1085 return result;
1086 }
1087
1088 /* test if a field is present */
1089 int
1090 HttpHeader::has(http_hdr_type id) const
1091 {
1092 assert_eid(id);
1093 assert(id != HDR_OTHER);
1094 debugs(55, 9, this << " lookup for " << id);
1095 return CBIT_TEST(mask, id);
1096 }
1097
1098 void
1099 HttpHeader::putInt(http_hdr_type id, int number)
1100 {
1101 assert_eid(id);
1102 assert(Headers[id].type == ftInt); /* must be of an appropriate type */
1103 assert(number >= 0);
1104 addEntry(new HttpHeaderEntry(id, NULL, xitoa(number)));
1105 }
1106
1107 void
1108 HttpHeader::putInt64(http_hdr_type id, int64_t number)
1109 {
1110 assert_eid(id);
1111 assert(Headers[id].type == ftInt64); /* must be of an appropriate type */
1112 assert(number >= 0);
1113 addEntry(new HttpHeaderEntry(id, NULL, xint64toa(number)));
1114 }
1115
1116 void
1117 HttpHeader::putTime(http_hdr_type id, time_t htime)
1118 {
1119 assert_eid(id);
1120 assert(Headers[id].type == ftDate_1123); /* must be of an appropriate type */
1121 assert(htime >= 0);
1122 addEntry(new HttpHeaderEntry(id, NULL, mkrfc1123(htime)));
1123 }
1124
1125 void
1126 HttpHeader::insertTime(http_hdr_type id, time_t htime)
1127 {
1128 assert_eid(id);
1129 assert(Headers[id].type == ftDate_1123); /* must be of an appropriate type */
1130 assert(htime >= 0);
1131 insertEntry(new HttpHeaderEntry(id, NULL, mkrfc1123(htime)));
1132 }
1133
1134 void
1135 HttpHeader::putStr(http_hdr_type id, const char *str)
1136 {
1137 assert_eid(id);
1138 assert(Headers[id].type == ftStr); /* must be of an appropriate type */
1139 assert(str);
1140 addEntry(new HttpHeaderEntry(id, NULL, str));
1141 }
1142
1143 void
1144 HttpHeader::putAuth(const char *auth_scheme, const char *realm)
1145 {
1146 assert(auth_scheme && realm);
1147 httpHeaderPutStrf(this, HDR_WWW_AUTHENTICATE, "%s realm=\"%s\"", auth_scheme, realm);
1148 }
1149
1150 void
1151 HttpHeader::putCc(const HttpHdrCc * cc)
1152 {
1153 MemBuf mb;
1154 Packer p;
1155 assert(cc);
1156 /* remove old directives if any */
1157 delById(HDR_CACHE_CONTROL);
1158 /* pack into mb */
1159 mb.init();
1160 packerToMemInit(&p, &mb);
1161 cc->packInto(&p);
1162 /* put */
1163 addEntry(new HttpHeaderEntry(HDR_CACHE_CONTROL, NULL, mb.buf));
1164 /* cleanup */
1165 packerClean(&p);
1166 mb.clean();
1167 }
1168
1169 void
1170 HttpHeader::putContRange(const HttpHdrContRange * cr)
1171 {
1172 MemBuf mb;
1173 Packer p;
1174 assert(cr);
1175 /* remove old directives if any */
1176 delById(HDR_CONTENT_RANGE);
1177 /* pack into mb */
1178 mb.init();
1179 packerToMemInit(&p, &mb);
1180 httpHdrContRangePackInto(cr, &p);
1181 /* put */
1182 addEntry(new HttpHeaderEntry(HDR_CONTENT_RANGE, NULL, mb.buf));
1183 /* cleanup */
1184 packerClean(&p);
1185 mb.clean();
1186 }
1187
1188 void
1189 HttpHeader::putRange(const HttpHdrRange * range)
1190 {
1191 MemBuf mb;
1192 Packer p;
1193 assert(range);
1194 /* remove old directives if any */
1195 delById(HDR_RANGE);
1196 /* pack into mb */
1197 mb.init();
1198 packerToMemInit(&p, &mb);
1199 range->packInto(&p);
1200 /* put */
1201 addEntry(new HttpHeaderEntry(HDR_RANGE, NULL, mb.buf));
1202 /* cleanup */
1203 packerClean(&p);
1204 mb.clean();
1205 }
1206
1207 void
1208 HttpHeader::putSc(HttpHdrSc *sc)
1209 {
1210 MemBuf mb;
1211 Packer p;
1212 assert(sc);
1213 /* remove old directives if any */
1214 delById(HDR_SURROGATE_CONTROL);
1215 /* pack into mb */
1216 mb.init();
1217 packerToMemInit(&p, &mb);
1218 sc->packInto(&p);
1219 /* put */
1220 addEntry(new HttpHeaderEntry(HDR_SURROGATE_CONTROL, NULL, mb.buf));
1221 /* cleanup */
1222 packerClean(&p);
1223 mb.clean();
1224 }
1225
1226 void
1227 HttpHeader::putWarning(const int code, const char *const text)
1228 {
1229 char buf[512];
1230 snprintf(buf, sizeof(buf), "%i %s \"%s\"", code, visible_appname_string, text);
1231 putStr(HDR_WARNING, buf);
1232 }
1233
1234 /* add extension header (these fields are not parsed/analyzed/joined, etc.) */
1235 void
1236 HttpHeader::putExt(const char *name, const char *value)
1237 {
1238 assert(name && value);
1239 debugs(55, 8, this << " adds ext entry " << name << " : " << value);
1240 addEntry(new HttpHeaderEntry(HDR_OTHER, name, value));
1241 }
1242
1243 int
1244 HttpHeader::getInt(http_hdr_type id) const
1245 {
1246 assert_eid(id);
1247 assert(Headers[id].type == ftInt); /* must be of an appropriate type */
1248 HttpHeaderEntry *e;
1249
1250 if ((e = findEntry(id)))
1251 return e->getInt();
1252
1253 return -1;
1254 }
1255
1256 int64_t
1257 HttpHeader::getInt64(http_hdr_type id) const
1258 {
1259 assert_eid(id);
1260 assert(Headers[id].type == ftInt64); /* must be of an appropriate type */
1261 HttpHeaderEntry *e;
1262
1263 if ((e = findEntry(id)))
1264 return e->getInt64();
1265
1266 return -1;
1267 }
1268
1269 time_t
1270 HttpHeader::getTime(http_hdr_type id) const
1271 {
1272 HttpHeaderEntry *e;
1273 time_t value = -1;
1274 assert_eid(id);
1275 assert(Headers[id].type == ftDate_1123); /* must be of an appropriate type */
1276
1277 if ((e = findEntry(id))) {
1278 value = parse_rfc1123(e->value.termedBuf());
1279 httpHeaderNoteParsedEntry(e->id, e->value, value < 0);
1280 }
1281
1282 return value;
1283 }
1284
1285 /* sync with httpHeaderGetLastStr */
1286 const char *
1287 HttpHeader::getStr(http_hdr_type id) const
1288 {
1289 HttpHeaderEntry *e;
1290 assert_eid(id);
1291 assert(Headers[id].type == ftStr); /* must be of an appropriate type */
1292
1293 if ((e = findEntry(id))) {
1294 httpHeaderNoteParsedEntry(e->id, e->value, 0); /* no errors are possible */
1295 return e->value.termedBuf();
1296 }
1297
1298 return NULL;
1299 }
1300
1301 /* unusual */
1302 const char *
1303 HttpHeader::getLastStr(http_hdr_type id) const
1304 {
1305 HttpHeaderEntry *e;
1306 assert_eid(id);
1307 assert(Headers[id].type == ftStr); /* must be of an appropriate type */
1308
1309 if ((e = findLastEntry(id))) {
1310 httpHeaderNoteParsedEntry(e->id, e->value, 0); /* no errors are possible */
1311 return e->value.termedBuf();
1312 }
1313
1314 return NULL;
1315 }
1316
1317 HttpHdrCc *
1318 HttpHeader::getCc() const
1319 {
1320 if (!CBIT_TEST(mask, HDR_CACHE_CONTROL))
1321 return NULL;
1322 PROF_start(HttpHeader_getCc);
1323
1324 String s;
1325 getList(HDR_CACHE_CONTROL, &s);
1326
1327 HttpHdrCc *cc=new HttpHdrCc();
1328
1329 if (!cc->parse(s)) {
1330 delete cc;
1331 cc = NULL;
1332 }
1333
1334 HttpHeaderStats[owner].ccParsedCount++;
1335
1336 if (cc)
1337 httpHdrCcUpdateStats(cc, &HttpHeaderStats[owner].ccTypeDistr);
1338
1339 httpHeaderNoteParsedEntry(HDR_CACHE_CONTROL, s, !cc);
1340
1341 PROF_stop(HttpHeader_getCc);
1342
1343 return cc;
1344 }
1345
1346 HttpHdrRange *
1347 HttpHeader::getRange() const
1348 {
1349 HttpHdrRange *r = NULL;
1350 HttpHeaderEntry *e;
1351 /* some clients will send "Request-Range" _and_ *matching* "Range"
1352 * who knows, some clients might send Request-Range only;
1353 * this "if" should work correctly in both cases;
1354 * hopefully no clients send mismatched headers! */
1355
1356 if ((e = findEntry(HDR_RANGE)) ||
1357 (e = findEntry(HDR_REQUEST_RANGE))) {
1358 r = HttpHdrRange::ParseCreate(&e->value);
1359 httpHeaderNoteParsedEntry(e->id, e->value, !r);
1360 }
1361
1362 return r;
1363 }
1364
1365 HttpHdrSc *
1366 HttpHeader::getSc() const
1367 {
1368 if (!CBIT_TEST(mask, HDR_SURROGATE_CONTROL))
1369 return NULL;
1370
1371 String s;
1372
1373 (void) getList(HDR_SURROGATE_CONTROL, &s);
1374
1375 HttpHdrSc *sc = httpHdrScParseCreate(s);
1376
1377 ++HttpHeaderStats[owner].ccParsedCount;
1378
1379 if (sc)
1380 sc->updateStats(&HttpHeaderStats[owner].scTypeDistr);
1381
1382 httpHeaderNoteParsedEntry(HDR_SURROGATE_CONTROL, s, !sc);
1383
1384 return sc;
1385 }
1386
1387 HttpHdrContRange *
1388 HttpHeader::getContRange() const
1389 {
1390 HttpHdrContRange *cr = NULL;
1391 HttpHeaderEntry *e;
1392
1393 if ((e = findEntry(HDR_CONTENT_RANGE))) {
1394 cr = httpHdrContRangeParseCreate(e->value.termedBuf());
1395 httpHeaderNoteParsedEntry(e->id, e->value, !cr);
1396 }
1397
1398 return cr;
1399 }
1400
1401 const char *
1402 HttpHeader::getAuth(http_hdr_type id, const char *auth_scheme) const
1403 {
1404 const char *field;
1405 int l;
1406 assert(auth_scheme);
1407 field = getStr(id);
1408
1409 if (!field) /* no authorization field */
1410 return NULL;
1411
1412 l = strlen(auth_scheme);
1413
1414 if (!l || strncasecmp(field, auth_scheme, l)) /* wrong scheme */
1415 return NULL;
1416
1417 field += l;
1418
1419 if (!xisspace(*field)) /* wrong scheme */
1420 return NULL;
1421
1422 /* skip white space */
1423 field += xcountws(field);
1424
1425 if (!*field) /* no authorization cookie */
1426 return NULL;
1427
1428 static char decodedAuthToken[8192];
1429 const int decodedLen = base64_decode(decodedAuthToken, sizeof(decodedAuthToken)-1, field);
1430 decodedAuthToken[decodedLen] = '\0';
1431 return decodedAuthToken;
1432 }
1433
1434 ETag
1435 HttpHeader::getETag(http_hdr_type id) const
1436 {
1437 ETag etag = {NULL, -1};
1438 HttpHeaderEntry *e;
1439 assert(Headers[id].type == ftETag); /* must be of an appropriate type */
1440
1441 if ((e = findEntry(id)))
1442 etagParseInit(&etag, e->value.termedBuf());
1443
1444 return etag;
1445 }
1446
1447 TimeOrTag
1448 HttpHeader::getTimeOrTag(http_hdr_type id) const
1449 {
1450 TimeOrTag tot;
1451 HttpHeaderEntry *e;
1452 assert(Headers[id].type == ftDate_1123_or_ETag); /* must be of an appropriate type */
1453 memset(&tot, 0, sizeof(tot));
1454
1455 if ((e = findEntry(id))) {
1456 const char *str = e->value.termedBuf();
1457 /* try as an ETag */
1458
1459 if (etagParseInit(&tot.tag, str)) {
1460 tot.valid = tot.tag.str != NULL;
1461 tot.time = -1;
1462 } else {
1463 /* or maybe it is time? */
1464 tot.time = parse_rfc1123(str);
1465 tot.valid = tot.time >= 0;
1466 tot.tag.str = NULL;
1467 }
1468 }
1469
1470 assert(tot.time < 0 || !tot.tag.str); /* paranoid */
1471 return tot;
1472 }
1473
1474 /*
1475 * HttpHeaderEntry
1476 */
1477
1478 HttpHeaderEntry::HttpHeaderEntry(http_hdr_type anId, const char *aName, const char *aValue)
1479 {
1480 assert_eid(anId);
1481 id = anId;
1482
1483 if (id != HDR_OTHER)
1484 name = Headers[id].name;
1485 else
1486 name = aName;
1487
1488 value = aValue;
1489
1490 Headers[id].stat.aliveCount++;
1491
1492 debugs(55, 9, "created HttpHeaderEntry " << this << ": '" << name << " : " << value );
1493 }
1494
1495 HttpHeaderEntry::~HttpHeaderEntry()
1496 {
1497 assert_eid(id);
1498 debugs(55, 9, "destroying entry " << this << ": '" << name << ": " << value << "'");
1499 /* clean name if needed */
1500
1501 if (id == HDR_OTHER)
1502 name.clean();
1503
1504 value.clean();
1505
1506 assert(Headers[id].stat.aliveCount);
1507
1508 Headers[id].stat.aliveCount--;
1509
1510 id = HDR_BAD_HDR;
1511 }
1512
1513 /* parses and inits header entry, returns true/false */
1514 HttpHeaderEntry *
1515 HttpHeaderEntry::parse(const char *field_start, const char *field_end)
1516 {
1517 /* note: name_start == field_start */
1518 const char *name_end = (const char *)memchr(field_start, ':', field_end - field_start);
1519 int name_len = name_end ? name_end - field_start :0;
1520 const char *value_start = field_start + name_len + 1; /* skip ':' */
1521 /* note: value_end == field_end */
1522
1523 HeaderEntryParsedCount++;
1524
1525 /* do we have a valid field name within this field? */
1526
1527 if (!name_len || name_end > field_end)
1528 return NULL;
1529
1530 if (name_len > 65534) {
1531 /* String must be LESS THAN 64K and it adds a terminating NULL */
1532 debugs(55, 1, "WARNING: ignoring header name of " << name_len << " bytes");
1533 return NULL;
1534 }
1535
1536 if (Config.onoff.relaxed_header_parser && xisspace(field_start[name_len - 1])) {
1537 debugs(55, Config.onoff.relaxed_header_parser <= 0 ? 1 : 2,
1538 "NOTICE: Whitespace after header name in '" << getStringPrefix(field_start, field_end) << "'");
1539
1540 while (name_len > 0 && xisspace(field_start[name_len - 1]))
1541 name_len--;
1542
1543 if (!name_len)
1544 return NULL;
1545 }
1546
1547 /* now we know we can parse it */
1548
1549 debugs(55, 9, "parsing HttpHeaderEntry: near '" << getStringPrefix(field_start, field_end) << "'");
1550
1551 /* is it a "known" field? */
1552 http_hdr_type id = httpHeaderIdByName(field_start, name_len, Headers, HDR_ENUM_END);
1553
1554 String name;
1555
1556 String value;
1557
1558 if (id < 0)
1559 id = HDR_OTHER;
1560
1561 assert_eid(id);
1562
1563 /* set field name */
1564 if (id == HDR_OTHER)
1565 name.limitInit(field_start, name_len);
1566 else
1567 name = Headers[id].name;
1568
1569 /* trim field value */
1570 while (value_start < field_end && xisspace(*value_start))
1571 value_start++;
1572
1573 while (value_start < field_end && xisspace(field_end[-1]))
1574 field_end--;
1575
1576 if (field_end - value_start > 65534) {
1577 /* String must be LESS THAN 64K and it adds a terminating NULL */
1578 debugs(55, 1, "WARNING: ignoring '" << name << "' header of " << (field_end - value_start) << " bytes");
1579
1580 if (id == HDR_OTHER)
1581 name.clean();
1582
1583 return NULL;
1584 }
1585
1586 /* set field value */
1587 value.limitInit(value_start, field_end - value_start);
1588
1589 Headers[id].stat.seenCount++;
1590
1591 debugs(55, 9, "parsed HttpHeaderEntry: '" << name << ": " << value << "'");
1592
1593 return new HttpHeaderEntry(id, name.termedBuf(), value.termedBuf());
1594 }
1595
1596 HttpHeaderEntry *
1597 HttpHeaderEntry::clone() const
1598 {
1599 return new HttpHeaderEntry(id, name.termedBuf(), value.termedBuf());
1600 }
1601
1602 void
1603 HttpHeaderEntry::packInto(Packer * p) const
1604 {
1605 assert(p);
1606 packerAppend(p, name.rawBuf(), name.size());
1607 packerAppend(p, ": ", 2);
1608 packerAppend(p, value.rawBuf(), value.size());
1609 packerAppend(p, "\r\n", 2);
1610 }
1611
1612 int
1613 HttpHeaderEntry::getInt() const
1614 {
1615 assert_eid (id);
1616 assert (Headers[id].type == ftInt);
1617 int val = -1;
1618 int ok = httpHeaderParseInt(value.termedBuf(), &val);
1619 httpHeaderNoteParsedEntry(id, value, !ok);
1620 /* XXX: Should we check ok - ie
1621 * return ok ? -1 : value;
1622 */
1623 return val;
1624 }
1625
1626 int64_t
1627 HttpHeaderEntry::getInt64() const
1628 {
1629 assert_eid (id);
1630 assert (Headers[id].type == ftInt64);
1631 int64_t val = -1;
1632 int ok = httpHeaderParseOffset(value.termedBuf(), &val);
1633 httpHeaderNoteParsedEntry(id, value, !ok);
1634 /* XXX: Should we check ok - ie
1635 * return ok ? -1 : value;
1636 */
1637 return val;
1638 }
1639
1640 static void
1641 httpHeaderNoteParsedEntry(http_hdr_type id, String const &context, int error)
1642 {
1643 Headers[id].stat.parsCount++;
1644
1645 if (error) {
1646 Headers[id].stat.errCount++;
1647 debugs(55, 2, "cannot parse hdr field: '" << Headers[id].name << ": " << context << "'");
1648 }
1649 }
1650
1651 /*
1652 * Reports
1653 */
1654
1655 /* tmp variable used to pass stat info to dumpers */
1656 extern const HttpHeaderStat *dump_stat; /* argh! */
1657 const HttpHeaderStat *dump_stat = NULL;
1658
1659 void
1660 httpHeaderFieldStatDumper(StoreEntry * sentry, int idx, double val, double size, int count)
1661 {
1662 const int id = (int) val;
1663 const int valid_id = id >= 0 && id < HDR_ENUM_END;
1664 const char *name = valid_id ? Headers[id].name.termedBuf() : "INVALID";
1665 int visible = count > 0;
1666 /* for entries with zero count, list only those that belong to current type of message */
1667
1668 if (!visible && valid_id && dump_stat->owner_mask)
1669 visible = CBIT_TEST(*dump_stat->owner_mask, id);
1670
1671 if (visible)
1672 storeAppendPrintf(sentry, "%2d\t %-20s\t %5d\t %6.2f\n",
1673 id, name, count, xdiv(count, dump_stat->busyDestroyedCount));
1674 }
1675
1676 static void
1677 httpHeaderFldsPerHdrDumper(StoreEntry * sentry, int idx, double val, double size, int count)
1678 {
1679 if (count)
1680 storeAppendPrintf(sentry, "%2d\t %5d\t %5d\t %6.2f\n",
1681 idx, (int) val, count,
1682 xpercent(count, dump_stat->destroyedCount));
1683 }
1684
1685
1686 static void
1687 httpHeaderStatDump(const HttpHeaderStat * hs, StoreEntry * e)
1688 {
1689 assert(hs && e);
1690
1691 dump_stat = hs;
1692 storeAppendPrintf(e, "\nHeader Stats: %s\n", hs->label);
1693 storeAppendPrintf(e, "\nField type distribution\n");
1694 storeAppendPrintf(e, "%2s\t %-20s\t %5s\t %6s\n",
1695 "id", "name", "count", "#/header");
1696 hs->fieldTypeDistr.dump(e, httpHeaderFieldStatDumper);
1697 storeAppendPrintf(e, "\nCache-control directives distribution\n");
1698 storeAppendPrintf(e, "%2s\t %-20s\t %5s\t %6s\n",
1699 "id", "name", "count", "#/cc_field");
1700 hs->ccTypeDistr.dump(e, httpHdrCcStatDumper);
1701 storeAppendPrintf(e, "\nSurrogate-control directives distribution\n");
1702 storeAppendPrintf(e, "%2s\t %-20s\t %5s\t %6s\n",
1703 "id", "name", "count", "#/sc_field");
1704 hs->scTypeDistr.dump(e, httpHdrScStatDumper);
1705 storeAppendPrintf(e, "\nNumber of fields per header distribution\n");
1706 storeAppendPrintf(e, "%2s\t %-5s\t %5s\t %6s\n",
1707 "id", "#flds", "count", "%total");
1708 hs->hdrUCountDistr.dump(e, httpHeaderFldsPerHdrDumper);
1709 dump_stat = NULL;
1710 }
1711
1712 void
1713 httpHeaderStoreReport(StoreEntry * e)
1714 {
1715 int i;
1716 http_hdr_type ht;
1717 assert(e);
1718
1719 HttpHeaderStats[0].parsedCount =
1720 HttpHeaderStats[hoRequest].parsedCount + HttpHeaderStats[hoReply].parsedCount;
1721 HttpHeaderStats[0].ccParsedCount =
1722 HttpHeaderStats[hoRequest].ccParsedCount + HttpHeaderStats[hoReply].ccParsedCount;
1723 HttpHeaderStats[0].destroyedCount =
1724 HttpHeaderStats[hoRequest].destroyedCount + HttpHeaderStats[hoReply].destroyedCount;
1725 HttpHeaderStats[0].busyDestroyedCount =
1726 HttpHeaderStats[hoRequest].busyDestroyedCount + HttpHeaderStats[hoReply].busyDestroyedCount;
1727
1728 for (i = 1; i < HttpHeaderStatCount; i++) {
1729 httpHeaderStatDump(HttpHeaderStats + i, e);
1730 storeAppendPrintf(e, "%s\n", "<br>");
1731 }
1732
1733 /* field stats for all messages */
1734 storeAppendPrintf(e, "\nHttp Fields Stats (replies and requests)\n");
1735
1736 storeAppendPrintf(e, "%2s\t %-25s\t %5s\t %6s\t %6s\n",
1737 "id", "name", "#alive", "%err", "%repeat");
1738
1739 for (ht = (http_hdr_type)0; ht < HDR_ENUM_END; ++ht) {
1740 HttpHeaderFieldInfo *f = Headers + ht;
1741 storeAppendPrintf(e, "%2d\t %-25s\t %5d\t %6.3f\t %6.3f\n",
1742 f->id, f->name.termedBuf(), f->stat.aliveCount,
1743 xpercent(f->stat.errCount, f->stat.parsCount),
1744 xpercent(f->stat.repCount, f->stat.seenCount));
1745 }
1746
1747 storeAppendPrintf(e, "Headers Parsed: %d + %d = %d\n",
1748 HttpHeaderStats[hoRequest].parsedCount,
1749 HttpHeaderStats[hoReply].parsedCount,
1750 HttpHeaderStats[0].parsedCount);
1751 storeAppendPrintf(e, "Hdr Fields Parsed: %d\n", HeaderEntryParsedCount);
1752 }
1753
1754 http_hdr_type
1755 httpHeaderIdByName(const char *name, size_t name_len, const HttpHeaderFieldInfo * info, int end)
1756 {
1757 if (name_len > 0) {
1758 for (int i = 0; i < end; ++i) {
1759 if (name_len != info[i].name.size())
1760 continue;
1761
1762 if (!strncasecmp(name, info[i].name.rawBuf(), name_len))
1763 return info[i].id;
1764 }
1765 }
1766
1767 return HDR_BAD_HDR;
1768 }
1769
1770 http_hdr_type
1771 httpHeaderIdByNameDef(const char *name, int name_len)
1772 {
1773 if (!Headers)
1774 Headers = httpHeaderBuildFieldsInfo(HeadersAttrs, HDR_ENUM_END);
1775
1776 return httpHeaderIdByName(name, name_len, Headers, HDR_ENUM_END);
1777 }
1778
1779 const char *
1780 httpHeaderNameById(int id)
1781 {
1782 if (!Headers)
1783 Headers = httpHeaderBuildFieldsInfo(HeadersAttrs, HDR_ENUM_END);
1784
1785 assert(id >= 0 && id < HDR_ENUM_END);
1786
1787 return Headers[id].name.termedBuf();
1788 }
1789
1790 int
1791 HttpHeader::hasListMember(http_hdr_type id, const char *member, const char separator) const
1792 {
1793 int result = 0;
1794 const char *pos = NULL;
1795 const char *item;
1796 int ilen;
1797 int mlen = strlen(member);
1798
1799 assert(id >= 0);
1800
1801 String header (getStrOrList(id));
1802
1803 while (strListGetItem(&header, separator, &item, &ilen, &pos)) {
1804 if (strncasecmp(item, member, mlen) == 0
1805 && (item[mlen] == '=' || item[mlen] == separator || item[mlen] == ';' || item[mlen] == '\0')) {
1806 result = 1;
1807 break;
1808 }
1809 }
1810
1811 return result;
1812 }
1813
1814 int
1815 HttpHeader::hasByNameListMember(const char *name, const char *member, const char separator) const
1816 {
1817 int result = 0;
1818 const char *pos = NULL;
1819 const char *item;
1820 int ilen;
1821 int mlen = strlen(member);
1822
1823 assert(name);
1824
1825 String header (getByName(name));
1826
1827 while (strListGetItem(&header, separator, &item, &ilen, &pos)) {
1828 if (strncasecmp(item, member, mlen) == 0
1829 && (item[mlen] == '=' || item[mlen] == separator || item[mlen] == ';' || item[mlen] == '\0')) {
1830 result = 1;
1831 break;
1832 }
1833 }
1834
1835 return result;
1836 }
1837
1838 void
1839 HttpHeader::removeHopByHopEntries()
1840 {
1841 removeConnectionHeaderEntries();
1842
1843 const HttpHeaderEntry *e;
1844 HttpHeaderPos pos = HttpHeaderInitPos;
1845 int headers_deleted = 0;
1846 while ((e = getEntry(&pos))) {
1847 int id = e->id;
1848 if (CBIT_TEST(HopByHopHeadersMask, id)) {
1849 delAt(pos, headers_deleted);
1850 CBIT_CLR(mask, id);
1851 }
1852 }
1853 }
1854
1855 void
1856 HttpHeader::removeConnectionHeaderEntries()
1857 {
1858 if (has(HDR_CONNECTION)) {
1859 /* anything that matches Connection list member will be deleted */
1860 String strConnection;
1861
1862 (void) getList(HDR_CONNECTION, &strConnection);
1863 const HttpHeaderEntry *e;
1864 HttpHeaderPos pos = HttpHeaderInitPos;
1865 /*
1866 * think: on-average-best nesting of the two loops (hdrEntry
1867 * and strListItem) @?@
1868 */
1869 /*
1870 * maybe we should delete standard stuff ("keep-alive","close")
1871 * from strConnection first?
1872 */
1873
1874 int headers_deleted = 0;
1875 while ((e = getEntry(&pos))) {
1876 if (strListIsMember(&strConnection, e->name.termedBuf(), ','))
1877 delAt(pos, headers_deleted);
1878 }
1879 if (headers_deleted)
1880 refreshMask();
1881 }
1882 }