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 58 HTTP Reply (Response) */
12 #include "acl/AclSizeLimit.h"
13 #include "acl/FilledChecklist.h"
14 #include "base/EnumIterator.h"
17 #include "HttpHdrCc.h"
18 #include "HttpHdrContRange.h"
19 #include "HttpHdrSc.h"
20 #include "HttpReply.h"
21 #include "HttpRequest.h"
23 #include "SquidConfig.h"
24 #include "SquidTime.h"
30 /* If we receive a 304 from the origin during a cache revalidation, we must
31 * update the headers of the existing entry. Specifically, we need to update all
32 * end-to-end headers and not any hop-by-hop headers (rfc2616 13.5.3).
34 * This is not the whole story though: since it is possible for a faulty/malicious
35 * origin server to set headers it should not in a 304, we must explicitly ignore
36 * these too. Specifically all entity-headers except those permitted in a 304
37 * (rfc2616 10.3.5) must be ignored.
39 * The list of headers we don't update is made up of:
40 * all hop-by-hop headers
41 * all entity-headers except Expires and Content-Location
43 * These headers are now stored in RegisteredHeadersHash.gperf and accessible
44 * as Http::HeaderLookupTable.lookup(id).denied304
46 static HttpHeaderMask Denied304HeadersMask
;
48 /* module initialization */
50 httpReplyInitModule(void)
52 assert(Http::scNone
== 0); // HttpReply::parse() interface assumes that
53 httpHeaderMaskInit(&Denied304HeadersMask
, 0);
55 for (auto id
: WholeEnum
<Http::HdrType
>()) {
56 if (Http::HeaderLookupTable
.lookup(id
).denied304
)
57 CBIT_SET(Denied304HeadersMask
, id
);
61 HttpReply::HttpReply() : HttpMsg(hoReply
), date (0), last_modified (0),
62 expires (0), surrogate_control (NULL
), content_range (NULL
), keep_alive (0),
63 protoPrefix("HTTP/"), bodySizeMax(-2)
68 HttpReply::~HttpReply()
79 pstate
= psReadyToParseStartLine
;
83 void HttpReply::reset()
86 // reset should not reset the protocol; could have made protoPrefix a
87 // virtual function instead, but it is not clear whether virtual methods
88 // are allowed with MEMPROXY_CLASS() and whether some cbdata void*
89 // conversions are not going to kill virtual tables
90 const String pfx
= protoPrefix
;
99 // we used to assert that the pipe is NULL, but now the message only
100 // points to a pipe that is owned and initiated by another object.
107 bodySizeMax
= -2; // hack: make calculatedBodySizeMax() false
111 HttpReply::packHeadersInto(Packable
* p
) const
115 p
->append("\r\n", 2);
119 HttpReply::packInto(Packable
* p
) const
125 /* create memBuf, create mem-based packer, pack, destroy packer, return MemBuf */
127 HttpReply::pack() const
129 MemBuf
*mb
= new MemBuf
;
136 HttpReply::make304() const
138 static const Http::HdrType ImsEntries
[] = {Http::HdrType::DATE
, Http::HdrType::CONTENT_TYPE
, Http::HdrType::EXPIRES
, Http::HdrType::LAST_MODIFIED
, /* eof */ Http::HdrType::OTHER
};
140 HttpReply
*rv
= new HttpReply
;
144 /* rv->content_length; */
146 rv
->last_modified
= last_modified
;
147 rv
->expires
= expires
;
148 rv
->content_type
= content_type
;
149 /* rv->cache_control */
150 /* rv->content_range */
152 rv
->sline
.set(Http::ProtocolVersion(), Http::scNotModified
, NULL
);
154 for (t
= 0; ImsEntries
[t
] != Http::HdrType::OTHER
; ++t
) {
155 if ((e
= header
.findEntry(ImsEntries
[t
])))
156 rv
->header
.addEntry(e
->clone());
164 HttpReply::packed304Reply() const
166 /* Not as efficient as skipping the header duplication,
167 * but easier to maintain
169 HttpReply
*temp
= make304();
170 MemBuf
*rv
= temp
->pack();
176 HttpReply::setHeaders(Http::StatusCode status
, const char *reason
,
177 const char *ctype
, int64_t clen
, time_t lmt
, time_t expiresTime
)
180 sline
.set(Http::ProtocolVersion(), status
, reason
);
182 hdr
->putStr(Http::HdrType::SERVER
, visible_appname_string
);
183 hdr
->putStr(Http::HdrType::MIME_VERSION
, "1.0");
184 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
187 hdr
->putStr(Http::HdrType::CONTENT_TYPE
, ctype
);
188 content_type
= ctype
;
190 content_type
= String();
193 hdr
->putInt64(Http::HdrType::CONTENT_LENGTH
, clen
);
195 if (expiresTime
>= 0)
196 hdr
->putTime(Http::HdrType::EXPIRES
, expiresTime
);
198 if (lmt
> 0) /* this used to be lmt != 0 @?@ */
199 hdr
->putTime(Http::HdrType::LAST_MODIFIED
, lmt
);
201 date
= squid_curtime
;
203 content_length
= clen
;
205 expires
= expiresTime
;
211 HttpReply::redirect(Http::StatusCode status
, const char *loc
)
214 sline
.set(Http::ProtocolVersion(), status
, NULL
);
216 hdr
->putStr(Http::HdrType::SERVER
, APP_FULLNAME
);
217 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
218 hdr
->putInt64(Http::HdrType::CONTENT_LENGTH
, 0);
219 hdr
->putStr(Http::HdrType::LOCATION
, loc
);
220 date
= squid_curtime
;
224 /* compare the validators of two replies.
226 * 0 = they do not match
229 HttpReply::validatorsMatch(HttpReply
const * otherRep
) const
233 /* Numbers first - easiest to check */
235 /* TODO: remove -1 bypass */
237 if (content_length
!= otherRep
->content_length
238 && content_length
> -1 &&
239 otherRep
->content_length
> -1)
243 one
= header
.getStrOrList(Http::HdrType::ETAG
);
245 two
= otherRep
->header
.getStrOrList(Http::HdrType::ETAG
);
247 if (one
.size()==0 || two
.size()==0 || one
.caseCmp(two
)!=0 ) {
253 if (last_modified
!= otherRep
->last_modified
)
257 one
= header
.getStrOrList(Http::HdrType::CONTENT_MD5
);
259 two
= otherRep
->header
.getStrOrList(Http::HdrType::CONTENT_MD5
);
261 if (one
.size()==0 || two
.size()==0 || one
.caseCmp(two
)!=0 ) {
271 HttpReply::updateOnNotModified(HttpReply
const * freshRep
)
277 /* update raw headers */
278 header
.update(&freshRep
->header
,
279 (const HttpHeaderMask
*) &Denied304HeadersMask
);
286 /* internal routines */
289 HttpReply::hdrExpirationTime()
291 /* The s-maxage and max-age directive takes priority over Expires */
295 if (cache_control
->hasSMaxAge())
296 return date
+ cache_control
->sMaxAge();
298 if (cache_control
->hasMaxAge())
299 return date
+ cache_control
->maxAge();
302 * Conservatively handle the case when we have a max-age
303 * header, but no Date for reference?
306 if (cache_control
->hasSMaxAge())
307 return squid_curtime
;
309 if (cache_control
->hasMaxAge())
310 return squid_curtime
;
314 if (Config
.onoff
.vary_ignore_expire
&&
315 header
.has(Http::HdrType::VARY
)) {
316 const time_t d
= header
.getTime(Http::HdrType::DATE
);
317 const time_t e
= header
.getTime(Http::HdrType::EXPIRES
);
323 if (header
.has(Http::HdrType::EXPIRES
)) {
324 const time_t e
= header
.getTime(Http::HdrType::EXPIRES
);
326 * HTTP/1.0 says that robust implementations should consider
327 * bad or malformed Expires header as equivalent to "expires
330 return e
< 0 ? squid_curtime
: e
;
336 /* sync this routine when you update HttpReply struct */
338 HttpReply::hdrCacheInit()
340 HttpMsg::hdrCacheInit();
342 http_ver
= sline
.version
;
343 content_length
= header
.getInt64(Http::HdrType::CONTENT_LENGTH
);
344 date
= header
.getTime(Http::HdrType::DATE
);
345 last_modified
= header
.getTime(Http::HdrType::LAST_MODIFIED
);
346 surrogate_control
= header
.getSc();
347 content_range
= header
.getContRange();
348 keep_alive
= persistent() ? 1 : 0;
349 const char *str
= header
.getStr(Http::HdrType::CONTENT_TYPE
);
352 content_type
.limitInit(str
, strcspn(str
, ";\t "));
354 content_type
= String();
356 /* be sure to set expires after date and cache-control */
357 expires
= hdrExpirationTime();
360 /* sync this routine when you update HttpReply struct */
362 HttpReply::hdrCacheClean()
364 content_type
.clean();
367 delete cache_control
;
368 cache_control
= NULL
;
371 if (surrogate_control
) {
372 delete surrogate_control
;
373 surrogate_control
= NULL
;
377 httpHdrContRangeDestroy(content_range
);
378 content_range
= NULL
;
383 * Returns the body size of a HTTP response
386 HttpReply::bodySize(const HttpRequestMethod
& method
) const
388 if (sline
.version
.major
< 1)
390 else if (method
.id() == Http::METHOD_HEAD
)
392 else if (sline
.status() == Http::scOkay
)
393 (void) 0; /* common case, continue */
394 else if (sline
.status() == Http::scNoContent
)
396 else if (sline
.status() == Http::scNotModified
)
398 else if (sline
.status() < Http::scOkay
)
401 return content_length
;
405 * Checks the first line of an HTTP Reply is valid.
406 * currently only checks "HTTP/" exists.
408 * NP: not all error cases are detected yet. Some are left for detection later in parse.
411 HttpReply::sanityCheckStartLine(const char *buf
, const size_t hdr_len
, Http::StatusCode
*error
)
413 // hack warning: using psize instead of size here due to type mismatches with MemBuf.
415 // content is long enough to possibly hold a reply
416 // 4 being magic size of a 3-digit number plus space delimiter
417 if (hdr_len
< (size_t)(protoPrefix
.psize() + 4)) {
419 debugs(58, 3, "Too small reply header (" << hdr_len
<< " bytes)");
420 *error
= Http::scInvalidHeader
;
426 // catch missing or mismatched protocol identifier
427 // allow special-case for ICY protocol (non-HTTP identifier) in response to faked HTTP request.
428 if (strncmp(buf
, "ICY", 3) == 0) {
430 pos
= protoPrefix
.psize();
433 if (protoPrefix
.cmp(buf
, protoPrefix
.size()) != 0) {
434 debugs(58, 3, "missing protocol prefix (" << protoPrefix
<< ") in '" << buf
<< "'");
435 *error
= Http::scInvalidHeader
;
439 // catch missing or negative status value (negative '-' is not a digit)
440 pos
= protoPrefix
.psize();
442 // skip arbitrary number of digits and a dot in the verion portion
443 while ((size_t)pos
<= hdr_len
&& (*(buf
+pos
) == '.' || xisdigit(*(buf
+pos
)) ) ) ++pos
;
445 // catch missing version info
446 if (pos
== protoPrefix
.psize()) {
447 debugs(58, 3, "missing protocol version numbers (ie. " << protoPrefix
<< "/1.0) in '" << buf
<< "'");
448 *error
= Http::scInvalidHeader
;
453 // skip arbitrary number of spaces...
454 while ((size_t)pos
<= hdr_len
&& (char)*(buf
+pos
) == ' ') ++pos
;
456 if ((size_t)pos
< hdr_len
&& !xisdigit(*(buf
+pos
))) {
457 debugs(58, 3, "missing or invalid status number in '" << buf
<< "'");
458 *error
= Http::scInvalidHeader
;
466 HttpReply::parseFirstLine(const char *blk_start
, const char *blk_end
)
468 return sline
.parse(protoPrefix
, blk_start
, blk_end
);
471 /* handy: resets and returns -1 */
473 HttpReply::httpMsgParseError()
475 int result(HttpMsg::httpMsgParseError());
476 /* indicate an error in the status line */
477 sline
.set(Http::ProtocolVersion(), Http::scInvalidHeader
);
482 * Indicate whether or not we would usually expect an entity-body
483 * along with this response
486 HttpReply::expectingBody(const HttpRequestMethod
& req_method
, int64_t& theSize
) const
488 bool expectBody
= true;
490 if (req_method
== Http::METHOD_HEAD
)
492 else if (sline
.status() == Http::scNoContent
)
494 else if (sline
.status() == Http::scNotModified
)
496 else if (sline
.status() < Http::scOkay
)
502 if (header
.chunked())
504 else if (content_length
>= 0)
505 theSize
= content_length
;
514 HttpReply::receivedBodyTooLarge(HttpRequest
& request
, int64_t receivedSize
)
516 calcMaxBodySize(request
);
517 debugs(58, 3, HERE
<< receivedSize
<< " >? " << bodySizeMax
);
518 return bodySizeMax
>= 0 && receivedSize
> bodySizeMax
;
522 HttpReply::expectedBodyTooLarge(HttpRequest
& request
)
524 calcMaxBodySize(request
);
525 debugs(58, 7, HERE
<< "bodySizeMax=" << bodySizeMax
);
527 if (bodySizeMax
< 0) // no body size limit
530 int64_t expectedSize
= -1;
531 if (!expectingBody(request
.method
, expectedSize
))
534 debugs(58, 6, HERE
<< expectedSize
<< " >? " << bodySizeMax
);
536 if (expectedSize
< 0) // expecting body of an unknown length
539 return expectedSize
> bodySizeMax
;
543 HttpReply::calcMaxBodySize(HttpRequest
& request
) const
545 // hack: -2 is used as "we have not calculated max body size yet" state
546 if (bodySizeMax
!= -2) // already tried
550 // short-circuit ACL testing if there are none configured
551 if (!Config
.ReplyBodySize
)
554 ACLFilledChecklist
ch(NULL
, &request
, NULL
);
555 // XXX: cont-cast becomes irrelevant when checklist is HttpReply::Pointer
556 ch
.reply
= const_cast<HttpReply
*>(this);
557 HTTPMSGLOCK(ch
.reply
);
558 for (AclSizeLimit
*l
= Config
.ReplyBodySize
; l
; l
= l
-> next
) {
559 /* if there is no ACL list or if the ACLs listed match use this size value */
560 if (!l
->aclList
|| ch
.fastCheck(l
->aclList
) == ACCESS_ALLOWED
) {
561 debugs(58, 4, HERE
<< "bodySizeMax=" << bodySizeMax
);
562 bodySizeMax
= l
->size
; // may be -1
568 // XXX: check that this is sufficient for eCAP cloning
570 HttpReply::clone() const
572 HttpReply
*rep
= new HttpReply();
573 rep
->sline
= sline
; // used in hdrCacheInit() call below
574 rep
->header
.append(&header
);
576 rep
->hdr_sz
= hdr_sz
;
577 rep
->http_ver
= http_ver
;
578 rep
->pstate
= pstate
;
579 rep
->body_pipe
= body_pipe
;
581 // keep_alive is handled in hdrCacheInit()
585 bool HttpReply::inheritProperties(const HttpMsg
*aMsg
)
587 const HttpReply
*aRep
= dynamic_cast<const HttpReply
*>(aMsg
);
590 keep_alive
= aRep
->keep_alive
;
591 sources
= aRep
->sources
;
595 void HttpReply::removeStaleWarnings()
598 if (header
.getList(Http::HdrType::WARNING
, &warning
)) {
599 const String newWarning
= removeStaleWarningValues(warning
);
600 if (warning
.size() && warning
.size() == newWarning
.size())
601 return; // some warnings are there and none changed
602 header
.delById(Http::HdrType::WARNING
);
603 if (newWarning
.size()) { // some warnings left
604 HttpHeaderEntry
*const e
=
605 new HttpHeaderEntry(Http::HdrType::WARNING
, NULL
, newWarning
.termedBuf());
612 * Remove warning-values with warn-date different from Date value from
613 * a single header entry. Returns a string with all valid warning-values.
615 String
HttpReply::removeStaleWarningValues(const String
&value
)
618 const char *item
= 0;
621 while (strListGetItem(&value
, ',', &item
, &len
, &pos
)) {
623 // Does warning-value have warn-date (which contains quoted date)?
624 // We scan backwards, looking for two quoted strings.
625 // warning-value = warn-code SP warn-agent SP warn-text [SP warn-date]
626 const char *p
= item
+ len
- 1;
628 while (p
>= item
&& xisspace(*p
)) --p
; // skip whitespace
630 // warning-value MUST end with quote
631 if (p
>= item
&& *p
== '"') {
632 const char *const warnDateEnd
= p
;
634 while (p
>= item
&& *p
!= '"') --p
; // find the next quote
636 const char *warnDateBeg
= p
+ 1;
638 while (p
>= item
&& xisspace(*p
)) --p
; // skip whitespace
640 if (p
>= item
&& *p
== '"' && warnDateBeg
- p
> 2) {
643 warnDate
.append(warnDateBeg
, warnDateEnd
- warnDateBeg
);
644 const time_t time
= parse_rfc1123(warnDate
.termedBuf());
645 keep
= (time
> 0 && time
== date
); // keep valid and matching date
651 newValue
.append(", ");
652 newValue
.append(item
, len
);