/
HttpHeader.cc
1752 lines (1463 loc) · 51.7 KB
/
HttpHeader.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 1996-2022 The Squid Software Foundation and contributors
*
* Squid software is distributed under GPLv2+ license and includes
* contributions from numerous individuals and organizations.
* Please see the COPYING and CONTRIBUTORS files for details.
*/
/* DEBUG: section 55 HTTP Header */
#include "squid.h"
#include "base/CharacterSet.h"
#include "base/EnumIterator.h"
#include "base/Raw.h"
#include "base64.h"
#include "globals.h"
#include "http/ContentLengthInterpreter.h"
#include "HttpHdrCc.h"
#include "HttpHdrContRange.h"
#include "HttpHdrScTarget.h" // also includes HttpHdrSc.h
#include "HttpHeader.h"
#include "HttpHeaderFieldInfo.h"
#include "HttpHeaderStat.h"
#include "HttpHeaderTools.h"
#include "MemBuf.h"
#include "mgr/Registration.h"
#include "mime_header.h"
#include "sbuf/StringConvert.h"
#include "SquidConfig.h"
#include "StatHist.h"
#include "Store.h"
#include "StrList.h"
#include "time/gadgets.h"
#include "TimeOrTag.h"
#include "util.h"
#include <algorithm>
#include <array>
/* XXX: the whole set of API managing the entries vector should be rethought
* after the parse4r-ng effort is complete.
*/
/*
* On naming conventions:
*
* HTTP/1.1 defines message-header as
*
* message-header = field-name ":" [ field-value ] CRLF
* field-name = token
* field-value = *( field-content | LWS )
*
* HTTP/1.1 does not give a name name a group of all message-headers in a message.
* Squid 1.1 seems to refer to that group _plus_ start-line as "headers".
*
* HttpHeader is an object that represents all message-headers in a message.
* HttpHeader does not manage start-line.
*
* HttpHeader is implemented as a collection of header "entries".
* An entry is a (field_id, field_name, field_value) triplet.
*/
/*
* local constants and vars
*/
// statistics counters for headers. clients must not allow Http::HdrType::BAD_HDR to be counted
std::vector<HttpHeaderFieldStat> headerStatsTable(Http::HdrType::enumEnd_);
/* request-only headers. Used for cachemgr */
static HttpHeaderMask RequestHeadersMask; /* set run-time using RequestHeaders */
/* reply-only headers. Used for cachemgr */
static HttpHeaderMask ReplyHeadersMask; /* set run-time using ReplyHeaders */
/* header accounting */
// NP: keep in sync with enum http_hdr_owner_type
static std::array<HttpHeaderStat, hoEnd> HttpHeaderStats = {{
HttpHeaderStat(/*hoNone*/ "all", nullptr),
#if USE_HTCP
HttpHeaderStat(/*hoHtcpReply*/ "HTCP reply", &ReplyHeadersMask),
#endif
HttpHeaderStat(/*hoRequest*/ "request", &RequestHeadersMask),
HttpHeaderStat(/*hoReply*/ "reply", &ReplyHeadersMask)
#if USE_OPENSSL
, HttpHeaderStat(/*hoErrorDetail*/ "error detail templates", nullptr)
#endif
/* hoEnd */
}
};
static int HeaderEntryParsedCount = 0;
/*
* forward declarations and local routines
*/
class StoreEntry;
// update parse statistics for header id; if error is true also account
// for errors and write to debug log what happened
static void httpHeaderNoteParsedEntry(Http::HdrType id, String const &value, bool error);
static void httpHeaderStatDump(const HttpHeaderStat * hs, StoreEntry * e);
/** store report about current header usage and other stats */
static void httpHeaderStoreReport(StoreEntry * e);
/*
* Module initialization routines
*/
static void
httpHeaderRegisterWithCacheManager(void)
{
Mgr::RegisterAction("http_headers",
"HTTP Header Statistics",
httpHeaderStoreReport, 0, 1);
}
void
httpHeaderInitModule(void)
{
/* check that we have enough space for masks */
assert(8 * sizeof(HttpHeaderMask) >= Http::HdrType::enumEnd_);
// masks are needed for stats page still
for (auto h : WholeEnum<Http::HdrType>()) {
if (Http::HeaderLookupTable.lookup(h).request)
CBIT_SET(RequestHeadersMask,h);
if (Http::HeaderLookupTable.lookup(h).reply)
CBIT_SET(ReplyHeadersMask,h);
}
assert(HttpHeaderStats[0].label && "httpHeaderInitModule() called via main()");
assert(HttpHeaderStats[hoEnd-1].label && "HttpHeaderStats created with all elements");
/* init dependent modules */
httpHdrCcInitModule();
httpHdrScInitModule();
httpHeaderRegisterWithCacheManager();
}
/*
* HttpHeader Implementation
*/
HttpHeader::HttpHeader() : owner (hoNone), len (0), conflictingContentLength_(false)
{
entries.reserve(32);
httpHeaderMaskInit(&mask, 0);
}
HttpHeader::HttpHeader(const http_hdr_owner_type anOwner): owner(anOwner), len(0), conflictingContentLength_(false)
{
assert(anOwner > hoNone && anOwner < hoEnd);
debugs(55, 7, "init-ing hdr: " << this << " owner: " << owner);
entries.reserve(32);
httpHeaderMaskInit(&mask, 0);
}
// XXX: Delete as unused, expensive, and violating copy semantics by skipping Warnings
HttpHeader::HttpHeader(const HttpHeader &other): owner(other.owner), len(other.len), conflictingContentLength_(false)
{
entries.reserve(other.entries.capacity());
httpHeaderMaskInit(&mask, 0);
update(&other); // will update the mask as well
}
HttpHeader::~HttpHeader()
{
clean();
}
// XXX: Delete as unused, expensive, and violating assignment semantics by skipping Warnings
HttpHeader &
HttpHeader::operator =(const HttpHeader &other)
{
if (this != &other) {
// we do not really care, but the caller probably does
assert(owner == other.owner);
clean();
update(&other); // will update the mask as well
len = other.len;
conflictingContentLength_ = other.conflictingContentLength_;
teUnsupported_ = other.teUnsupported_;
}
return *this;
}
void
HttpHeader::clean()
{
assert(owner > hoNone && owner < hoEnd);
debugs(55, 7, "cleaning hdr: " << this << " owner: " << owner);
if (owner <= hoReply) {
/*
* An unfortunate bug. The entries array is initialized
* such that count is set to zero. httpHeaderClean() seems to
* be called both when 'hdr' is created, and destroyed. Thus,
* we accumulate a large number of zero counts for 'hdr' before
* it is ever used. Can't think of a good way to fix it, except
* adding a state variable that indicates whether or not 'hdr'
* has been used. As a hack, just never count zero-sized header
* arrays.
*/
if (!entries.empty())
HttpHeaderStats[owner].hdrUCountDistr.count(entries.size());
++ HttpHeaderStats[owner].destroyedCount;
HttpHeaderStats[owner].busyDestroyedCount += entries.size() > 0;
} // if (owner <= hoReply)
for (HttpHeaderEntry *e : entries) {
if (e == nullptr)
continue;
if (!Http::any_valid_header(e->id)) {
debugs(55, DBG_CRITICAL, "ERROR: Squid BUG: invalid entry (" << e->id << "). Ignored.");
} else {
if (owner <= hoReply)
HttpHeaderStats[owner].fieldTypeDistr.count(e->id);
delete e;
}
}
entries.clear();
httpHeaderMaskInit(&mask, 0);
len = 0;
conflictingContentLength_ = false;
teUnsupported_ = false;
}
/* append entries (also see httpHeaderUpdate) */
void
HttpHeader::append(const HttpHeader * src)
{
assert(src);
assert(src != this);
debugs(55, 7, "appending hdr: " << this << " += " << src);
for (auto e : src->entries) {
if (e)
addEntry(e->clone());
}
}
bool
HttpHeader::needUpdate(HttpHeader const *fresh) const
{
for (const auto e: fresh->entries) {
if (!e || skipUpdateHeader(e->id))
continue;
String value;
if (!hasNamed(e->name, &value) ||
(value != fresh->getByName(e->name)))
return true;
}
return false;
}
bool
HttpHeader::skipUpdateHeader(const Http::HdrType id) const
{
return
// TODO: Consider updating Vary headers after comparing the magnitude of
// the required changes (and/or cache losses) with compliance gains.
(id == Http::HdrType::VARY);
}
void
HttpHeader::update(HttpHeader const *fresh)
{
assert(fresh);
assert(this != fresh);
const HttpHeaderEntry *e;
HttpHeaderPos pos = HttpHeaderInitPos;
while ((e = fresh->getEntry(&pos))) {
/* deny bad guys (ok to check for Http::HdrType::OTHER) here */
if (skipUpdateHeader(e->id))
continue;
if (e->id != Http::HdrType::OTHER)
delById(e->id);
else
delByName(e->name);
}
pos = HttpHeaderInitPos;
while ((e = fresh->getEntry(&pos))) {
/* deny bad guys (ok to check for Http::HdrType::OTHER) here */
if (skipUpdateHeader(e->id))
continue;
debugs(55, 7, "Updating header '" << Http::HeaderLookupTable.lookup(e->id).name << "' in cached entry");
addEntry(e->clone());
}
}
bool
HttpHeader::Isolate(const char **parse_start, size_t l, const char **blk_start, const char **blk_end)
{
/*
* parse_start points to the first line of HTTP message *headers*,
* not including the request or status lines
*/
const size_t end = headersEnd(*parse_start, l);
if (end) {
*blk_start = *parse_start;
*blk_end = *parse_start + end - 1;
assert(**blk_end == '\n');
// Point blk_end to the first character after the last header field.
// In other words, blk_end should point to the CR?LF header terminator.
if (end > 1 && *(*blk_end - 1) == '\r')
--(*blk_end);
*parse_start += end;
}
return end;
}
int
HttpHeader::parse(const char *buf, size_t buf_len, bool atEnd, size_t &hdr_sz, Http::ContentLengthInterpreter &clen)
{
const char *parse_start = buf;
const char *blk_start, *blk_end;
hdr_sz = 0;
if (!Isolate(&parse_start, buf_len, &blk_start, &blk_end)) {
// XXX: do not parse non-isolated headers even if the connection is closed.
// Treat unterminated headers as "partial headers" framing errors.
if (!atEnd)
return 0;
blk_start = parse_start;
blk_end = blk_start + strlen(blk_start);
}
if (parse(blk_start, blk_end - blk_start, clen)) {
hdr_sz = parse_start - buf;
return 1;
}
return -1;
}
// XXX: callers treat this return as boolean.
// XXX: A better mechanism is needed to signal different types of error.
// lexicon, syntax, semantics, validation, access policy - are all (ab)using 'return 0'
int
HttpHeader::parse(const char *header_start, size_t hdrLen, Http::ContentLengthInterpreter &clen)
{
const char *field_ptr = header_start;
const char *header_end = header_start + hdrLen; // XXX: remove
int warnOnError = (Config.onoff.relaxed_header_parser <= 0 ? DBG_IMPORTANT : 2);
assert(header_start && header_end);
debugs(55, 7, "parsing hdr: (" << this << ")" << std::endl << getStringPrefix(header_start, hdrLen));
++ HttpHeaderStats[owner].parsedCount;
char *nulpos;
if ((nulpos = (char*)memchr(header_start, '\0', hdrLen))) {
debugs(55, DBG_IMPORTANT, "WARNING: HTTP header contains NULL characters {" <<
getStringPrefix(header_start, nulpos-header_start) << "}\nNULL\n{" << getStringPrefix(nulpos+1, hdrLen-(nulpos-header_start)-1));
clean();
return 0;
}
/* common format headers are "<name>:[ws]<value>" lines delimited by <CRLF>.
* continuation lines start with a (single) space or tab */
while (field_ptr < header_end) {
const char *field_start = field_ptr;
const char *field_end;
const char *hasBareCr = nullptr;
size_t lines = 0;
do {
const char *this_line = field_ptr;
field_ptr = (const char *)memchr(field_ptr, '\n', header_end - field_ptr);
++lines;
if (!field_ptr) {
// missing <LF>
clean();
return 0;
}
field_end = field_ptr;
++field_ptr; /* Move to next line */
if (field_end > this_line && field_end[-1] == '\r') {
--field_end; /* Ignore CR LF */
if (owner == hoRequest && field_end > this_line) {
bool cr_only = true;
for (const char *p = this_line; p < field_end && cr_only; ++p) {
if (*p != '\r')
cr_only = false;
}
if (cr_only) {
debugs(55, DBG_IMPORTANT, "SECURITY WARNING: Rejecting HTTP request with a CR+ "
"header field to prevent request smuggling attacks: {" <<
getStringPrefix(header_start, hdrLen) << "}");
clean();
return 0;
}
}
}
/* Barf on stray CR characters */
if (memchr(this_line, '\r', field_end - this_line)) {
hasBareCr = "bare CR";
debugs(55, warnOnError, "WARNING: suspicious CR characters in HTTP header {" <<
getStringPrefix(field_start, field_end-field_start) << "}");
if (Config.onoff.relaxed_header_parser) {
char *p = (char *) this_line; /* XXX Warning! This destroys original header content and violates specifications somewhat */
while ((p = (char *)memchr(p, '\r', field_end - p)) != nullptr) {
*p = ' ';
++p;
}
} else {
clean();
return 0;
}
}
if (this_line + 1 == field_end && this_line > field_start) {
debugs(55, warnOnError, "WARNING: Blank continuation line in HTTP header {" <<
getStringPrefix(header_start, hdrLen) << "}");
clean();
return 0;
}
} while (field_ptr < header_end && (*field_ptr == ' ' || *field_ptr == '\t'));
if (field_start == field_end) {
if (field_ptr < header_end) {
debugs(55, warnOnError, "WARNING: unparsable HTTP header field near {" <<
getStringPrefix(field_start, hdrLen-(field_start-header_start)) << "}");
clean();
return 0;
}
break; /* terminating blank line */
}
const auto e = HttpHeaderEntry::parse(field_start, field_end, owner);
if (!e) {
debugs(55, warnOnError, "WARNING: unparsable HTTP header field {" <<
getStringPrefix(field_start, field_end-field_start) << "}");
debugs(55, warnOnError, " in {" << getStringPrefix(header_start, hdrLen) << "}");
clean();
return 0;
}
if (lines > 1 || hasBareCr) {
const auto framingHeader = (e->id == Http::HdrType::CONTENT_LENGTH || e->id == Http::HdrType::TRANSFER_ENCODING);
if (framingHeader) {
if (!hasBareCr) // already warned about bare CRs
debugs(55, warnOnError, "WARNING: obs-fold in framing-sensitive " << e->name << ": " << e->value);
delete e;
clean();
return 0;
}
}
if (e->id == Http::HdrType::CONTENT_LENGTH && !clen.checkField(e->value)) {
delete e;
if (Config.onoff.relaxed_header_parser)
continue; // clen has printed any necessary warnings
clean();
return 0;
}
addEntry(e);
}
if (clen.headerWideProblem) {
debugs(55, warnOnError, "WARNING: " << clen.headerWideProblem <<
" Content-Length field values in" <<
Raw("header", header_start, hdrLen));
}
String rawTe;
if (clen.prohibitedAndIgnored()) {
// prohibitedAndIgnored() includes trailer header blocks
// being parsed as a case to forbid/ignore these headers.
// RFC 7230 section 3.3.2: A server MUST NOT send a Content-Length
// header field in any response with a status code of 1xx (Informational)
// or 204 (No Content). And RFC 7230 3.3.3#1 tells recipients to ignore
// such Content-Lengths.
if (delById(Http::HdrType::CONTENT_LENGTH))
debugs(55, 3, "Content-Length is " << clen.prohibitedAndIgnored());
// The same RFC 7230 3.3.3#1-based logic applies to Transfer-Encoding
// banned by RFC 7230 section 3.3.1.
if (delById(Http::HdrType::TRANSFER_ENCODING))
debugs(55, 3, "Transfer-Encoding is " << clen.prohibitedAndIgnored());
} else if (getByIdIfPresent(Http::HdrType::TRANSFER_ENCODING, &rawTe)) {
// RFC 2616 section 4.4: ignore Content-Length with Transfer-Encoding
// RFC 7230 section 3.3.3 #3: Transfer-Encoding overwrites Content-Length
delById(Http::HdrType::CONTENT_LENGTH);
// and clen state becomes irrelevant
if (rawTe.caseCmp("chunked") == 0) {
; // leave header present for chunked() method
} else if (rawTe.caseCmp("identity") == 0) { // deprecated. no coding
delById(Http::HdrType::TRANSFER_ENCODING);
} else {
// This also rejects multiple encodings until we support them properly.
debugs(55, warnOnError, "WARNING: unsupported Transfer-Encoding used by client: " << rawTe);
teUnsupported_ = true;
}
} else if (clen.sawBad) {
// ensure our callers do not accidentally see bad Content-Length values
delById(Http::HdrType::CONTENT_LENGTH);
conflictingContentLength_ = true; // TODO: Rename to badContentLength_.
} else if (clen.needsSanitizing) {
// RFC 7230 section 3.3.2: MUST either reject or ... [sanitize];
// ensure our callers see a clean Content-Length value or none at all
delById(Http::HdrType::CONTENT_LENGTH);
if (clen.sawGood) {
putInt64(Http::HdrType::CONTENT_LENGTH, clen.value);
debugs(55, 5, "sanitized Content-Length to be " << clen.value);
}
}
return 1; /* even if no fields where found, it is a valid header */
}
/* packs all the entries using supplied packer */
void
HttpHeader::packInto(Packable * p, bool mask_sensitive_info) const
{
HttpHeaderPos pos = HttpHeaderInitPos;
const HttpHeaderEntry *e;
assert(p);
debugs(55, 7, this << " into " << p <<
(mask_sensitive_info ? " while masking" : ""));
/* pack all entries one by one */
while ((e = getEntry(&pos))) {
if (!mask_sensitive_info) {
e->packInto(p);
continue;
}
bool maskThisEntry = false;
switch (e->id) {
case Http::HdrType::AUTHORIZATION:
case Http::HdrType::PROXY_AUTHORIZATION:
maskThisEntry = true;
break;
case Http::HdrType::FTP_ARGUMENTS:
if (const HttpHeaderEntry *cmd = findEntry(Http::HdrType::FTP_COMMAND))
maskThisEntry = (cmd->value == "PASS");
break;
default:
break;
}
if (maskThisEntry) {
p->append(e->name.rawContent(), e->name.length());
p->append(": ** NOT DISPLAYED **\r\n", 23);
} else {
e->packInto(p);
}
}
/* Pack in the "special" entries */
/* Cache-Control */
}
/* returns next valid entry */
HttpHeaderEntry *
HttpHeader::getEntry(HttpHeaderPos * pos) const
{
assert(pos);
assert(*pos >= HttpHeaderInitPos && *pos < static_cast<ssize_t>(entries.size()));
for (++(*pos); *pos < static_cast<ssize_t>(entries.size()); ++(*pos)) {
if (entries[*pos])
return static_cast<HttpHeaderEntry*>(entries[*pos]);
}
return nullptr;
}
/*
* returns a pointer to a specified entry if any
* note that we return one entry so it does not make much sense to ask for
* "list" headers
*/
HttpHeaderEntry *
HttpHeader::findEntry(Http::HdrType id) const
{
assert(any_registered_header(id));
assert(!Http::HeaderLookupTable.lookup(id).list);
/* check mask first */
if (!CBIT_TEST(mask, id))
return nullptr;
/* looks like we must have it, do linear search */
for (auto e : entries) {
if (e && e->id == id)
return e;
}
/* hm.. we thought it was there, but it was not found */
assert(false);
return nullptr; /* not reached */
}
/*
* same as httpHeaderFindEntry
*/
HttpHeaderEntry *
HttpHeader::findLastEntry(Http::HdrType id) const
{
assert(any_registered_header(id));
assert(!Http::HeaderLookupTable.lookup(id).list);
/* check mask first */
if (!CBIT_TEST(mask, id))
return nullptr;
for (auto e = entries.rbegin(); e != entries.rend(); ++e) {
if (*e && (*e)->id == id)
return *e;
}
/* hm.. we thought it was there, but it was not found */
assert(false);
return nullptr; /* not reached */
}
int
HttpHeader::delByName(const SBuf &name)
{
int count = 0;
HttpHeaderPos pos = HttpHeaderInitPos;
httpHeaderMaskInit(&mask, 0); /* temporal inconsistency */
debugs(55, 9, "deleting '" << name << "' fields in hdr " << this);
while (const HttpHeaderEntry *e = getEntry(&pos)) {
if (!e->name.caseCmp(name))
delAt(pos, count);
else
CBIT_SET(mask, e->id);
}
return count;
}
/* deletes all entries with a given id, returns the #entries deleted */
int
HttpHeader::delById(Http::HdrType id)
{
debugs(55, 8, this << " del-by-id " << id);
assert(any_registered_header(id));
if (!CBIT_TEST(mask, id))
return 0;
int count = 0;
HttpHeaderPos pos = HttpHeaderInitPos;
while (HttpHeaderEntry *e = getEntry(&pos)) {
if (e->id == id)
delAt(pos, count); // deletes e
}
CBIT_CLR(mask, id);
assert(count);
return count;
}
/*
* deletes an entry at pos and leaves a gap; leaving a gap makes it
* possible to iterate(search) and delete fields at the same time
* NOTE: Does not update the header mask. Caller must follow up with
* a call to refreshMask() if headers_deleted was incremented.
*/
void
HttpHeader::delAt(HttpHeaderPos pos, int &headers_deleted)
{
HttpHeaderEntry *e;
assert(pos >= HttpHeaderInitPos && pos < static_cast<ssize_t>(entries.size()));
e = static_cast<HttpHeaderEntry*>(entries[pos]);
entries[pos] = nullptr;
/* decrement header length, allow for ": " and crlf */
len -= e->name.length() + 2 + e->value.size() + 2;
assert(len >= 0);
delete e;
++headers_deleted;
}
/*
* Compacts the header storage
*/
void
HttpHeader::compact()
{
// TODO: optimize removal, or possibly make it so that's not needed.
entries.erase( std::remove(entries.begin(), entries.end(), nullptr),
entries.end());
}
/*
* Refreshes the header mask. Required after delAt() calls.
*/
void
HttpHeader::refreshMask()
{
httpHeaderMaskInit(&mask, 0);
debugs(55, 7, "refreshing the mask in hdr " << this);
for (auto e : entries) {
if (e)
CBIT_SET(mask, e->id);
}
}
/* appends an entry;
* does not call e->clone() so one should not reuse "*e"
*/
void
HttpHeader::addEntry(HttpHeaderEntry * e)
{
assert(e);
assert(any_HdrType_enum_value(e->id));
assert(e->name.length());
debugs(55, 7, this << " adding entry: " << e->id << " at " << entries.size());
if (e->id != Http::HdrType::BAD_HDR) {
if (CBIT_TEST(mask, e->id)) {
++ headerStatsTable[e->id].repCount;
} else {
CBIT_SET(mask, e->id);
}
}
entries.push_back(e);
/* increment header length, allow for ": " and crlf */
len += e->name.length() + 2 + e->value.size() + 2;
}
/* inserts an entry;
* does not call e->clone() so one should not reuse "*e"
*/
void
HttpHeader::insertEntry(HttpHeaderEntry * e)
{
assert(e);
assert(any_valid_header(e->id));
debugs(55, 7, this << " adding entry: " << e->id << " at " << entries.size());
// Http::HdrType::BAD_HDR is filtered out by assert_any_valid_header
if (CBIT_TEST(mask, e->id)) {
++ headerStatsTable[e->id].repCount;
} else {
CBIT_SET(mask, e->id);
}
entries.insert(entries.begin(),e);
/* increment header length, allow for ": " and crlf */
len += e->name.length() + 2 + e->value.size() + 2;
}
bool
HttpHeader::getList(Http::HdrType id, String *s) const
{
debugs(55, 9, this << " joining for id " << id);
/* only fields from ListHeaders array can be "listed" */
assert(Http::HeaderLookupTable.lookup(id).list);
if (!CBIT_TEST(mask, id))
return false;
for (auto e: entries) {
if (e && e->id == id)
strListAdd(s, e->value.termedBuf(), ',');
}
/*
* note: we might get an empty (size==0) string if there was an "empty"
* header. This results in an empty length String, which may have a NULL
* buffer.
*/
/* temporary warning: remove it? (Is it useful for diagnostics ?) */
if (!s->size())
debugs(55, 3, "empty list header: " << Http::HeaderLookupTable.lookup(id).name << "(" << id << ")");
else
debugs(55, 6, this << ": joined for id " << id << ": " << s);
return true;
}
/* return a list of entries with the same id separated by ',' and ws */
String
HttpHeader::getList(Http::HdrType id) const
{
HttpHeaderEntry *e;
HttpHeaderPos pos = HttpHeaderInitPos;
debugs(55, 9, this << "joining for id " << id);
/* only fields from ListHeaders array can be "listed" */
assert(Http::HeaderLookupTable.lookup(id).list);
if (!CBIT_TEST(mask, id))
return String();
String s;
while ((e = getEntry(&pos))) {
if (e->id == id)
strListAdd(&s, e->value.termedBuf(), ',');
}
/*
* note: we might get an empty (size==0) string if there was an "empty"
* header. This results in an empty length String, which may have a NULL
* buffer.
*/
/* temporary warning: remove it? (Is it useful for diagnostics ?) */
if (!s.size())
debugs(55, 3, "empty list header: " << Http::HeaderLookupTable.lookup(id).name << "(" << id << ")");
else
debugs(55, 6, this << ": joined for id " << id << ": " << s);
return s;
}
/* return a string or list of entries with the same id separated by ',' and ws */
String
HttpHeader::getStrOrList(Http::HdrType id) const
{
HttpHeaderEntry *e;
if (Http::HeaderLookupTable.lookup(id).list)
return getList(id);
if ((e = findEntry(id)))
return e->value;
return String();
}
/*
* Returns the value of the specified header and/or an undefined String.
*/
String
HttpHeader::getByName(const char *name) const
{
String result;
// ignore presence: return undefined string if an empty header is present
(void)hasNamed(name, strlen(name), &result);
return result;
}
String
HttpHeader::getByName(const SBuf &name) const
{
String result;
// ignore presence: return undefined string if an empty header is present
(void)hasNamed(name, &result);
return result;
}
String
HttpHeader::getById(Http::HdrType id) const
{
String result;
(void)getByIdIfPresent(id, &result);
return result;
}
bool
HttpHeader::hasNamed(const SBuf &s, String *result) const
{
return hasNamed(s.rawContent(), s.length(), result);
}
bool
HttpHeader::getByIdIfPresent(Http::HdrType id, String *result) const
{
if (id == Http::HdrType::BAD_HDR)
return false;
if (!has(id))
return false;
if (result)
*result = getStrOrList(id);
return true;
}
bool
HttpHeader::hasNamed(const char *name, unsigned int namelen, String *result) const
{
Http::HdrType id;
HttpHeaderPos pos = HttpHeaderInitPos;
HttpHeaderEntry *e;
assert(name);
/* First try the quick path */
id = Http::HeaderLookupTable.lookup(name,namelen).id;
if (id != Http::HdrType::BAD_HDR) {
if (getByIdIfPresent(id, result))
return true;
}
/* Sorry, an unknown header name. Do linear search */
bool found = false;
while ((e = getEntry(&pos))) {
if (e->id == Http::HdrType::OTHER && e->name.length() == namelen && e->name.caseCmp(name, namelen) == 0) {
found = true;
if (!result)
break;
strListAdd(result, e->value.termedBuf(), ',');
}
}
return found;
}
/*
* Returns a the value of the specified list member, if any.
*/
SBuf
HttpHeader::getByNameListMember(const char *name, const char *member, const char separator) const
{
assert(name);
const auto header = getByName(name);
return ::getListMember(header, member, separator);
}
/*
* returns a the value of the specified list member, if any.
*/
SBuf
HttpHeader::getListMember(Http::HdrType id, const char *member, const char separator) const
{
assert(any_registered_header(id));
const auto header = getStrOrList(id);
return ::getListMember(header, member, separator);
}
/* test if a field is present */
int
HttpHeader::has(Http::HdrType id) const
{
assert(any_registered_header(id));
debugs(55, 9, this << " lookup for " << id);
return CBIT_TEST(mask, id);
}
void
HttpHeader::addVia(const AnyP::ProtocolVersion &ver, const HttpHeader *from)
{
// TODO: do not add Via header for messages where Squid itself
// generated the message (i.e., Downloader or ESI) there should be no Via header added at all.
if (Config.onoff.via) {
SBuf buf;
// RFC 7230 section 5.7.1.: protocol-name is omitted when
// the received protocol is HTTP.
if (ver.protocol > AnyP::PROTO_NONE && ver.protocol < AnyP::PROTO_UNKNOWN &&
ver.protocol != AnyP::PROTO_HTTP && ver.protocol != AnyP::PROTO_HTTPS)
buf.appendf("%s/", AnyP::ProtocolType_str[ver.protocol]);
buf.appendf("%d.%d %s", ver.major, ver.minor, ThisCache);
const HttpHeader *hdr = from ? from : this;
SBuf strVia = StringToSBuf(hdr->getList(Http::HdrType::VIA));
if (!strVia.isEmpty())
strVia.append(", ", 2);
strVia.append(buf);
// XXX: putStr() still suffers from String size limits
Must(strVia.length() < String::SizeMaxXXX());
delById(Http::HdrType::VIA);
putStr(Http::HdrType::VIA, strVia.c_str());
}
}