2 * Copyright (C) 1996-2022 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"
28 HttpReply::HttpReply():
29 Http::Message(hoReply
),
33 surrogate_control(nullptr),
37 content_range(nullptr)
42 HttpReply::~HttpReply()
53 pstate
= Http::Message::psReadyToParseStartLine
;
57 void HttpReply::reset()
60 // reset should not reset the protocol; could have made protoPrefix a
61 // virtual function instead, but it is not clear whether virtual methods
62 // are allowed with MEMPROXY_CLASS() and whether some cbdata void*
63 // conversions are not going to kill virtual tables
64 const String pfx
= protoPrefix
;
73 // we used to assert that the pipe is NULL, but now the message only
74 // points to a pipe that is owned and initiated by another object.
81 bodySizeMax
= -2; // hack: make calculatedBodySizeMax() false
85 HttpReply::packHeadersUsingFastPacker(Packable
&p
) const
93 HttpReply::packHeadersUsingSlowPacker(Packable
&p
) const
97 packHeadersUsingFastPacker(buf
);
98 p
.append(buf
.content(), buf
.contentSize());
102 HttpReply::packInto(MemBuf
&buf
) const
104 packHeadersUsingFastPacker(buf
);
108 /* create memBuf, create mem-based packer, pack, destroy packer, return MemBuf */
110 HttpReply::pack() const
112 MemBuf
*mb
= new MemBuf
;
119 HttpReply::MakeConnectionEstablished() {
121 HttpReplyPointer
rep(new HttpReply
);
122 rep
->sline
.set(Http::ProtocolVersion(), Http::scOkay
, "Connection established");
127 HttpReply::make304() const
129 static const Http::HdrType ImsEntries
[] = {Http::HdrType::DATE
, Http::HdrType::CONTENT_TYPE
, Http::HdrType::EXPIRES
, Http::HdrType::LAST_MODIFIED
, /* eof */ Http::HdrType::OTHER
};
131 const HttpReplyPointer
rv(new HttpReply
);
135 /* rv->content_length; */
137 rv
->last_modified
= last_modified
;
138 rv
->expires
= expires
;
139 rv
->content_type
= content_type
;
140 /* rv->content_range */
142 rv
->sline
.set(Http::ProtocolVersion(), Http::scNotModified
, nullptr);
144 for (t
= 0; ImsEntries
[t
] != Http::HdrType::OTHER
; ++t
) {
145 if ((e
= header
.findEntry(ImsEntries
[t
])))
146 rv
->header
.addEntry(e
->clone());
149 rv
->putCc(cache_control
);
156 HttpReply::packed304Reply() const
158 /* Not as efficient as skipping the header duplication,
159 * but easier to maintain
161 const auto temp
= make304();
162 MemBuf
*rv
= temp
->pack();
167 HttpReply::setHeaders(Http::StatusCode status
, const char *reason
,
168 const char *ctype
, int64_t clen
, time_t lmt
, time_t expiresTime
)
171 sline
.set(Http::ProtocolVersion(), status
, reason
);
173 hdr
->putStr(Http::HdrType::SERVER
, visible_appname_string
);
174 hdr
->putStr(Http::HdrType::MIME_VERSION
, "1.0");
175 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
178 hdr
->putStr(Http::HdrType::CONTENT_TYPE
, ctype
);
179 content_type
= ctype
;
181 content_type
= String();
184 hdr
->putInt64(Http::HdrType::CONTENT_LENGTH
, clen
);
186 if (expiresTime
>= 0)
187 hdr
->putTime(Http::HdrType::EXPIRES
, expiresTime
);
189 if (lmt
> 0) /* this used to be lmt != 0 @?@ */
190 hdr
->putTime(Http::HdrType::LAST_MODIFIED
, lmt
);
192 date
= squid_curtime
;
194 content_length
= clen
;
196 expires
= expiresTime
;
202 HttpReply::redirect(Http::StatusCode status
, const char *loc
)
205 sline
.set(Http::ProtocolVersion(), status
, nullptr);
207 hdr
->putStr(Http::HdrType::SERVER
, APP_FULLNAME
);
208 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
209 hdr
->putInt64(Http::HdrType::CONTENT_LENGTH
, 0);
210 hdr
->putStr(Http::HdrType::LOCATION
, loc
);
211 date
= squid_curtime
;
215 /* compare the validators of two replies.
217 * 0 = they do not match
220 HttpReply::validatorsMatch(HttpReply
const * otherRep
) const
224 /* Numbers first - easiest to check */
226 /* TODO: remove -1 bypass */
228 if (content_length
!= otherRep
->content_length
229 && content_length
> -1 &&
230 otherRep
->content_length
> -1)
234 one
= header
.getStrOrList(Http::HdrType::ETAG
);
236 two
= otherRep
->header
.getStrOrList(Http::HdrType::ETAG
);
238 if (one
.size()==0 || two
.size()==0 || one
.caseCmp(two
)!=0 ) {
244 if (last_modified
!= otherRep
->last_modified
)
248 one
= header
.getStrOrList(Http::HdrType::CONTENT_MD5
);
250 two
= otherRep
->header
.getStrOrList(Http::HdrType::CONTENT_MD5
);
252 if (one
.size()==0 || two
.size()==0 || one
.caseCmp(two
)!=0 ) {
262 HttpReply::recreateOnNotModified(const HttpReply
&reply304
) const
264 // If enough 304s do not update, then this expensive checking is cheaper
265 // than blindly storing reply prefix identical to the already stored one.
266 if (!header
.needUpdate(&reply304
.header
))
269 const Pointer cloned
= clone();
270 cloned
->header
.update(&reply304
.header
);
271 cloned
->hdrCacheClean();
272 cloned
->header
.compact();
273 cloned
->hdrCacheInit();
277 /* internal routines */
280 HttpReply::hdrExpirationTime()
282 /* The s-maxage and max-age directive takes priority over Expires */
287 * Conservatively handle the case when we have a max-age
288 * header, but no Date for reference?
290 if (cache_control
->hasSMaxAge(&maxAge
) || cache_control
->hasMaxAge(&maxAge
))
291 return (date
>= 0) ? date
+ maxAge
: squid_curtime
;
294 if (Config
.onoff
.vary_ignore_expire
&&
295 header
.has(Http::HdrType::VARY
)) {
296 const time_t d
= header
.getTime(Http::HdrType::DATE
);
297 const time_t e
= header
.getTime(Http::HdrType::EXPIRES
);
303 if (header
.has(Http::HdrType::EXPIRES
)) {
304 const time_t e
= header
.getTime(Http::HdrType::EXPIRES
);
306 * HTTP/1.0 says that robust implementations should consider
307 * bad or malformed Expires header as equivalent to "expires
310 return e
< 0 ? squid_curtime
: e
;
316 /* sync this routine when you update HttpReply struct */
318 HttpReply::hdrCacheInit()
320 Http::Message::hdrCacheInit();
322 http_ver
= sline
.version
;
323 content_length
= header
.getInt64(Http::HdrType::CONTENT_LENGTH
);
324 date
= header
.getTime(Http::HdrType::DATE
);
325 last_modified
= header
.getTime(Http::HdrType::LAST_MODIFIED
);
326 surrogate_control
= header
.getSc();
327 content_range
= (sline
.status() == Http::scPartialContent
) ?
328 header
.getContRange() : nullptr;
329 keep_alive
= persistent() ? 1 : 0;
330 const char *str
= header
.getStr(Http::HdrType::CONTENT_TYPE
);
333 content_type
.assign(str
, strcspn(str
, ";\t "));
335 content_type
= String();
337 /* be sure to set expires after date and cache-control */
338 expires
= hdrExpirationTime();
341 const HttpHdrContRange
*
342 HttpReply::contentRange() const
344 assert(!content_range
|| sline
.status() == Http::scPartialContent
);
345 return content_range
;
348 /* sync this routine when you update HttpReply struct */
350 HttpReply::hdrCacheClean()
352 content_type
.clean();
355 delete cache_control
;
356 cache_control
= nullptr;
359 if (surrogate_control
) {
360 delete surrogate_control
;
361 surrogate_control
= nullptr;
365 delete content_range
;
366 content_range
= nullptr;
371 * Returns the body size of a HTTP response
374 HttpReply::bodySize(const HttpRequestMethod
& method
) const
376 if (sline
.version
.major
< 1)
378 else if (method
.id() == Http::METHOD_HEAD
)
380 else if (sline
.status() == Http::scOkay
)
381 (void) 0; /* common case, continue */
382 else if (sline
.status() == Http::scNoContent
)
384 else if (sline
.status() == Http::scNotModified
)
386 else if (sline
.status() < Http::scOkay
)
389 return content_length
;
393 * Checks the first line of an HTTP Reply is valid.
394 * currently only checks "HTTP/" exists.
396 * NP: not all error cases are detected yet. Some are left for detection later in parse.
399 HttpReply::sanityCheckStartLine(const char *buf
, const size_t hdr_len
, Http::StatusCode
*error
)
401 // hack warning: using psize instead of size here due to type mismatches with MemBuf.
403 // content is long enough to possibly hold a reply
404 // 4 being magic size of a 3-digit number plus space delimiter
405 if (hdr_len
< (size_t)(protoPrefix
.psize() + 4)) {
407 debugs(58, 3, "Too small reply header (" << hdr_len
<< " bytes)");
408 *error
= Http::scInvalidHeader
;
414 // catch missing or mismatched protocol identifier
415 // allow special-case for ICY protocol (non-HTTP identifier) in response to faked HTTP request.
416 if (strncmp(buf
, "ICY", 3) == 0) {
418 pos
= protoPrefix
.psize();
421 if (protoPrefix
.cmp(buf
, protoPrefix
.size()) != 0) {
422 debugs(58, 3, "missing protocol prefix (" << protoPrefix
<< ") in '" << buf
<< "'");
423 *error
= Http::scInvalidHeader
;
427 // catch missing or negative status value (negative '-' is not a digit)
428 pos
= protoPrefix
.psize();
430 // skip arbitrary number of digits and a dot in the version portion
431 while ((size_t)pos
<= hdr_len
&& (*(buf
+pos
) == '.' || xisdigit(*(buf
+pos
)) ) ) ++pos
;
433 // catch missing version info
434 if (pos
== protoPrefix
.psize()) {
435 debugs(58, 3, "missing protocol version numbers (ie. " << protoPrefix
<< "/1.0) in '" << buf
<< "'");
436 *error
= Http::scInvalidHeader
;
441 // skip arbitrary number of spaces...
442 while ((size_t)pos
<= hdr_len
&& (char)*(buf
+pos
) == ' ') ++pos
;
444 if ((size_t)pos
< hdr_len
&& !xisdigit(*(buf
+pos
))) {
445 debugs(58, 3, "missing or invalid status number in '" << buf
<< "'");
446 *error
= Http::scInvalidHeader
;
454 HttpReply::parseFirstLine(const char *blk_start
, const char *blk_end
)
456 return sline
.parse(protoPrefix
, blk_start
, blk_end
);
460 HttpReply::configureContentLengthInterpreter(Http::ContentLengthInterpreter
&interpreter
)
462 interpreter
.applyStatusCodeRules(sline
.status());
466 HttpReply::parseHeader(Http1::Parser
&hp
)
468 Http::ContentLengthInterpreter clen
;
469 return Message::parseHeader(hp
, clen
);
472 /* handy: resets and returns -1 */
474 HttpReply::httpMsgParseError()
476 int result(Http::Message::httpMsgParseError());
477 /* indicate an error in the status line */
478 sline
.set(Http::ProtocolVersion(), Http::scInvalidHeader
);
483 * Indicate whether or not we would usually expect an entity-body
484 * along with this response
487 HttpReply::expectingBody(const HttpRequestMethod
& req_method
, int64_t& theSize
) const
489 bool expectBody
= true;
491 if (req_method
== Http::METHOD_HEAD
)
493 else if (sline
.status() == Http::scNoContent
)
495 else if (sline
.status() == Http::scNotModified
)
497 // TODO: Consider assuming that gray-area 0xx responses have bodies, like 9xx responses.
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, receivedSize
<< " >? " << bodySizeMax
);
520 return bodySizeMax
>= 0 && receivedSize
> bodySizeMax
;
524 HttpReply::expectedBodyTooLarge(HttpRequest
& request
)
526 calcMaxBodySize(request
);
527 debugs(58, 7, "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, 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(nullptr, &request
, nullptr);
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
).allowed()) {
563 debugs(58, 4, "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()
588 HttpReply::inheritProperties(const Http::Message
*aMsg
)
590 const HttpReply
*aRep
= dynamic_cast<const HttpReply
*>(aMsg
);
593 keep_alive
= aRep
->keep_alive
;
594 sources
= aRep
->sources
;
598 void HttpReply::removeStaleWarnings()
601 if (header
.getList(Http::HdrType::WARNING
, &warning
)) {
602 const String newWarning
= removeStaleWarningValues(warning
);
603 if (warning
.size() && warning
.size() == newWarning
.size())
604 return; // some warnings are there and none changed
605 header
.delById(Http::HdrType::WARNING
);
606 if (newWarning
.size()) { // some warnings left
607 HttpHeaderEntry
*const e
=
608 new HttpHeaderEntry(Http::HdrType::WARNING
, SBuf(), newWarning
.termedBuf());
615 * Remove warning-values with warn-date different from Date value from
616 * a single header entry. Returns a string with all valid warning-values.
618 String
HttpReply::removeStaleWarningValues(const String
&value
)
621 const char *item
= nullptr;
623 const char *pos
= nullptr;
624 while (strListGetItem(&value
, ',', &item
, &len
, &pos
)) {
626 // Does warning-value have warn-date (which contains quoted date)?
627 // We scan backwards, looking for two quoted strings.
628 // warning-value = warn-code SP warn-agent SP warn-text [SP warn-date]
629 const char *p
= item
+ len
- 1;
631 while (p
>= item
&& xisspace(*p
)) --p
; // skip whitespace
633 // warning-value MUST end with quote
634 if (p
>= item
&& *p
== '"') {
635 const char *const warnDateEnd
= p
;
637 while (p
>= item
&& *p
!= '"') --p
; // find the next quote
639 const char *warnDateBeg
= p
+ 1;
641 while (p
>= item
&& xisspace(*p
)) --p
; // skip whitespace
643 if (p
>= item
&& *p
== '"' && warnDateBeg
- p
> 2) {
646 warnDate
.append(warnDateBeg
, warnDateEnd
- warnDateBeg
);
647 const time_t time
= Time::ParseRfc1123(warnDate
.termedBuf());
648 keep
= (time
> 0 && time
== date
); // keep valid and matching date
654 newValue
.append(", ");
655 newValue
.append(item
, len
);
663 HttpReply::olderThan(const HttpReply
*them
) const
665 if (!them
|| !them
->date
|| !date
)
667 return date
< them
->date
;
671 HttpReply::removeIrrelevantContentLength() {
672 if (Http::ProhibitsContentLength(sline
.status()))
673 if (header
.delById(Http::HdrType::CONTENT_LENGTH
))
674 debugs(58, 3, "Removing unexpected Content-Length header");