]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/HttpReply.cc
2 * Copyright (C) 1996-2018 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"
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::packHeadersInto(Packable
* p
) const
93 HttpReply::packInto(Packable
* p
) const
99 /* create memBuf, create mem-based packer, pack, destroy packer, return MemBuf */
101 HttpReply::pack() const
103 MemBuf
*mb
= new MemBuf
;
110 HttpReply::make304() const
112 static const Http::HdrType ImsEntries
[] = {Http::HdrType::DATE
, Http::HdrType::CONTENT_TYPE
, Http::HdrType::EXPIRES
, Http::HdrType::LAST_MODIFIED
, /* eof */ Http::HdrType::OTHER
};
114 HttpReply
*rv
= new HttpReply
;
118 /* rv->content_length; */
120 rv
->last_modified
= last_modified
;
121 rv
->expires
= expires
;
122 rv
->content_type
= content_type
;
123 /* rv->content_range */
125 rv
->sline
.set(Http::ProtocolVersion(), Http::scNotModified
, NULL
);
127 for (t
= 0; ImsEntries
[t
] != Http::HdrType::OTHER
; ++t
) {
128 if ((e
= header
.findEntry(ImsEntries
[t
])))
129 rv
->header
.addEntry(e
->clone());
132 rv
->putCc(cache_control
);
139 HttpReply::packed304Reply() const
141 /* Not as efficient as skipping the header duplication,
142 * but easier to maintain
144 HttpReply
*temp
= make304();
145 MemBuf
*rv
= temp
->pack();
151 HttpReply::setHeaders(Http::StatusCode status
, const char *reason
,
152 const char *ctype
, int64_t clen
, time_t lmt
, time_t expiresTime
)
155 sline
.set(Http::ProtocolVersion(), status
, reason
);
157 hdr
->putStr(Http::HdrType::SERVER
, visible_appname_string
);
158 hdr
->putStr(Http::HdrType::MIME_VERSION
, "1.0");
159 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
162 hdr
->putStr(Http::HdrType::CONTENT_TYPE
, ctype
);
163 content_type
= ctype
;
165 content_type
= String();
168 hdr
->putInt64(Http::HdrType::CONTENT_LENGTH
, clen
);
170 if (expiresTime
>= 0)
171 hdr
->putTime(Http::HdrType::EXPIRES
, expiresTime
);
173 if (lmt
> 0) /* this used to be lmt != 0 @?@ */
174 hdr
->putTime(Http::HdrType::LAST_MODIFIED
, lmt
);
176 date
= squid_curtime
;
178 content_length
= clen
;
180 expires
= expiresTime
;
186 HttpReply::redirect(Http::StatusCode status
, const char *loc
)
189 sline
.set(Http::ProtocolVersion(), status
, NULL
);
191 hdr
->putStr(Http::HdrType::SERVER
, APP_FULLNAME
);
192 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
193 hdr
->putInt64(Http::HdrType::CONTENT_LENGTH
, 0);
194 hdr
->putStr(Http::HdrType::LOCATION
, loc
);
195 date
= squid_curtime
;
199 /* compare the validators of two replies.
201 * 0 = they do not match
204 HttpReply::validatorsMatch(HttpReply
const * otherRep
) const
208 /* Numbers first - easiest to check */
210 /* TODO: remove -1 bypass */
212 if (content_length
!= otherRep
->content_length
213 && content_length
> -1 &&
214 otherRep
->content_length
> -1)
218 one
= header
.getStrOrList(Http::HdrType::ETAG
);
220 two
= otherRep
->header
.getStrOrList(Http::HdrType::ETAG
);
222 if (one
.size()==0 || two
.size()==0 || one
.caseCmp(two
)!=0 ) {
228 if (last_modified
!= otherRep
->last_modified
)
232 one
= header
.getStrOrList(Http::HdrType::CONTENT_MD5
);
234 two
= otherRep
->header
.getStrOrList(Http::HdrType::CONTENT_MD5
);
236 if (one
.size()==0 || two
.size()==0 || one
.caseCmp(two
)!=0 ) {
246 HttpReply::updateOnNotModified(HttpReply
const * freshRep
)
250 /* update raw headers */
251 if (!header
.update(&freshRep
->header
))
264 /* internal routines */
267 HttpReply::hdrExpirationTime()
269 /* The s-maxage and max-age directive takes priority over Expires */
274 * Conservatively handle the case when we have a max-age
275 * header, but no Date for reference?
277 if (cache_control
->hasSMaxAge(&maxAge
) || cache_control
->hasMaxAge(&maxAge
))
278 return (date
>= 0) ? date
+ maxAge
: squid_curtime
;
281 if (Config
.onoff
.vary_ignore_expire
&&
282 header
.has(Http::HdrType::VARY
)) {
283 const time_t d
= header
.getTime(Http::HdrType::DATE
);
284 const time_t e
= header
.getTime(Http::HdrType::EXPIRES
);
290 if (header
.has(Http::HdrType::EXPIRES
)) {
291 const time_t e
= header
.getTime(Http::HdrType::EXPIRES
);
293 * HTTP/1.0 says that robust implementations should consider
294 * bad or malformed Expires header as equivalent to "expires
297 return e
< 0 ? squid_curtime
: e
;
303 /* sync this routine when you update HttpReply struct */
305 HttpReply::hdrCacheInit()
307 Http::Message::hdrCacheInit();
309 http_ver
= sline
.version
;
310 content_length
= header
.getInt64(Http::HdrType::CONTENT_LENGTH
);
311 date
= header
.getTime(Http::HdrType::DATE
);
312 last_modified
= header
.getTime(Http::HdrType::LAST_MODIFIED
);
313 surrogate_control
= header
.getSc();
314 content_range
= (sline
.status() == Http::scPartialContent
) ?
315 header
.getContRange() : nullptr;
316 keep_alive
= persistent() ? 1 : 0;
317 const char *str
= header
.getStr(Http::HdrType::CONTENT_TYPE
);
320 content_type
.limitInit(str
, strcspn(str
, ";\t "));
322 content_type
= String();
324 /* be sure to set expires after date and cache-control */
325 expires
= hdrExpirationTime();
328 const HttpHdrContRange
*
329 HttpReply::contentRange() const
331 assert(!content_range
|| sline
.status() == Http::scPartialContent
);
332 return content_range
;
335 /* sync this routine when you update HttpReply struct */
337 HttpReply::hdrCacheClean()
339 content_type
.clean();
342 delete cache_control
;
343 cache_control
= NULL
;
346 if (surrogate_control
) {
347 delete surrogate_control
;
348 surrogate_control
= NULL
;
352 delete content_range
;
353 content_range
= NULL
;
358 * Returns the body size of a HTTP response
361 HttpReply::bodySize(const HttpRequestMethod
& method
) const
363 if (sline
.version
.major
< 1)
365 else if (method
.id() == Http::METHOD_HEAD
)
367 else if (sline
.status() == Http::scOkay
)
368 (void) 0; /* common case, continue */
369 else if (sline
.status() == Http::scNoContent
)
371 else if (sline
.status() == Http::scNotModified
)
373 else if (sline
.status() < Http::scOkay
)
376 return content_length
;
380 * Checks the first line of an HTTP Reply is valid.
381 * currently only checks "HTTP/" exists.
383 * NP: not all error cases are detected yet. Some are left for detection later in parse.
386 HttpReply::sanityCheckStartLine(const char *buf
, const size_t hdr_len
, Http::StatusCode
*error
)
388 // hack warning: using psize instead of size here due to type mismatches with MemBuf.
390 // content is long enough to possibly hold a reply
391 // 4 being magic size of a 3-digit number plus space delimiter
392 if (hdr_len
< (size_t)(protoPrefix
.psize() + 4)) {
394 debugs(58, 3, "Too small reply header (" << hdr_len
<< " bytes)");
395 *error
= Http::scInvalidHeader
;
401 // catch missing or mismatched protocol identifier
402 // allow special-case for ICY protocol (non-HTTP identifier) in response to faked HTTP request.
403 if (strncmp(buf
, "ICY", 3) == 0) {
405 pos
= protoPrefix
.psize();
408 if (protoPrefix
.cmp(buf
, protoPrefix
.size()) != 0) {
409 debugs(58, 3, "missing protocol prefix (" << protoPrefix
<< ") in '" << buf
<< "'");
410 *error
= Http::scInvalidHeader
;
414 // catch missing or negative status value (negative '-' is not a digit)
415 pos
= protoPrefix
.psize();
417 // skip arbitrary number of digits and a dot in the verion portion
418 while ((size_t)pos
<= hdr_len
&& (*(buf
+pos
) == '.' || xisdigit(*(buf
+pos
)) ) ) ++pos
;
420 // catch missing version info
421 if (pos
== protoPrefix
.psize()) {
422 debugs(58, 3, "missing protocol version numbers (ie. " << protoPrefix
<< "/1.0) in '" << buf
<< "'");
423 *error
= Http::scInvalidHeader
;
428 // skip arbitrary number of spaces...
429 while ((size_t)pos
<= hdr_len
&& (char)*(buf
+pos
) == ' ') ++pos
;
431 if ((size_t)pos
< hdr_len
&& !xisdigit(*(buf
+pos
))) {
432 debugs(58, 3, "missing or invalid status number in '" << buf
<< "'");
433 *error
= Http::scInvalidHeader
;
441 HttpReply::parseFirstLine(const char *blk_start
, const char *blk_end
)
443 return sline
.parse(protoPrefix
, blk_start
, blk_end
);
446 /* handy: resets and returns -1 */
448 HttpReply::httpMsgParseError()
450 int result(Http::Message::httpMsgParseError());
451 /* indicate an error in the status line */
452 sline
.set(Http::ProtocolVersion(), Http::scInvalidHeader
);
457 * Indicate whether or not we would usually expect an entity-body
458 * along with this response
461 HttpReply::expectingBody(const HttpRequestMethod
& req_method
, int64_t& theSize
) const
463 bool expectBody
= true;
465 if (req_method
== Http::METHOD_HEAD
)
467 else if (sline
.status() == Http::scNoContent
)
469 else if (sline
.status() == Http::scNotModified
)
471 else if (sline
.status() < Http::scOkay
)
477 if (header
.chunked())
479 else if (content_length
>= 0)
480 theSize
= content_length
;
489 HttpReply::receivedBodyTooLarge(HttpRequest
& request
, int64_t receivedSize
)
491 calcMaxBodySize(request
);
492 debugs(58, 3, HERE
<< receivedSize
<< " >? " << bodySizeMax
);
493 return bodySizeMax
>= 0 && receivedSize
> bodySizeMax
;
497 HttpReply::expectedBodyTooLarge(HttpRequest
& request
)
499 calcMaxBodySize(request
);
500 debugs(58, 7, HERE
<< "bodySizeMax=" << bodySizeMax
);
502 if (bodySizeMax
< 0) // no body size limit
505 int64_t expectedSize
= -1;
506 if (!expectingBody(request
.method
, expectedSize
))
509 debugs(58, 6, HERE
<< expectedSize
<< " >? " << bodySizeMax
);
511 if (expectedSize
< 0) // expecting body of an unknown length
514 return expectedSize
> bodySizeMax
;
518 HttpReply::calcMaxBodySize(HttpRequest
& request
) const
520 // hack: -2 is used as "we have not calculated max body size yet" state
521 if (bodySizeMax
!= -2) // already tried
525 // short-circuit ACL testing if there are none configured
526 if (!Config
.ReplyBodySize
)
529 ACLFilledChecklist
ch(NULL
, &request
, NULL
);
530 // XXX: cont-cast becomes irrelevant when checklist is HttpReply::Pointer
531 ch
.reply
= const_cast<HttpReply
*>(this);
532 HTTPMSGLOCK(ch
.reply
);
533 for (AclSizeLimit
*l
= Config
.ReplyBodySize
; l
; l
= l
-> next
) {
534 /* if there is no ACL list or if the ACLs listed match use this size value */
535 if (!l
->aclList
|| ch
.fastCheck(l
->aclList
).allowed()) {
536 debugs(58, 4, HERE
<< "bodySizeMax=" << bodySizeMax
);
537 bodySizeMax
= l
->size
; // may be -1
543 // XXX: check that this is sufficient for eCAP cloning
545 HttpReply::clone() const
547 HttpReply
*rep
= new HttpReply();
548 rep
->sline
= sline
; // used in hdrCacheInit() call below
549 rep
->header
.append(&header
);
551 rep
->hdr_sz
= hdr_sz
;
552 rep
->http_ver
= http_ver
;
553 rep
->pstate
= pstate
;
554 rep
->body_pipe
= body_pipe
;
556 // keep_alive is handled in hdrCacheInit()
561 HttpReply::inheritProperties(const Http::Message
*aMsg
)
563 const HttpReply
*aRep
= dynamic_cast<const HttpReply
*>(aMsg
);
566 keep_alive
= aRep
->keep_alive
;
567 sources
= aRep
->sources
;
571 void HttpReply::removeStaleWarnings()
574 if (header
.getList(Http::HdrType::WARNING
, &warning
)) {
575 const String newWarning
= removeStaleWarningValues(warning
);
576 if (warning
.size() && warning
.size() == newWarning
.size())
577 return; // some warnings are there and none changed
578 header
.delById(Http::HdrType::WARNING
);
579 if (newWarning
.size()) { // some warnings left
580 HttpHeaderEntry
*const e
=
581 new HttpHeaderEntry(Http::HdrType::WARNING
, SBuf(), newWarning
.termedBuf());
588 * Remove warning-values with warn-date different from Date value from
589 * a single header entry. Returns a string with all valid warning-values.
591 String
HttpReply::removeStaleWarningValues(const String
&value
)
594 const char *item
= 0;
597 while (strListGetItem(&value
, ',', &item
, &len
, &pos
)) {
599 // Does warning-value have warn-date (which contains quoted date)?
600 // We scan backwards, looking for two quoted strings.
601 // warning-value = warn-code SP warn-agent SP warn-text [SP warn-date]
602 const char *p
= item
+ len
- 1;
604 while (p
>= item
&& xisspace(*p
)) --p
; // skip whitespace
606 // warning-value MUST end with quote
607 if (p
>= item
&& *p
== '"') {
608 const char *const warnDateEnd
= p
;
610 while (p
>= item
&& *p
!= '"') --p
; // find the next quote
612 const char *warnDateBeg
= p
+ 1;
614 while (p
>= item
&& xisspace(*p
)) --p
; // skip whitespace
616 if (p
>= item
&& *p
== '"' && warnDateBeg
- p
> 2) {
619 warnDate
.append(warnDateBeg
, warnDateEnd
- warnDateBeg
);
620 const time_t time
= parse_rfc1123(warnDate
.termedBuf());
621 keep
= (time
> 0 && time
== date
); // keep valid and matching date
627 newValue
.append(", ");
628 newValue
.append(item
, len
);
636 HttpReply::olderThan(const HttpReply
*them
) const
638 if (!them
|| !them
->date
|| !date
)
640 return date
< them
->date
;