]> git.ipfire.org Git - thirdparty/squid.git/blob - src/HttpReply.cc
Replace Packer object API with Packable API
[thirdparty/squid.git] / src / HttpReply.cc
1 /*
2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
3 *
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.
7 */
8
9 /* DEBUG: section 58 HTTP Reply (Response) */
10
11 #include "squid.h"
12 #include "acl/AclSizeLimit.h"
13 #include "acl/FilledChecklist.h"
14 #include "globals.h"
15 #include "HttpBody.h"
16 #include "HttpHdrCc.h"
17 #include "HttpHdrContRange.h"
18 #include "HttpHdrSc.h"
19 #include "HttpReply.h"
20 #include "HttpRequest.h"
21 #include "MemBuf.h"
22 #include "SquidConfig.h"
23 #include "SquidTime.h"
24 #include "Store.h"
25 #include "StrList.h"
26
27 /* local constants */
28
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).
32 *
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.
37 *
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
41 */
42 static HttpHeaderMask Denied304HeadersMask;
43 static http_hdr_type Denied304HeadersArr[] = {
44 // hop-by-hop headers
45 HDR_CONNECTION, HDR_KEEP_ALIVE, HDR_PROXY_AUTHENTICATE, HDR_PROXY_AUTHORIZATION,
46 HDR_TE, HDR_TRAILER, HDR_TRANSFER_ENCODING, HDR_UPGRADE,
47 // entity headers
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
50 };
51
52 /* module initialization */
53 void
54 httpReplyInitModule(void)
55 {
56 assert(Http::scNone == 0); // HttpReply::parse() interface assumes that
57 httpHeaderMaskInit(&Denied304HeadersMask, 0);
58 httpHeaderCalcMask(&Denied304HeadersMask, Denied304HeadersArr, countof(Denied304HeadersArr));
59 }
60
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)
64 {
65 init();
66 }
67
68 HttpReply::~HttpReply()
69 {
70 if (do_clean)
71 clean();
72 }
73
74 void
75 HttpReply::init()
76 {
77 hdrCacheInit();
78 sline.init();
79 pstate = psReadyToParseStartLine;
80 do_clean = true;
81 }
82
83 void HttpReply::reset()
84 {
85
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;
91 clean();
92 init();
93 protoPrefix = pfx;
94 }
95
96 void
97 HttpReply::clean()
98 {
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.
101 body_pipe = NULL;
102
103 body.clear();
104 hdrCacheClean();
105 header.clean();
106 sline.clean();
107 bodySizeMax = -2; // hack: make calculatedBodySizeMax() false
108 }
109
110 void
111 HttpReply::packHeadersInto(Packable * p) const
112 {
113 sline.packInto(p);
114 header.packInto(p);
115 p->append("\r\n", 2);
116 }
117
118 void
119 HttpReply::packInto(Packable * p)
120 {
121 packHeadersInto(p);
122 body.packInto(p);
123 }
124
125 /* create memBuf, create mem-based packer, pack, destroy packer, return MemBuf */
126 MemBuf *
127 HttpReply::pack()
128 {
129 MemBuf *mb = new MemBuf;
130 mb->init();
131 packInto(mb);
132 return mb;
133 }
134
135 HttpReply *
136 HttpReply::make304() const
137 {
138 static const http_hdr_type ImsEntries[] = {HDR_DATE, HDR_CONTENT_TYPE, HDR_EXPIRES, HDR_LAST_MODIFIED, /* eof */ HDR_OTHER};
139
140 HttpReply *rv = new HttpReply;
141 int t;
142 HttpHeaderEntry *e;
143
144 /* rv->content_length; */
145 rv->date = date;
146 rv->last_modified = last_modified;
147 rv->expires = expires;
148 rv->content_type = content_type;
149 /* rv->cache_control */
150 /* rv->content_range */
151 /* rv->keep_alive */
152 rv->sline.set(Http::ProtocolVersion(), Http::scNotModified, NULL);
153
154 for (t = 0; ImsEntries[t] != HDR_OTHER; ++t)
155 if ((e = header.findEntry(ImsEntries[t])))
156 rv->header.addEntry(e->clone());
157
158 /* rv->body */
159 return rv;
160 }
161
162 MemBuf *
163 HttpReply::packed304Reply()
164 {
165 /* Not as efficient as skipping the header duplication,
166 * but easier to maintain
167 */
168 HttpReply *temp = make304();
169 MemBuf *rv = temp->pack();
170 delete temp;
171 return rv;
172 }
173
174 void
175 HttpReply::setHeaders(Http::StatusCode status, const char *reason,
176 const char *ctype, int64_t clen, time_t lmt, time_t expiresTime)
177 {
178 HttpHeader *hdr;
179 sline.set(Http::ProtocolVersion(), status, reason);
180 hdr = &header;
181 hdr->putStr(HDR_SERVER, visible_appname_string);
182 hdr->putStr(HDR_MIME_VERSION, "1.0");
183 hdr->putTime(HDR_DATE, squid_curtime);
184
185 if (ctype) {
186 hdr->putStr(HDR_CONTENT_TYPE, ctype);
187 content_type = ctype;
188 } else
189 content_type = String();
190
191 if (clen >= 0)
192 hdr->putInt64(HDR_CONTENT_LENGTH, clen);
193
194 if (expiresTime >= 0)
195 hdr->putTime(HDR_EXPIRES, expiresTime);
196
197 if (lmt > 0) /* this used to be lmt != 0 @?@ */
198 hdr->putTime(HDR_LAST_MODIFIED, lmt);
199
200 date = squid_curtime;
201
202 content_length = clen;
203
204 expires = expiresTime;
205
206 last_modified = lmt;
207 }
208
209 void
210 HttpReply::redirect(Http::StatusCode status, const char *loc)
211 {
212 HttpHeader *hdr;
213 sline.set(Http::ProtocolVersion(), status, NULL);
214 hdr = &header;
215 hdr->putStr(HDR_SERVER, APP_FULLNAME);
216 hdr->putTime(HDR_DATE, squid_curtime);
217 hdr->putInt64(HDR_CONTENT_LENGTH, 0);
218 hdr->putStr(HDR_LOCATION, loc);
219 date = squid_curtime;
220 content_length = 0;
221 }
222
223 /* compare the validators of two replies.
224 * 1 = they match
225 * 0 = they do not match
226 */
227 int
228 HttpReply::validatorsMatch(HttpReply const * otherRep) const
229 {
230 String one,two;
231 assert (otherRep);
232 /* Numbers first - easiest to check */
233 /* Content-Length */
234 /* TODO: remove -1 bypass */
235
236 if (content_length != otherRep->content_length
237 && content_length > -1 &&
238 otherRep->content_length > -1)
239 return 0;
240
241 /* ETag */
242 one = header.getStrOrList(HDR_ETAG);
243
244 two = otherRep->header.getStrOrList(HDR_ETAG);
245
246 if (one.size()==0 || two.size()==0 || one.caseCmp(two)!=0 ) {
247 one.clean();
248 two.clean();
249 return 0;
250 }
251
252 if (last_modified != otherRep->last_modified)
253 return 0;
254
255 /* MD5 */
256 one = header.getStrOrList(HDR_CONTENT_MD5);
257
258 two = otherRep->header.getStrOrList(HDR_CONTENT_MD5);
259
260 if (one.size()==0 || two.size()==0 || one.caseCmp(two)!=0 ) {
261 one.clean();
262 two.clean();
263 return 0;
264 }
265
266 return 1;
267 }
268
269 void
270 HttpReply::updateOnNotModified(HttpReply const * freshRep)
271 {
272 assert(freshRep);
273
274 /* clean cache */
275 hdrCacheClean();
276 /* update raw headers */
277 header.update(&freshRep->header,
278 (const HttpHeaderMask *) &Denied304HeadersMask);
279
280 header.compact();
281 /* init cache */
282 hdrCacheInit();
283 }
284
285 /* internal routines */
286
287 time_t
288 HttpReply::hdrExpirationTime()
289 {
290 /* The s-maxage and max-age directive takes priority over Expires */
291
292 if (cache_control) {
293 if (date >= 0) {
294 if (cache_control->hasSMaxAge())
295 return date + cache_control->sMaxAge();
296
297 if (cache_control->hasMaxAge())
298 return date + cache_control->maxAge();
299 } else {
300 /*
301 * Conservatively handle the case when we have a max-age
302 * header, but no Date for reference?
303 */
304
305 if (cache_control->hasSMaxAge())
306 return squid_curtime;
307
308 if (cache_control->hasMaxAge())
309 return squid_curtime;
310 }
311 }
312
313 if (Config.onoff.vary_ignore_expire &&
314 header.has(HDR_VARY)) {
315 const time_t d = header.getTime(HDR_DATE);
316 const time_t e = header.getTime(HDR_EXPIRES);
317
318 if (d == e)
319 return -1;
320 }
321
322 if (header.has(HDR_EXPIRES)) {
323 const time_t e = header.getTime(HDR_EXPIRES);
324 /*
325 * HTTP/1.0 says that robust implementations should consider
326 * bad or malformed Expires header as equivalent to "expires
327 * immediately."
328 */
329 return e < 0 ? squid_curtime : e;
330 }
331
332 return -1;
333 }
334
335 /* sync this routine when you update HttpReply struct */
336 void
337 HttpReply::hdrCacheInit()
338 {
339 HttpMsg::hdrCacheInit();
340
341 http_ver = sline.version;
342 content_length = header.getInt64(HDR_CONTENT_LENGTH);
343 date = header.getTime(HDR_DATE);
344 last_modified = header.getTime(HDR_LAST_MODIFIED);
345 surrogate_control = header.getSc();
346 content_range = header.getContRange();
347 keep_alive = persistent() ? 1 : 0;
348 const char *str = header.getStr(HDR_CONTENT_TYPE);
349
350 if (str)
351 content_type.limitInit(str, strcspn(str, ";\t "));
352 else
353 content_type = String();
354
355 /* be sure to set expires after date and cache-control */
356 expires = hdrExpirationTime();
357 }
358
359 /* sync this routine when you update HttpReply struct */
360 void
361 HttpReply::hdrCacheClean()
362 {
363 content_type.clean();
364
365 if (cache_control) {
366 delete cache_control;
367 cache_control = NULL;
368 }
369
370 if (surrogate_control) {
371 delete surrogate_control;
372 surrogate_control = NULL;
373 }
374
375 if (content_range) {
376 httpHdrContRangeDestroy(content_range);
377 content_range = NULL;
378 }
379 }
380
381 /*
382 * Returns the body size of a HTTP response
383 */
384 int64_t
385 HttpReply::bodySize(const HttpRequestMethod& method) const
386 {
387 if (sline.version.major < 1)
388 return -1;
389 else if (method.id() == Http::METHOD_HEAD)
390 return 0;
391 else if (sline.status() == Http::scOkay)
392 (void) 0; /* common case, continue */
393 else if (sline.status() == Http::scNoContent)
394 return 0;
395 else if (sline.status() == Http::scNotModified)
396 return 0;
397 else if (sline.status() < Http::scOkay)
398 return 0;
399
400 return content_length;
401 }
402
403 /**
404 * Checks the first line of an HTTP Reply is valid.
405 * currently only checks "HTTP/" exists.
406 *
407 * NP: not all error cases are detected yet. Some are left for detection later in parse.
408 */
409 bool
410 HttpReply::sanityCheckStartLine(const char *buf, const size_t hdr_len, Http::StatusCode *error)
411 {
412 // hack warning: using psize instead of size here due to type mismatches with MemBuf.
413
414 // content is long enough to possibly hold a reply
415 // 4 being magic size of a 3-digit number plus space delimiter
416 if (hdr_len < (size_t)(protoPrefix.psize() + 4)) {
417 if (hdr_len > 0) {
418 debugs(58, 3, "Too small reply header (" << hdr_len << " bytes)");
419 *error = Http::scInvalidHeader;
420 }
421 return false;
422 }
423
424 int pos;
425 // catch missing or mismatched protocol identifier
426 // allow special-case for ICY protocol (non-HTTP identifier) in response to faked HTTP request.
427 if (strncmp(buf, "ICY", 3) == 0) {
428 protoPrefix = "ICY";
429 pos = protoPrefix.psize();
430 } else {
431
432 if (protoPrefix.cmp(buf, protoPrefix.size()) != 0) {
433 debugs(58, 3, "missing protocol prefix (" << protoPrefix << ") in '" << buf << "'");
434 *error = Http::scInvalidHeader;
435 return false;
436 }
437
438 // catch missing or negative status value (negative '-' is not a digit)
439 pos = protoPrefix.psize();
440
441 // skip arbitrary number of digits and a dot in the verion portion
442 while ((size_t)pos <= hdr_len && (*(buf+pos) == '.' || xisdigit(*(buf+pos)) ) ) ++pos;
443
444 // catch missing version info
445 if (pos == protoPrefix.psize()) {
446 debugs(58, 3, "missing protocol version numbers (ie. " << protoPrefix << "/1.0) in '" << buf << "'");
447 *error = Http::scInvalidHeader;
448 return false;
449 }
450 }
451
452 // skip arbitrary number of spaces...
453 while ((size_t)pos <= hdr_len && (char)*(buf+pos) == ' ') ++pos;
454
455 if ((size_t)pos < hdr_len && !xisdigit(*(buf+pos))) {
456 debugs(58, 3, "missing or invalid status number in '" << buf << "'");
457 *error = Http::scInvalidHeader;
458 return false;
459 }
460
461 return true;
462 }
463
464 bool
465 HttpReply::parseFirstLine(const char *blk_start, const char *blk_end)
466 {
467 return sline.parse(protoPrefix, blk_start, blk_end);
468 }
469
470 /* handy: resets and returns -1 */
471 int
472 HttpReply::httpMsgParseError()
473 {
474 int result(HttpMsg::httpMsgParseError());
475 /* indicate an error in the status line */
476 sline.set(Http::ProtocolVersion(), Http::scInvalidHeader);
477 return result;
478 }
479
480 /*
481 * Indicate whether or not we would usually expect an entity-body
482 * along with this response
483 */
484 bool
485 HttpReply::expectingBody(const HttpRequestMethod& req_method, int64_t& theSize) const
486 {
487 bool expectBody = true;
488
489 if (req_method == Http::METHOD_HEAD)
490 expectBody = false;
491 else if (sline.status() == Http::scNoContent)
492 expectBody = false;
493 else if (sline.status() == Http::scNotModified)
494 expectBody = false;
495 else if (sline.status() < Http::scOkay)
496 expectBody = false;
497 else
498 expectBody = true;
499
500 if (expectBody) {
501 if (header.chunked())
502 theSize = -1;
503 else if (content_length >= 0)
504 theSize = content_length;
505 else
506 theSize = -1;
507 }
508
509 return expectBody;
510 }
511
512 bool
513 HttpReply::receivedBodyTooLarge(HttpRequest& request, int64_t receivedSize)
514 {
515 calcMaxBodySize(request);
516 debugs(58, 3, HERE << receivedSize << " >? " << bodySizeMax);
517 return bodySizeMax >= 0 && receivedSize > bodySizeMax;
518 }
519
520 bool
521 HttpReply::expectedBodyTooLarge(HttpRequest& request)
522 {
523 calcMaxBodySize(request);
524 debugs(58, 7, HERE << "bodySizeMax=" << bodySizeMax);
525
526 if (bodySizeMax < 0) // no body size limit
527 return false;
528
529 int64_t expectedSize = -1;
530 if (!expectingBody(request.method, expectedSize))
531 return false;
532
533 debugs(58, 6, HERE << expectedSize << " >? " << bodySizeMax);
534
535 if (expectedSize < 0) // expecting body of an unknown length
536 return false;
537
538 return expectedSize > bodySizeMax;
539 }
540
541 void
542 HttpReply::calcMaxBodySize(HttpRequest& request) const
543 {
544 // hack: -2 is used as "we have not calculated max body size yet" state
545 if (bodySizeMax != -2) // already tried
546 return;
547 bodySizeMax = -1;
548
549 // short-circuit ACL testing if there are none configured
550 if (!Config.ReplyBodySize)
551 return;
552
553 ACLFilledChecklist ch(NULL, &request, NULL);
554 // XXX: cont-cast becomes irrelevant when checklist is HttpReply::Pointer
555 ch.reply = const_cast<HttpReply *>(this);
556 HTTPMSGLOCK(ch.reply);
557 for (AclSizeLimit *l = Config.ReplyBodySize; l; l = l -> next) {
558 /* if there is no ACL list or if the ACLs listed match use this size value */
559 if (!l->aclList || ch.fastCheck(l->aclList) == ACCESS_ALLOWED) {
560 debugs(58, 4, HERE << "bodySizeMax=" << bodySizeMax);
561 bodySizeMax = l->size; // may be -1
562 break;
563 }
564 }
565 }
566
567 // XXX: check that this is sufficient for eCAP cloning
568 HttpReply *
569 HttpReply::clone() const
570 {
571 HttpReply *rep = new HttpReply();
572 rep->sline = sline; // used in hdrCacheInit() call below
573 rep->header.append(&header);
574 rep->hdrCacheInit();
575 rep->hdr_sz = hdr_sz;
576 rep->http_ver = http_ver;
577 rep->pstate = pstate;
578 rep->body_pipe = body_pipe;
579
580 // keep_alive is handled in hdrCacheInit()
581 return rep;
582 }
583
584 bool HttpReply::inheritProperties(const HttpMsg *aMsg)
585 {
586 const HttpReply *aRep = dynamic_cast<const HttpReply*>(aMsg);
587 if (!aRep)
588 return false;
589 keep_alive = aRep->keep_alive;
590 return true;
591 }
592
593 void HttpReply::removeStaleWarnings()
594 {
595 String warning;
596 if (header.getList(HDR_WARNING, &warning)) {
597 const String newWarning = removeStaleWarningValues(warning);
598 if (warning.size() && warning.size() == newWarning.size())
599 return; // some warnings are there and none changed
600 header.delById(HDR_WARNING);
601 if (newWarning.size()) { // some warnings left
602 HttpHeaderEntry *const e =
603 new HttpHeaderEntry(HDR_WARNING, NULL, newWarning.termedBuf());
604 header.addEntry(e);
605 }
606 }
607 }
608
609 /**
610 * Remove warning-values with warn-date different from Date value from
611 * a single header entry. Returns a string with all valid warning-values.
612 */
613 String HttpReply::removeStaleWarningValues(const String &value)
614 {
615 String newValue;
616 const char *item = 0;
617 int len = 0;
618 const char *pos = 0;
619 while (strListGetItem(&value, ',', &item, &len, &pos)) {
620 bool keep = true;
621 // Does warning-value have warn-date (which contains quoted date)?
622 // We scan backwards, looking for two quoted strings.
623 // warning-value = warn-code SP warn-agent SP warn-text [SP warn-date]
624 const char *p = item + len - 1;
625
626 while (p >= item && xisspace(*p)) --p; // skip whitespace
627
628 // warning-value MUST end with quote
629 if (p >= item && *p == '"') {
630 const char *const warnDateEnd = p;
631 --p;
632 while (p >= item && *p != '"') --p; // find the next quote
633
634 const char *warnDateBeg = p + 1;
635 --p;
636 while (p >= item && xisspace(*p)) --p; // skip whitespace
637
638 if (p >= item && *p == '"' && warnDateBeg - p > 2) {
639 // found warn-text
640 String warnDate;
641 warnDate.append(warnDateBeg, warnDateEnd - warnDateBeg);
642 const time_t time = parse_rfc1123(warnDate.termedBuf());
643 keep = (time > 0 && time == date); // keep valid and matching date
644 }
645 }
646
647 if (keep) {
648 if (newValue.size())
649 newValue.append(", ");
650 newValue.append(item, len);
651 }
652 }
653
654 return newValue;
655 }
656