2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
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.
9 /* DEBUG: section 55 HTTP Header */
12 #include "base/EnumIterator.h"
15 #include "HttpHdrCc.h"
16 #include "HttpHdrContRange.h"
17 #include "HttpHdrScTarget.h" // also includes HttpHdrSc.h
18 #include "HttpHeader.h"
19 #include "HttpHeaderFieldInfo.h"
20 #include "HttpHeaderStat.h"
21 #include "HttpHeaderTools.h"
23 #include "mgr/Registration.h"
24 #include "profiler/Profiler.h"
26 #include "SquidConfig.h"
27 //#include "SquidString.h" // pulled by HttpHdrCc.h
31 #include "TimeOrTag.h"
36 /* XXX: the whole set of API managing the entries vector should be rethought
37 * after the parse4r-ng effort is complete.
41 * On naming conventions:
43 * HTTP/1.1 defines message-header as
45 * message-header = field-name ":" [ field-value ] CRLF
47 * field-value = *( field-content | LWS )
49 * HTTP/1.1 does not give a name name a group of all message-headers in a message.
50 * Squid 1.1 seems to refer to that group _plus_ start-line as "headers".
52 * HttpHeader is an object that represents all message-headers in a message.
53 * HttpHeader does not manage start-line.
55 * HttpHeader is implemented as a collection of header "entries".
56 * An entry is a (field_id, field_name, field_value) triplet.
60 * local constants and vars
63 // statistics counters for headers. clients must not allow Http::HdrType::BAD_HDR to be counted
64 std::vector
<HttpHeaderFieldStat
> headerStatsTable(Http::HdrType::enumEnd_
);
66 /* request-only headers. Used for cachemgr */
67 static HttpHeaderMask RequestHeadersMask
; /* set run-time using RequestHeaders */
69 /* reply-only headers. Used for cachemgr */
70 static HttpHeaderMask ReplyHeadersMask
; /* set run-time using ReplyHeaders */
72 /* header accounting */
73 // NP: keep in sync with enum http_hdr_owner_type
74 static HttpHeaderStat HttpHeaderStats
[] = {
75 HttpHeaderStat(/*hoNone*/ "all", NULL
),
77 HttpHeaderStat(/*hoHtcpReply*/ "HTCP reply", &ReplyHeadersMask
),
79 HttpHeaderStat(/*hoRequest*/ "request", &RequestHeadersMask
),
80 HttpHeaderStat(/*hoReply*/ "reply", &ReplyHeadersMask
)
86 static int HttpHeaderStatCount
= countof(HttpHeaderStats
);
88 static int HeaderEntryParsedCount
= 0;
91 * forward declarations and local routines
96 // update parse statistics for header id; if error is true also account
97 // for errors and write to debug log what happened
98 static void httpHeaderNoteParsedEntry(Http::HdrType id
, String
const &value
, bool error
);
99 static void httpHeaderStatDump(const HttpHeaderStat
* hs
, StoreEntry
* e
);
100 /** store report about current header usage and other stats */
101 static void httpHeaderStoreReport(StoreEntry
* e
);
104 * Module initialization routines
108 httpHeaderRegisterWithCacheManager(void)
110 Mgr::RegisterAction("http_headers",
111 "HTTP Header Statistics",
112 httpHeaderStoreReport
, 0, 1);
116 httpHeaderInitModule(void)
118 /* check that we have enough space for masks */
119 assert(8 * sizeof(HttpHeaderMask
) >= Http::HdrType::enumEnd_
);
121 // masks are needed for stats page still
122 for (auto h
: WholeEnum
<Http::HdrType
>()) {
123 if (Http::HeaderLookupTable
.lookup(h
).request
)
124 CBIT_SET(RequestHeadersMask
,h
);
125 if (Http::HeaderLookupTable
.lookup(h
).reply
)
126 CBIT_SET(ReplyHeadersMask
,h
);
129 /* header stats initialized by class constructor */
130 assert(HttpHeaderStatCount
== hoReply
+ 1);
132 /* init dependent modules */
133 httpHdrCcInitModule();
134 httpHdrScInitModule();
136 httpHeaderRegisterWithCacheManager();
140 * HttpHeader Implementation
143 HttpHeader::HttpHeader() : owner (hoNone
), len (0), conflictingContentLength_(false)
145 httpHeaderMaskInit(&mask
, 0);
148 HttpHeader::HttpHeader(const http_hdr_owner_type anOwner
): owner(anOwner
), len(0), conflictingContentLength_(false)
150 assert(anOwner
> hoNone
&& anOwner
< hoEnd
);
151 debugs(55, 7, "init-ing hdr: " << this << " owner: " << owner
);
152 httpHeaderMaskInit(&mask
, 0);
155 HttpHeader::HttpHeader(const HttpHeader
&other
): owner(other
.owner
), len(other
.len
), conflictingContentLength_(false)
157 httpHeaderMaskInit(&mask
, 0);
158 update(&other
, NULL
); // will update the mask as well
161 HttpHeader::~HttpHeader()
167 HttpHeader::operator =(const HttpHeader
&other
)
169 if (this != &other
) {
170 // we do not really care, but the caller probably does
171 assert(owner
== other
.owner
);
173 update(&other
, NULL
); // will update the mask as well
175 conflictingContentLength_
= other
.conflictingContentLength_
;
184 assert(owner
> hoNone
&& owner
< hoEnd
);
185 debugs(55, 7, "cleaning hdr: " << this << " owner: " << owner
);
187 PROF_start(HttpHeaderClean
);
189 if (owner
<= hoReply
) {
191 * An unfortunate bug. The entries array is initialized
192 * such that count is set to zero. httpHeaderClean() seems to
193 * be called both when 'hdr' is created, and destroyed. Thus,
194 * we accumulate a large number of zero counts for 'hdr' before
195 * it is ever used. Can't think of a good way to fix it, except
196 * adding a state variable that indicates whether or not 'hdr'
197 * has been used. As a hack, just never count zero-sized header
200 if (!entries
.empty())
201 HttpHeaderStats
[owner
].hdrUCountDistr
.count(entries
.size());
203 ++ HttpHeaderStats
[owner
].destroyedCount
;
205 HttpHeaderStats
[owner
].busyDestroyedCount
+= entries
.size() > 0;
206 } // if (owner <= hoReply)
208 for (HttpHeaderEntry
*e
: entries
) {
211 if (!Http::any_valid_header(e
->id
)) {
212 debugs(55, DBG_CRITICAL
, "BUG: invalid entry (" << e
->id
<< "). Ignored.");
214 if (owner
<= hoReply
)
215 HttpHeaderStats
[owner
].fieldTypeDistr
.count(e
->id
);
221 httpHeaderMaskInit(&mask
, 0);
223 conflictingContentLength_
= false;
224 PROF_stop(HttpHeaderClean
);
227 /* append entries (also see httpHeaderUpdate) */
229 HttpHeader::append(const HttpHeader
* src
)
233 debugs(55, 7, "appending hdr: " << this << " += " << src
);
235 for (auto e
: src
->entries
) {
237 addEntry(e
->clone());
242 HttpHeader::update (HttpHeader
const *fresh
, HttpHeaderMask
const *denied_mask
)
244 const HttpHeaderEntry
*e
;
245 HttpHeaderPos pos
= HttpHeaderInitPos
;
247 assert(this != fresh
);
249 while ((e
= fresh
->getEntry(&pos
))) {
250 /* deny bad guys (ok to check for Http::HdrType::OTHER) here */
252 if (denied_mask
&& CBIT_TEST(*denied_mask
, e
->id
))
255 if (e
->id
!= Http::HdrType::OTHER
)
258 delByName(e
->name
.termedBuf());
261 pos
= HttpHeaderInitPos
;
262 while ((e
= fresh
->getEntry(&pos
))) {
263 /* deny bad guys (ok to check for Http::HdrType::OTHER) here */
265 if (denied_mask
&& CBIT_TEST(*denied_mask
, e
->id
))
268 debugs(55, 7, "Updating header '" << Http::HeaderLookupTable
.lookup(e
->id
).name
<< "' in cached entry");
270 addEntry(e
->clone());
275 HttpHeader::parse(const char *header_start
, size_t hdrLen
)
277 const char *field_ptr
= header_start
;
278 const char *header_end
= header_start
+ hdrLen
; // XXX: remove
279 HttpHeaderEntry
*e
, *e2
;
280 int warnOnError
= (Config
.onoff
.relaxed_header_parser
<= 0 ? DBG_IMPORTANT
: 2);
282 PROF_start(HttpHeaderParse
);
284 assert(header_start
&& header_end
);
285 debugs(55, 7, "parsing hdr: (" << this << ")" << std::endl
<< getStringPrefix(header_start
, hdrLen
));
286 ++ HttpHeaderStats
[owner
].parsedCount
;
289 if ((nulpos
= (char*)memchr(header_start
, '\0', hdrLen
))) {
290 debugs(55, DBG_IMPORTANT
, "WARNING: HTTP header contains NULL characters {" <<
291 getStringPrefix(header_start
, nulpos
-header_start
) << "}\nNULL\n{" << getStringPrefix(nulpos
+1, hdrLen
-(nulpos
-header_start
)-1));
292 PROF_stop(HttpHeaderParse
);
297 /* common format headers are "<name>:[ws]<value>" lines delimited by <CRLF>.
298 * continuation lines start with a (single) space or tab */
299 while (field_ptr
< header_end
) {
300 const char *field_start
= field_ptr
;
301 const char *field_end
;
304 const char *this_line
= field_ptr
;
305 field_ptr
= (const char *)memchr(field_ptr
, '\n', header_end
- field_ptr
);
309 PROF_stop(HttpHeaderParse
);
314 field_end
= field_ptr
;
316 ++field_ptr
; /* Move to next line */
318 if (field_end
> this_line
&& field_end
[-1] == '\r') {
319 --field_end
; /* Ignore CR LF */
321 if (owner
== hoRequest
&& field_end
> this_line
) {
323 for (const char *p
= this_line
; p
< field_end
&& cr_only
; ++p
) {
328 debugs(55, DBG_IMPORTANT
, "SECURITY WARNING: Rejecting HTTP request with a CR+ "
329 "header field to prevent request smuggling attacks: {" <<
330 getStringPrefix(header_start
, hdrLen
) << "}");
331 PROF_stop(HttpHeaderParse
);
338 /* Barf on stray CR characters */
339 if (memchr(this_line
, '\r', field_end
- this_line
)) {
340 debugs(55, warnOnError
, "WARNING: suspicious CR characters in HTTP header {" <<
341 getStringPrefix(field_start
, field_end
-field_start
) << "}");
343 if (Config
.onoff
.relaxed_header_parser
) {
344 char *p
= (char *) this_line
; /* XXX Warning! This destroys original header content and violates specifications somewhat */
346 while ((p
= (char *)memchr(p
, '\r', field_end
- p
)) != NULL
) {
351 PROF_stop(HttpHeaderParse
);
357 if (this_line
+ 1 == field_end
&& this_line
> field_start
) {
358 debugs(55, warnOnError
, "WARNING: Blank continuation line in HTTP header {" <<
359 getStringPrefix(header_start
, hdrLen
) << "}");
360 PROF_stop(HttpHeaderParse
);
364 } while (field_ptr
< header_end
&& (*field_ptr
== ' ' || *field_ptr
== '\t'));
366 if (field_start
== field_end
) {
367 if (field_ptr
< header_end
) {
368 debugs(55, warnOnError
, "WARNING: unparseable HTTP header field near {" <<
369 getStringPrefix(field_start
, hdrLen
-(field_start
-header_start
)) << "}");
370 PROF_stop(HttpHeaderParse
);
375 break; /* terminating blank line */
378 if ((e
= HttpHeaderEntry::parse(field_start
, field_end
)) == NULL
) {
379 debugs(55, warnOnError
, "WARNING: unparseable HTTP header field {" <<
380 getStringPrefix(field_start
, field_end
-field_start
) << "}");
381 debugs(55, warnOnError
, " in {" << getStringPrefix(header_start
, hdrLen
) << "}");
383 if (Config
.onoff
.relaxed_header_parser
)
386 PROF_stop(HttpHeaderParse
);
391 // XXX: RFC 7230 Section 3.3.3 item #4 requires sending a 502 error in
392 // several cases that we do not yet cover. TODO: Rewrite to cover more.
393 if (e
->id
== Http::HdrType::CONTENT_LENGTH
&& (e2
= findEntry(e
->id
)) != nullptr) {
394 if (e
->value
!= e2
->value
) {
396 debugs(55, warnOnError
, "WARNING: found two conflicting content-length headers in {" <<
397 getStringPrefix(header_start
, hdrLen
) << "}");
399 if (!Config
.onoff
.relaxed_header_parser
) {
401 PROF_stop(HttpHeaderParse
);
406 if (!httpHeaderParseOffset(e
->value
.termedBuf(), &l1
)) {
407 debugs(55, DBG_IMPORTANT
, "WARNING: Unparseable content-length '" << e
->value
<< "'");
410 } else if (!httpHeaderParseOffset(e2
->value
.termedBuf(), &l2
)) {
411 debugs(55, DBG_IMPORTANT
, "WARNING: Unparseable content-length '" << e2
->value
<< "'");
415 conflictingContentLength_
= true;
420 debugs(55, warnOnError
, "NOTICE: found double content-length header");
423 if (Config
.onoff
.relaxed_header_parser
)
426 PROF_stop(HttpHeaderParse
);
432 if (e
->id
== Http::HdrType::OTHER
&& stringHasWhitespace(e
->name
.termedBuf())) {
433 debugs(55, warnOnError
, "WARNING: found whitespace in HTTP header name {" <<
434 getStringPrefix(field_start
, field_end
-field_start
) << "}");
436 if (!Config
.onoff
.relaxed_header_parser
) {
438 PROF_stop(HttpHeaderParse
);
448 // RFC 2616 section 4.4: ignore Content-Length with Transfer-Encoding
449 delById(Http::HdrType::CONTENT_LENGTH
);
450 // RFC 7230 section 3.3.3 #4: ignore Content-Length conflicts with Transfer-Encoding
451 conflictingContentLength_
= false;
452 } else if (conflictingContentLength_
) {
453 // ensure our callers do not see the conflicting Content-Length value
454 delById(Http::HdrType::CONTENT_LENGTH
);
457 PROF_stop(HttpHeaderParse
);
458 return 1; /* even if no fields where found, it is a valid header */
461 /* packs all the entries using supplied packer */
463 HttpHeader::packInto(Packable
* p
, bool mask_sensitive_info
) const
465 HttpHeaderPos pos
= HttpHeaderInitPos
;
466 const HttpHeaderEntry
*e
;
468 debugs(55, 7, this << " into " << p
<<
469 (mask_sensitive_info
? " while masking" : ""));
470 /* pack all entries one by one */
471 while ((e
= getEntry(&pos
))) {
472 if (!mask_sensitive_info
) {
477 bool maskThisEntry
= false;
479 case Http::HdrType::AUTHORIZATION
:
480 case Http::HdrType::PROXY_AUTHORIZATION
:
481 maskThisEntry
= true;
484 case Http::HdrType::FTP_ARGUMENTS
:
485 if (const HttpHeaderEntry
*cmd
= findEntry(Http::HdrType::FTP_COMMAND
))
486 maskThisEntry
= (cmd
->value
== "PASS");
493 p
->append(e
->name
.rawBuf(), e
->name
.size());
494 p
->append(": ** NOT DISPLAYED **\r\n", 23);
500 /* Pack in the "special" entries */
505 /* returns next valid entry */
507 HttpHeader::getEntry(HttpHeaderPos
* pos
) const
510 assert(*pos
>= HttpHeaderInitPos
&& *pos
< static_cast<ssize_t
>(entries
.size()));
512 for (++(*pos
); *pos
< static_cast<ssize_t
>(entries
.size()); ++(*pos
)) {
514 return static_cast<HttpHeaderEntry
*>(entries
[*pos
]);
521 * returns a pointer to a specified entry if any
522 * note that we return one entry so it does not make much sense to ask for
526 HttpHeader::findEntry(Http::HdrType id
) const
528 assert(any_registered_header(id
));
529 assert(!Http::HeaderLookupTable
.lookup(id
).list
);
531 /* check mask first */
533 if (!CBIT_TEST(mask
, id
))
536 /* looks like we must have it, do linear search */
537 for (auto e
: entries
) {
538 if (e
&& e
->id
== id
)
542 /* hm.. we thought it was there, but it was not found */
544 return nullptr; /* not reached */
548 * same as httpHeaderFindEntry
551 HttpHeader::findLastEntry(Http::HdrType id
) const
553 assert(any_registered_header(id
));
554 assert(!Http::HeaderLookupTable
.lookup(id
).list
);
556 /* check mask first */
557 if (!CBIT_TEST(mask
, id
))
560 for (auto e
= entries
.rbegin(); e
!= entries
.rend(); ++e
) {
561 if (*e
&& (*e
)->id
== id
)
565 /* hm.. we thought it was there, but it was not found */
567 return nullptr; /* not reached */
571 * deletes all fields with a given name if any, returns #fields deleted;
574 HttpHeader::delByName(const char *name
)
577 HttpHeaderPos pos
= HttpHeaderInitPos
;
579 httpHeaderMaskInit(&mask
, 0); /* temporal inconsistency */
580 debugs(55, 9, "deleting '" << name
<< "' fields in hdr " << this);
582 while ((e
= getEntry(&pos
))) {
583 if (!e
->name
.caseCmp(name
))
586 CBIT_SET(mask
, e
->id
);
592 /* deletes all entries with a given id, returns the #entries deleted */
594 HttpHeader::delById(Http::HdrType id
)
596 debugs(55, 8, this << " del-by-id " << id
);
597 assert(any_registered_header(id
));
600 if (!CBIT_TEST(mask
, id
))
603 //replace matching items with nil and count them
604 std::replace_if(entries
.begin(), entries
.end(),
605 [&](const HttpHeaderEntry
*e
) {
606 if (e
&& e
->id
== id
) {
620 * deletes an entry at pos and leaves a gap; leaving a gap makes it
621 * possible to iterate(search) and delete fields at the same time
622 * NOTE: Does not update the header mask. Caller must follow up with
623 * a call to refreshMask() if headers_deleted was incremented.
626 HttpHeader::delAt(HttpHeaderPos pos
, int &headers_deleted
)
629 assert(pos
>= HttpHeaderInitPos
&& pos
< static_cast<ssize_t
>(entries
.size()));
630 e
= static_cast<HttpHeaderEntry
*>(entries
[pos
]);
632 /* decrement header length, allow for ": " and crlf */
633 len
-= e
->name
.size() + 2 + e
->value
.size() + 2;
640 * Compacts the header storage
643 HttpHeader::compact()
645 // TODO: optimize removal, or possibly make it so that's not needed.
646 entries
.erase( std::remove(entries
.begin(), entries
.end(), nullptr),
651 * Refreshes the header mask. Required after delAt() calls.
654 HttpHeader::refreshMask()
656 httpHeaderMaskInit(&mask
, 0);
657 debugs(55, 7, "refreshing the mask in hdr " << this);
658 for (auto e
: entries
) {
660 CBIT_SET(mask
, e
->id
);
665 * does not call e->clone() so one should not reuse "*e"
668 HttpHeader::addEntry(HttpHeaderEntry
* e
)
671 assert(any_HdrType_enum_value(e
->id
));
672 assert(e
->name
.size());
674 debugs(55, 7, this << " adding entry: " << e
->id
<< " at " << entries
.size());
676 if (e
->id
!= Http::HdrType::BAD_HDR
) {
677 if (CBIT_TEST(mask
, e
->id
)) {
678 ++ headerStatsTable
[e
->id
].repCount
;
680 CBIT_SET(mask
, e
->id
);
684 entries
.push_back(e
);
686 /* increment header length, allow for ": " and crlf */
687 len
+= e
->name
.size() + 2 + e
->value
.size() + 2;
691 * does not call e->clone() so one should not reuse "*e"
694 HttpHeader::insertEntry(HttpHeaderEntry
* e
)
697 assert(any_valid_header(e
->id
));
699 debugs(55, 7, this << " adding entry: " << e
->id
<< " at " << entries
.size());
701 // Http::HdrType::BAD_HDR is filtered out by assert_any_valid_header
702 if (CBIT_TEST(mask
, e
->id
)) {
703 ++ headerStatsTable
[e
->id
].repCount
;
705 CBIT_SET(mask
, e
->id
);
708 entries
.insert(entries
.begin(),e
);
710 /* increment header length, allow for ": " and crlf */
711 len
+= e
->name
.size() + 2 + e
->value
.size() + 2;
715 HttpHeader::getList(Http::HdrType id
, String
*s
) const
717 debugs(55, 9, this << " joining for id " << id
);
718 /* only fields from ListHeaders array can be "listed" */
719 assert(Http::HeaderLookupTable
.lookup(id
).list
);
721 if (!CBIT_TEST(mask
, id
))
724 for (auto e
: entries
) {
725 if (e
&& e
->id
== id
)
726 strListAdd(s
, e
->value
.termedBuf(), ',');
730 * note: we might get an empty (size==0) string if there was an "empty"
731 * header. This results in an empty length String, which may have a NULL
734 /* temporary warning: remove it? (Is it useful for diagnostics ?) */
736 debugs(55, 3, "empty list header: " << Http::HeaderLookupTable
.lookup(id
).name
<< "(" << id
<< ")");
738 debugs(55, 6, this << ": joined for id " << id
<< ": " << s
);
743 /* return a list of entries with the same id separated by ',' and ws */
745 HttpHeader::getList(Http::HdrType id
) const
748 HttpHeaderPos pos
= HttpHeaderInitPos
;
749 debugs(55, 9, this << "joining for id " << id
);
750 /* only fields from ListHeaders array can be "listed" */
751 assert(Http::HeaderLookupTable
.lookup(id
).list
);
753 if (!CBIT_TEST(mask
, id
))
758 while ((e
= getEntry(&pos
))) {
760 strListAdd(&s
, e
->value
.termedBuf(), ',');
764 * note: we might get an empty (size==0) string if there was an "empty"
765 * header. This results in an empty length String, which may have a NULL
768 /* temporary warning: remove it? (Is it useful for diagnostics ?) */
770 debugs(55, 3, "empty list header: " << Http::HeaderLookupTable
.lookup(id
).name
<< "(" << id
<< ")");
772 debugs(55, 6, this << ": joined for id " << id
<< ": " << s
);
777 /* return a string or list of entries with the same id separated by ',' and ws */
779 HttpHeader::getStrOrList(Http::HdrType id
) const
783 if (Http::HeaderLookupTable
.lookup(id
).list
)
786 if ((e
= findEntry(id
)))
793 * Returns the value of the specified header and/or an undefined String.
796 HttpHeader::getByName(const char *name
) const
799 // ignore presence: return undefined string if an empty header is present
800 (void)getByNameIfPresent(name
, strlen(name
), result
);
805 HttpHeader::getByName(const SBuf
&name
) const
808 // ignore presence: return undefined string if an empty header is present
809 (void)getByNameIfPresent(name
, result
);
814 HttpHeader::getById(Http::HdrType id
) const
817 (void)getByIdIfPresent(id
,result
);
822 HttpHeader::getByNameIfPresent(const SBuf
&s
, String
&result
) const
824 return getByNameIfPresent(s
.rawContent(), s
.length(), result
);
828 HttpHeader::getByIdIfPresent(Http::HdrType id
, String
&result
) const
830 if (id
== Http::HdrType::BAD_HDR
)
834 result
= getStrOrList(id
);
839 HttpHeader::getByNameIfPresent(const char *name
, int namelen
, String
&result
) const
842 HttpHeaderPos pos
= HttpHeaderInitPos
;
847 /* First try the quick path */
848 id
= Http::HeaderLookupTable
.lookup(name
,namelen
).id
;
850 if (id
!= Http::HdrType::BAD_HDR
) {
851 if (getByIdIfPresent(id
, result
))
855 /* Sorry, an unknown header name. Do linear search */
857 while ((e
= getEntry(&pos
))) {
858 if (e
->id
== Http::HdrType::OTHER
&& e
->name
.caseCmp(name
) == 0) {
860 strListAdd(&result
, e
->value
.termedBuf(), ',');
868 * Returns a the value of the specified list member, if any.
871 HttpHeader::getByNameListMember(const char *name
, const char *member
, const char separator
) const
874 const char *pos
= NULL
;
877 int mlen
= strlen(member
);
881 header
= getByName(name
);
885 while (strListGetItem(&header
, separator
, &item
, &ilen
, &pos
)) {
886 if (strncmp(item
, member
, mlen
) == 0 && item
[mlen
] == '=') {
887 result
.append(item
+ mlen
+ 1, ilen
- mlen
- 1);
896 * returns a the value of the specified list member, if any.
899 HttpHeader::getListMember(Http::HdrType id
, const char *member
, const char separator
) const
902 const char *pos
= NULL
;
905 int mlen
= strlen(member
);
907 assert(any_registered_header(id
));
909 header
= getStrOrList(id
);
912 while (strListGetItem(&header
, separator
, &item
, &ilen
, &pos
)) {
913 if (strncmp(item
, member
, mlen
) == 0 && item
[mlen
] == '=') {
914 result
.append(item
+ mlen
+ 1, ilen
- mlen
- 1);
923 /* test if a field is present */
925 HttpHeader::has(Http::HdrType id
) const
927 assert(any_registered_header(id
));
928 debugs(55, 9, this << " lookup for " << id
);
929 return CBIT_TEST(mask
, id
);
933 HttpHeader::putInt(Http::HdrType id
, int number
)
935 assert(any_registered_header(id
));
936 assert(Http::HeaderLookupTable
.lookup(id
).type
== Http::HdrFieldType::ftInt
); /* must be of an appropriate type */
938 addEntry(new HttpHeaderEntry(id
, NULL
, xitoa(number
)));
942 HttpHeader::putInt64(Http::HdrType id
, int64_t number
)
944 assert(any_registered_header(id
));
945 assert(Http::HeaderLookupTable
.lookup(id
).type
== Http::HdrFieldType::ftInt64
); /* must be of an appropriate type */
947 addEntry(new HttpHeaderEntry(id
, NULL
, xint64toa(number
)));
951 HttpHeader::putTime(Http::HdrType id
, time_t htime
)
953 assert(any_registered_header(id
));
954 assert(Http::HeaderLookupTable
.lookup(id
).type
== Http::HdrFieldType::ftDate_1123
); /* must be of an appropriate type */
956 addEntry(new HttpHeaderEntry(id
, NULL
, mkrfc1123(htime
)));
960 HttpHeader::putStr(Http::HdrType id
, const char *str
)
962 assert(any_registered_header(id
));
963 assert(Http::HeaderLookupTable
.lookup(id
).type
== Http::HdrFieldType::ftStr
); /* must be of an appropriate type */
965 addEntry(new HttpHeaderEntry(id
, NULL
, str
));
969 HttpHeader::putAuth(const char *auth_scheme
, const char *realm
)
971 assert(auth_scheme
&& realm
);
972 httpHeaderPutStrf(this, Http::HdrType::WWW_AUTHENTICATE
, "%s realm=\"%s\"", auth_scheme
, realm
);
976 HttpHeader::putCc(const HttpHdrCc
* cc
)
979 /* remove old directives if any */
980 delById(Http::HdrType::CACHE_CONTROL
);
986 addEntry(new HttpHeaderEntry(Http::HdrType::CACHE_CONTROL
, NULL
, mb
.buf
));
992 HttpHeader::putContRange(const HttpHdrContRange
* cr
)
995 /* remove old directives if any */
996 delById(Http::HdrType::CONTENT_RANGE
);
1000 httpHdrContRangePackInto(cr
, &mb
);
1002 addEntry(new HttpHeaderEntry(Http::HdrType::CONTENT_RANGE
, NULL
, mb
.buf
));
1008 HttpHeader::putRange(const HttpHdrRange
* range
)
1011 /* remove old directives if any */
1012 delById(Http::HdrType::RANGE
);
1016 range
->packInto(&mb
);
1018 addEntry(new HttpHeaderEntry(Http::HdrType::RANGE
, NULL
, mb
.buf
));
1024 HttpHeader::putSc(HttpHdrSc
*sc
)
1027 /* remove old directives if any */
1028 delById(Http::HdrType::SURROGATE_CONTROL
);
1034 addEntry(new HttpHeaderEntry(Http::HdrType::SURROGATE_CONTROL
, NULL
, mb
.buf
));
1040 HttpHeader::putWarning(const int code
, const char *const text
)
1043 snprintf(buf
, sizeof(buf
), "%i %s \"%s\"", code
, visible_appname_string
, text
);
1044 putStr(Http::HdrType::WARNING
, buf
);
1047 /* add extension header (these fields are not parsed/analyzed/joined, etc.) */
1049 HttpHeader::putExt(const char *name
, const char *value
)
1051 assert(name
&& value
);
1052 debugs(55, 8, this << " adds ext entry " << name
<< " : " << value
);
1053 addEntry(new HttpHeaderEntry(Http::HdrType::OTHER
, name
, value
));
1057 HttpHeader::getInt(Http::HdrType id
) const
1059 assert(any_registered_header(id
));
1060 assert(Http::HeaderLookupTable
.lookup(id
).type
== Http::HdrFieldType::ftInt
); /* must be of an appropriate type */
1063 if ((e
= findEntry(id
)))
1070 HttpHeader::getInt64(Http::HdrType id
) const
1072 assert(any_registered_header(id
));
1073 assert(Http::HeaderLookupTable
.lookup(id
).type
== Http::HdrFieldType::ftInt64
); /* must be of an appropriate type */
1076 if ((e
= findEntry(id
)))
1077 return e
->getInt64();
1083 HttpHeader::getTime(Http::HdrType id
) const
1087 assert(any_registered_header(id
));
1088 assert(Http::HeaderLookupTable
.lookup(id
).type
== Http::HdrFieldType::ftDate_1123
); /* must be of an appropriate type */
1090 if ((e
= findEntry(id
))) {
1091 value
= parse_rfc1123(e
->value
.termedBuf());
1092 httpHeaderNoteParsedEntry(e
->id
, e
->value
, value
< 0);
1098 /* sync with httpHeaderGetLastStr */
1100 HttpHeader::getStr(Http::HdrType id
) const
1103 assert(any_registered_header(id
));
1104 assert(Http::HeaderLookupTable
.lookup(id
).type
== Http::HdrFieldType::ftStr
); /* must be of an appropriate type */
1106 if ((e
= findEntry(id
))) {
1107 httpHeaderNoteParsedEntry(e
->id
, e
->value
, false); /* no errors are possible */
1108 return e
->value
.termedBuf();
1116 HttpHeader::getLastStr(Http::HdrType id
) const
1119 assert(any_registered_header(id
));
1120 assert(Http::HeaderLookupTable
.lookup(id
).type
== Http::HdrFieldType::ftStr
); /* must be of an appropriate type */
1122 if ((e
= findLastEntry(id
))) {
1123 httpHeaderNoteParsedEntry(e
->id
, e
->value
, false); /* no errors are possible */
1124 return e
->value
.termedBuf();
1131 HttpHeader::getCc() const
1133 if (!CBIT_TEST(mask
, Http::HdrType::CACHE_CONTROL
))
1135 PROF_start(HttpHeader_getCc
);
1138 getList(Http::HdrType::CACHE_CONTROL
, &s
);
1140 HttpHdrCc
*cc
=new HttpHdrCc();
1142 if (!cc
->parse(s
)) {
1147 ++ HttpHeaderStats
[owner
].ccParsedCount
;
1150 httpHdrCcUpdateStats(cc
, &HttpHeaderStats
[owner
].ccTypeDistr
);
1152 httpHeaderNoteParsedEntry(Http::HdrType::CACHE_CONTROL
, s
, !cc
);
1154 PROF_stop(HttpHeader_getCc
);
1160 HttpHeader::getRange() const
1162 HttpHdrRange
*r
= NULL
;
1164 /* some clients will send "Request-Range" _and_ *matching* "Range"
1165 * who knows, some clients might send Request-Range only;
1166 * this "if" should work correctly in both cases;
1167 * hopefully no clients send mismatched headers! */
1169 if ((e
= findEntry(Http::HdrType::RANGE
)) ||
1170 (e
= findEntry(Http::HdrType::REQUEST_RANGE
))) {
1171 r
= HttpHdrRange::ParseCreate(&e
->value
);
1172 httpHeaderNoteParsedEntry(e
->id
, e
->value
, !r
);
1179 HttpHeader::getSc() const
1181 if (!CBIT_TEST(mask
, Http::HdrType::SURROGATE_CONTROL
))
1186 (void) getList(Http::HdrType::SURROGATE_CONTROL
, &s
);
1188 HttpHdrSc
*sc
= httpHdrScParseCreate(s
);
1190 ++ HttpHeaderStats
[owner
].ccParsedCount
;
1193 sc
->updateStats(&HttpHeaderStats
[owner
].scTypeDistr
);
1195 httpHeaderNoteParsedEntry(Http::HdrType::SURROGATE_CONTROL
, s
, !sc
);
1201 HttpHeader::getContRange() const
1203 HttpHdrContRange
*cr
= NULL
;
1206 if ((e
= findEntry(Http::HdrType::CONTENT_RANGE
))) {
1207 cr
= httpHdrContRangeParseCreate(e
->value
.termedBuf());
1208 httpHeaderNoteParsedEntry(e
->id
, e
->value
, !cr
);
1215 HttpHeader::getAuth(Http::HdrType id
, const char *auth_scheme
) const
1219 assert(auth_scheme
);
1222 if (!field
) /* no authorization field */
1225 l
= strlen(auth_scheme
);
1227 if (!l
|| strncasecmp(field
, auth_scheme
, l
)) /* wrong scheme */
1232 if (!xisspace(*field
)) /* wrong scheme */
1235 /* skip white space */
1236 for (; field
&& xisspace(*field
); ++field
);
1238 if (!*field
) /* no authorization cookie */
1241 static char decodedAuthToken
[8192];
1242 struct base64_decode_ctx ctx
;
1243 base64_decode_init(&ctx
);
1244 size_t decodedLen
= 0;
1245 if (!base64_decode_update(&ctx
, &decodedLen
, reinterpret_cast<uint8_t*>(decodedAuthToken
), strlen(field
), reinterpret_cast<const uint8_t*>(field
)) ||
1246 !base64_decode_final(&ctx
)) {
1249 decodedAuthToken
[decodedLen
] = '\0';
1250 return decodedAuthToken
;
1254 HttpHeader::getETag(Http::HdrType id
) const
1256 ETag etag
= {NULL
, -1};
1258 assert(Http::HeaderLookupTable
.lookup(id
).type
== Http::HdrFieldType::ftETag
); /* must be of an appropriate type */
1260 if ((e
= findEntry(id
)))
1261 etagParseInit(&etag
, e
->value
.termedBuf());
1267 HttpHeader::getTimeOrTag(Http::HdrType id
) const
1271 assert(Http::HeaderLookupTable
.lookup(id
).type
== Http::HdrFieldType::ftDate_1123_or_ETag
); /* must be of an appropriate type */
1272 memset(&tot
, 0, sizeof(tot
));
1274 if ((e
= findEntry(id
))) {
1275 const char *str
= e
->value
.termedBuf();
1276 /* try as an ETag */
1278 if (etagParseInit(&tot
.tag
, str
)) {
1279 tot
.valid
= tot
.tag
.str
!= NULL
;
1282 /* or maybe it is time? */
1283 tot
.time
= parse_rfc1123(str
);
1284 tot
.valid
= tot
.time
>= 0;
1289 assert(tot
.time
< 0 || !tot
.tag
.str
); /* paranoid */
1297 HttpHeaderEntry::HttpHeaderEntry(Http::HdrType anId
, const char *aName
, const char *aValue
)
1299 assert(any_HdrType_enum_value(anId
));
1302 if (id
!= Http::HdrType::OTHER
)
1303 name
= Http::HeaderLookupTable
.lookup(id
).name
;
1309 if (id
!= Http::HdrType::BAD_HDR
)
1310 ++ headerStatsTable
[id
].aliveCount
;
1312 debugs(55, 9, "created HttpHeaderEntry " << this << ": '" << name
<< " : " << value
);
1315 HttpHeaderEntry::~HttpHeaderEntry()
1317 debugs(55, 9, "destroying entry " << this << ": '" << name
<< ": " << value
<< "'");
1319 if (id
!= Http::HdrType::BAD_HDR
) {
1320 assert(headerStatsTable
[id
].aliveCount
);
1321 -- headerStatsTable
[id
].aliveCount
;
1322 id
= Http::HdrType::BAD_HDR
; // it already is BAD_HDR, no sense in resetting it
1327 /* parses and inits header entry, returns true/false */
1329 HttpHeaderEntry::parse(const char *field_start
, const char *field_end
)
1331 /* note: name_start == field_start */
1332 const char *name_end
= (const char *)memchr(field_start
, ':', field_end
- field_start
);
1333 int name_len
= name_end
? name_end
- field_start
:0;
1334 const char *value_start
= field_start
+ name_len
+ 1; /* skip ':' */
1335 /* note: value_end == field_end */
1337 ++ HeaderEntryParsedCount
;
1339 /* do we have a valid field name within this field? */
1341 if (!name_len
|| name_end
> field_end
)
1344 if (name_len
> 65534) {
1345 /* String must be LESS THAN 64K and it adds a terminating NULL */
1346 debugs(55, DBG_IMPORTANT
, "WARNING: ignoring header name of " << name_len
<< " bytes");
1350 if (Config
.onoff
.relaxed_header_parser
&& xisspace(field_start
[name_len
- 1])) {
1351 debugs(55, Config
.onoff
.relaxed_header_parser
<= 0 ? 1 : 2,
1352 "NOTICE: Whitespace after header name in '" << getStringPrefix(field_start
, field_end
-field_start
) << "'");
1354 while (name_len
> 0 && xisspace(field_start
[name_len
- 1]))
1361 /* now we know we can parse it */
1363 debugs(55, 9, "parsing HttpHeaderEntry: near '" << getStringPrefix(field_start
, field_end
-field_start
) << "'");
1365 /* is it a "known" field? */
1366 Http::HdrType id
= Http::HeaderLookupTable
.lookup(field_start
,name_len
).id
;
1367 debugs(55, 9, "got hdr-id=" << id
);
1373 if (id
== Http::HdrType::BAD_HDR
)
1374 id
= Http::HdrType::OTHER
;
1376 /* set field name */
1377 if (id
== Http::HdrType::OTHER
)
1378 name
.limitInit(field_start
, name_len
);
1380 name
= Http::HeaderLookupTable
.lookup(id
).name
;
1382 /* trim field value */
1383 while (value_start
< field_end
&& xisspace(*value_start
))
1386 while (value_start
< field_end
&& xisspace(field_end
[-1]))
1389 if (field_end
- value_start
> 65534) {
1390 /* String must be LESS THAN 64K and it adds a terminating NULL */
1391 debugs(55, DBG_IMPORTANT
, "WARNING: ignoring '" << name
<< "' header of " << (field_end
- value_start
) << " bytes");
1393 if (id
== Http::HdrType::OTHER
)
1399 /* set field value */
1400 value
.limitInit(value_start
, field_end
- value_start
);
1402 if (id
!= Http::HdrType::BAD_HDR
)
1403 ++ headerStatsTable
[id
].seenCount
;
1405 debugs(55, 9, "parsed HttpHeaderEntry: '" << name
<< ": " << value
<< "'");
1407 return new HttpHeaderEntry(id
, name
.termedBuf(), value
.termedBuf());
1411 HttpHeaderEntry::clone() const
1413 return new HttpHeaderEntry(id
, name
.termedBuf(), value
.termedBuf());
1417 HttpHeaderEntry::packInto(Packable
* p
) const
1420 p
->append(name
.rawBuf(), name
.size());
1422 p
->append(value
.rawBuf(), value
.size());
1423 p
->append("\r\n", 2);
1427 HttpHeaderEntry::getInt() const
1430 int ok
= httpHeaderParseInt(value
.termedBuf(), &val
);
1431 httpHeaderNoteParsedEntry(id
, value
, ok
== 0);
1432 /* XXX: Should we check ok - ie
1433 * return ok ? -1 : value;
1439 HttpHeaderEntry::getInt64() const
1442 int ok
= httpHeaderParseOffset(value
.termedBuf(), &val
);
1443 httpHeaderNoteParsedEntry(id
, value
, ok
== 0);
1444 /* XXX: Should we check ok - ie
1445 * return ok ? -1 : value;
1451 httpHeaderNoteParsedEntry(Http::HdrType id
, String
const &context
, bool error
)
1453 if (id
!= Http::HdrType::BAD_HDR
)
1454 ++ headerStatsTable
[id
].parsCount
;
1457 if (id
!= Http::HdrType::BAD_HDR
)
1458 ++ headerStatsTable
[id
].errCount
;
1459 debugs(55, 2, "cannot parse hdr field: '" << Http::HeaderLookupTable
.lookup(id
).name
<< ": " << context
<< "'");
1467 /* tmp variable used to pass stat info to dumpers */
1468 extern const HttpHeaderStat
*dump_stat
; /* argh! */
1469 const HttpHeaderStat
*dump_stat
= NULL
;
1472 httpHeaderFieldStatDumper(StoreEntry
* sentry
, int, double val
, double, int count
)
1474 const int id
= static_cast<int>(val
);
1475 const bool valid_id
= Http::any_valid_header(static_cast<Http::HdrType
>(id
));
1476 const char *name
= valid_id
? Http::HeaderLookupTable
.lookup(static_cast<Http::HdrType
>(id
)).name
: "INVALID";
1477 int visible
= count
> 0;
1478 /* for entries with zero count, list only those that belong to current type of message */
1480 if (!visible
&& valid_id
&& dump_stat
->owner_mask
)
1481 visible
= CBIT_TEST(*dump_stat
->owner_mask
, id
);
1484 storeAppendPrintf(sentry
, "%2d\t %-20s\t %5d\t %6.2f\n",
1485 id
, name
, count
, xdiv(count
, dump_stat
->busyDestroyedCount
));
1489 httpHeaderFldsPerHdrDumper(StoreEntry
* sentry
, int idx
, double val
, double, int count
)
1492 storeAppendPrintf(sentry
, "%2d\t %5d\t %5d\t %6.2f\n",
1493 idx
, (int) val
, count
,
1494 xpercent(count
, dump_stat
->destroyedCount
));
1498 httpHeaderStatDump(const HttpHeaderStat
* hs
, StoreEntry
* e
)
1504 storeAppendPrintf(e
, "\nHeader Stats: %s\n", hs
->label
);
1505 storeAppendPrintf(e
, "\nField type distribution\n");
1506 storeAppendPrintf(e
, "%2s\t %-20s\t %5s\t %6s\n",
1507 "id", "name", "count", "#/header");
1508 hs
->fieldTypeDistr
.dump(e
, httpHeaderFieldStatDumper
);
1509 storeAppendPrintf(e
, "\nCache-control directives distribution\n");
1510 storeAppendPrintf(e
, "%2s\t %-20s\t %5s\t %6s\n",
1511 "id", "name", "count", "#/cc_field");
1512 hs
->ccTypeDistr
.dump(e
, httpHdrCcStatDumper
);
1513 storeAppendPrintf(e
, "\nSurrogate-control directives distribution\n");
1514 storeAppendPrintf(e
, "%2s\t %-20s\t %5s\t %6s\n",
1515 "id", "name", "count", "#/sc_field");
1516 hs
->scTypeDistr
.dump(e
, httpHdrScStatDumper
);
1517 storeAppendPrintf(e
, "\nNumber of fields per header distribution\n");
1518 storeAppendPrintf(e
, "%2s\t %-5s\t %5s\t %6s\n",
1519 "id", "#flds", "count", "%total");
1520 hs
->hdrUCountDistr
.dump(e
, httpHeaderFldsPerHdrDumper
);
1521 storeAppendPrintf(e
, "\n");
1526 httpHeaderStoreReport(StoreEntry
* e
)
1531 HttpHeaderStats
[0].parsedCount
=
1532 HttpHeaderStats
[hoRequest
].parsedCount
+ HttpHeaderStats
[hoReply
].parsedCount
;
1533 HttpHeaderStats
[0].ccParsedCount
=
1534 HttpHeaderStats
[hoRequest
].ccParsedCount
+ HttpHeaderStats
[hoReply
].ccParsedCount
;
1535 HttpHeaderStats
[0].destroyedCount
=
1536 HttpHeaderStats
[hoRequest
].destroyedCount
+ HttpHeaderStats
[hoReply
].destroyedCount
;
1537 HttpHeaderStats
[0].busyDestroyedCount
=
1538 HttpHeaderStats
[hoRequest
].busyDestroyedCount
+ HttpHeaderStats
[hoReply
].busyDestroyedCount
;
1540 for (i
= 1; i
< HttpHeaderStatCount
; ++i
) {
1541 httpHeaderStatDump(HttpHeaderStats
+ i
, e
);
1544 /* field stats for all messages */
1545 storeAppendPrintf(e
, "\nHttp Fields Stats (replies and requests)\n");
1547 storeAppendPrintf(e
, "%2s\t %-25s\t %5s\t %6s\t %6s\n",
1548 "id", "name", "#alive", "%err", "%repeat");
1550 // scan heaaderTable and output
1551 for (auto h
: WholeEnum
<Http::HdrType
>()) {
1552 auto stats
= headerStatsTable
[h
];
1553 storeAppendPrintf(e
, "%2d\t %-25s\t %5d\t %6.3f\t %6.3f\n",
1554 Http::HeaderLookupTable
.lookup(h
).id
,
1555 Http::HeaderLookupTable
.lookup(h
).name
,
1557 xpercent(stats
.errCount
, stats
.parsCount
),
1558 xpercent(stats
.repCount
, stats
.seenCount
));
1561 storeAppendPrintf(e
, "Headers Parsed: %d + %d = %d\n",
1562 HttpHeaderStats
[hoRequest
].parsedCount
,
1563 HttpHeaderStats
[hoReply
].parsedCount
,
1564 HttpHeaderStats
[0].parsedCount
);
1565 storeAppendPrintf(e
, "Hdr Fields Parsed: %d\n", HeaderEntryParsedCount
);
1569 HttpHeader::hasListMember(Http::HdrType id
, const char *member
, const char separator
) const
1572 const char *pos
= NULL
;
1575 int mlen
= strlen(member
);
1577 assert(any_registered_header(id
));
1579 String
header (getStrOrList(id
));
1581 while (strListGetItem(&header
, separator
, &item
, &ilen
, &pos
)) {
1582 if (strncasecmp(item
, member
, mlen
) == 0
1583 && (item
[mlen
] == '=' || item
[mlen
] == separator
|| item
[mlen
] == ';' || item
[mlen
] == '\0')) {
1593 HttpHeader::hasByNameListMember(const char *name
, const char *member
, const char separator
) const
1596 const char *pos
= NULL
;
1599 int mlen
= strlen(member
);
1603 String
header (getByName(name
));
1605 while (strListGetItem(&header
, separator
, &item
, &ilen
, &pos
)) {
1606 if (strncasecmp(item
, member
, mlen
) == 0
1607 && (item
[mlen
] == '=' || item
[mlen
] == separator
|| item
[mlen
] == ';' || item
[mlen
] == '\0')) {
1617 HttpHeader::removeHopByHopEntries()
1619 removeConnectionHeaderEntries();
1621 const HttpHeaderEntry
*e
;
1622 HttpHeaderPos pos
= HttpHeaderInitPos
;
1623 int headers_deleted
= 0;
1624 while ((e
= getEntry(&pos
))) {
1625 Http::HdrType id
= e
->id
;
1626 if (Http::HeaderLookupTable
.lookup(id
).hopbyhop
) {
1627 delAt(pos
, headers_deleted
);
1634 HttpHeader::removeConnectionHeaderEntries()
1636 if (has(Http::HdrType::CONNECTION
)) {
1637 /* anything that matches Connection list member will be deleted */
1638 String strConnection
;
1640 (void) getList(Http::HdrType::CONNECTION
, &strConnection
);
1641 const HttpHeaderEntry
*e
;
1642 HttpHeaderPos pos
= HttpHeaderInitPos
;
1644 * think: on-average-best nesting of the two loops (hdrEntry
1645 * and strListItem) @?@
1648 * maybe we should delete standard stuff ("keep-alive","close")
1649 * from strConnection first?
1652 int headers_deleted
= 0;
1653 while ((e
= getEntry(&pos
))) {
1654 if (strListIsMember(&strConnection
, e
->name
.termedBuf(), ','))
1655 delAt(pos
, headers_deleted
);
1657 if (headers_deleted
)