2 * Copyright (C) 1996-2020 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"
16 #include "http/ContentLengthInterpreter.h"
18 #include "HttpHdrCc.h"
19 #include "HttpHdrContRange.h"
20 #include "HttpHdrSc.h"
21 #include "HttpReply.h"
22 #include "HttpRequest.h"
24 #include "SquidConfig.h"
25 #include "SquidTime.h"
29 HttpReply::HttpReply():
30 Http::Message(hoReply
),
34 surrogate_control(nullptr),
38 content_range(nullptr)
43 HttpReply::~HttpReply()
54 pstate
= Http::Message::psReadyToParseStartLine
;
58 void HttpReply::reset()
61 // reset should not reset the protocol; could have made protoPrefix a
62 // virtual function instead, but it is not clear whether virtual methods
63 // are allowed with MEMPROXY_CLASS() and whether some cbdata void*
64 // conversions are not going to kill virtual tables
65 const String pfx
= protoPrefix
;
74 // we used to assert that the pipe is NULL, but now the message only
75 // points to a pipe that is owned and initiated by another object.
82 bodySizeMax
= -2; // hack: make calculatedBodySizeMax() false
86 HttpReply::packHeadersUsingFastPacker(Packable
&p
) const
94 HttpReply::packHeadersUsingSlowPacker(Packable
&p
) const
98 packHeadersUsingFastPacker(buf
);
99 p
.append(buf
.content(), buf
.contentSize());
103 HttpReply::packInto(MemBuf
&buf
) const
105 packHeadersUsingFastPacker(buf
);
109 /* create memBuf, create mem-based packer, pack, destroy packer, return MemBuf */
111 HttpReply::pack() const
113 MemBuf
*mb
= new MemBuf
;
120 HttpReply::MakeConnectionEstablished() {
122 HttpReplyPointer
rep(new HttpReply
);
123 rep
->sline
.set(Http::ProtocolVersion(), Http::scOkay
, "Connection established");
128 HttpReply::make304() const
130 static const Http::HdrType ImsEntries
[] = {Http::HdrType::DATE
, Http::HdrType::CONTENT_TYPE
, Http::HdrType::EXPIRES
, Http::HdrType::LAST_MODIFIED
, /* eof */ Http::HdrType::OTHER
};
132 const HttpReplyPointer
rv(new HttpReply
);
136 /* rv->content_length; */
138 rv
->last_modified
= last_modified
;
139 rv
->expires
= expires
;
140 rv
->content_type
= content_type
;
141 /* rv->content_range */
143 rv
->sline
.set(Http::ProtocolVersion(), Http::scNotModified
, NULL
);
145 for (t
= 0; ImsEntries
[t
] != Http::HdrType::OTHER
; ++t
) {
146 if ((e
= header
.findEntry(ImsEntries
[t
])))
147 rv
->header
.addEntry(e
->clone());
150 rv
->putCc(cache_control
);
157 HttpReply::packed304Reply() const
159 /* Not as efficient as skipping the header duplication,
160 * but easier to maintain
162 const auto temp
= make304();
163 MemBuf
*rv
= temp
->pack();
168 HttpReply::setHeaders(Http::StatusCode status
, const char *reason
,
169 const char *ctype
, int64_t clen
, time_t lmt
, time_t expiresTime
)
172 sline
.set(Http::ProtocolVersion(), status
, reason
);
174 hdr
->putStr(Http::HdrType::SERVER
, visible_appname_string
);
175 hdr
->putStr(Http::HdrType::MIME_VERSION
, "1.0");
176 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
179 hdr
->putStr(Http::HdrType::CONTENT_TYPE
, ctype
);
180 content_type
= ctype
;
182 content_type
= String();
185 hdr
->putInt64(Http::HdrType::CONTENT_LENGTH
, clen
);
187 if (expiresTime
>= 0)
188 hdr
->putTime(Http::HdrType::EXPIRES
, expiresTime
);
190 if (lmt
> 0) /* this used to be lmt != 0 @?@ */
191 hdr
->putTime(Http::HdrType::LAST_MODIFIED
, lmt
);
193 date
= squid_curtime
;
195 content_length
= clen
;
197 expires
= expiresTime
;
203 HttpReply::redirect(Http::StatusCode status
, const char *loc
)
206 sline
.set(Http::ProtocolVersion(), status
, NULL
);
208 hdr
->putStr(Http::HdrType::SERVER
, APP_FULLNAME
);
209 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
210 hdr
->putInt64(Http::HdrType::CONTENT_LENGTH
, 0);
211 hdr
->putStr(Http::HdrType::LOCATION
, loc
);
212 date
= squid_curtime
;
216 /* compare the validators of two replies.
218 * 0 = they do not match
221 HttpReply::validatorsMatch(HttpReply
const * otherRep
) const
225 /* Numbers first - easiest to check */
227 /* TODO: remove -1 bypass */
229 if (content_length
!= otherRep
->content_length
230 && content_length
> -1 &&
231 otherRep
->content_length
> -1)
235 one
= header
.getStrOrList(Http::HdrType::ETAG
);
237 two
= otherRep
->header
.getStrOrList(Http::HdrType::ETAG
);
239 if (one
.size()==0 || two
.size()==0 || one
.caseCmp(two
)!=0 ) {
245 if (last_modified
!= otherRep
->last_modified
)
249 one
= header
.getStrOrList(Http::HdrType::CONTENT_MD5
);
251 two
= otherRep
->header
.getStrOrList(Http::HdrType::CONTENT_MD5
);
253 if (one
.size()==0 || two
.size()==0 || one
.caseCmp(two
)!=0 ) {
263 HttpReply::recreateOnNotModified(const HttpReply
&reply304
) const
265 // If enough 304s do not update, then this expensive checking is cheaper
266 // than blindly storing reply prefix identical to the already stored one.
267 if (!header
.needUpdate(&reply304
.header
))
270 const Pointer cloned
= clone();
271 cloned
->header
.update(&reply304
.header
);
272 cloned
->hdrCacheClean();
273 cloned
->header
.compact();
274 cloned
->hdrCacheInit();
278 /* internal routines */
281 HttpReply::hdrExpirationTime()
283 /* The s-maxage and max-age directive takes priority over Expires */
288 * Conservatively handle the case when we have a max-age
289 * header, but no Date for reference?
291 if (cache_control
->hasSMaxAge(&maxAge
) || cache_control
->hasMaxAge(&maxAge
))
292 return (date
>= 0) ? date
+ maxAge
: squid_curtime
;
295 if (Config
.onoff
.vary_ignore_expire
&&
296 header
.has(Http::HdrType::VARY
)) {
297 const time_t d
= header
.getTime(Http::HdrType::DATE
);
298 const time_t e
= header
.getTime(Http::HdrType::EXPIRES
);
304 if (header
.has(Http::HdrType::EXPIRES
)) {
305 const time_t e
= header
.getTime(Http::HdrType::EXPIRES
);
307 * HTTP/1.0 says that robust implementations should consider
308 * bad or malformed Expires header as equivalent to "expires
311 return e
< 0 ? squid_curtime
: e
;
317 /* sync this routine when you update HttpReply struct */
319 HttpReply::hdrCacheInit()
321 Http::Message::hdrCacheInit();
323 http_ver
= sline
.version
;
324 content_length
= header
.getInt64(Http::HdrType::CONTENT_LENGTH
);
325 date
= header
.getTime(Http::HdrType::DATE
);
326 last_modified
= header
.getTime(Http::HdrType::LAST_MODIFIED
);
327 surrogate_control
= header
.getSc();
328 content_range
= (sline
.status() == Http::scPartialContent
) ?
329 header
.getContRange() : nullptr;
330 keep_alive
= persistent() ? 1 : 0;
331 const char *str
= header
.getStr(Http::HdrType::CONTENT_TYPE
);
334 content_type
.assign(str
, strcspn(str
, ";\t "));
336 content_type
= String();
338 /* be sure to set expires after date and cache-control */
339 expires
= hdrExpirationTime();
342 const HttpHdrContRange
*
343 HttpReply::contentRange() const
345 assert(!content_range
|| sline
.status() == Http::scPartialContent
);
346 return content_range
;
349 /* sync this routine when you update HttpReply struct */
351 HttpReply::hdrCacheClean()
353 content_type
.clean();
356 delete cache_control
;
357 cache_control
= NULL
;
360 if (surrogate_control
) {
361 delete surrogate_control
;
362 surrogate_control
= NULL
;
366 delete content_range
;
367 content_range
= NULL
;
372 * Returns the body size of a HTTP response
375 HttpReply::bodySize(const HttpRequestMethod
& method
) const
377 if (sline
.version
.major
< 1)
379 else if (method
.id() == Http::METHOD_HEAD
)
381 else if (sline
.status() == Http::scOkay
)
382 (void) 0; /* common case, continue */
383 else if (sline
.status() == Http::scNoContent
)
385 else if (sline
.status() == Http::scNotModified
)
387 else if (sline
.status() < Http::scOkay
)
390 return content_length
;
394 * Checks the first line of an HTTP Reply is valid.
395 * currently only checks "HTTP/" exists.
397 * NP: not all error cases are detected yet. Some are left for detection later in parse.
400 HttpReply::sanityCheckStartLine(const char *buf
, const size_t hdr_len
, Http::StatusCode
*error
)
402 // hack warning: using psize instead of size here due to type mismatches with MemBuf.
404 // content is long enough to possibly hold a reply
405 // 4 being magic size of a 3-digit number plus space delimiter
406 if (hdr_len
< (size_t)(protoPrefix
.psize() + 4)) {
408 debugs(58, 3, "Too small reply header (" << hdr_len
<< " bytes)");
409 *error
= Http::scInvalidHeader
;
415 // catch missing or mismatched protocol identifier
416 // allow special-case for ICY protocol (non-HTTP identifier) in response to faked HTTP request.
417 if (strncmp(buf
, "ICY", 3) == 0) {
419 pos
= protoPrefix
.psize();
422 if (protoPrefix
.cmp(buf
, protoPrefix
.size()) != 0) {
423 debugs(58, 3, "missing protocol prefix (" << protoPrefix
<< ") in '" << buf
<< "'");
424 *error
= Http::scInvalidHeader
;
428 // catch missing or negative status value (negative '-' is not a digit)
429 pos
= protoPrefix
.psize();
431 // skip arbitrary number of digits and a dot in the verion portion
432 while ((size_t)pos
<= hdr_len
&& (*(buf
+pos
) == '.' || xisdigit(*(buf
+pos
)) ) ) ++pos
;
434 // catch missing version info
435 if (pos
== protoPrefix
.psize()) {
436 debugs(58, 3, "missing protocol version numbers (ie. " << protoPrefix
<< "/1.0) in '" << buf
<< "'");
437 *error
= Http::scInvalidHeader
;
442 // skip arbitrary number of spaces...
443 while ((size_t)pos
<= hdr_len
&& (char)*(buf
+pos
) == ' ') ++pos
;
445 if ((size_t)pos
< hdr_len
&& !xisdigit(*(buf
+pos
))) {
446 debugs(58, 3, "missing or invalid status number in '" << buf
<< "'");
447 *error
= Http::scInvalidHeader
;
455 HttpReply::parseFirstLine(const char *blk_start
, const char *blk_end
)
457 return sline
.parse(protoPrefix
, blk_start
, blk_end
);
461 HttpReply::configureContentLengthInterpreter(Http::ContentLengthInterpreter
&interpreter
)
463 interpreter
.applyStatusCodeRules(sline
.status());
467 HttpReply::parseHeader(Http1::Parser
&hp
)
469 Http::ContentLengthInterpreter clen
;
470 return Message::parseHeader(hp
, clen
);
473 /* handy: resets and returns -1 */
475 HttpReply::httpMsgParseError()
477 int result(Http::Message::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 // TODO: Consider assuming that gray-area 0xx responses have bodies, like 9xx responses.
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
).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()
589 HttpReply::inheritProperties(const Http::Message
*aMsg
)
591 const HttpReply
*aRep
= dynamic_cast<const HttpReply
*>(aMsg
);
594 keep_alive
= aRep
->keep_alive
;
595 sources
= aRep
->sources
;
599 void HttpReply::removeStaleWarnings()
602 if (header
.getList(Http::HdrType::WARNING
, &warning
)) {
603 const String newWarning
= removeStaleWarningValues(warning
);
604 if (warning
.size() && warning
.size() == newWarning
.size())
605 return; // some warnings are there and none changed
606 header
.delById(Http::HdrType::WARNING
);
607 if (newWarning
.size()) { // some warnings left
608 HttpHeaderEntry
*const e
=
609 new HttpHeaderEntry(Http::HdrType::WARNING
, SBuf(), newWarning
.termedBuf());
616 * Remove warning-values with warn-date different from Date value from
617 * a single header entry. Returns a string with all valid warning-values.
619 String
HttpReply::removeStaleWarningValues(const String
&value
)
622 const char *item
= 0;
625 while (strListGetItem(&value
, ',', &item
, &len
, &pos
)) {
627 // Does warning-value have warn-date (which contains quoted date)?
628 // We scan backwards, looking for two quoted strings.
629 // warning-value = warn-code SP warn-agent SP warn-text [SP warn-date]
630 const char *p
= item
+ len
- 1;
632 while (p
>= item
&& xisspace(*p
)) --p
; // skip whitespace
634 // warning-value MUST end with quote
635 if (p
>= item
&& *p
== '"') {
636 const char *const warnDateEnd
= p
;
638 while (p
>= item
&& *p
!= '"') --p
; // find the next quote
640 const char *warnDateBeg
= p
+ 1;
642 while (p
>= item
&& xisspace(*p
)) --p
; // skip whitespace
644 if (p
>= item
&& *p
== '"' && warnDateBeg
- p
> 2) {
647 warnDate
.append(warnDateBeg
, warnDateEnd
- warnDateBeg
);
648 const time_t time
= parse_rfc1123(warnDate
.termedBuf());
649 keep
= (time
> 0 && time
== date
); // keep valid and matching date
655 newValue
.append(", ");
656 newValue
.append(item
, len
);
664 HttpReply::olderThan(const HttpReply
*them
) const
666 if (!them
|| !them
->date
|| !date
)
668 return date
< them
->date
;
672 HttpReply::removeIrrelevantContentLength() {
673 if (Http::ProhibitsContentLength(sline
.status()))
674 if (header
.delById(Http::HdrType::CONTENT_LENGTH
))
675 debugs(58, 3, "Removing unexpected Content-Length header");