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 58 HTTP Reply (Response) */
12 #include "acl/AclSizeLimit.h"
13 #include "acl/FilledChecklist.h"
16 #include "HttpHdrCc.h"
17 #include "HttpHdrContRange.h"
18 #include "HttpHdrSc.h"
19 #include "HttpReply.h"
20 #include "HttpRequest.h"
22 #include "SquidConfig.h"
23 #include "SquidTime.h"
29 /* If we receive a 304 from the origin during a cache revalidation, we must
30 * update the headers of the existing entry. Specifically, we need to update all
31 * end-to-end headers and not any hop-by-hop headers (rfc2616 13.5.3).
33 * This is not the whole story though: since it is possible for a faulty/malicious
34 * origin server to set headers it should not in a 304, we must explicitly ignore
35 * these too. Specifically all entity-headers except those permitted in a 304
36 * (rfc2616 10.3.5) must be ignored.
38 * The list of headers we don't update is made up of:
39 * all hop-by-hop headers
40 * all entity-headers except Expires and Content-Location
42 static HttpHeaderMask Denied304HeadersMask
;
43 static http_hdr_type Denied304HeadersArr
[] = {
45 HDR_CONNECTION
, HDR_KEEP_ALIVE
, HDR_PROXY_AUTHENTICATE
, HDR_PROXY_AUTHORIZATION
,
46 HDR_TE
, HDR_TRAILER
, HDR_TRANSFER_ENCODING
, HDR_UPGRADE
,
48 HDR_ALLOW
, HDR_CONTENT_ENCODING
, HDR_CONTENT_LANGUAGE
, HDR_CONTENT_LENGTH
,
49 HDR_CONTENT_MD5
, HDR_CONTENT_RANGE
, HDR_CONTENT_TYPE
, HDR_LAST_MODIFIED
52 /* module initialization */
54 httpReplyInitModule(void)
56 assert(Http::scNone
== 0); // HttpReply::parse() interface assumes that
57 httpHeaderMaskInit(&Denied304HeadersMask
, 0);
58 httpHeaderCalcMask(&Denied304HeadersMask
, Denied304HeadersArr
, countof(Denied304HeadersArr
));
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(Packer
* p
) const
115 packerAppend(p
, "\r\n", 2);
119 HttpReply::packInto(Packer
* p
)
125 /* create memBuf, create mem-based packer, pack, destroy packer, return MemBuf */
129 MemBuf
*mb
= new MemBuf
;
133 packerToMemInit(&p
, mb
);
140 HttpReply::make304() const
142 static const http_hdr_type ImsEntries
[] = {HDR_DATE
, HDR_CONTENT_TYPE
, HDR_EXPIRES
, HDR_LAST_MODIFIED
, /* eof */ HDR_OTHER
};
144 HttpReply
*rv
= new HttpReply
;
148 /* rv->content_length; */
150 rv
->last_modified
= last_modified
;
151 rv
->expires
= expires
;
152 rv
->content_type
= content_type
;
153 /* rv->cache_control */
154 /* rv->content_range */
156 rv
->sline
.set(Http::ProtocolVersion(), Http::scNotModified
, NULL
);
158 for (t
= 0; ImsEntries
[t
] != HDR_OTHER
; ++t
)
159 if ((e
= header
.findEntry(ImsEntries
[t
])))
160 rv
->header
.addEntry(e
->clone());
167 HttpReply::packed304Reply()
169 /* Not as efficient as skipping the header duplication,
170 * but easier to maintain
172 HttpReply
*temp
= make304();
173 MemBuf
*rv
= temp
->pack();
179 HttpReply::setHeaders(Http::StatusCode status
, const char *reason
,
180 const char *ctype
, int64_t clen
, time_t lmt
, time_t expiresTime
)
183 sline
.set(Http::ProtocolVersion(), status
, reason
);
185 hdr
->putStr(HDR_SERVER
, visible_appname_string
);
186 hdr
->putStr(HDR_MIME_VERSION
, "1.0");
187 hdr
->putTime(HDR_DATE
, squid_curtime
);
190 hdr
->putStr(HDR_CONTENT_TYPE
, ctype
);
191 content_type
= ctype
;
193 content_type
= String();
196 hdr
->putInt64(HDR_CONTENT_LENGTH
, clen
);
198 if (expiresTime
>= 0)
199 hdr
->putTime(HDR_EXPIRES
, expiresTime
);
201 if (lmt
> 0) /* this used to be lmt != 0 @?@ */
202 hdr
->putTime(HDR_LAST_MODIFIED
, lmt
);
204 date
= squid_curtime
;
206 content_length
= clen
;
208 expires
= expiresTime
;
214 HttpReply::redirect(Http::StatusCode status
, const char *loc
)
217 sline
.set(Http::ProtocolVersion(), status
, NULL
);
219 hdr
->putStr(HDR_SERVER
, APP_FULLNAME
);
220 hdr
->putTime(HDR_DATE
, squid_curtime
);
221 hdr
->putInt64(HDR_CONTENT_LENGTH
, 0);
222 hdr
->putStr(HDR_LOCATION
, loc
);
223 date
= squid_curtime
;
227 /* compare the validators of two replies.
229 * 0 = they do not match
232 HttpReply::validatorsMatch(HttpReply
const * otherRep
) const
236 /* Numbers first - easiest to check */
238 /* TODO: remove -1 bypass */
240 if (content_length
!= otherRep
->content_length
241 && content_length
> -1 &&
242 otherRep
->content_length
> -1)
246 one
= header
.getStrOrList(HDR_ETAG
);
248 two
= otherRep
->header
.getStrOrList(HDR_ETAG
);
250 if (one
.size()==0 || two
.size()==0 || one
.caseCmp(two
)!=0 ) {
256 if (last_modified
!= otherRep
->last_modified
)
260 one
= header
.getStrOrList(HDR_CONTENT_MD5
);
262 two
= otherRep
->header
.getStrOrList(HDR_CONTENT_MD5
);
264 if (one
.size()==0 || two
.size()==0 || one
.caseCmp(two
)!=0 ) {
274 HttpReply::updateOnNotModified(HttpReply
const * freshRep
)
280 /* update raw headers */
281 header
.update(&freshRep
->header
,
282 (const HttpHeaderMask
*) &Denied304HeadersMask
);
289 /* internal routines */
292 HttpReply::hdrExpirationTime()
294 /* The s-maxage and max-age directive takes priority over Expires */
298 if (cache_control
->hasSMaxAge())
299 return date
+ cache_control
->sMaxAge();
301 if (cache_control
->hasMaxAge())
302 return date
+ cache_control
->maxAge();
305 * Conservatively handle the case when we have a max-age
306 * header, but no Date for reference?
309 if (cache_control
->hasSMaxAge())
310 return squid_curtime
;
312 if (cache_control
->hasMaxAge())
313 return squid_curtime
;
317 if (Config
.onoff
.vary_ignore_expire
&&
318 header
.has(HDR_VARY
)) {
319 const time_t d
= header
.getTime(HDR_DATE
);
320 const time_t e
= header
.getTime(HDR_EXPIRES
);
326 if (header
.has(HDR_EXPIRES
)) {
327 const time_t e
= header
.getTime(HDR_EXPIRES
);
329 * HTTP/1.0 says that robust implementations should consider
330 * bad or malformed Expires header as equivalent to "expires
333 return e
< 0 ? squid_curtime
: e
;
339 /* sync this routine when you update HttpReply struct */
341 HttpReply::hdrCacheInit()
343 HttpMsg::hdrCacheInit();
345 http_ver
= sline
.version
;
346 content_length
= header
.getInt64(HDR_CONTENT_LENGTH
);
347 date
= header
.getTime(HDR_DATE
);
348 last_modified
= header
.getTime(HDR_LAST_MODIFIED
);
349 surrogate_control
= header
.getSc();
350 content_range
= header
.getContRange();
351 keep_alive
= persistent() ? 1 : 0;
352 const char *str
= header
.getStr(HDR_CONTENT_TYPE
);
355 content_type
.limitInit(str
, strcspn(str
, ";\t "));
357 content_type
= String();
359 /* be sure to set expires after date and cache-control */
360 expires
= hdrExpirationTime();
363 /* sync this routine when you update HttpReply struct */
365 HttpReply::hdrCacheClean()
367 content_type
.clean();
370 delete cache_control
;
371 cache_control
= NULL
;
374 if (surrogate_control
) {
375 delete surrogate_control
;
376 surrogate_control
= NULL
;
380 httpHdrContRangeDestroy(content_range
);
381 content_range
= NULL
;
386 * Returns the body size of a HTTP response
389 HttpReply::bodySize(const HttpRequestMethod
& method
) const
391 if (sline
.version
.major
< 1)
393 else if (method
.id() == Http::METHOD_HEAD
)
395 else if (sline
.status() == Http::scOkay
)
396 (void) 0; /* common case, continue */
397 else if (sline
.status() == Http::scNoContent
)
399 else if (sline
.status() == Http::scNotModified
)
401 else if (sline
.status() < Http::scOkay
)
404 return content_length
;
408 * Checks the first line of an HTTP Reply is valid.
409 * currently only checks "HTTP/" exists.
411 * NP: not all error cases are detected yet. Some are left for detection later in parse.
414 HttpReply::sanityCheckStartLine(MemBuf
*buf
, const size_t hdr_len
, Http::StatusCode
*error
)
416 // hack warning: using psize instead of size here due to type mismatches with MemBuf.
418 // content is long enough to possibly hold a reply
419 // 4 being magic size of a 3-digit number plus space delimiter
420 if ( buf
->contentSize() < (protoPrefix
.psize() + 4) ) {
422 debugs(58, 3, HERE
<< "Too small reply header (" << hdr_len
<< " bytes)");
423 *error
= Http::scInvalidHeader
;
429 // catch missing or mismatched protocol identifier
430 // allow special-case for ICY protocol (non-HTTP identifier) in response to faked HTTP request.
431 if (strncmp(buf
->content(), "ICY", 3) == 0) {
433 pos
= protoPrefix
.psize();
436 if (protoPrefix
.cmp(buf
->content(), protoPrefix
.size()) != 0) {
437 debugs(58, 3, "HttpReply::sanityCheckStartLine: missing protocol prefix (" << protoPrefix
<< ") in '" << buf
->content() << "'");
438 *error
= Http::scInvalidHeader
;
442 // catch missing or negative status value (negative '-' is not a digit)
443 pos
= protoPrefix
.psize();
445 // skip arbitrary number of digits and a dot in the verion portion
446 while ( pos
<= buf
->contentSize() && (*(buf
->content()+pos
) == '.' || xisdigit(*(buf
->content()+pos
)) ) ) ++pos
;
448 // catch missing version info
449 if (pos
== protoPrefix
.psize()) {
450 debugs(58, 3, "HttpReply::sanityCheckStartLine: missing protocol version numbers (ie. " << protoPrefix
<< "/1.0) in '" << buf
->content() << "'");
451 *error
= Http::scInvalidHeader
;
456 // skip arbitrary number of spaces...
457 while (pos
<= buf
->contentSize() && (char)*(buf
->content()+pos
) == ' ') ++pos
;
459 if (pos
< buf
->contentSize() && !xisdigit(*(buf
->content()+pos
))) {
460 debugs(58, 3, "HttpReply::sanityCheckStartLine: missing or invalid status number in '" << buf
->content() << "'");
461 *error
= Http::scInvalidHeader
;
469 HttpReply::parseFirstLine(const char *blk_start
, const char *blk_end
)
471 return sline
.parse(protoPrefix
, blk_start
, blk_end
);
474 /* handy: resets and returns -1 */
476 HttpReply::httpMsgParseError()
478 int result(HttpMsg::httpMsgParseError());
479 /* indicate an error in the status line */
480 sline
.set(Http::ProtocolVersion(), Http::scInvalidHeader
);
485 * Indicate whether or not we would usually expect an entity-body
486 * along with this response
489 HttpReply::expectingBody(const HttpRequestMethod
& req_method
, int64_t& theSize
) const
491 bool expectBody
= true;
493 if (req_method
== Http::METHOD_HEAD
)
495 else if (sline
.status() == Http::scNoContent
)
497 else if (sline
.status() == Http::scNotModified
)
499 else if (sline
.status() < Http::scOkay
)
505 if (header
.chunked())
507 else if (content_length
>= 0)
508 theSize
= content_length
;
517 HttpReply::receivedBodyTooLarge(HttpRequest
& request
, int64_t receivedSize
)
519 calcMaxBodySize(request
);
520 debugs(58, 3, HERE
<< receivedSize
<< " >? " << bodySizeMax
);
521 return bodySizeMax
>= 0 && receivedSize
> bodySizeMax
;
525 HttpReply::expectedBodyTooLarge(HttpRequest
& request
)
527 calcMaxBodySize(request
);
528 debugs(58, 7, HERE
<< "bodySizeMax=" << bodySizeMax
);
530 if (bodySizeMax
< 0) // no body size limit
533 int64_t expectedSize
= -1;
534 if (!expectingBody(request
.method
, expectedSize
))
537 debugs(58, 6, HERE
<< expectedSize
<< " >? " << bodySizeMax
);
539 if (expectedSize
< 0) // expecting body of an unknown length
542 return expectedSize
> bodySizeMax
;
546 HttpReply::calcMaxBodySize(HttpRequest
& request
) const
548 // hack: -2 is used as "we have not calculated max body size yet" state
549 if (bodySizeMax
!= -2) // already tried
553 // short-circuit ACL testing if there are none configured
554 if (!Config
.ReplyBodySize
)
557 ACLFilledChecklist
ch(NULL
, &request
, NULL
);
558 // XXX: cont-cast becomes irrelevant when checklist is HttpReply::Pointer
559 ch
.reply
= const_cast<HttpReply
*>(this);
560 HTTPMSGLOCK(ch
.reply
);
561 for (AclSizeLimit
*l
= Config
.ReplyBodySize
; l
; l
= l
-> next
) {
562 /* if there is no ACL list or if the ACLs listed match use this size value */
563 if (!l
->aclList
|| ch
.fastCheck(l
->aclList
) == ACCESS_ALLOWED
) {
564 debugs(58, 4, HERE
<< "bodySizeMax=" << bodySizeMax
);
565 bodySizeMax
= l
->size
; // may be -1
571 // XXX: check that this is sufficient for eCAP cloning
573 HttpReply::clone() const
575 HttpReply
*rep
= new HttpReply();
576 rep
->sline
= sline
; // used in hdrCacheInit() call below
577 rep
->header
.append(&header
);
579 rep
->hdr_sz
= hdr_sz
;
580 rep
->http_ver
= http_ver
;
581 rep
->pstate
= pstate
;
582 rep
->body_pipe
= body_pipe
;
584 // keep_alive is handled in hdrCacheInit()
588 bool HttpReply::inheritProperties(const HttpMsg
*aMsg
)
590 const HttpReply
*aRep
= dynamic_cast<const HttpReply
*>(aMsg
);
593 keep_alive
= aRep
->keep_alive
;
597 void HttpReply::removeStaleWarnings()
600 if (header
.getList(HDR_WARNING
, &warning
)) {
601 const String newWarning
= removeStaleWarningValues(warning
);
602 if (warning
.size() && warning
.size() == newWarning
.size())
603 return; // some warnings are there and none changed
604 header
.delById(HDR_WARNING
);
605 if (newWarning
.size()) { // some warnings left
606 HttpHeaderEntry
*const e
=
607 new HttpHeaderEntry(HDR_WARNING
, NULL
, newWarning
.termedBuf());
614 * Remove warning-values with warn-date different from Date value from
615 * a single header entry. Returns a string with all valid warning-values.
617 String
HttpReply::removeStaleWarningValues(const String
&value
)
620 const char *item
= 0;
623 while (strListGetItem(&value
, ',', &item
, &len
, &pos
)) {
625 // Does warning-value have warn-date (which contains quoted date)?
626 // We scan backwards, looking for two quoted strings.
627 // warning-value = warn-code SP warn-agent SP warn-text [SP warn-date]
628 const char *p
= item
+ len
- 1;
630 while (p
>= item
&& xisspace(*p
)) --p
; // skip whitespace
632 // warning-value MUST end with quote
633 if (p
>= item
&& *p
== '"') {
634 const char *const warnDateEnd
= p
;
636 while (p
>= item
&& *p
!= '"') --p
; // find the next quote
638 const char *warnDateBeg
= p
+ 1;
640 while (p
>= item
&& xisspace(*p
)) --p
; // skip whitespace
642 if (p
>= item
&& *p
== '"' && warnDateBeg
- p
> 2) {
645 warnDate
.append(warnDateBeg
, warnDateEnd
- warnDateBeg
);
646 const time_t time
= parse_rfc1123(warnDate
.termedBuf());
647 keep
= (time
> 0 && time
== date
); // keep valid and matching date
653 newValue
.append(", ");
654 newValue
.append(item
, len
);