2 * Copyright (C) 1996-2015 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 66 HTTP Header Tools */
12 #include "acl/FilledChecklist.h"
13 #include "acl/Gadgets.h"
14 #include "client_side.h"
15 #include "client_side_request.h"
16 #include "comm/Connection.h"
17 #include "compat/strtoll.h"
18 #include "ConfigParser.h"
21 #include "http/RegisteredHeaders.h"
22 #include "HttpHdrContRange.h"
23 #include "HttpHeader.h"
24 #include "HttpHeaderFieldInfo.h"
25 #include "HttpHeaderTools.h"
26 #include "HttpRequest.h"
28 #include "SquidConfig.h"
33 #include "ssl/support.h"
40 static void httpHeaderPutStrvf(HttpHeader
* hdr
, Http::HdrType id
, const char *fmt
, va_list vargs
);
43 httpHeaderMaskInit(HttpHeaderMask
* mask
, int value
)
45 memset(mask
, value
, sizeof(*mask
));
48 /** calculates a bit mask of a given array; does not reset mask! */
50 httpHeaderCalcMask(HttpHeaderMask
* mask
, Http::HdrType http_hdr_type_enums
[], size_t count
)
53 const int * enums
= (const int *) http_hdr_type_enums
;
54 assert(mask
&& enums
);
55 assert(count
< sizeof(*mask
) * 8); /* check for overflow */
57 for (i
= 0; i
< count
; ++i
) {
58 assert(!CBIT_TEST(*mask
, enums
[i
])); /* check for duplicates */
59 CBIT_SET(*mask
, enums
[i
]);
63 /* same as httpHeaderPutStr, but formats the string using snprintf first */
65 httpHeaderPutStrf(HttpHeader
* hdr
, Http::HdrType id
, const char *fmt
,...)
70 httpHeaderPutStrvf(hdr
, id
, fmt
, args
);
74 /* used by httpHeaderPutStrf */
76 httpHeaderPutStrvf(HttpHeader
* hdr
, Http::HdrType id
, const char *fmt
, va_list vargs
)
80 mb
.vappendf(fmt
, vargs
);
81 hdr
->putStr(id
, mb
.buf
);
85 /** wrapper arrounf PutContRange */
87 httpHeaderAddContRange(HttpHeader
* hdr
, HttpHdrRangeSpec spec
, int64_t ent_len
)
89 HttpHdrContRange
*cr
= httpHdrContRangeCreate();
90 assert(hdr
&& ent_len
>= 0);
91 httpHdrContRangeSet(cr
, spec
, ent_len
);
92 hdr
->putContRange(cr
);
93 httpHdrContRangeDestroy(cr
);
97 * return true if a given directive is found in at least one of
98 * the "connection" header-fields note: if Http::HdrType::PROXY_CONNECTION is
99 * present we ignore Http::HdrType::CONNECTION.
102 httpHeaderHasConnDir(const HttpHeader
* hdr
, const char *directive
)
106 /* what type of header do we have? */
108 #if USE_HTTP_VIOLATIONS
109 if (hdr
->has(Http::HdrType::PROXY_CONNECTION
))
110 list
= hdr
->getList(Http::HdrType::PROXY_CONNECTION
);
113 if (hdr
->has(Http::HdrType::CONNECTION
))
114 list
= hdr
->getList(Http::HdrType::CONNECTION
);
118 res
= strListIsMember(&list
, directive
, ',');
125 /** handy to printf prefixes of potentially very long buffers */
127 getStringPrefix(const char *str
, size_t sz
)
129 #define SHORT_PREFIX_SIZE 512
130 LOCAL_ARRAY(char, buf
, SHORT_PREFIX_SIZE
);
131 xstrncpy(buf
, str
, (sz
+1 > SHORT_PREFIX_SIZE
) ? SHORT_PREFIX_SIZE
: sz
);
136 * parses an int field, complains if soemthing went wrong, returns true on
140 httpHeaderParseInt(const char *start
, int *value
)
143 *value
= atoi(start
);
145 if (!*value
&& !xisdigit(*start
)) {
146 debugs(66, 2, "failed to parse an int header field near '" << start
<< "'");
154 httpHeaderParseOffset(const char *start
, int64_t * value
)
157 int64_t res
= strtoll(start
, NULL
, 10);
158 if (!res
&& EINVAL
== errno
) /* maybe not portable? */
165 * Parses a quoted-string field (RFC 2616 section 2.2), complains if
166 * something went wrong, returns non-zero on success.
167 * Un-escapes quoted-pair characters found within the string.
168 * start should point at the first double-quote.
171 httpHeaderParseQuotedString(const char *start
, const int len
, String
*val
)
173 const char *end
, *pos
;
176 debugs(66, 2, HERE
<< "failed to parse a quoted-string header field near '" << start
<< "'");
181 while (*pos
!= '"' && len
> (pos
-start
)) {
185 if ((pos
-start
) > len
|| *pos
!= '\n') {
186 debugs(66, 2, HERE
<< "failed to parse a quoted-string header field with '\\r' octet " << (start
-pos
)
187 << " bytes into '" << start
<< "'");
195 if ( (pos
-start
) > len
|| (*pos
!= ' ' && *pos
!= '\t')) {
196 debugs(66, 2, HERE
<< "failed to parse multiline quoted-string header field '" << start
<< "'");
200 // TODO: replace the entire LWS with a space
203 debugs(66, 2, HERE
<< "len < pos-start => " << len
<< " < " << (pos
-start
));
207 bool quoted
= (*pos
== '\\');
210 if (!*pos
|| (pos
-start
) > len
) {
211 debugs(66, 2, HERE
<< "failed to parse a quoted-string header field near '" << start
<< "'");
217 while (end
< (start
+len
) && *end
!= '\\' && *end
!= '\"' && (unsigned char)*end
> 0x1F && *end
!= 0x7F)
219 if (((unsigned char)*end
<= 0x1F && *end
!= '\r' && *end
!= '\n') || *end
== 0x7F) {
220 debugs(66, 2, HERE
<< "failed to parse a quoted-string header field with CTL octet " << (start
-pos
)
221 << " bytes into '" << start
<< "'");
225 val
->append(pos
, end
-pos
);
230 debugs(66, 2, HERE
<< "failed to parse a quoted-string header field which did not end with \" ");
234 /* Make sure it's defined even if empty "" */
235 if (!val
->termedBuf())
236 val
->limitInit("", 0);
241 httpHeaderQuoteString(const char *raw
)
245 // TODO: Optimize by appending a sequence of characters instead of a char.
246 // This optimization may be easier with Tokenizer after raw becomes SBuf.
248 // RFC 7230 says a "sender SHOULD NOT generate a quoted-pair in a
249 // quoted-string except where necessary" (i.e., DQUOTE and backslash)
250 bool needInnerQuote
= false;
251 for (const char *s
= raw
; !needInnerQuote
&& *s
; ++s
)
252 needInnerQuote
= *s
== '"' || *s
== '\\';
255 quotedStr
.append('"');
257 if (needInnerQuote
) {
258 for (const char *s
= raw
; *s
; ++s
) {
259 if (*s
== '"' || *s
== '\\')
260 quotedStr
.append('\\');
261 quotedStr
.append(*s
);
264 quotedStr
.append(raw
);
267 quotedStr
.append('"');
272 * Checks the anonymizer (header_access) configuration.
274 * \retval 0 Header is explicitly blocked for removal
275 * \retval 1 Header is explicitly allowed
276 * \retval 1 Header has been replaced, the current version can be used.
277 * \retval 1 Header has no access controls to test
280 httpHdrMangle(HttpHeaderEntry
* e
, HttpRequest
* request
, int req_or_rep
)
284 /* check with anonymizer tables */
285 HeaderManglers
*hms
= NULL
;
288 if (ROR_REQUEST
== req_or_rep
) {
289 hms
= Config
.request_header_access
;
290 } else if (ROR_REPLY
== req_or_rep
) {
291 hms
= Config
.reply_header_access
;
293 /* error. But let's call it "request". */
294 hms
= Config
.request_header_access
;
297 /* manglers are not configured for this message kind */
301 const headerMangler
*hm
= hms
->find(*e
);
303 /* mangler or checklist went away. default allow */
304 if (!hm
|| !hm
->access_list
) {
308 ACLFilledChecklist
checklist(hm
->access_list
, request
, NULL
);
310 if (checklist
.fastCheck() == ACCESS_ALLOWED
) {
311 /* aclCheckFast returns true for allow. */
313 } else if (NULL
== hm
->replacement
) {
314 /* It was denied, and we don't have any replacement */
317 /* It was denied, but we have a replacement. Replace the
318 * header on the fly, and return that the new header
321 e
->value
= hm
->replacement
;
328 /** Mangles headers for a list of headers. */
330 httpHdrMangleList(HttpHeader
* l
, HttpRequest
* request
, int req_or_rep
)
333 HttpHeaderPos p
= HttpHeaderInitPos
;
335 int headers_deleted
= 0;
336 while ((e
= l
->getEntry(&p
)))
337 if (0 == httpHdrMangle(e
, request
, req_or_rep
))
338 l
->delAt(p
, headers_deleted
);
345 void header_mangler_clean(headerMangler
&m
)
347 aclDestroyAccessList(&m
.access_list
);
348 safe_free(m
.replacement
);
352 void header_mangler_dump_access(StoreEntry
* entry
, const char *option
,
353 const headerMangler
&m
, const char *name
)
355 if (m
.access_list
!= NULL
) {
356 storeAppendPrintf(entry
, "%s ", option
);
357 dump_acl_access(entry
, name
, m
.access_list
);
362 void header_mangler_dump_replacement(StoreEntry
* entry
, const char *option
,
363 const headerMangler
&m
, const char *name
)
366 storeAppendPrintf(entry
, "%s %s %s\n", option
, name
, m
.replacement
);
369 HeaderManglers::HeaderManglers()
371 memset(known
, 0, sizeof(known
));
372 memset(&all
, 0, sizeof(all
));
375 HeaderManglers::~HeaderManglers()
377 for (int i
= 0; i
< Http::HdrType::ENUM_END
; ++i
)
378 header_mangler_clean(known
[i
]);
380 typedef ManglersByName::iterator MBNI
;
381 for (MBNI i
= custom
.begin(); i
!= custom
.end(); ++i
)
382 header_mangler_clean(i
->second
);
384 header_mangler_clean(all
);
388 HeaderManglers::dumpAccess(StoreEntry
* entry
, const char *name
) const
390 for (int i
= 0; headerTable
[i
].name
!= nullptr; ++i
) {
391 header_mangler_dump_access(entry
, name
, known
[i
], headerTable
[i
].name
);
394 typedef ManglersByName::const_iterator MBNCI
;
395 for (MBNCI i
= custom
.begin(); i
!= custom
.end(); ++i
)
396 header_mangler_dump_access(entry
, name
, i
->second
, i
->first
.c_str());
398 header_mangler_dump_access(entry
, name
, all
, "All");
402 HeaderManglers::dumpReplacement(StoreEntry
* entry
, const char *name
) const
404 for (int i
= 0; headerTable
[i
].name
!= nullptr; ++i
) {
405 header_mangler_dump_replacement(entry
, name
, known
[i
],headerTable
[i
].name
);
408 typedef ManglersByName::const_iterator MBNCI
;
409 for (MBNCI i
= custom
.begin(); i
!= custom
.end(); ++i
) {
410 header_mangler_dump_replacement(entry
, name
, i
->second
,
414 header_mangler_dump_replacement(entry
, name
, all
, "All");
418 HeaderManglers::track(const char *name
)
420 Http::HdrType id
= HeaderLookupTable
.lookup(SBuf(name
));
422 if (id
== Http::HdrType::BAD_HDR
) { // special keyword or a custom header
423 if (strcmp(name
, "All") == 0)
424 id
= Http::HdrType::ENUM_END
;
425 else if (strcmp(name
, "Other") == 0)
426 id
= Http::HdrType::OTHER
;
429 headerMangler
*m
= NULL
;
430 if (id
== Http::HdrType::ENUM_END
) {
432 } else if (id
== Http::HdrType::BAD_HDR
) {
435 m
= &known
[id
]; // including Http::HdrType::OTHER
443 HeaderManglers::setReplacement(const char *name
, const char *value
)
445 // for backword compatibility, we allow replacements to be configured
446 // for headers w/o access rules, but such replacements are ignored
447 headerMangler
*m
= track(name
);
449 safe_free(m
->replacement
); // overwrite old value if any
450 m
->replacement
= xstrdup(value
);
453 const headerMangler
*
454 HeaderManglers::find(const HttpHeaderEntry
&e
) const
456 // a known header with a configured ACL list
457 if (e
.id
!= Http::HdrType::OTHER
&& e
.id
< Http::HdrType::ENUM_END
&&
458 known
[e
.id
].access_list
)
462 if (e
.id
== Http::HdrType::OTHER
) {
463 // does it have an ACL list configured?
464 // Optimize: use a name type that we do not need to convert to here
465 const ManglersByName::const_iterator i
= custom
.find(e
.name
.termedBuf());
466 if (i
!= custom
.end())
470 // Next-to-last resort: "Other" rules match any custom header
471 if (e
.id
== Http::HdrType::OTHER
&& known
[Http::HdrType::OTHER
].access_list
)
472 return &known
[Http::HdrType::OTHER
];
474 // Last resort: "All" rules match any header
482 httpHdrAdd(HttpHeader
*heads
, HttpRequest
*request
, const AccessLogEntryPointer
&al
, HeaderWithAclList
&headersAdd
)
484 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
486 for (HeaderWithAclList::const_iterator hwa
= headersAdd
.begin(); hwa
!= headersAdd
.end(); ++hwa
) {
487 if (!hwa
->aclList
|| checklist
.fastCheck(hwa
->aclList
) == ACCESS_ALLOWED
) {
488 const char *fieldValue
= NULL
;
493 hwa
->valueFormat
->assemble(mb
, al
, 0);
494 fieldValue
= mb
.content();
497 fieldValue
= hwa
->fieldValue
.c_str();
500 if (!fieldValue
|| fieldValue
[0] == '\0')
503 HttpHeaderEntry
*e
= new HttpHeaderEntry(hwa
->fieldId
, hwa
->fieldName
.c_str(),