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 p
->append("\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
);
139 HttpReply::make304() const
141 static const http_hdr_type ImsEntries
[] = {HDR_DATE
, HDR_CONTENT_TYPE
, HDR_EXPIRES
, HDR_LAST_MODIFIED
, /* eof */ HDR_OTHER
};
143 HttpReply
*rv
= new HttpReply
;
147 /* rv->content_length; */
149 rv
->last_modified
= last_modified
;
150 rv
->expires
= expires
;
151 rv
->content_type
= content_type
;
152 /* rv->cache_control */
153 /* rv->content_range */
155 rv
->sline
.set(Http::ProtocolVersion(), Http::scNotModified
, NULL
);
157 for (t
= 0; ImsEntries
[t
] != HDR_OTHER
; ++t
)
158 if ((e
= header
.findEntry(ImsEntries
[t
])))
159 rv
->header
.addEntry(e
->clone());
166 HttpReply::packed304Reply()
168 /* Not as efficient as skipping the header duplication,
169 * but easier to maintain
171 HttpReply
*temp
= make304();
172 MemBuf
*rv
= temp
->pack();
178 HttpReply::setHeaders(Http::StatusCode status
, const char *reason
,
179 const char *ctype
, int64_t clen
, time_t lmt
, time_t expiresTime
)
182 sline
.set(Http::ProtocolVersion(), status
, reason
);
184 hdr
->putStr(HDR_SERVER
, visible_appname_string
);
185 hdr
->putStr(HDR_MIME_VERSION
, "1.0");
186 hdr
->putTime(HDR_DATE
, squid_curtime
);
189 hdr
->putStr(HDR_CONTENT_TYPE
, ctype
);
190 content_type
= ctype
;
192 content_type
= String();
195 hdr
->putInt64(HDR_CONTENT_LENGTH
, clen
);
197 if (expiresTime
>= 0)
198 hdr
->putTime(HDR_EXPIRES
, expiresTime
);
200 if (lmt
> 0) /* this used to be lmt != 0 @?@ */
201 hdr
->putTime(HDR_LAST_MODIFIED
, lmt
);
203 date
= squid_curtime
;
205 content_length
= clen
;
207 expires
= expiresTime
;
213 HttpReply::redirect(Http::StatusCode status
, const char *loc
)
216 sline
.set(Http::ProtocolVersion(), status
, NULL
);
218 hdr
->putStr(HDR_SERVER
, APP_FULLNAME
);
219 hdr
->putTime(HDR_DATE
, squid_curtime
);
220 hdr
->putInt64(HDR_CONTENT_LENGTH
, 0);
221 hdr
->putStr(HDR_LOCATION
, loc
);
222 date
= squid_curtime
;
226 /* compare the validators of two replies.
228 * 0 = they do not match
231 HttpReply::validatorsMatch(HttpReply
const * otherRep
) const
235 /* Numbers first - easiest to check */
237 /* TODO: remove -1 bypass */
239 if (content_length
!= otherRep
->content_length
240 && content_length
> -1 &&
241 otherRep
->content_length
> -1)
245 one
= header
.getStrOrList(HDR_ETAG
);
247 two
= otherRep
->header
.getStrOrList(HDR_ETAG
);
249 if (one
.size()==0 || two
.size()==0 || one
.caseCmp(two
)!=0 ) {
255 if (last_modified
!= otherRep
->last_modified
)
259 one
= header
.getStrOrList(HDR_CONTENT_MD5
);
261 two
= otherRep
->header
.getStrOrList(HDR_CONTENT_MD5
);
263 if (one
.size()==0 || two
.size()==0 || one
.caseCmp(two
)!=0 ) {
273 HttpReply::updateOnNotModified(HttpReply
const * freshRep
)
279 /* update raw headers */
280 header
.update(&freshRep
->header
,
281 (const HttpHeaderMask
*) &Denied304HeadersMask
);
288 /* internal routines */
291 HttpReply::hdrExpirationTime()
293 /* The s-maxage and max-age directive takes priority over Expires */
297 if (cache_control
->hasSMaxAge())
298 return date
+ cache_control
->sMaxAge();
300 if (cache_control
->hasMaxAge())
301 return date
+ cache_control
->maxAge();
304 * Conservatively handle the case when we have a max-age
305 * header, but no Date for reference?
308 if (cache_control
->hasSMaxAge())
309 return squid_curtime
;
311 if (cache_control
->hasMaxAge())
312 return squid_curtime
;
316 if (Config
.onoff
.vary_ignore_expire
&&
317 header
.has(HDR_VARY
)) {
318 const time_t d
= header
.getTime(HDR_DATE
);
319 const time_t e
= header
.getTime(HDR_EXPIRES
);
325 if (header
.has(HDR_EXPIRES
)) {
326 const time_t e
= header
.getTime(HDR_EXPIRES
);
328 * HTTP/1.0 says that robust implementations should consider
329 * bad or malformed Expires header as equivalent to "expires
332 return e
< 0 ? squid_curtime
: e
;
338 /* sync this routine when you update HttpReply struct */
340 HttpReply::hdrCacheInit()
342 HttpMsg::hdrCacheInit();
344 http_ver
= sline
.version
;
345 content_length
= header
.getInt64(HDR_CONTENT_LENGTH
);
346 date
= header
.getTime(HDR_DATE
);
347 last_modified
= header
.getTime(HDR_LAST_MODIFIED
);
348 surrogate_control
= header
.getSc();
349 content_range
= header
.getContRange();
350 keep_alive
= persistent() ? 1 : 0;
351 const char *str
= header
.getStr(HDR_CONTENT_TYPE
);
354 content_type
.limitInit(str
, strcspn(str
, ";\t "));
356 content_type
= String();
358 /* be sure to set expires after date and cache-control */
359 expires
= hdrExpirationTime();
362 /* sync this routine when you update HttpReply struct */
364 HttpReply::hdrCacheClean()
366 content_type
.clean();
369 delete cache_control
;
370 cache_control
= NULL
;
373 if (surrogate_control
) {
374 delete surrogate_control
;
375 surrogate_control
= NULL
;
379 httpHdrContRangeDestroy(content_range
);
380 content_range
= NULL
;
385 * Returns the body size of a HTTP response
388 HttpReply::bodySize(const HttpRequestMethod
& method
) const
390 if (sline
.version
.major
< 1)
392 else if (method
.id() == Http::METHOD_HEAD
)
394 else if (sline
.status() == Http::scOkay
)
395 (void) 0; /* common case, continue */
396 else if (sline
.status() == Http::scNoContent
)
398 else if (sline
.status() == Http::scNotModified
)
400 else if (sline
.status() < Http::scOkay
)
403 return content_length
;
407 * Checks the first line of an HTTP Reply is valid.
408 * currently only checks "HTTP/" exists.
410 * NP: not all error cases are detected yet. Some are left for detection later in parse.
413 HttpReply::sanityCheckStartLine(const char *buf
, const size_t hdr_len
, Http::StatusCode
*error
)
415 // hack warning: using psize instead of size here due to type mismatches with MemBuf.
417 // content is long enough to possibly hold a reply
418 // 4 being magic size of a 3-digit number plus space delimiter
419 if (hdr_len
< (size_t)(protoPrefix
.psize() + 4)) {
421 debugs(58, 3, "Too small reply header (" << hdr_len
<< " bytes)");
422 *error
= Http::scInvalidHeader
;
428 // catch missing or mismatched protocol identifier
429 // allow special-case for ICY protocol (non-HTTP identifier) in response to faked HTTP request.
430 if (strncmp(buf
, "ICY", 3) == 0) {
432 pos
= protoPrefix
.psize();
435 if (protoPrefix
.cmp(buf
, protoPrefix
.size()) != 0) {
436 debugs(58, 3, "missing protocol prefix (" << protoPrefix
<< ") in '" << buf
<< "'");
437 *error
= Http::scInvalidHeader
;
441 // catch missing or negative status value (negative '-' is not a digit)
442 pos
= protoPrefix
.psize();
444 // skip arbitrary number of digits and a dot in the verion portion
445 while ((size_t)pos
<= hdr_len
&& (*(buf
+pos
) == '.' || xisdigit(*(buf
+pos
)) ) ) ++pos
;
447 // catch missing version info
448 if (pos
== protoPrefix
.psize()) {
449 debugs(58, 3, "missing protocol version numbers (ie. " << protoPrefix
<< "/1.0) in '" << buf
<< "'");
450 *error
= Http::scInvalidHeader
;
455 // skip arbitrary number of spaces...
456 while ((size_t)pos
<= hdr_len
&& (char)*(buf
+pos
) == ' ') ++pos
;
458 if ((size_t)pos
< hdr_len
&& !xisdigit(*(buf
+pos
))) {
459 debugs(58, 3, "missing or invalid status number in '" << buf
<< "'");
460 *error
= Http::scInvalidHeader
;
468 HttpReply::parseFirstLine(const char *blk_start
, const char *blk_end
)
470 return sline
.parse(protoPrefix
, blk_start
, blk_end
);
473 /* handy: resets and returns -1 */
475 HttpReply::httpMsgParseError()
477 int result(HttpMsg::httpMsgParseError());
478 /* indicate an error in the status line */
479 sline
.set(Http::ProtocolVersion(), Http::scInvalidHeader
);
484 * Indicate whether or not we would usually expect an entity-body
485 * along with this response
488 HttpReply::expectingBody(const HttpRequestMethod
& req_method
, int64_t& theSize
) const
490 bool expectBody
= true;
492 if (req_method
== Http::METHOD_HEAD
)
494 else if (sline
.status() == Http::scNoContent
)
496 else if (sline
.status() == Http::scNotModified
)
498 else if (sline
.status() < Http::scOkay
)
504 if (header
.chunked())
506 else if (content_length
>= 0)
507 theSize
= content_length
;
516 HttpReply::receivedBodyTooLarge(HttpRequest
& request
, int64_t receivedSize
)
518 calcMaxBodySize(request
);
519 debugs(58, 3, HERE
<< receivedSize
<< " >? " << bodySizeMax
);
520 return bodySizeMax
>= 0 && receivedSize
> bodySizeMax
;
524 HttpReply::expectedBodyTooLarge(HttpRequest
& request
)
526 calcMaxBodySize(request
);
527 debugs(58, 7, HERE
<< "bodySizeMax=" << bodySizeMax
);
529 if (bodySizeMax
< 0) // no body size limit
532 int64_t expectedSize
= -1;
533 if (!expectingBody(request
.method
, expectedSize
))
536 debugs(58, 6, HERE
<< expectedSize
<< " >? " << bodySizeMax
);
538 if (expectedSize
< 0) // expecting body of an unknown length
541 return expectedSize
> bodySizeMax
;
545 HttpReply::calcMaxBodySize(HttpRequest
& request
) const
547 // hack: -2 is used as "we have not calculated max body size yet" state
548 if (bodySizeMax
!= -2) // already tried
552 // short-circuit ACL testing if there are none configured
553 if (!Config
.ReplyBodySize
)
556 ACLFilledChecklist
ch(NULL
, &request
, NULL
);
557 // XXX: cont-cast becomes irrelevant when checklist is HttpReply::Pointer
558 ch
.reply
= const_cast<HttpReply
*>(this);
559 HTTPMSGLOCK(ch
.reply
);
560 for (AclSizeLimit
*l
= Config
.ReplyBodySize
; l
; l
= l
-> next
) {
561 /* if there is no ACL list or if the ACLs listed match use this size value */
562 if (!l
->aclList
|| ch
.fastCheck(l
->aclList
) == ACCESS_ALLOWED
) {
563 debugs(58, 4, HERE
<< "bodySizeMax=" << bodySizeMax
);
564 bodySizeMax
= l
->size
; // may be -1
570 // XXX: check that this is sufficient for eCAP cloning
572 HttpReply::clone() const
574 HttpReply
*rep
= new HttpReply();
575 rep
->sline
= sline
; // used in hdrCacheInit() call below
576 rep
->header
.append(&header
);
578 rep
->hdr_sz
= hdr_sz
;
579 rep
->http_ver
= http_ver
;
580 rep
->pstate
= pstate
;
581 rep
->body_pipe
= body_pipe
;
583 // keep_alive is handled in hdrCacheInit()
587 bool HttpReply::inheritProperties(const HttpMsg
*aMsg
)
589 const HttpReply
*aRep
= dynamic_cast<const HttpReply
*>(aMsg
);
592 keep_alive
= aRep
->keep_alive
;
596 void HttpReply::removeStaleWarnings()
599 if (header
.getList(HDR_WARNING
, &warning
)) {
600 const String newWarning
= removeStaleWarningValues(warning
);
601 if (warning
.size() && warning
.size() == newWarning
.size())
602 return; // some warnings are there and none changed
603 header
.delById(HDR_WARNING
);
604 if (newWarning
.size()) { // some warnings left
605 HttpHeaderEntry
*const e
=
606 new HttpHeaderEntry(HDR_WARNING
, NULL
, newWarning
.termedBuf());
613 * Remove warning-values with warn-date different from Date value from
614 * a single header entry. Returns a string with all valid warning-values.
616 String
HttpReply::removeStaleWarningValues(const String
&value
)
619 const char *item
= 0;
622 while (strListGetItem(&value
, ',', &item
, &len
, &pos
)) {
624 // Does warning-value have warn-date (which contains quoted date)?
625 // We scan backwards, looking for two quoted strings.
626 // warning-value = warn-code SP warn-agent SP warn-text [SP warn-date]
627 const char *p
= item
+ len
- 1;
629 while (p
>= item
&& xisspace(*p
)) --p
; // skip whitespace
631 // warning-value MUST end with quote
632 if (p
>= item
&& *p
== '"') {
633 const char *const warnDateEnd
= p
;
635 while (p
>= item
&& *p
!= '"') --p
; // find the next quote
637 const char *warnDateBeg
= p
+ 1;
639 while (p
>= item
&& xisspace(*p
)) --p
; // skip whitespace
641 if (p
>= item
&& *p
== '"' && warnDateBeg
- p
> 2) {
644 warnDate
.append(warnDateBeg
, warnDateEnd
- warnDateBeg
);
645 const time_t time
= parse_rfc1123(warnDate
.termedBuf());
646 keep
= (time
> 0 && time
== date
); // keep valid and matching date
652 newValue
.append(", ");
653 newValue
.append(item
, len
);