Squid Web Cache master
Loading...
Searching...
No Matches
HttpHeader.cc
Go to the documentation of this file.
1/*
2 * Copyright (C) 1996-2026 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9/* DEBUG: section 55 HTTP Header */
10
11#include "squid.h"
12#include "base/Assure.h"
13#include "base/CharacterSet.h"
14#include "base/EnumIterator.h"
15#include "base/Raw.h"
16#include "base64.h"
17#include "globals.h"
19#include "HttpHdrCc.h"
20#include "HttpHdrContRange.h"
21#include "HttpHdrScTarget.h" // also includes HttpHdrSc.h
22#include "HttpHeader.h"
23#include "HttpHeaderFieldStat.h"
24#include "HttpHeaderStat.h"
25#include "HttpHeaderTools.h"
26#include "MemBuf.h"
27#include "mgr/Registration.h"
28#include "mime_header.h"
29#include "sbuf/Stream.h"
30#include "sbuf/StringConvert.h"
31#include "SquidConfig.h"
32#include "StatHist.h"
33#include "Store.h"
34#include "StrList.h"
35#include "time/gadgets.h"
36#include "TimeOrTag.h"
37#include "util.h"
38
39#include <algorithm>
40#include <array>
41
42/* XXX: the whole set of API managing the entries vector should be rethought
43 * after the parse4r-ng effort is complete.
44 */
45
46/*
47 * On naming conventions:
48 *
49 * HTTP/1.1 defines message-header as
50 *
51 * message-header = field-name ":" [ field-value ] CRLF
52 * field-name = token
53 * field-value = *( field-content | LWS )
54 *
55 * HTTP/1.1 does not give a name name a group of all message-headers in a message.
56 * Squid 1.1 seems to refer to that group _plus_ start-line as "headers".
57 *
58 * HttpHeader is an object that represents all message-headers in a message.
59 * HttpHeader does not manage start-line.
60 *
61 * HttpHeader is implemented as a collection of header "entries".
62 * An entry is a (field_id, field_name, field_value) triplet.
63 */
64
65/*
66 * local constants and vars
67 */
68
69// statistics counters for headers. clients must not allow Http::HdrType::BAD_HDR to be counted
70std::vector<HttpHeaderFieldStat> headerStatsTable(Http::HdrType::enumEnd_);
71
72/* request-only headers. Used for cachemgr */
73static HttpHeaderMask RequestHeadersMask; /* set run-time using RequestHeaders */
74
75/* reply-only headers. Used for cachemgr */
76static HttpHeaderMask ReplyHeadersMask; /* set run-time using ReplyHeaders */
77
78/* header accounting */
79// NP: keep in sync with enum http_hdr_owner_type
80static std::array<HttpHeaderStat, hoEnd> HttpHeaderStats = {{
81 HttpHeaderStat(/*hoNone*/ "all", nullptr),
82#if USE_HTCP
83 HttpHeaderStat(/*hoHtcpReply*/ "HTCP reply", &ReplyHeadersMask),
84#endif
85 HttpHeaderStat(/*hoRequest*/ "request", &RequestHeadersMask),
86 HttpHeaderStat(/*hoReply*/ "reply", &ReplyHeadersMask)
87#if USE_OPENSSL
88 , HttpHeaderStat(/*hoErrorDetail*/ "error detail templates", nullptr)
89#endif
90 /* hoEnd */
91 }
92};
93
95
96/*
97 * forward declarations and local routines
98 */
99
100class StoreEntry;
101
102// update parse statistics for header id; if error is true also account
103// for errors and write to debug log what happened
104static void httpHeaderNoteParsedEntry(Http::HdrType id, String const &value, bool error);
105static void httpHeaderStatDump(const HttpHeaderStat * hs, StoreEntry * e);
107static void httpHeaderStoreReport(StoreEntry * e);
108
109/*
110 * Module initialization routines
111 */
112
113static void
115{
116 Mgr::RegisterAction("http_headers",
117 "HTTP Header Statistics",
119}
120
121static void
123{
124 memset(mask, value, sizeof(*mask));
125}
126
128static const char *
129getStringPrefix(const char *str, size_t sz)
130{
131#define SHORT_PREFIX_SIZE 512
132 LOCAL_ARRAY(char, buf, SHORT_PREFIX_SIZE);
133 xstrncpy(buf, str, (sz+1 > SHORT_PREFIX_SIZE) ? SHORT_PREFIX_SIZE : sz);
134 return buf;
135}
136
137void
139{
140 /* check that we have enough space for masks */
142
143 // masks are needed for stats page still
144 for (auto h : WholeEnum<Http::HdrType>()) {
145 if (Http::HeaderLookupTable.lookup(h).request)
147 if (Http::HeaderLookupTable.lookup(h).reply)
149 }
150
151 assert(HttpHeaderStats[0].label && "httpHeaderInitModule() called via main()");
152 assert(HttpHeaderStats[hoEnd-1].label && "HttpHeaderStats created with all elements");
153
154 /* init dependent modules */
156
158}
159
166int
167httpHeaderParseQuotedString(const char *start, const int len, String *val)
168{
169 const char *end, *pos;
170 val->clean();
171 if (*start != '"') {
172 debugs(66, 2, "failed to parse a quoted-string header field near '" << start << "'");
173 return 0;
174 }
175 pos = start + 1;
176
177 while (*pos != '"' && len > (pos-start)) {
178
179 if (*pos =='\r') {
180 ++pos;
181 if ((pos-start) > len || *pos != '\n') {
182 debugs(66, 2, "failed to parse a quoted-string header field with '\\r' octet " << (start-pos)
183 << " bytes into '" << start << "'");
184 val->clean();
185 return 0;
186 }
187 }
188
189 if (*pos == '\n') {
190 ++pos;
191 if ( (pos-start) > len || (*pos != ' ' && *pos != '\t')) {
192 debugs(66, 2, "failed to parse multiline quoted-string header field '" << start << "'");
193 val->clean();
194 return 0;
195 }
196 // TODO: replace the entire LWS with a space
197 val->append(" ");
198 ++pos;
199 debugs(66, 2, "len < pos-start => " << len << " < " << (pos-start));
200 continue;
201 }
202
203 bool quoted = (*pos == '\\');
204 if (quoted) {
205 ++pos;
206 if (!*pos || (pos-start) > len) {
207 debugs(66, 2, "failed to parse a quoted-string header field near '" << start << "'");
208 val->clean();
209 return 0;
210 }
211 }
212 end = pos;
213 while (end < (start+len) && *end != '\\' && *end != '\"' && (unsigned char)*end > 0x1F && *end != 0x7F)
214 ++end;
215 if (((unsigned char)*end <= 0x1F && *end != '\r' && *end != '\n') || *end == 0x7F) {
216 debugs(66, 2, "failed to parse a quoted-string header field with CTL octet " << (start-pos)
217 << " bytes into '" << start << "'");
218 val->clean();
219 return 0;
220 }
221 val->append(pos, end-pos);
222 pos = end;
223 }
224
225 if (*pos != '\"') {
226 debugs(66, 2, "failed to parse a quoted-string header field which did not end with \" ");
227 val->clean();
228 return 0;
229 }
230 /* Make sure it's defined even if empty "" */
231 if (!val->termedBuf())
232 val->assign("", 0);
233 return 1;
234}
235
236SBuf
237httpHeaderQuoteString(const char *raw)
238{
239 assert(raw);
240
241 // TODO: Optimize by appending a sequence of characters instead of a char.
242 // This optimization may be easier with Tokenizer after raw becomes SBuf.
243
244 // RFC 7230 says a "sender SHOULD NOT generate a quoted-pair in a
245 // quoted-string except where necessary" (i.e., DQUOTE and backslash)
246 bool needInnerQuote = false;
247 for (const char *s = raw; !needInnerQuote && *s; ++s)
248 needInnerQuote = *s == '"' || *s == '\\';
249
250 SBuf quotedStr;
251 quotedStr.append('"');
252
253 if (needInnerQuote) {
254 for (const char *s = raw; *s; ++s) {
255 if (*s == '"' || *s == '\\')
256 quotedStr.append('\\');
257 quotedStr.append(*s);
258 }
259 } else {
260 quotedStr.append(raw);
261 }
262
263 quotedStr.append('"');
264 return quotedStr;
265}
266
267SBuf
268Http::SlowlyParseQuotedString(const char * const description, const char * const start, const size_t length)
269{
270 String s;
271 if (!httpHeaderParseQuotedString(start, length, &s))
272 throw TextException(ToSBuf("Cannot parse ", description, " as a quoted string"), Here());
273 return StringToSBuf(s);
274}
275
276/*
277 * HttpHeader Implementation
278 */
279
280HttpHeader::HttpHeader(const http_hdr_owner_type anOwner): owner(anOwner), len(0), conflictingContentLength_(false)
281{
282 assert(anOwner > hoNone && anOwner < hoEnd);
283 debugs(55, 7, "init-ing hdr: " << this << " owner: " << owner);
284 entries.reserve(32);
286}
287
288// XXX: Delete as unused, expensive, and violating copy semantics by skipping Warnings
289HttpHeader::HttpHeader(const HttpHeader &other): owner(other.owner), len(other.len), conflictingContentLength_(false)
290{
291 entries.reserve(other.entries.capacity());
293 update(&other); // will update the mask as well
294}
295
300
301// XXX: Delete as unused, expensive, and violating assignment semantics by skipping Warnings
304{
305 if (this != &other) {
306 // we do not really care, but the caller probably does
307 assert(owner == other.owner);
308 clean();
309 update(&other); // will update the mask as well
310 len = other.len;
313 }
314 return *this;
315}
316
317void
319{
320
321 assert(owner > hoNone && owner < hoEnd);
322 debugs(55, 7, "cleaning hdr: " << this << " owner: " << owner);
323
324 if (owner <= hoReply) {
325 /*
326 * An unfortunate bug. The entries array is initialized
327 * such that count is set to zero. httpHeaderClean() seems to
328 * be called both when 'hdr' is created, and destroyed. Thus,
329 * we accumulate a large number of zero counts for 'hdr' before
330 * it is ever used. Can't think of a good way to fix it, except
331 * adding a state variable that indicates whether or not 'hdr'
332 * has been used. As a hack, just never count zero-sized header
333 * arrays.
334 */
335 if (!entries.empty())
336 HttpHeaderStats[owner].hdrUCountDistr.count(entries.size());
337
338 ++ HttpHeaderStats[owner].destroyedCount;
339
340 HttpHeaderStats[owner].busyDestroyedCount += entries.size() > 0;
341 } // if (owner <= hoReply)
342
343 for (HttpHeaderEntry *e : entries) {
344 if (e == nullptr)
345 continue;
346 if (!Http::any_valid_header(e->id)) {
347 debugs(55, DBG_CRITICAL, "ERROR: Squid BUG: invalid entry (" << e->id << "). Ignored.");
348 } else {
349 if (owner <= hoReply)
350 HttpHeaderStats[owner].fieldTypeDistr.count(e->id);
351 delete e;
352 }
353 }
354
355 entries.clear();
357 len = 0;
359 teUnsupported_ = false;
360}
361
362/* append entries (also see httpHeaderUpdate) */
363void
365{
366 assert(src);
367 assert(src != this);
368 debugs(55, 7, "appending hdr: " << this << " += " << src);
369
370 for (auto e : src->entries) {
371 if (e)
372 addEntry(e->clone());
373 }
374}
375
376bool
378{
379 for (const auto e: fresh->entries) {
380 if (!e || skipUpdateHeader(e->id))
381 continue;
382 String value;
383 if (!hasNamed(e->name, &value) ||
384 (value != fresh->getByName(e->name)))
385 return true;
386 }
387 return false;
388}
389
390bool
392{
393 return
394 // TODO: Consider updating Vary headers after comparing the magnitude of
395 // the required changes (and/or cache losses) with compliance gains.
396 (id == Http::HdrType::VARY);
397}
398
399void
401{
402 assert(fresh);
403 assert(this != fresh);
404
405 const HttpHeaderEntry *e;
407
408 while ((e = fresh->getEntry(&pos))) {
409 /* deny bad guys (ok to check for Http::HdrType::OTHER) here */
410
411 if (skipUpdateHeader(e->id))
412 continue;
413
414 if (e->id != Http::HdrType::OTHER)
415 delById(e->id);
416 else
417 delByName(e->name);
418 }
419
420 pos = HttpHeaderInitPos;
421 while ((e = fresh->getEntry(&pos))) {
422 /* deny bad guys (ok to check for Http::HdrType::OTHER) here */
423
424 if (skipUpdateHeader(e->id))
425 continue;
426
427 debugs(55, 7, "Updating header '" << Http::HeaderLookupTable.lookup(e->id).name << "' in cached entry");
428
429 addEntry(e->clone());
430 }
431}
432
433bool
434HttpHeader::Isolate(const char **parse_start, size_t l, const char **blk_start, const char **blk_end)
435{
436 /*
437 * parse_start points to the first line of HTTP message *headers*,
438 * not including the request or status lines
439 */
440 const size_t end = headersEnd(*parse_start, l);
441
442 if (end) {
443 *blk_start = *parse_start;
444 *blk_end = *parse_start + end - 1;
445 assert(**blk_end == '\n');
446 // Point blk_end to the first character after the last header field.
447 // In other words, blk_end should point to the CR?LF header terminator.
448 if (end > 1 && *(*blk_end - 1) == '\r')
449 --(*blk_end);
450 *parse_start += end;
451 }
452 return end;
453}
454
455int
456HttpHeader::parse(const char *buf, size_t buf_len, bool atEnd, size_t &hdr_sz, Http::ContentLengthInterpreter &clen)
457{
458 const char *parse_start = buf;
459 const char *blk_start, *blk_end;
460 hdr_sz = 0;
461
462 if (!Isolate(&parse_start, buf_len, &blk_start, &blk_end)) {
463 // XXX: do not parse non-isolated headers even if the connection is closed.
464 // Treat unterminated headers as "partial headers" framing errors.
465 if (!atEnd)
466 return 0;
467 blk_start = parse_start;
468 blk_end = blk_start + strlen(blk_start);
469 }
470
471 if (parse(blk_start, blk_end - blk_start, clen)) {
472 hdr_sz = parse_start - buf;
473 return 1;
474 }
475 return -1;
476}
477
478// XXX: callers treat this return as boolean.
479// XXX: A better mechanism is needed to signal different types of error.
480// lexicon, syntax, semantics, validation, access policy - are all (ab)using 'return 0'
481int
482HttpHeader::parse(const char *header_start, size_t hdrLen, Http::ContentLengthInterpreter &clen)
483{
484 const char *field_ptr = header_start;
485 const char *header_end = header_start + hdrLen; // XXX: remove
486 int warnOnError = (Config.onoff.relaxed_header_parser <= 0 ? DBG_IMPORTANT : 2);
487
488 assert(header_start && header_end);
489 debugs(55, 7, "parsing hdr: (" << this << ")" << std::endl << getStringPrefix(header_start, hdrLen));
490 ++ HttpHeaderStats[owner].parsedCount;
491
492 char *nulpos;
493 if ((nulpos = (char*)memchr(header_start, '\0', hdrLen))) {
494 debugs(55, DBG_IMPORTANT, "WARNING: HTTP header contains NULL characters {" <<
495 getStringPrefix(header_start, nulpos-header_start) << "}\nNULL\n{" << getStringPrefix(nulpos+1, hdrLen-(nulpos-header_start)-1));
496 clean();
497 return 0;
498 }
499
500 /* common format headers are "<name>:[ws]<value>" lines delimited by <CRLF>.
501 * continuation lines start with a (single) space or tab */
502 while (field_ptr < header_end) {
503 const char *field_start = field_ptr;
504 const char *field_end;
505
506 const char *hasBareCr = nullptr;
507 size_t lines = 0;
508 do {
509 const char *this_line = field_ptr;
510 field_ptr = (const char *)memchr(field_ptr, '\n', header_end - field_ptr);
511 ++lines;
512
513 if (!field_ptr) {
514 // missing <LF>
515 clean();
516 return 0;
517 }
518
519 field_end = field_ptr;
520
521 ++field_ptr; /* Move to next line */
522
523 if (field_end > this_line && field_end[-1] == '\r') {
524 --field_end; /* Ignore CR LF */
525
526 if (owner == hoRequest && field_end > this_line) {
527 bool cr_only = true;
528 for (const char *p = this_line; p < field_end && cr_only; ++p) {
529 if (*p != '\r')
530 cr_only = false;
531 }
532 if (cr_only) {
533 debugs(55, DBG_IMPORTANT, "SECURITY WARNING: Rejecting HTTP request with a CR+ "
534 "header field to prevent request smuggling attacks: {" <<
535 getStringPrefix(header_start, hdrLen) << "}");
536 clean();
537 return 0;
538 }
539 }
540 }
541
542 /* Barf on stray CR characters */
543 if (memchr(this_line, '\r', field_end - this_line)) {
544 hasBareCr = "bare CR";
545 debugs(55, warnOnError, "WARNING: suspicious CR characters in HTTP header {" <<
546 getStringPrefix(field_start, field_end-field_start) << "}");
547
549 char *p = (char *) this_line; /* XXX Warning! This destroys original header content and violates specifications somewhat */
550
551 while ((p = (char *)memchr(p, '\r', field_end - p)) != nullptr) {
552 *p = ' ';
553 ++p;
554 }
555 } else {
556 clean();
557 return 0;
558 }
559 }
560
561 if (this_line + 1 == field_end && this_line > field_start) {
562 debugs(55, warnOnError, "WARNING: Blank continuation line in HTTP header {" <<
563 getStringPrefix(header_start, hdrLen) << "}");
564 clean();
565 return 0;
566 }
567 } while (field_ptr < header_end && (*field_ptr == ' ' || *field_ptr == '\t'));
568
569 if (field_start == field_end) {
570 if (field_ptr < header_end) {
571 debugs(55, warnOnError, "WARNING: unparsable HTTP header field near {" <<
572 getStringPrefix(field_start, hdrLen-(field_start-header_start)) << "}");
573 clean();
574 return 0;
575 }
576
577 break; /* terminating blank line */
578 }
579
580 const auto e = HttpHeaderEntry::parse(field_start, field_end, owner);
581 if (!e) {
582 debugs(55, warnOnError, "WARNING: unparsable HTTP header field {" <<
583 getStringPrefix(field_start, field_end-field_start) << "}");
584 debugs(55, warnOnError, " in {" << getStringPrefix(header_start, hdrLen) << "}");
585
586 clean();
587 return 0;
588 }
589
590 if (lines > 1 || hasBareCr) {
591 const auto framingHeader = (e->id == Http::HdrType::CONTENT_LENGTH || e->id == Http::HdrType::TRANSFER_ENCODING);
592 if (framingHeader) {
593 if (!hasBareCr) // already warned about bare CRs
594 debugs(55, warnOnError, "WARNING: obs-fold in framing-sensitive " << e->name << ": " << e->value);
595 delete e;
596 clean();
597 return 0;
598 }
599 }
600
601 if (e->id == Http::HdrType::CONTENT_LENGTH && !clen.checkField(e->value)) {
602 delete e;
603
605 continue; // clen has printed any necessary warnings
606
607 clean();
608 return 0;
609 }
610
611 addEntry(e);
612 }
613
614 if (clen.headerWideProblem) {
615 debugs(55, warnOnError, "WARNING: " << clen.headerWideProblem <<
616 " Content-Length field values in" <<
617 Raw("header", header_start, hdrLen));
618 }
619
620 String rawTe;
621 if (clen.prohibitedAndIgnored()) {
622 // prohibitedAndIgnored() includes trailer header blocks
623 // being parsed as a case to forbid/ignore these headers.
624
625 // RFC 7230 section 3.3.2: A server MUST NOT send a Content-Length
626 // header field in any response with a status code of 1xx (Informational)
627 // or 204 (No Content). And RFC 7230 3.3.3#1 tells recipients to ignore
628 // such Content-Lengths.
630 debugs(55, 3, "Content-Length is " << clen.prohibitedAndIgnored());
631
632 // The same RFC 7230 3.3.3#1-based logic applies to Transfer-Encoding
633 // banned by RFC 7230 section 3.3.1.
635 debugs(55, 3, "Transfer-Encoding is " << clen.prohibitedAndIgnored());
636
638 // RFC 2616 section 4.4: ignore Content-Length with Transfer-Encoding
639 // RFC 7230 section 3.3.3 #3: Transfer-Encoding overwrites Content-Length
641 // and clen state becomes irrelevant
642
643 if (rawTe.caseCmp("chunked") == 0) {
644 ; // leave header present for chunked() method
645 } else {
646 // This also rejects multiple encodings until we support them properly.
647 debugs(55, warnOnError, "WARNING: unsupported Transfer-Encoding used by client: " << rawTe);
648 teUnsupported_ = true;
649 }
650
651 } else if (clen.sawBad) {
652 // ensure our callers do not accidentally see bad Content-Length values
654 conflictingContentLength_ = true; // TODO: Rename to badContentLength_.
655 } else if (clen.needsSanitizing) {
656 // RFC 7230 section 3.3.2: MUST either reject or ... [sanitize];
657 // ensure our callers see a clean Content-Length value or none at all
659 if (clen.sawGood) {
661 debugs(55, 5, "sanitized Content-Length to be " << clen.value);
662 }
663 }
664
665 return 1; /* even if no fields where found, it is a valid header */
666}
667
668/* packs all the entries using supplied packer */
669void
670HttpHeader::packInto(Packable * p, bool mask_sensitive_info) const
671{
673 const HttpHeaderEntry *e;
674 assert(p);
675 debugs(55, 7, this << " into " << p <<
676 (mask_sensitive_info ? " while masking" : ""));
677 /* pack all entries one by one */
678 while ((e = getEntry(&pos))) {
679 if (!mask_sensitive_info) {
680 e->packInto(p);
681 continue;
682 }
683
684 bool maskThisEntry = false;
685 switch (e->id) {
688 maskThisEntry = true;
689 break;
690
693 maskThisEntry = (cmd->value == "PASS");
694 break;
695
696 default:
697 break;
698 }
699 if (maskThisEntry) {
700 p->append(e->name.rawContent(), e->name.length());
701 p->append(": ** NOT DISPLAYED **\r\n", 23);
702 } else {
703 e->packInto(p);
704 }
705
706 }
707 /* Pack in the "special" entries */
708
709 /* Cache-Control */
710}
711
712/* returns next valid entry */
715{
716 assert(pos);
717 assert(*pos >= HttpHeaderInitPos && *pos < static_cast<ssize_t>(entries.size()));
718
719 for (++(*pos); *pos < static_cast<ssize_t>(entries.size()); ++(*pos)) {
720 if (entries[*pos])
721 return static_cast<HttpHeaderEntry*>(entries[*pos]);
722 }
723
724 return nullptr;
725}
726
727/*
728 * returns a pointer to a specified entry if any
729 * note that we return one entry so it does not make much sense to ask for
730 * "list" headers
731 */
734{
735 assert(any_registered_header(id));
736 assert(!Http::HeaderLookupTable.lookup(id).list);
737
738 /* check mask first */
739
740 if (!CBIT_TEST(mask, id))
741 return nullptr;
742
743 /* looks like we must have it, do linear search */
744 for (auto e : entries) {
745 if (e && e->id == id)
746 return e;
747 }
748
749 /* hm.. we thought it was there, but it was not found */
750 assert(false);
751 return nullptr; /* not reached */
752}
753
754/*
755 * same as httpHeaderFindEntry
756 */
759{
760 assert(any_registered_header(id));
761 assert(!Http::HeaderLookupTable.lookup(id).list);
762
763 /* check mask first */
764 if (!CBIT_TEST(mask, id))
765 return nullptr;
766
767 for (auto e = entries.rbegin(); e != entries.rend(); ++e) {
768 if (*e && (*e)->id == id)
769 return *e;
770 }
771
772 /* hm.. we thought it was there, but it was not found */
773 assert(false);
774 return nullptr; /* not reached */
775}
776
777int
779{
780 int count = 0;
782 httpHeaderMaskInit(&mask, 0); /* temporal inconsistency */
783 debugs(55, 9, "deleting '" << name << "' fields in hdr " << this);
784
785 while (const HttpHeaderEntry *e = getEntry(&pos)) {
786 if (!e->name.caseCmp(name))
787 delAt(pos, count);
788 else
789 CBIT_SET(mask, e->id);
790 }
791
792 return count;
793}
794
795/* deletes all entries with a given id, returns the #entries deleted */
796int
798{
799 debugs(55, 8, this << " del-by-id " << id);
800 assert(any_registered_header(id));
801
802 if (!CBIT_TEST(mask, id))
803 return 0;
804
805 int count = 0;
806
808 while (HttpHeaderEntry *e = getEntry(&pos)) {
809 if (e->id == id)
810 delAt(pos, count); // deletes e
811 }
812
813 CBIT_CLR(mask, id);
814 assert(count);
815 return count;
816}
817
818/*
819 * deletes an entry at pos and leaves a gap; leaving a gap makes it
820 * possible to iterate(search) and delete fields at the same time
821 * NOTE: Does not update the header mask. Caller must follow up with
822 * a call to refreshMask() if headers_deleted was incremented.
823 */
824void
825HttpHeader::delAt(HttpHeaderPos pos, int &headers_deleted)
826{
828 assert(pos >= HttpHeaderInitPos && pos < static_cast<ssize_t>(entries.size()));
829 e = static_cast<HttpHeaderEntry*>(entries[pos]);
830 entries[pos] = nullptr;
831 /* decrement header length, allow for ": " and crlf */
832 len -= e->name.length() + 2 + e->value.size() + 2;
833 assert(len >= 0);
834 delete e;
835 ++headers_deleted;
836}
837
838/*
839 * Compacts the header storage
840 */
841void
843{
844 // TODO: optimize removal, or possibly make it so that's not needed.
845 entries.erase( std::remove(entries.begin(), entries.end(), nullptr),
846 entries.end());
847}
848
849/*
850 * Refreshes the header mask. Required after delAt() calls.
851 */
852void
854{
856 debugs(55, 7, "refreshing the mask in hdr " << this);
857 for (auto e : entries) {
858 if (e)
859 CBIT_SET(mask, e->id);
860 }
861}
862
863/* appends an entry;
864 * does not call e->clone() so one should not reuse "*e"
865 */
866void
868{
869 assert(e);
870 assert(any_HdrType_enum_value(e->id));
871 assert(e->name.length());
872
873 debugs(55, 7, this << " adding entry: " << e->id << " at " << entries.size());
874
875 if (e->id != Http::HdrType::BAD_HDR) {
876 if (CBIT_TEST(mask, e->id)) {
877 ++ headerStatsTable[e->id].repCount;
878 } else {
879 CBIT_SET(mask, e->id);
880 }
881 }
882
883 entries.push_back(e);
884
885 len += e->length();
886}
887
888bool
890{
891 debugs(55, 9, this << " joining for id " << id);
892 /* only fields from ListHeaders array can be "listed" */
893 assert(Http::HeaderLookupTable.lookup(id).list);
894
895 if (!CBIT_TEST(mask, id))
896 return false;
897
898 for (auto e: entries) {
899 if (e && e->id == id)
900 strListAdd(s, e->value.termedBuf(), ',');
901 }
902
903 /*
904 * note: we might get an empty (size==0) string if there was an "empty"
905 * header. This results in an empty length String, which may have a NULL
906 * buffer.
907 */
908 /* temporary warning: remove it? (Is it useful for diagnostics ?) */
909 if (!s->size())
910 debugs(55, 3, "empty list header: " << Http::HeaderLookupTable.lookup(id).name << "(" << id << ")");
911 else
912 debugs(55, 6, this << ": joined for id " << id << ": " << s);
913
914 return true;
915}
916
917/* return a list of entries with the same id separated by ',' and ws */
918String
920{
923 debugs(55, 9, this << "joining for id " << id);
924 /* only fields from ListHeaders array can be "listed" */
925 assert(Http::HeaderLookupTable.lookup(id).list);
926
927 if (!CBIT_TEST(mask, id))
928 return String();
929
930 String s;
931
932 while ((e = getEntry(&pos))) {
933 if (e->id == id)
934 strListAdd(&s, e->value.termedBuf(), ',');
935 }
936
937 /*
938 * note: we might get an empty (size==0) string if there was an "empty"
939 * header. This results in an empty length String, which may have a NULL
940 * buffer.
941 */
942 /* temporary warning: remove it? (Is it useful for diagnostics ?) */
943 if (!s.size())
944 debugs(55, 3, "empty list header: " << Http::HeaderLookupTable.lookup(id).name << "(" << id << ")");
945 else
946 debugs(55, 6, this << ": joined for id " << id << ": " << s);
947
948 return s;
949}
950
951/* return a string or list of entries with the same id separated by ',' and ws */
952String
954{
956
957 if (Http::HeaderLookupTable.lookup(id).list)
958 return getList(id);
959
960 if ((e = findEntry(id)))
961 return e->value;
962
963 return String();
964}
965
966/*
967 * Returns the value of the specified header and/or an undefined String.
968 */
969String
970HttpHeader::getByName(const char *name) const
971{
972 String result;
973 // ignore presence: return undefined string if an empty header is present
974 (void)hasNamed(name, strlen(name), &result);
975 return result;
976}
977
978String
979HttpHeader::getByName(const SBuf &name) const
980{
981 String result;
982 // ignore presence: return undefined string if an empty header is present
983 (void)hasNamed(name, &result);
984 return result;
985}
986
987String
989{
990 String result;
991 (void)getByIdIfPresent(id, &result);
992 return result;
993}
994
995bool
996HttpHeader::hasNamed(const SBuf &s, String *result) const
997{
998 return hasNamed(s.rawContent(), s.length(), result);
999}
1000
1001bool
1003{
1004 if (id == Http::HdrType::BAD_HDR)
1005 return false;
1006 if (!has(id))
1007 return false;
1008 if (result)
1009 *result = getStrOrList(id);
1010 return true;
1011}
1012
1013bool
1014HttpHeader::hasNamed(const char *name, unsigned int namelen, String *result) const
1015{
1016 Http::HdrType id;
1018 HttpHeaderEntry *e;
1019
1020 assert(name);
1021
1022 /* First try the quick path */
1023 id = Http::HeaderLookupTable.lookup(name,namelen).id;
1024
1025 if (id != Http::HdrType::BAD_HDR) {
1026 if (getByIdIfPresent(id, result))
1027 return true;
1028 }
1029
1030 /* Sorry, an unknown header name. Do linear search */
1031 bool found = false;
1032 while ((e = getEntry(&pos))) {
1033 if (e->id == Http::HdrType::OTHER && e->name.length() == namelen && e->name.caseCmp(name, namelen) == 0) {
1034 found = true;
1035 if (!result)
1036 break;
1037 strListAdd(result, e->value.termedBuf(), ',');
1038 }
1039 }
1040
1041 return found;
1042}
1043
1044/*
1045 * Returns a the value of the specified list member, if any.
1046 */
1047SBuf
1048HttpHeader::getByNameListMember(const char *name, const char *member, const char separator) const
1049{
1050 assert(name);
1051 const auto header = getByName(name);
1052 return ::getListMember(header, member, separator);
1053}
1054
1055/*
1056 * returns a the value of the specified list member, if any.
1057 */
1058SBuf
1059HttpHeader::getListMember(Http::HdrType id, const char *member, const char separator) const
1060{
1061 assert(any_registered_header(id));
1062 const auto header = getStrOrList(id);
1063 return ::getListMember(header, member, separator);
1064}
1065
1066/* test if a field is present */
1067int
1069{
1070 assert(any_registered_header(id));
1071 debugs(55, 9, this << " lookup for " << id);
1072 return CBIT_TEST(mask, id);
1073}
1074
1075void
1077{
1078 // TODO: do not add Via header for messages where Squid itself
1079 // generated the message (i.e., Downloader) there should be no Via header added at all.
1080
1081 if (Config.onoff.via) {
1082 SBuf buf;
1083 // RFC 7230 section 5.7.1.: protocol-name is omitted when
1084 // the received protocol is HTTP.
1087 buf.appendf("%s/", AnyP::ProtocolType_str[ver.protocol]);
1088 buf.appendf("%d.%d %s", ver.major, ver.minor, ThisCache);
1089 const HttpHeader *hdr = from ? from : this;
1091 if (!strVia.isEmpty())
1092 strVia.append(", ", 2);
1093 strVia.append(buf);
1095 }
1096}
1097
1098void
1100{
1101 assert(any_registered_header(id));
1102 assert(Http::HeaderLookupTable.lookup(id).type == Http::HdrFieldType::ftInt); /* must be of an appropriate type */
1103 assert(number >= 0);
1105}
1106
1107void
1109{
1110 assert(any_registered_header(id));
1111 assert(Http::HeaderLookupTable.lookup(id).type == Http::HdrFieldType::ftInt64); /* must be of an appropriate type */
1112 assert(number >= 0);
1114}
1115
1116void
1118{
1119 assert(any_registered_header(id));
1120 assert(Http::HeaderLookupTable.lookup(id).type == Http::HdrFieldType::ftDate_1123); /* must be of an appropriate type */
1121 assert(htime >= 0);
1123}
1124
1125void
1127{
1128 assert(any_registered_header(id));
1129 assert(Http::HeaderLookupTable.lookup(id).type == Http::HdrFieldType::ftStr); /* must be of an appropriate type */
1130 assert(str);
1131 addEntry(new HttpHeaderEntry(id, SBuf(), str));
1132}
1133
1134void
1135HttpHeader::putAuth(const char *auth_scheme, const char *realm)
1136{
1137 assert(auth_scheme && realm);
1138 httpHeaderPutStrf(this, Http::HdrType::WWW_AUTHENTICATE, "%s realm=\"%s\"", auth_scheme, realm);
1139}
1140
1141void
1143{
1144 /* remove old directives if any */
1146 /* pack into mb */
1147 MemBuf mb;
1148 mb.init();
1149 cc.packInto(&mb);
1150 /* put */
1152 /* cleanup */
1153 mb.clean();
1154}
1155
1156void
1158{
1159 assert(cr);
1160 /* remove old directives if any */
1162 /* pack into mb */
1163 MemBuf mb;
1164 mb.init();
1165 httpHdrContRangePackInto(cr, &mb);
1166 /* put */
1168 /* cleanup */
1169 mb.clean();
1170}
1171
1172void
1174{
1175 assert(range);
1176 /* remove old directives if any */
1178 /* pack into mb */
1179 MemBuf mb;
1180 mb.init();
1181 range->packInto(&mb);
1182 /* put */
1184 /* cleanup */
1185 mb.clean();
1186}
1187
1188void
1190{
1191 assert(sc);
1192 /* remove old directives if any */
1194 /* pack into mb */
1195 MemBuf mb;
1196 mb.init();
1197 sc->packInto(&mb);
1198 /* put */
1200 /* cleanup */
1201 mb.clean();
1202}
1203
1204/* add extension header (these fields are not parsed/analyzed/joined, etc.) */
1205void
1206HttpHeader::putExt(const char *name, const char *value)
1207{
1208 assert(name && value);
1209 debugs(55, 8, this << " adds ext entry " << name << " : " << value);
1211}
1212
1213void
1215{
1216 assert(any_registered_header(id));
1218
1219 // XXX: HttpHeaderEntry::value suffers from String size limits
1220 Assure(newValue.length() < String::SizeMaxXXX());
1221
1222 if (!CBIT_TEST(mask, id)) {
1223 auto newValueCopy = newValue; // until HttpHeaderEntry::value becomes SBuf
1224 addEntry(new HttpHeaderEntry(id, SBuf(), newValueCopy.c_str()));
1225 return;
1226 }
1227
1228 auto foundSameName = false;
1229 for (auto &e: entries) {
1230 if (!e || e->id != id)
1231 continue;
1232
1233 if (foundSameName) {
1234 // get rid of this repeated same-name entry
1235 delete e;
1236 e = nullptr;
1237 continue;
1238 }
1239
1240 if (newValue.cmp(e->value.termedBuf()) != 0)
1241 e->value.assign(newValue.rawContent(), newValue.plength());
1242
1243 foundSameName = true;
1244 // continue to delete any repeated same-name entries
1245 }
1246 assert(foundSameName);
1247 debugs(55, 5, "synced: " << Http::HeaderLookupTable.lookup(id).name << ": " << newValue);
1248}
1249
1250int
1252{
1253 assert(any_registered_header(id));
1254 assert(Http::HeaderLookupTable.lookup(id).type == Http::HdrFieldType::ftInt); /* must be of an appropriate type */
1255 HttpHeaderEntry *e;
1256
1257 if ((e = findEntry(id)))
1258 return e->getInt();
1259
1260 return -1;
1261}
1262
1263int64_t
1265{
1266 assert(any_registered_header(id));
1267 assert(Http::HeaderLookupTable.lookup(id).type == Http::HdrFieldType::ftInt64); /* must be of an appropriate type */
1268 HttpHeaderEntry *e;
1269
1270 if ((e = findEntry(id)))
1271 return e->getInt64();
1272
1273 return -1;
1274}
1275
1276time_t
1278{
1279 HttpHeaderEntry *e;
1280 time_t value = -1;
1281 assert(any_registered_header(id));
1282 assert(Http::HeaderLookupTable.lookup(id).type == Http::HdrFieldType::ftDate_1123); /* must be of an appropriate type */
1283
1284 if ((e = findEntry(id))) {
1285 value = Time::ParseRfc1123(e->value.termedBuf());
1286 httpHeaderNoteParsedEntry(e->id, e->value, value < 0);
1287 }
1288
1289 return value;
1290}
1291
1292/* sync with httpHeaderGetLastStr */
1293const char *
1295{
1296 HttpHeaderEntry *e;
1297 assert(any_registered_header(id));
1298 assert(Http::HeaderLookupTable.lookup(id).type == Http::HdrFieldType::ftStr); /* must be of an appropriate type */
1299
1300 if ((e = findEntry(id))) {
1301 httpHeaderNoteParsedEntry(e->id, e->value, false); /* no errors are possible */
1302 return e->value.termedBuf();
1303 }
1304
1305 return nullptr;
1306}
1307
1308/* unusual */
1309const char *
1311{
1312 HttpHeaderEntry *e;
1313 assert(any_registered_header(id));
1314 assert(Http::HeaderLookupTable.lookup(id).type == Http::HdrFieldType::ftStr); /* must be of an appropriate type */
1315
1316 if ((e = findLastEntry(id))) {
1317 httpHeaderNoteParsedEntry(e->id, e->value, false); /* no errors are possible */
1318 return e->value.termedBuf();
1319 }
1320
1321 return nullptr;
1322}
1323
1324HttpHdrCc *
1326{
1328 return nullptr;
1329
1330 String s;
1332
1333 HttpHdrCc *cc=new HttpHdrCc();
1334
1335 if (!cc->parse(s)) {
1336 delete cc;
1337 cc = nullptr;
1338 }
1339
1340 ++ HttpHeaderStats[owner].ccParsedCount;
1341
1342 if (cc)
1343 httpHdrCcUpdateStats(cc, &HttpHeaderStats[owner].ccTypeDistr);
1344
1346
1347 return cc;
1348}
1349
1352{
1353 HttpHdrRange *r = nullptr;
1354 HttpHeaderEntry *e;
1355 /* some clients will send "Request-Range" _and_ *matching* "Range"
1356 * who knows, some clients might send Request-Range only;
1357 * this "if" should work correctly in both cases;
1358 * hopefully no clients send mismatched headers! */
1359
1360 if ((e = findEntry(Http::HdrType::RANGE)) ||
1364 }
1365
1366 return r;
1367}
1368
1369HttpHdrSc *
1371{
1373 return nullptr;
1374
1375 String s;
1376
1378
1380
1381 ++ HttpHeaderStats[owner].ccParsedCount;
1382
1383 if (sc)
1384 sc->updateStats(&HttpHeaderStats[owner].scTypeDistr);
1385
1387
1388 return sc;
1389}
1390
1393{
1394 HttpHdrContRange *cr = nullptr;
1395 HttpHeaderEntry *e;
1396
1399 httpHeaderNoteParsedEntry(e->id, e->value, !cr);
1400 }
1401
1402 return cr;
1403}
1404
1405SBuf
1406HttpHeader::getAuthToken(Http::HdrType id, const char *auth_scheme) const
1407{
1408 const char *field;
1409 int l;
1410 assert(auth_scheme);
1411 field = getStr(id);
1412
1413 static const SBuf nil;
1414 if (!field) /* no authorization field */
1415 return nil;
1416
1417 l = strlen(auth_scheme);
1418
1419 if (!l || strncasecmp(field, auth_scheme, l)) /* wrong scheme */
1420 return nil;
1421
1422 field += l;
1423
1424 if (!xisspace(*field)) /* wrong scheme */
1425 return nil;
1426
1427 /* skip white space */
1428 for (; field && xisspace(*field); ++field);
1429
1430 if (!*field) /* no authorization cookie */
1431 return nil;
1432
1433 const auto fieldLen = strlen(field);
1434 SBuf result;
1435 char *decodedAuthToken = result.rawAppendStart(BASE64_DECODE_LENGTH(fieldLen));
1436 struct base64_decode_ctx ctx;
1437 base64_decode_init(&ctx);
1438 size_t decodedLen = 0;
1439 if (!base64_decode_update(&ctx, &decodedLen, reinterpret_cast<uint8_t*>(decodedAuthToken), fieldLen, field) ||
1440 !base64_decode_final(&ctx)) {
1441 return nil;
1442 }
1443 result.rawAppendFinish(decodedAuthToken, decodedLen);
1444 return result;
1445}
1446
1447ETag
1449{
1450 ETag etag = {nullptr, -1};
1451 HttpHeaderEntry *e;
1452 assert(Http::HeaderLookupTable.lookup(id).type == Http::HdrFieldType::ftETag); /* must be of an appropriate type */
1453
1454 if ((e = findEntry(id)))
1455 etagParseInit(&etag, e->value.termedBuf());
1456
1457 return etag;
1458}
1459
1462{
1463 TimeOrTag tot;
1464 HttpHeaderEntry *e;
1465 assert(Http::HeaderLookupTable.lookup(id).type == Http::HdrFieldType::ftDate_1123_or_ETag); /* must be of an appropriate type */
1466 memset(&tot, 0, sizeof(tot));
1467
1468 if ((e = findEntry(id))) {
1469 const char *str = e->value.termedBuf();
1470 /* try as an ETag */
1471
1472 if (etagParseInit(&tot.tag, str)) {
1473 tot.valid = tot.tag.str != nullptr;
1474 tot.time = -1;
1475 } else {
1476 /* or maybe it is time? */
1477 tot.time = Time::ParseRfc1123(str);
1478 tot.valid = tot.time >= 0;
1479 tot.tag.str = nullptr;
1480 }
1481 }
1482
1483 assert(tot.time < 0 || !tot.tag.str); /* paranoid */
1484 return tot;
1485}
1486
1487/*
1488 * HttpHeaderEntry
1489 */
1490
1491HttpHeaderEntry::HttpHeaderEntry(Http::HdrType anId, const SBuf &aName, const char *aValue)
1492{
1493 assert(any_HdrType_enum_value(anId));
1494 id = anId;
1495
1496 if (id != Http::HdrType::OTHER)
1498 else
1499 name = aName;
1500
1501 value = aValue;
1502
1503 if (id != Http::HdrType::BAD_HDR)
1504 ++ headerStatsTable[id].aliveCount;
1505
1506 debugs(55, 9, "created HttpHeaderEntry " << this << ": '" << name << " : " << value );
1507}
1508
1510{
1511 debugs(55, 9, "destroying entry " << this << ": '" << name << ": " << value << "'");
1512
1513 if (id != Http::HdrType::BAD_HDR) {
1514 assert(headerStatsTable[id].aliveCount);
1515 -- headerStatsTable[id].aliveCount;
1516 id = Http::HdrType::BAD_HDR; // it already is BAD_HDR, no sense in resetting it
1517 }
1518
1519}
1520
1521/* parses and inits header entry, returns true/false */
1523HttpHeaderEntry::parse(const char *field_start, const char *field_end, const http_hdr_owner_type msgType)
1524{
1525 /* note: name_start == field_start */
1526 const char *name_end = (const char *)memchr(field_start, ':', field_end - field_start);
1527 int name_len = name_end ? name_end - field_start :0;
1528 const char *value_start = field_start + name_len + 1; /* skip ':' */
1529 /* note: value_end == field_end */
1530
1532
1533 /* do we have a valid field name within this field? */
1534
1535 if (!name_len || name_end > field_end)
1536 return nullptr;
1537
1538 if (name_len > 65534) {
1539 /* String must be LESS THAN 64K and it adds a terminating NULL */
1540 // TODO: update this to show proper name_len in Raw markup, but not print all that
1541 debugs(55, 2, "ignoring huge header field (" << Raw("field_start", field_start, 100) << "...)");
1542 return nullptr;
1543 }
1544
1545 /*
1546 * RFC 7230 section 3.2.4:
1547 * "No whitespace is allowed between the header field-name and colon.
1548 * ...
1549 * A server MUST reject any received request message that contains
1550 * whitespace between a header field-name and colon with a response code
1551 * of 400 (Bad Request). A proxy MUST remove any such whitespace from a
1552 * response message before forwarding the message downstream."
1553 */
1554 if (xisspace(field_start[name_len - 1])) {
1555
1556 if (msgType == hoRequest)
1557 return nullptr;
1558
1559 // for now, also let relaxed parser remove this BWS from any non-HTTP messages
1560 const bool stripWhitespace = (msgType == hoReply) ||
1562 if (!stripWhitespace)
1563 return nullptr; // reject if we cannot strip
1564
1565 debugs(55, Config.onoff.relaxed_header_parser <= 0 ? 1 : 2,
1566 "WARNING: Whitespace after header name in '" << getStringPrefix(field_start, field_end-field_start) << "'");
1567
1568 while (name_len > 0 && xisspace(field_start[name_len - 1]))
1569 --name_len;
1570
1571 if (!name_len) {
1572 debugs(55, 2, "found header with only whitespace for name");
1573 return nullptr;
1574 }
1575 }
1576
1577 /* RFC 7230 section 3.2:
1578 *
1579 * header-field = field-name ":" OWS field-value OWS
1580 * field-name = token
1581 * token = 1*TCHAR
1582 */
1583 for (const char *pos = field_start; pos < (field_start+name_len); ++pos) {
1584 if (!CharacterSet::TCHAR[*pos]) {
1585 debugs(55, 2, "found header with invalid characters in " <<
1586 Raw("field-name", field_start, min(name_len,100)) << "...");
1587 return nullptr;
1588 }
1589 }
1590
1591 /* now we know we can parse it */
1592
1593 debugs(55, 9, "parsing HttpHeaderEntry: near '" << getStringPrefix(field_start, field_end-field_start) << "'");
1594
1595 /* is it a "known" field? */
1596 Http::HdrType id = Http::HeaderLookupTable.lookup(field_start,name_len).id;
1597 debugs(55, 9, "got hdr-id=" << id);
1598
1599 SBuf theName;
1600
1601 String value;
1602
1603 if (id == Http::HdrType::BAD_HDR)
1605
1606 /* set field name */
1607 if (id == Http::HdrType::OTHER)
1608 theName.append(field_start, name_len);
1609 else
1610 theName = Http::HeaderLookupTable.lookup(id).name;
1611
1612 /* trim field value */
1613 while (value_start < field_end && xisspace(*value_start))
1614 ++value_start;
1615
1616 while (value_start < field_end && xisspace(field_end[-1]))
1617 --field_end;
1618
1619 if (field_end - value_start > 65534) {
1620 /* String must be LESS THAN 64K and it adds a terminating NULL */
1621 debugs(55, 2, "WARNING: found '" << theName << "' header of " << (field_end - value_start) << " bytes");
1622 return nullptr;
1623 }
1624
1625 /* set field value */
1626 value.assign(value_start, field_end - value_start);
1627
1628 if (id != Http::HdrType::BAD_HDR)
1629 ++ headerStatsTable[id].seenCount;
1630
1631 debugs(55, 9, "parsed HttpHeaderEntry: '" << theName << ": " << value << "'");
1632
1633 return new HttpHeaderEntry(id, theName, value.termedBuf());
1634}
1635
1638{
1639 return new HttpHeaderEntry(id, name, value.termedBuf());
1640}
1641
1642void
1644{
1645 assert(p);
1646 p->append(name.rawContent(), name.length());
1647 p->append(": ", 2);
1648 p->append(value.rawBuf(), value.size());
1649 p->append("\r\n", 2);
1650}
1651
1652int
1654{
1655 int val = -1;
1656 int ok = httpHeaderParseInt(value.termedBuf(), &val);
1657 httpHeaderNoteParsedEntry(id, value, ok == 0);
1658 /* XXX: Should we check ok - ie
1659 * return ok ? -1 : value;
1660 */
1661 return val;
1662}
1663
1664int64_t
1666{
1667 int64_t val = -1;
1668 const bool ok = httpHeaderParseOffset(value.termedBuf(), &val);
1670 return val; // remains -1 if !ok (XXX: bad method API)
1671}
1672
1673static void
1675{
1676 if (id != Http::HdrType::BAD_HDR)
1677 ++ headerStatsTable[id].parsCount;
1678
1679 if (error) {
1680 if (id != Http::HdrType::BAD_HDR)
1681 ++ headerStatsTable[id].errCount;
1682 debugs(55, 2, "cannot parse hdr field: '" << Http::HeaderLookupTable.lookup(id).name << ": " << context << "'");
1683 }
1684}
1685
1686/*
1687 * Reports
1688 */
1689
1690/* tmp variable used to pass stat info to dumpers */
1691extern const HttpHeaderStat *dump_stat; /* argh! */
1692const HttpHeaderStat *dump_stat = nullptr;
1693
1694static void
1695httpHeaderFieldStatDumper(StoreEntry * sentry, int, double val, double, int count)
1696{
1697 const int id = static_cast<int>(val);
1698 const bool valid_id = Http::any_valid_header(static_cast<Http::HdrType>(id));
1699 const char *name = valid_id ? Http::HeaderLookupTable.lookup(static_cast<Http::HdrType>(id)).name : "INVALID";
1700 int visible = count > 0;
1701 /* for entries with zero count, list only those that belong to current type of message */
1702
1703 if (!visible && valid_id && dump_stat->owner_mask)
1704 visible = CBIT_TEST(*dump_stat->owner_mask, id);
1705
1706 if (visible)
1707 storeAppendPrintf(sentry, "%2d\t %-20s\t %5d\t %6.2f\n",
1708 id, name, count, xdiv(count, dump_stat->busyDestroyedCount));
1709}
1710
1711static void
1712httpHeaderFldsPerHdrDumper(StoreEntry * sentry, int idx, double val, double, int count)
1713{
1714 if (count)
1715 storeAppendPrintf(sentry, "%2d\t %5d\t %5d\t %6.2f\n",
1716 idx, (int) val, count,
1718}
1719
1720static void
1722{
1723 assert(hs);
1724 assert(e);
1725
1726 if (!hs->owner_mask)
1727 return; // these HttpHeaderStat objects were not meant to be dumped here
1728
1729 dump_stat = hs;
1730 storeAppendPrintf(e, "\nHeader Stats: %s\n", hs->label);
1731 storeAppendPrintf(e, "\nField type distribution\n");
1732 storeAppendPrintf(e, "%2s\t %-20s\t %5s\t %6s\n",
1733 "id", "name", "count", "#/header");
1735 storeAppendPrintf(e, "\nCache-control directives distribution\n");
1736 storeAppendPrintf(e, "%2s\t %-20s\t %5s\t %6s\n",
1737 "id", "name", "count", "#/cc_field");
1739 storeAppendPrintf(e, "\nSurrogate-control directives distribution\n");
1740 storeAppendPrintf(e, "%2s\t %-20s\t %5s\t %6s\n",
1741 "id", "name", "count", "#/sc_field");
1743 storeAppendPrintf(e, "\nNumber of fields per header distribution\n");
1744 storeAppendPrintf(e, "%2s\t %-5s\t %5s\t %6s\n",
1745 "id", "#flds", "count", "%total");
1747 storeAppendPrintf(e, "\n");
1748 dump_stat = nullptr;
1749}
1750
1751void
1753{
1754 assert(e);
1755
1756 HttpHeaderStats[0].parsedCount =
1757 HttpHeaderStats[hoRequest].parsedCount + HttpHeaderStats[hoReply].parsedCount;
1758 HttpHeaderStats[0].ccParsedCount =
1759 HttpHeaderStats[hoRequest].ccParsedCount + HttpHeaderStats[hoReply].ccParsedCount;
1760 HttpHeaderStats[0].destroyedCount =
1761 HttpHeaderStats[hoRequest].destroyedCount + HttpHeaderStats[hoReply].destroyedCount;
1762 HttpHeaderStats[0].busyDestroyedCount =
1763 HttpHeaderStats[hoRequest].busyDestroyedCount + HttpHeaderStats[hoReply].busyDestroyedCount;
1764
1765 for (const auto &stats: HttpHeaderStats)
1766 httpHeaderStatDump(&stats, e);
1767
1768 /* field stats for all messages */
1769 storeAppendPrintf(e, "\nHttp Fields Stats (replies and requests)\n");
1770
1771 storeAppendPrintf(e, "%2s\t %-25s\t %5s\t %6s\t %6s\n",
1772 "id", "name", "#alive", "%err", "%repeat");
1773
1774 // scan heaaderTable and output
1775 for (auto h : WholeEnum<Http::HdrType>()) {
1776 auto stats = headerStatsTable[h];
1777 storeAppendPrintf(e, "%2d\t %-25s\t %5d\t %6.3f\t %6.3f\n",
1778 Http::HeaderLookupTable.lookup(h).id,
1779 Http::HeaderLookupTable.lookup(h).name,
1780 stats.aliveCount,
1781 xpercent(stats.errCount, stats.parsCount),
1782 xpercent(stats.repCount, stats.seenCount));
1783 }
1784
1785 storeAppendPrintf(e, "Headers Parsed: %d + %d = %d\n",
1786 HttpHeaderStats[hoRequest].parsedCount,
1787 HttpHeaderStats[hoReply].parsedCount,
1788 HttpHeaderStats[0].parsedCount);
1789 storeAppendPrintf(e, "Hdr Fields Parsed: %d\n", HeaderEntryParsedCount);
1790}
1791
1792int
1793HttpHeader::hasListMember(Http::HdrType id, const char *member, const char separator) const
1794{
1795 int result = 0;
1796 const char *pos = nullptr;
1797 const char *item;
1798 int ilen;
1799 int mlen = strlen(member);
1800
1801 assert(any_registered_header(id));
1802
1803 String header (getStrOrList(id));
1804
1805 while (strListGetItem(&header, separator, &item, &ilen, &pos)) {
1806 if (strncasecmp(item, member, mlen) == 0
1807 && (item[mlen] == '=' || item[mlen] == separator || item[mlen] == ';' || item[mlen] == '\0')) {
1808 result = 1;
1809 break;
1810 }
1811 }
1812
1813 return result;
1814}
1815
1816int
1817HttpHeader::hasByNameListMember(const char *name, const char *member, const char separator) const
1818{
1819 int result = 0;
1820 const char *pos = nullptr;
1821 const char *item;
1822 int ilen;
1823 int mlen = strlen(member);
1824
1825 assert(name);
1826
1827 String header (getByName(name));
1828
1829 while (strListGetItem(&header, separator, &item, &ilen, &pos)) {
1830 if (strncasecmp(item, member, mlen) == 0
1831 && (item[mlen] == '=' || item[mlen] == separator || item[mlen] == ';' || item[mlen] == '\0')) {
1832 result = 1;
1833 break;
1834 }
1835 }
1836
1837 return result;
1838}
1839
1840void
1842{
1844
1845 const HttpHeaderEntry *e;
1847 int headers_deleted = 0;
1848 while ((e = getEntry(&pos))) {
1849 Http::HdrType id = e->id;
1850 if (Http::HeaderLookupTable.lookup(id).hopbyhop) {
1851 delAt(pos, headers_deleted);
1852 CBIT_CLR(mask, id);
1853 }
1854 }
1855}
1856
1857void
1859{
1861 /* anything that matches Connection list member will be deleted */
1862 String strConnection;
1863
1864 (void) getList(Http::HdrType::CONNECTION, &strConnection);
1865 const HttpHeaderEntry *e;
1867 /*
1868 * think: on-average-best nesting of the two loops (hdrEntry
1869 * and strListItem) @?@
1870 */
1871 /*
1872 * maybe we should delete standard stuff ("keep-alive","close")
1873 * from strConnection first?
1874 */
1875
1876 int headers_deleted = 0;
1877 while ((e = getEntry(&pos))) {
1878 if (strListIsMember(&strConnection, e->name, ','))
1879 delAt(pos, headers_deleted);
1880 }
1881 if (headers_deleted)
1882 refreshMask();
1883 }
1884}
1885
#define Assure(condition)
Definition Assure.h:35
int etagParseInit(ETag *etag, const char *str)
Definition ETag.cc:29
#define Here()
source code location of the caller
Definition Here.h:15
void httpHdrCcUpdateStats(const HttpHdrCc *cc, StatHist *hist)
Definition HttpHdrCc.cc:342
void httpHdrCcStatDumper(StoreEntry *sentry, int, double val, double, int count)
Definition HttpHdrCc.cc:352
void httpHdrContRangePackInto(const HttpHdrContRange *range, Packable *p)
HttpHdrContRange * httpHdrContRangeParseCreate(const char *str)
void httpHdrScStatDumper(StoreEntry *sentry, int, double val, double, int count)
Definition HttpHdrSc.cc:266
HttpHdrSc * httpHdrScParseCreate(const String &str)
Definition HttpHdrSc.cc:59
void httpHdrScInitModule(void)
Definition HttpHdrSc.cc:48
char HttpHeaderMask[12]
bool httpHeaderParseOffset(const char *start, int64_t *value, char **endPtr)
int httpHeaderParseInt(const char *start, int *value)
void httpHeaderPutStrf(HttpHeader *hdr, Http::HdrType id, const char *fmt,...)
static std::array< HttpHeaderStat, hoEnd > HttpHeaderStats
Definition HttpHeader.cc:80
static HttpHeaderMask RequestHeadersMask
Definition HttpHeader.cc:73
SBuf httpHeaderQuoteString(const char *raw)
quotes string using RFC 7230 quoted-string rules
static int HeaderEntryParsedCount
Definition HttpHeader.cc:94
static void httpHeaderStoreReport(StoreEntry *e)
static const char * getStringPrefix(const char *str, size_t sz)
#define SHORT_PREFIX_SIZE
const HttpHeaderStat * dump_stat
static void httpHeaderFieldStatDumper(StoreEntry *sentry, int, double val, double, int count)
static void httpHeaderFldsPerHdrDumper(StoreEntry *sentry, int idx, double val, double, int count)
static void httpHeaderRegisterWithCacheManager(void)
static void httpHeaderStatDump(const HttpHeaderStat *hs, StoreEntry *e)
std::vector< HttpHeaderFieldStat > headerStatsTable(Http::HdrType::enumEnd_)
int httpHeaderParseQuotedString(const char *start, const int len, String *val)
static void httpHeaderNoteParsedEntry(Http::HdrType id, String const &value, bool error)
void httpHeaderInitModule(void)
static void httpHeaderMaskInit(HttpHeaderMask *mask, int value)
static HttpHeaderMask ReplyHeadersMask
Definition HttpHeader.cc:76
http_hdr_owner_type
Definition HttpHeader.h:31
@ hoRequest
Definition HttpHeader.h:36
@ hoNone
Definition HttpHeader.h:32
@ hoReply
Definition HttpHeader.h:37
@ hoEnd
Definition HttpHeader.h:41
ssize_t HttpHeaderPos
Definition HttpHeader.h:45
#define HttpHeaderInitPos
Definition HttpHeader.h:48
class SquidConfig Config
int strListGetItem(const String *str, char del, const char **item, int *ilen, const char **pos)
Definition StrList.cc:78
void strListAdd(String &str, const char *item, const size_t itemSize, const char delimiter)
Appends the given item of a given size to a delimiter-separated list in str.
Definition StrList.cc:18
int strListIsMember(const String *list, const SBuf &m, char del)
Definition StrList.cc:46
SBuf StringToSBuf(const String &s)
create a new SBuf from a String by copying contents
void error(char *format,...)
#define assert(EX)
Definition assert.h:17
void base64_decode_init(struct base64_decode_ctx *ctx)
Definition base64.cc:54
int base64_decode_update(struct base64_decode_ctx *ctx, size_t *dst_length, uint8_t *dst, size_t src_length, const char *src)
Definition base64.cc:129
int base64_decode_final(struct base64_decode_ctx *ctx)
Definition base64.cc:159
#define BASE64_DECODE_LENGTH(length)
Definition base64.h:116
unsigned int major
major version number
ProtocolType protocol
which protocol this version is for
unsigned int minor
minor version number
static const CharacterSet TCHAR
Definition ETag.h:18
const char * str
quoted-string
Definition ETag.h:20
bool parse(const String &s)
parse a header-string and fill in appropriate values.
Definition HttpHdrCc.cc:117
void packInto(Packable *p) const
Definition HttpHdrCc.cc:268
void packInto(Packable *p) const
static HttpHdrRange * ParseCreate(const String *range_spec)
void packInto(Packable *p) const
Definition HttpHdrSc.cc:223
void updateStats(StatHist *) const
Definition HttpHdrSc.cc:245
void packInto(Packable *p) const
static HttpHeaderEntry * parse(const char *field_start, const char *field_end, const http_hdr_owner_type msgType)
int getInt() const
HttpHeaderEntry * clone() const
size_t length() const
expected number of bytes written by packInto(), including ": " and CRLF
Definition HttpHeader.h:64
int64_t getInt64() const
HttpHeaderEntry(Http::HdrType id, const SBuf &name, const char *value)
Http::HdrType id
Definition HttpHeader.h:66
HTTP per header statistics.
StatHist scTypeDistr
HttpHeaderMask * owner_mask
const char * label
StatHist fieldTypeDistr
StatHist hdrUCountDistr
StatHist ccTypeDistr
SBuf getByNameListMember(const char *name, const char *member, const char separator) const
void removeHopByHopEntries()
void putStr(Http::HdrType id, const char *str)
TimeOrTag getTimeOrTag(Http::HdrType id) const
HttpHdrCc * getCc() const
bool getByIdIfPresent(Http::HdrType id, String *result) const
int hasByNameListMember(const char *name, const char *member, const char separator) const
void delAt(HttpHeaderPos pos, int &headers_deleted)
HttpHeader(const http_hdr_owner_type owner)
int parse(const char *header_start, size_t len, Http::ContentLengthInterpreter &interpreter)
SBuf getListMember(Http::HdrType id, const char *member, const char separator) const
void putCc(const HttpHdrCc &cc)
String getStrOrList(Http::HdrType id) const
ETag getETag(Http::HdrType id) const
void putInt(Http::HdrType id, int number)
void compact()
http_hdr_owner_type owner
Definition HttpHeader.h:177
int delById(Http::HdrType id)
String getList(Http::HdrType id) const
bool conflictingContentLength_
Definition HttpHeader.h:194
void putContRange(const HttpHdrContRange *cr)
void refreshMask()
void update(const HttpHeader *fresh)
SBuf getAuthToken(Http::HdrType id, const char *auth_scheme) const
HttpHeaderEntry * getEntry(HttpHeaderPos *pos) const
static bool Isolate(const char **parse_start, size_t l, const char **blk_start, const char **blk_end)
const char * getStr(Http::HdrType id) const
std::vector< HttpHeaderEntry *, PoolingAllocator< HttpHeaderEntry * > > entries
Definition HttpHeader.h:175
HttpHeader & operator=(const HttpHeader &other)
void putSc(HttpHdrSc *sc)
bool teUnsupported_
Definition HttpHeader.h:197
bool needUpdate(const HttpHeader *fresh) const
void putRange(const HttpHdrRange *range)
void addEntry(HttpHeaderEntry *e)
HttpHdrContRange * getContRange() const
void putInt64(Http::HdrType id, int64_t number)
void removeConnectionHeaderEntries()
String getByName(const SBuf &name) const
time_t getTime(Http::HdrType id) const
HttpHdrRange * getRange() const
void addVia(const AnyP::ProtocolVersion &ver, const HttpHeader *from=nullptr)
int has(Http::HdrType id) const
int64_t getInt64(Http::HdrType id) const
String getById(Http::HdrType id) const
void clean()
bool hasNamed(const SBuf &s, String *value=nullptr) const
int getInt(Http::HdrType id) const
HttpHeaderEntry * findEntry(Http::HdrType id) const
void putAuth(const char *auth_scheme, const char *realm)
const char * getLastStr(Http::HdrType id) const
void putExt(const char *name, const char *value)
HttpHeaderMask mask
Definition HttpHeader.h:176
void putTime(Http::HdrType id, time_t htime)
void updateOrAddStr(Http::HdrType, const SBuf &)
HttpHdrSc * getSc() const
void packInto(Packable *p, bool mask_sensitive_info=false) const
HttpHeaderEntry * findLastEntry(Http::HdrType id) const
void append(const HttpHeader *src)
bool skipUpdateHeader(const Http::HdrType id) const
int hasListMember(Http::HdrType id, const char *member, const char separator) const
int delByName(const SBuf &name)
bool sawBad
whether a malformed Content-Length value was present
const char * headerWideProblem
worst header-wide problem found (or nil)
const HeaderTableRecord & lookup(const char *buf, const std::size_t len) const
look record type up by name (C-string and length)
void clean()
Definition MemBuf.cc:110
void init(mb_size_t szInit, mb_size_t szMax)
Definition MemBuf.cc:93
char * buf
Definition MemBuf.h:134
virtual void append(const char *buf, int size)=0
Appends a c-string to existing packed data.
Definition Raw.h:21
Definition SBuf.h:94
char * rawAppendStart(size_type anticipatedSize)
Definition SBuf.cc:136
int caseCmp(const SBuf &S, const size_type n) const
shorthand version for case-insensitive compare()
Definition SBuf.h:287
const char * rawContent() const
Definition SBuf.cc:509
const char * c_str()
Definition SBuf.cc:516
size_type length() const
Returns the number of bytes stored in SBuf.
Definition SBuf.h:419
SBuf & appendf(const char *fmt,...) PRINTF_FORMAT_ARG2
Definition SBuf.cc:229
int cmp(const SBuf &S, const size_type n) const
shorthand version for compare()
Definition SBuf.h:279
int plength() const
Definition SBuf.h:426
bool isEmpty() const
Definition SBuf.h:435
SBuf & append(const SBuf &S)
Definition SBuf.cc:185
void rawAppendFinish(const char *start, size_type actualSize)
Definition SBuf.cc:144
struct SquidConfig::@90 onoff
int relaxed_header_parser
void dump(StoreEntry *sentry, StatHistBinDumper *bd) const
Definition StatHist.cc:171
static size_type SizeMaxXXX()
Definition SquidString.h:72
void clean()
Definition String.cc:104
void assign(const char *str, int len)
Definition String.cc:79
char const * rawBuf() const
Definition SquidString.h:91
char const * termedBuf() const
Definition SquidString.h:97
void append(char const *buf, int len)
Definition String.cc:131
int caseCmp(char const *) const
Definition String.cc:273
size_type size() const
Definition SquidString.h:78
an std::runtime_error with thrower location info
ETag tag
Definition TimeOrTag.h:20
time_t time
Definition TimeOrTag.h:21
int valid
Definition TimeOrTag.h:22
A const & min(A const &lhs, A const &rhs)
#define DBG_IMPORTANT
Definition Stream.h:38
#define debugs(SECTION, LEVEL, CONTENT)
Definition Stream.h:192
#define DBG_CRITICAL
Definition Stream.h:37
#define CBIT_SET(mask, bit)
Definition defines.h:72
#define CBIT_CLR(mask, bit)
Definition defines.h:73
#define CBIT_TEST(mask, bit)
Definition defines.h:74
char ThisCache[RFC2181_MAXHOSTNAMELEN<< 1]
size_t headersEnd(const char *mime, size_t l, bool &containsObsFold)
const char * ProtocolType_str[]
@ PROTO_NONE
@ PROTO_HTTPS
@ PROTO_UNKNOWN
@ PROTO_HTTP
SBuf SlowlyParseQuotedString(const char *description, const char *start, size_t length)
@ PROXY_AUTHORIZATION
@ TRANSFER_ENCODING
const HeaderLookupTable_t HeaderLookupTable
bool any_valid_header(const Http::HdrType id)
match any valid header type, including OTHER but not BAD
void RegisterAction(char const *action, char const *desc, OBJH *handler, Protected, Atomic, Format)
time_t ParseRfc1123(const char *)
Convert from RFC 1123 style time: "www, DD MMM YYYY hh:mm:ss ZZZ".
Definition rfc1123.cc:159
const char * FormatRfc1123(time_t)
Definition rfc1123.cc:202
SBuf ToSBuf(Args &&... args)
slowly stream-prints all arguments into a freshly allocated SBuf
Definition Stream.h:63
#define LOCAL_ARRAY(type, name, size)
Definition squid.h:62
void storeAppendPrintf(StoreEntry *e, const char *fmt,...)
Definition store.cc:855
number
double xpercent(double part, double whole)
Definition util.cc:40
double xdiv(double nom, double denom)
Definition util.cc:53
const char * xitoa(int num)
Definition util.cc:60
const char * xint64toa(int64_t num)
Definition util.cc:69
#define xisspace(x)
Definition xis.h:15
char * xstrncpy(char *dst, const char *src, size_t n)
Definition xstring.cc:37