http.cc
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1996-2020 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 11 Hypertext Transfer Protocol (HTTP) */
10 
11 /*
12  * Anonymizing patch by lutz@as-node.jena.thur.de
13  * have a look into http-anon.c to get more information.
14  */
15 
16 #include "squid.h"
17 #include "acl/FilledChecklist.h"
18 #include "base/AsyncJobCalls.h"
19 #include "base/TextException.h"
20 #include "base64.h"
21 #include "CachePeer.h"
22 #include "client_side.h"
23 #include "comm/Connection.h"
24 #include "comm/Read.h"
25 #include "comm/Write.h"
26 #include "CommRead.h"
27 #include "error/Detail.h"
28 #include "errorpage.h"
29 #include "fd.h"
30 #include "fde.h"
31 #include "globals.h"
32 #include "http.h"
35 #include "http/Stream.h"
36 #include "HttpControlMsg.h"
37 #include "HttpHdrCc.h"
38 #include "HttpHdrContRange.h"
39 #include "HttpHdrSc.h"
40 #include "HttpHdrScTarget.h"
41 #include "HttpHeaderTools.h"
42 #include "HttpReply.h"
43 #include "HttpRequest.h"
45 #include "log/access_log.h"
46 #include "MemBuf.h"
47 #include "MemObject.h"
48 #include "neighbors.h"
49 #include "pconn.h"
51 #include "profiler/Profiler.h"
52 #include "refresh.h"
53 #include "RefreshPattern.h"
54 #include "rfc1738.h"
55 #include "SquidConfig.h"
56 #include "SquidTime.h"
57 #include "StatCounters.h"
58 #include "Store.h"
59 #include "StrList.h"
60 #include "tools.h"
61 #include "util.h"
62 
63 #if USE_AUTH
64 #include "auth/UserRequest.h"
65 #endif
66 #if USE_DELAY_POOLS
67 #include "DelayPools.h"
68 #endif
69 
70 #define SQUID_ENTER_THROWING_CODE() try {
71 #define SQUID_EXIT_THROWING_CODE(status) \
72  status = true; \
73  } \
74  catch (const std::exception &e) { \
75  debugs (11, 1, "Exception error:" << e.what()); \
76  status = false; \
77  }
78 
80 
81 static const char *const crlf = "\r\n";
82 
84 static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request,
85  HttpHeader * hdr_out, const int we_do_ranges, const Http::StateFlags &);
86 
88  AsyncJob("HttpStateData"),
89  Client(theFwdState),
90  lastChunk(0),
91  httpChunkDecoder(NULL),
92  payloadSeen(0),
93  payloadTruncated(0),
94  sawDateGoBack(false)
95 {
96  debugs(11,5,HERE << "HttpStateData " << this << " created");
97  ignoreCacheControl = false;
98  surrogateNoStore = false;
100 
101  if (fwd->serverConnection() != NULL)
102  _peer = cbdataReference(fwd->serverConnection()->getPeer()); /* might be NULL */
103 
104  flags.peering = _peer;
107 
108  if (_peer) {
109  /*
110  * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here.
111  * We might end up getting the object from somewhere else if,
112  * for example, the request to this neighbor fails.
113  */
115  entry->releaseRequest(true);
116 
117 #if USE_DELAY_POOLS
119 #endif
120  }
121 
122  /*
123  * register the handler to free HTTP state data when the FD closes
124  */
128 }
129 
131 {
132  /*
133  * don't forget that ~Client() gets called automatically
134  */
135 
136  if (httpChunkDecoder)
137  delete httpChunkDecoder;
138 
140 
141  delete upgradeHeaderOut;
142 
143  debugs(11,5, HERE << "HttpStateData " << this << " destroyed; " << serverConnection);
144 }
145 
148 {
149  return serverConnection;
150 }
151 
152 void
154 {
155  debugs(11, 5, "httpStateFree: FD " << params.fd << ", httpState=" << params.data);
156  doneWithFwd = "httpStateConnClosed()"; // assume FwdState is monitoring too
157  mustStop("HttpStateData::httpStateConnClosed");
158 }
159 
160 void
162 {
163  debugs(11, 4, serverConnection << ": '" << entry->url() << "'");
164 
165  if (entry->store_status == STORE_PENDING) {
167  }
168 
169  closeServer();
170  mustStop("HttpStateData::httpTimeout");
171 }
172 
173 static StoreEntry *
175  assert(newEntry->mem_obj);
176  return newEntry->mem_obj->request ?
178  storeGetPublic(newEntry->mem_obj->storeId(), newEntry->mem_obj->method);
179 }
180 
183 static void
185 {
186  int remove = 0;
187  int forbidden = 0;
188 
189  // If the incoming response already goes into a public entry, then there is
190  // nothing to remove. This protects ready-for-collapsing entries as well.
191  if (!EBIT_TEST(e->flags, KEY_PRIVATE))
192  return;
193 
194  // If the new/incoming response cannot be stored, then it does not
195  // compete with the old stored response for the public key, and the
196  // old stored response should be left as is.
197  if (e->mem_obj->request && !e->mem_obj->request->flags.cachable)
198  return;
199 
200  switch (status) {
201 
202  case Http::scOkay:
203 
205 
207 
209 
210  case Http::scFound:
211 
212  case Http::scSeeOther:
213 
214  case Http::scGone:
215 
216  case Http::scNotFound:
217  remove = 1;
218 
219  break;
220 
221  case Http::scForbidden:
222 
224  forbidden = 1;
225 
226  break;
227 
228 #if WORK_IN_PROGRESS
229 
231  forbidden = 1;
232 
233  break;
234 
235 #endif
236 
237  default:
238 #if QUESTIONABLE
239  /*
240  * Any 2xx response should eject previously cached entities...
241  */
242 
243  if (status >= 200 && status < 300)
244  remove = 1;
245 
246 #endif
247 
248  break;
249  }
250 
251  if (!remove && !forbidden)
252  return;
253 
255 
256  if (pe != NULL) {
257  assert(e != pe);
258 #if USE_HTCP
260 #endif
261  pe->release(true);
262  }
263 
268  if (e->mem_obj->request)
270  else
272 
273  if (pe != NULL) {
274  assert(e != pe);
275 #if USE_HTCP
277 #endif
278  pe->release(true);
279  }
280 }
281 
282 void
284 {
285  if (request->flags.accelerated && reply->surrogate_control) {
287 
288  if (sctusable) {
289  if (sctusable->hasNoStore() ||
291  && sctusable->noStoreRemote())) {
292  surrogateNoStore = true;
293  // Be conservative for now and make it non-shareable because
294  // there is no enough information here to make the decision.
295  entry->makePrivate(false);
296  }
297 
298  /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
299  * accelerated request or not...
300  * Still, this is an abstraction breach. - RC
301  */
302  if (sctusable->hasMaxAge()) {
303  if (sctusable->maxAge() < sctusable->maxStale())
304  reply->expires = reply->date + sctusable->maxAge();
305  else
306  reply->expires = reply->date + sctusable->maxStale();
307 
308  /* And update the timestamps */
309  entry->timestampsSet();
310  }
311 
312  /* We ignore cache-control directives as per the Surrogate specification */
313  ignoreCacheControl = true;
314 
315  delete sctusable;
316  }
317  }
318 }
319 
322 {
323  HttpReply const *rep = finalReply();
324  HttpHeader const *hdr = &rep->header;
325  const char *v;
326 #if USE_HTTP_VIOLATIONS
327 
328  const RefreshPattern *R = NULL;
329 
330  /* This strange looking define first looks up the refresh pattern
331  * and then checks if the specified flag is set. The main purpose
332  * of this is to simplify the refresh pattern lookup and USE_HTTP_VIOLATIONS
333  * condition
334  */
335 #define REFRESH_OVERRIDE(flag) \
336  ((R = (R ? R : refreshLimits(entry->mem_obj->storeId()))) , \
337  (R && R->flags.flag))
338 #else
339 #define REFRESH_OVERRIDE(flag) 0
340 #endif
341 
343  return decision.make(ReuseDecision::doNotCacheButShare, "the entry has been released");
344 
345  // RFC 7234 section 4: a cache MUST use the most recent response
346  // (as determined by the Date header field)
347  // TODO: whether such responses could be shareable?
348  if (sawDateGoBack)
349  return decision.make(ReuseDecision::reuseNot, "the response has an older date header");
350 
351  // Check for Surrogate/1.0 protocol conditions
352  // NP: reverse-proxy traffic our parent server has instructed us never to cache
353  if (surrogateNoStore)
354  return decision.make(ReuseDecision::reuseNot, "Surrogate-Control:no-store");
355 
356  // RFC 2616: HTTP/1.1 Cache-Control conditions
357  if (!ignoreCacheControl) {
358  // XXX: check to see if the request headers alone were enough to prevent caching earlier
359  // (ie no-store request header) no need to check those all again here if so.
360  // for now we are not reliably doing that so we waste CPU re-checking request CC
361 
362  // RFC 2616 section 14.9.2 - MUST NOT cache any response with request CC:no-store
364  !REFRESH_OVERRIDE(ignore_no_store))
365  return decision.make(ReuseDecision::reuseNot,
366  "client request Cache-Control:no-store");
367 
368  // NP: request CC:no-cache only means cache READ is forbidden. STORE is permitted.
370  /* TODO: we are allowed to cache when no-cache= has parameters.
371  * Provided we strip away any of the listed headers unless they are revalidated
372  * successfully (ie, must revalidate AND these headers are prohibited on stale replies).
373  * That is a bit tricky for squid right now so we avoid caching entirely.
374  */
375  return decision.make(ReuseDecision::reuseNot,
376  "server reply Cache-Control:no-cache has parameters");
377  }
378 
379  // NP: request CC:private is undefined. We ignore.
380  // NP: other request CC flags are limiters on HIT/MISS. We don't care about here.
381 
382  // RFC 2616 section 14.9.2 - MUST NOT cache any response with CC:no-store
383  if (rep->cache_control && rep->cache_control->hasNoStore() &&
384  !REFRESH_OVERRIDE(ignore_no_store))
385  return decision.make(ReuseDecision::reuseNot,
386  "server reply Cache-Control:no-store");
387 
388  // RFC 2616 section 14.9.1 - MUST NOT cache any response with CC:private in a shared cache like Squid.
389  // CC:private overrides CC:public when both are present in a response.
390  // TODO: add a shared/private cache configuration possibility.
391  if (rep->cache_control &&
392  rep->cache_control->hasPrivate() &&
393  !REFRESH_OVERRIDE(ignore_private)) {
394  /* TODO: we are allowed to cache when private= has parameters.
395  * Provided we strip away any of the listed headers unless they are revalidated
396  * successfully (ie, must revalidate AND these headers are prohibited on stale replies).
397  * That is a bit tricky for squid right now so we avoid caching entirely.
398  */
399  return decision.make(ReuseDecision::reuseNot,
400  "server reply Cache-Control:private");
401  }
402  }
403 
404  // RFC 2068, sec 14.9.4 - MUST NOT cache any response with Authentication UNLESS certain CC controls are present
405  // allow HTTP violations to IGNORE those controls (ie re-block caching Auth)
406  if (request && (request->flags.auth || request->flags.authSent)) {
407  if (!rep->cache_control)
408  return decision.make(ReuseDecision::reuseNot,
409  "authenticated and server reply missing Cache-Control");
410 
411  if (ignoreCacheControl)
412  return decision.make(ReuseDecision::reuseNot,
413  "authenticated and ignoring Cache-Control");
414 
415  bool mayStore = false;
416  // HTTPbis pt6 section 3.2: a response CC:public is present
417  if (rep->cache_control->hasPublic()) {
418  debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:public");
419  mayStore = true;
420 
421  // HTTPbis pt6 section 3.2: a response CC:must-revalidate is present
422  } else if (rep->cache_control->hasMustRevalidate()) {
423  debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:must-revalidate");
424  mayStore = true;
425 
426 #if USE_HTTP_VIOLATIONS
427  // NP: given the must-revalidate exception we should also be able to exempt no-cache.
428  // HTTPbis WG verdict on this is that it is omitted from the spec due to being 'unexpected' by
429  // some. The caching+revalidate is not exactly unsafe though with Squids interpretation of no-cache
430  // (without parameters) as equivalent to must-revalidate in the reply.
431  } else if (rep->cache_control->hasNoCacheWithoutParameters()) {
432  debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:no-cache (equivalent to must-revalidate)");
433  mayStore = true;
434 #endif
435 
436  // HTTPbis pt6 section 3.2: a response CC:s-maxage is present
437  } else if (rep->cache_control->hasSMaxAge()) {
438  debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:s-maxage");
439  mayStore = true;
440  }
441 
442  if (!mayStore)
443  return decision.make(ReuseDecision::reuseNot, "authenticated transaction");
444 
445  // NP: response CC:no-cache is equivalent to CC:must-revalidate,max-age=0. We MAY cache, and do so.
446  // NP: other request CC flags are limiters on HIT/MISS/REFRESH. We don't care about here.
447  }
448 
449  /* HACK: The "multipart/x-mixed-replace" content type is used for
450  * continuous push replies. These are generally dynamic and
451  * probably should not be cachable
452  */
453  if ((v = hdr->getStr(Http::HdrType::CONTENT_TYPE)))
454  if (!strncasecmp(v, "multipart/x-mixed-replace", 25))
455  return decision.make(ReuseDecision::reuseNot, "Content-Type:multipart/x-mixed-replace");
456 
457  // TODO: if possible, provide more specific message for each status code
458  static const char *shareableError = "shareable error status code";
459  static const char *nonShareableError = "non-shareable error status code";
461  const char *statusReason = nonShareableError;
462 
463  switch (rep->sline.status()) {
464 
465  /* There are several situations when a non-cacheable response may be
466  * still shareable (e.g., among collapsed clients). We assume that these
467  * are 3xx and 5xx responses, indicating server problems and some of
468  * 4xx responses, common for all clients with a given cache key (e.g.,
469  * 404 Not Found or 414 URI Too Long). On the other hand, we should not
470  * share non-cacheable client-specific errors, such as 400 Bad Request
471  * or 406 Not Acceptable.
472  */
473 
474  /* Responses that are cacheable */
475 
476  case Http::scOkay:
477 
479 
481 
484 
485  case Http::scGone:
486  /*
487  * Don't cache objects that need to be refreshed on next request,
488  * unless we know how to refresh it.
489  */
490 
491  if (refreshIsCachable(entry) || REFRESH_OVERRIDE(store_stale))
492  decision.make(ReuseDecision::cachePositively, "refresh check returned cacheable");
493  else
494  decision.make(ReuseDecision::doNotCacheButShare, "refresh check returned non-cacheable");
495  break;
496 
497  /* Responses that only are cacheable if the server says so */
498 
499  case Http::scFound:
501  if (rep->date <= 0)
502  decision.make(ReuseDecision::doNotCacheButShare, "Date is missing/invalid");
503  else if (rep->expires > rep->date)
504  decision.make(ReuseDecision::cachePositively, "Expires > Date");
505  else
506  decision.make(ReuseDecision::doNotCacheButShare, "Expires <= Date");
507  break;
508 
509  /* These responses can be negatively cached. Most can also be shared. */
510  case Http::scNoContent:
511  case Http::scUseProxy:
512  case Http::scForbidden:
513  case Http::scNotFound:
515  case Http::scUriTooLong:
518  case Http::scBadGateway:
522  statusAnswer = ReuseDecision::doNotCacheButShare;
523  statusReason = shareableError;
524  // fall through to the actual decision making below
525 
526  case Http::scBadRequest: // no sharing; perhaps the server did not like something specific to this request
527 #if USE_HTTP_VIOLATIONS
528  if (Config.negativeTtl > 0)
529  decision.make(ReuseDecision::cacheNegatively, "Config.negativeTtl > 0");
530  else
531 #endif
532  decision.make(statusAnswer, statusReason);
533  break;
534 
535  /* these responses can never be cached, some
536  of them can be shared though */
537  case Http::scSeeOther:
538  case Http::scNotModified:
543  // TODO: use more specific reason for non-error status codes
544  decision.make(ReuseDecision::doNotCacheButShare, shareableError);
545  break;
546 
547  case Http::scPartialContent: /* Not yet supported. TODO: make shareable for suitable ranges */
549  case Http::scRequestTimeout: // TODO: is this shareable?
550  case Http::scConflict: // TODO: is this shareable?
556  case Http::scLocked: // TODO: is this shareable?
560  case Http::scInvalidHeader: /* Squid header parsing error */
562  decision.make(ReuseDecision::reuseNot, nonShareableError);
563  break;
564 
565  default:
566  /* RFC 2616 section 6.1.1: an unrecognized response MUST NOT be cached. */
567  decision.make(ReuseDecision::reuseNot, "unknown status code");
568  break;
569  }
570 
571  return decision.answer;
572 }
573 
575 static void
577 {
578  static const SBuf asterisk("*");
579  const char *pos = nullptr;
580  const char *item = nullptr;
581  int ilen = 0;
582 
583  while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
584  SBuf name(item, ilen);
585  if (name == asterisk) {
586  vstr = asterisk;
587  break;
588  }
589  name.toLower();
590  if (!vstr.isEmpty())
591  vstr.append(", ", 2);
592  vstr.append(name);
593  String hdr(request.header.getByName(name));
594  const char *value = hdr.termedBuf();
595  if (value) {
596  value = rfc1738_escape_part(value);
597  vstr.append("=\"", 2);
598  vstr.append(value);
599  vstr.append("\"", 1);
600  }
601 
602  hdr.clean();
603  }
604 }
605 
606 /*
607  * For Vary, store the relevant request headers as
608  * virtual headers in the reply
609  * Returns an empty SBuf if the variance cannot be stored
610  */
611 SBuf
613 {
614  SBuf vstr;
615  String vary;
616 
617  vary = reply->header.getList(Http::HdrType::VARY);
618  assembleVaryKey(vary, vstr, *request);
619 
620 #if X_ACCELERATOR_VARY
621  vary.clean();
623  assembleVaryKey(vary, vstr, *request);
624 #endif
625 
626  debugs(11, 3, vstr);
627  return vstr;
628 }
629 
630 void
632 {
633  if (flags.keepalive)
634  if (flags.peering && !flags.tunneling)
636 
637  if (reply->keep_alive) {
638  if (flags.peering && !flags.tunneling)
640 
642  && reply->bodySize(request->method) == -1 && !flags.chunked) {
643  debugs(11, DBG_IMPORTANT, "keepaliveAccounting: Impossible keep-alive header from '" << entry->url() << "'" );
644  // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" );
645  flags.keepalive_broken = true;
646  }
647  }
648 }
649 
650 void
652 {
653  if (reply->date > -1 && flags.toOrigin) {
654  int skew = abs((int)(reply->date - squid_curtime));
655 
656  if (skew > 86400)
657  debugs(11, 3, "" << request->url.host() << "'s clock is skewed by " << skew << " seconds!");
658  }
659 }
660 
667 void
669 {
672  /* NP: all exit points to this function MUST call ctx_exit(ctx) */
673  Ctx ctx = ctx_enter(entry->mem_obj->urlXXX());
674 
675  debugs(11, 3, "processReplyHeader: key '" << entry->getMD5Text() << "'");
676 
678 
679  if (!inBuf.length()) {
680  ctx_exit(ctx);
681  return;
682  }
683 
684  /* Attempt to parse the first line; this will define where the protocol, status, reason-phrase and header begin */
685  {
686  if (hp == NULL)
688 
689  bool parsedOk = hp->parse(inBuf);
690  // remember the actual received status-code before returning on errors,
691  // overwriting any previously stored value from earlier forwarding attempts
692  request->hier.peer_reply_status = hp->messageStatus(); // may still be scNone
693 
694  // sync the buffers after parsing.
695  inBuf = hp->remaining();
696 
697  if (hp->needsMoreData()) {
698  if (eof) { // no more data coming
699  /* Bug 2879: Replies may terminate with \r\n then EOF instead of \r\n\r\n.
700  * We also may receive truncated responses.
701  * Ensure here that we have at minimum two \r\n when EOF is seen.
702  */
703  inBuf.append("\r\n\r\n", 4);
704  // retry the parse
705  parsedOk = hp->parse(inBuf);
706  // sync the buffers after parsing.
707  inBuf = hp->remaining();
708  } else {
709  debugs(33, 5, "Incomplete response, waiting for end of response headers");
710  ctx_exit(ctx);
711  return;
712  }
713  }
714 
715  if (!parsedOk) {
716  // unrecoverable parsing error
717  // TODO: Use Raw! XXX: inBuf no longer has the [beginning of the] malformed header.
718  debugs(11, 3, "Non-HTTP-compliant header:\n---------\n" << inBuf << "\n----------");
719  flags.headers_parsed = true;
720  HttpReply *newrep = new HttpReply;
721  newrep->sline.set(Http::ProtocolVersion(), hp->parseStatusCode);
722  setVirginReply(newrep);
723  ctx_exit(ctx);
724  return;
725  }
726  }
727 
728  /* We know the whole response is in parser now */
729  debugs(11, 2, "HTTP Server " << serverConnection);
730  debugs(11, 2, "HTTP Server RESPONSE:\n---------\n" <<
731  hp->messageProtocol() << " " << hp->messageStatus() << " " << hp->reasonPhrase() << "\n" <<
732  hp->mimeHeader() <<
733  "----------");
734 
735  // reset payload tracking to begin after message headers
737 
738  HttpReply *newrep = new HttpReply;
739  // XXX: RFC 7230 indicates we MAY ignore the reason phrase,
740  // and use an empty string on unknown status.
741  // We do that now to avoid performance regression from using SBuf::c_str()
742  newrep->sline.set(Http::ProtocolVersion(1,1), hp->messageStatus() /* , hp->reasonPhrase() */);
743  newrep->sline.protocol = newrep->sline.version.protocol = hp->messageProtocol().protocol;
744  newrep->sline.version.major = hp->messageProtocol().major;
745  newrep->sline.version.minor = hp->messageProtocol().minor;
746 
747  // parse headers
748  if (!newrep->parseHeader(*hp)) {
749  // XXX: when Http::ProtocolVersion is a function, remove this hack. just set with messageProtocol()
751  newrep->sline.version.protocol = hp->messageProtocol().protocol;
752  newrep->sline.version.major = hp->messageProtocol().major;
753  newrep->sline.version.minor = hp->messageProtocol().minor;
754  debugs(11, 2, "error parsing response headers mime block");
755  }
756 
757  // done with Parser, now process using the HttpReply
758  hp = NULL;
759 
761 
762  newrep->removeStaleWarnings();
763 
764  if (newrep->sline.protocol == AnyP::PROTO_HTTP && Http::Is1xx(newrep->sline.status())) {
765  handle1xx(newrep);
766  ctx_exit(ctx);
767  return;
768  }
769 
770  flags.chunked = false;
771  if (newrep->sline.protocol == AnyP::PROTO_HTTP && newrep->header.chunked()) {
772  flags.chunked = true;
774  }
775 
778 
779  HttpReply *vrep = setVirginReply(newrep);
780  flags.headers_parsed = true;
781 
782  keepaliveAccounting(vrep);
783 
784  checkDateSkew(vrep);
785 
787 
788  ctx_exit(ctx);
789 }
790 
792 void
794 {
795  if (fwd->al)
796  fwd->al->reply = reply;
797 
798  HttpReply::Pointer msg(reply); // will destroy reply if unused
799 
800  // one 1xx at a time: we must not be called while waiting for previous 1xx
802  flags.handling1xx = true;
803 
804  const auto statusCode = reply->sline.status();
805 
806  // drop1xx() needs to handle HTTP 101 (Switching Protocols) responses
807  // specially because they indicate that the server has stopped speaking HTTP
810 
811  if (statusCode == Http::scContinue && request->forcedBodyContinuation)
812  return drop1xx("we have sent it already");
813 
814  if (!request->canHandle1xx())
815  return drop1xx("the client does not support it");
816 
817 #if USE_HTTP_VIOLATIONS
818  // check whether the 1xx response forwarding is allowed by squid.conf
819  if (Config.accessList.reply) {
821  ch.al = fwd->al;
822  ch.reply = reply;
823  ch.syncAle(originalRequest().getRaw(), nullptr);
824  HTTPMSGLOCK(ch.reply);
825  if (!ch.fastCheck().allowed()) // TODO: support slow lookups?
826  return drop1xx("http_reply_access blocked it");
827  }
828 #endif // USE_HTTP_VIOLATIONS
829 
831  if (const auto reason = blockSwitchingProtocols(*reply))
832  return drop1xx(reason);
833  }
834 
835  debugs(11, 2, HERE << "forwarding 1xx to client");
836 
837  // the Sink will use this to call us back after writing 1xx to the client
838  typedef NullaryMemFunT<HttpStateData> CbDialer;
839  const AsyncCall::Pointer cb = JobCallback(11, 3, CbDialer, this,
843  // If the call is not fired, then the Sink is gone, and HttpStateData
844  // will terminate due to an aborted store entry or another similar error.
845  // If we get stuck, it is not handle1xx fault if we could get stuck
846  // for similar reasons without a 1xx response.
847 }
848 
851 void
852 HttpStateData::drop1xx(const char *reason)
853 {
855  debugs(11, 2, "bad 101 because " << reason);
856  const auto err = new ErrorState(ERR_INVALID_RESP, Http::scBadGateway, request.getRaw(), fwd->al);
857  fwd->fail(err);
858  closeServer();
859  mustStop("prohibited HTTP/101 response");
860  return;
861  }
862 
863  debugs(11, 2, "ignoring 1xx because " << reason);
864  proceedAfter1xx();
865 }
866 
869 const char *
871 {
872  if (!upgradeHeaderOut)
873  return "Squid offered no Upgrade at all, but server switched to a tunnel";
874 
875  // See RFC 7230 section 6.7 for the corresponding MUSTs
876 
877  if (!reply.header.has(Http::HdrType::UPGRADE))
878  return "server did not send an Upgrade header field";
879 
880  if (!reply.header.hasListMember(Http::HdrType::CONNECTION, "upgrade", ','))
881  return "server did not send 'Connection: upgrade'";
882 
883  const auto acceptedProtos = reply.header.getList(Http::HdrType::UPGRADE);
884  const char *pos = nullptr;
885  const char *accepted = nullptr;
886  int acceptedLen = 0;
887  while (strListGetItem(&acceptedProtos, ',', &accepted, &acceptedLen, &pos)) {
888  debugs(11, 5, "server accepted at least" << Raw(nullptr, accepted, acceptedLen));
889  return nullptr; // OK: let the client validate server's selection
890  }
891 
892  return "server sent an essentially empty Upgrade header field";
893 }
894 
896 void
898 {
900 
902  // pass server connection ownership to request->clientConnectionManager
905  AsyncCall::Pointer call = asyncCall(11, 3, "ConnStateData::noteTakeServerConnectionControl",
908  ScheduleCallHere(call);
911  closeHandler = nullptr;
912  serverConnection = nullptr;
913  doneWithFwd = "switched protocols";
915  return;
916  }
917 
918  debugs(11, 2, "continuing with " << payloadSeen << " bytes in buffer after 1xx");
920 }
921 
925 bool
927 {
928  if (!_peer)
929  return true;
930 
931  // we are talking "through" rather than "to" our _peer
932  if (flags.tunneling)
933  return true;
934 
935  /*If this peer does not support connection pinning (authenticated
936  connections) return false
937  */
938  if (!_peer->connection_auth)
939  return false;
940 
941  const auto &rep = entry->mem().freshestReply();
942 
943  /*The peer supports connection pinning and the http reply status
944  is not unauthorized, so the related connection can be pinned
945  */
946  if (rep.sline.status() != Http::scUnauthorized)
947  return true;
948 
949  /*The server respond with Http::scUnauthorized and the peer configured
950  with "connection-auth=on" we know that the peer supports pinned
951  connections
952  */
953  if (_peer->connection_auth == 1)
954  return true;
955 
956  /*At this point peer has configured with "connection-auth=auto"
957  parameter so we need some extra checks to decide if we are going
958  to allow pinned connections or not
959  */
960 
961  /*if the peer configured with originserver just allow connection
962  pinning (squid 2.6 behaviour)
963  */
965  return true;
966 
967  /*if the connections it is already pinned it is OK*/
968  if (request->flags.pinned)
969  return true;
970 
971  /*Allow pinned connections only if the Proxy-support header exists in
972  reply and has in its list the "Session-Based-Authentication"
973  which means that the peer supports connection pinning.
974  */
975  if (rep.header.hasListMember(Http::HdrType::PROXY_SUPPORT, "Session-Based-Authentication", ','))
976  return true;
977 
978  return false;
979 }
980 
981 // Called when we parsed (and possibly adapted) the headers but
982 // had not starting storing (a.k.a., sending) the body yet.
983 void
985 {
987 
988  Ctx ctx = ctx_enter(entry->mem_obj->urlXXX());
989  HttpReply *rep = finalReply();
990  const Http::StatusCode statusCode = rep->sline.status();
991 
992  entry->timestampsSet();
993 
994  /* Check if object is cacheable or not based on reply code */
995  debugs(11, 3, "HTTP CODE: " << statusCode);
996 
997  if (StoreEntry *oldEntry = findPreviouslyCachedEntry(entry)) {
998  oldEntry->lock("HttpStateData::haveParsedReplyHeaders");
999  sawDateGoBack = rep->olderThan(oldEntry->hasFreshestReply());
1000  oldEntry->unlock("HttpStateData::haveParsedReplyHeaders");
1001  }
1002 
1005 
1006  bool varyFailure = false;
1007  if (rep->header.has(Http::HdrType::VARY)
1008 #if X_ACCELERATOR_VARY
1010 #endif
1011  ) {
1012  const SBuf vary(httpMakeVaryMark(request.getRaw(), rep));
1013 
1014  if (vary.isEmpty()) {
1015  // TODO: check whether such responses are shareable.
1016  // Do not share for now.
1017  entry->makePrivate(false);
1018  if (fwd->reforwardableStatus(rep->sline.status()))
1020  varyFailure = true;
1021  } else {
1022  entry->mem_obj->vary_headers = vary;
1023 
1024  // RFC 7231 section 7.1.4
1025  // Vary:* can be cached, but has mandatory revalidation
1026  static const SBuf asterisk("*");
1027  if (vary == asterisk)
1029  }
1030  }
1031 
1032  if (!varyFailure) {
1033  /*
1034  * If its not a reply that we will re-forward, then
1035  * allow the client to get it.
1036  */
1037  if (fwd->reforwardableStatus(rep->sline.status()))
1039 
1040  ReuseDecision decision(entry, statusCode);
1041 
1042  switch (reusableReply(decision)) {
1043 
1045  entry->makePrivate(false);
1046  break;
1047 
1049  if (!entry->makePublic()) {
1050  decision.make(ReuseDecision::doNotCacheButShare, "public key creation error");
1051  entry->makePrivate(true);
1052  }
1053  break;
1054 
1056  if (!entry->cacheNegatively()) {
1057  decision.make(ReuseDecision::doNotCacheButShare, "public key creation error");
1058  entry->makePrivate(true);
1059  }
1060  break;
1061 
1063  entry->makePrivate(true);
1064  break;
1065 
1066  default:
1067  assert(0);
1068  break;
1069  }
1070  debugs(11, 3, "decided: " << decision);
1071  }
1072 
1073  if (!ignoreCacheControl) {
1074  if (rep->cache_control) {
1075  // We are required to revalidate on many conditions.
1076  // For security reasons we do so even if storage was caused by refresh_pattern ignore-* option
1077 
1078  // CC:must-revalidate or CC:proxy-revalidate
1079  const bool ccMustRevalidate = (rep->cache_control->hasProxyRevalidate() || rep->cache_control->hasMustRevalidate());
1080 
1081  // CC:no-cache (only if there are no parameters)
1082  const bool ccNoCacheNoParams = rep->cache_control->hasNoCacheWithoutParameters();
1083 
1084  // CC:s-maxage=N
1085  const bool ccSMaxAge = rep->cache_control->hasSMaxAge();
1086 
1087  // CC:private (yes, these can sometimes be stored)
1088  const bool ccPrivate = rep->cache_control->hasPrivate();
1089 
1090  if (ccNoCacheNoParams || ccPrivate)
1092  else if (ccMustRevalidate || ccSMaxAge)
1094  }
1095 #if USE_HTTP_VIOLATIONS // response header Pragma::no-cache is undefined in HTTP
1096  else {
1097  // Expensive calculation. So only do it IF the CC: header is not present.
1098 
1099  /* HACK: Pragma: no-cache in _replies_ is not documented in HTTP,
1100  * but servers like "Active Imaging Webcast/2.0" sure do use it */
1101  if (rep->header.has(Http::HdrType::PRAGMA) &&
1102  rep->header.hasListMember(Http::HdrType::PRAGMA,"no-cache",','))
1104  }
1105 #endif
1106  }
1107 
1108 #if HEADERS_LOG
1109  headersLog(1, 0, request->method, rep);
1110 
1111 #endif
1112 
1113  ctx_exit(ctx);
1114 }
1115 
1118 {
1119  const HttpReply *rep = virginReply();
1123  static SBuf close("close", 5);
1124  if (httpHeaderHasConnDir(&rep->header, close))
1126 
1131  if (!flags.keepalive)
1133 
1137  if (flags.forceClose)
1139 
1144  if (!flags.request_sent) {
1145  debugs(11, 2, "Request not yet fully sent " << request->method << ' ' << entry->url());
1147  }
1148 
1161  if (!rep->keep_alive)
1163 
1164  return COMPLETE_PERSISTENT_MSG;
1165 }
1166 
1169 {
1170  debugs(11, 3, HERE << serverConnection << " eof=" << eof);
1171  if (eof) // already reached EOF
1173 
1174  /* If server fd is closing (but we have not been notified yet), stop Comm
1175  I/O to avoid assertions. TODO: Change Comm API to handle callers that
1176  want more I/O after async closing (usually initiated by others). */
1177  // XXX: add canReceive or s/canSend/canTalkToServer/
1180 
1186  if (lastChunk && flags.chunked)
1187  return statusIfComplete();
1188 
1189  const HttpReply *vrep = virginReply();
1190  debugs(11, 5, "persistentConnStatus: content_length=" << vrep->content_length);
1191 
1192  const int64_t clen = vrep->bodySize(request->method);
1193 
1194  debugs(11, 5, "persistentConnStatus: clen=" << clen);
1195 
1196  /* If the body size is unknown we must wait for EOF */
1197  if (clen < 0)
1198  return INCOMPLETE_MSG;
1199 
1202  if (clen > 0) {
1203  debugs(11,5, "payloadSeen=" << payloadSeen << " content_length=" << vrep->content_length);
1204 
1205  if (payloadSeen < vrep->content_length)
1206  return INCOMPLETE_MSG;
1207 
1208  if (payloadTruncated > 0) // already read more than needed
1209  return COMPLETE_NONPERSISTENT_MSG; // disable pconns
1210  }
1211 
1214  return statusIfComplete();
1215 }
1216 
1217 static void
1218 readDelayed(void *context, CommRead const &)
1219 {
1220  HttpStateData *state = static_cast<HttpStateData*>(context);
1221  state->flags.do_next_read = true;
1222  state->maybeReadVirginBody();
1223 }
1224 
1225 void
1227 {
1228  Must(!flags.do_next_read); // XXX: should have been set false by mayReadVirginBody()
1229  flags.do_next_read = false;
1230 
1231  debugs(11, 5, io.conn);
1232 
1233  // Bail out early on Comm::ERR_CLOSING - close handlers will tidy up for us
1234  if (io.flag == Comm::ERR_CLOSING) {
1235  debugs(11, 3, "http socket closing");
1236  return;
1237  }
1238 
1240  abortTransaction("store entry aborted while reading reply");
1241  return;
1242  }
1243 
1245  Must(io.conn->fd == serverConnection->fd);
1246 
1247  /*
1248  * Don't reset the timeout value here. The value should be
1249  * counting Config.Timeout.request and applies to the request
1250  * as a whole, not individual read() calls.
1251  * Plus, it breaks our lame *HalfClosed() detection
1252  */
1253 
1255  CommIoCbParams rd(this); // will be expanded with ReadNow results
1256  rd.conn = io.conn;
1258 
1259  if (rd.size <= 0) {
1260  assert(entry->mem_obj);
1261  AsyncCall::Pointer nilCall;
1262  entry->mem_obj->delayRead(DeferredRead(readDelayed, this, CommRead(io.conn, NULL, 0, nilCall)));
1263  return;
1264  }
1265 
1266  switch (Comm::ReadNow(rd, inBuf)) {
1267  case Comm::INPROGRESS:
1268  if (inBuf.isEmpty())
1269  debugs(33, 2, io.conn << ": no data to process, " << xstrerr(rd.xerrno));
1270  flags.do_next_read = true;
1272  return;
1273 
1274  case Comm::OK:
1275  {
1276  payloadSeen += rd.size;
1277 #if USE_DELAY_POOLS
1278  DelayId delayId = entry->mem_obj->mostBytesAllowed();
1279  delayId.bytesIn(rd.size);
1280 #endif
1281 
1282  statCounter.server.all.kbytes_in += rd.size;
1283  statCounter.server.http.kbytes_in += rd.size;
1284  ++ IOStats.Http.reads;
1285 
1286  int bin = 0;
1287  for (int clen = rd.size - 1; clen; ++bin)
1288  clen >>= 1;
1289 
1290  ++ IOStats.Http.read_hist[bin];
1291 
1293  }
1294 
1295  /* Continue to process previously read data */
1296  break;
1297 
1298  case Comm::ENDFILE: // close detected by 0-byte read
1299  eof = 1;
1300  flags.do_next_read = false;
1301 
1302  /* Continue to process previously read data */
1303  break;
1304 
1305  // case Comm::COMM_ERROR:
1306  default: // no other flags should ever occur
1307  debugs(11, 2, io.conn << ": read failure: " << xstrerr(rd.xerrno));
1308  const auto err = new ErrorState(ERR_READ_ERROR, Http::scBadGateway, fwd->request, fwd->al);
1309  err->xerrno = rd.xerrno;
1310  fwd->fail(err);
1311  flags.do_next_read = false;
1312  closeServer();
1313  mustStop("HttpStateData::readReply");
1314  return;
1315  }
1316 
1317  /* Process next response from buffer */
1318  processReply();
1319 }
1320 
1323 void
1325 {
1326 
1327  if (flags.handling1xx) { // we came back after handling a 1xx response
1328  debugs(11, 5, HERE << "done with 1xx handling");
1329  flags.handling1xx = false;
1331  }
1332 
1333  if (!flags.headers_parsed) { // have not parsed headers yet?
1334  PROF_start(HttpStateData_processReplyHeader);
1336  PROF_stop(HttpStateData_processReplyHeader);
1337 
1338  if (!continueAfterParsingHeader()) // parsing error or need more data
1339  return; // TODO: send errors to ICAP
1340 
1341  adaptOrFinalizeReply(); // may write to, abort, or "close" the entry
1342  }
1343 
1344  // kick more reads if needed and/or process the response body, if any
1345  PROF_start(HttpStateData_processReplyBody);
1346  processReplyBody(); // may call serverComplete()
1347  PROF_stop(HttpStateData_processReplyBody);
1348 }
1349 
1353 bool
1355 {
1356  if (flags.handling1xx) {
1357  debugs(11, 5, HERE << "wait for 1xx handling");
1359  return false;
1360  }
1361 
1362  if (!flags.headers_parsed && !eof) {
1363  debugs(11, 9, "needs more at " << inBuf.length());
1364  flags.do_next_read = true;
1368  maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
1369  return false;
1370  }
1371 
1375 
1376  if (flags.headers_parsed) { // parsed headers, possibly with errors
1377  // check for header parsing errors
1378  if (HttpReply *vrep = virginReply()) {
1379  const Http::StatusCode s = vrep->sline.status();
1380  const AnyP::ProtocolVersion &v = vrep->sline.version;
1381  if (s == Http::scInvalidHeader && v != Http::ProtocolVersion(0,9)) {
1382  debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Bad header encountered from " << entry->url() << " AKA " << request->url);
1384  } else if (s == Http::scHeaderTooLarge) {
1385  fwd->dontRetry(true);
1386  error = ERR_TOO_BIG;
1387  } else if (vrep->header.conflictingContentLength()) {
1388  fwd->dontRetry(true);
1390  } else if (vrep->header.unsupportedTe()) {
1391  fwd->dontRetry(true);
1393  } else {
1394  return true; // done parsing, got reply, and no error
1395  }
1396  } else {
1397  // parsed headers but got no reply
1398  debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: No reply at all for " << entry->url() << " AKA " << request->url);
1400  }
1401  } else {
1402  assert(eof);
1403  if (inBuf.length()) {
1405  debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Headers did not parse at all for " << entry->url() << " AKA " << request->url);
1406  } else {
1408  debugs(11, (request->flags.accelerated?DBG_IMPORTANT:2), "WARNING: HTTP: Invalid Response: No object data received for " << entry->url() << " AKA " << request->url);
1409  }
1410  }
1411 
1412  assert(error != ERR_NONE);
1413  entry->reset();
1415  flags.do_next_read = false;
1416  closeServer();
1417  mustStop("HttpStateData::continueAfterParsingHeader");
1418  return false; // quit on error
1419 }
1420 
1423 void
1425 {
1427 
1428  HttpReply *vrep = virginReply();
1429  int64_t clen = -1;
1430  if (!vrep->expectingBody(request->method, clen) || clen < 0)
1431  return; // no body or a body of unknown size, including chunked
1432 
1433  if (payloadSeen - payloadTruncated <= clen)
1434  return; // we did not read too much or already took care of the extras
1435 
1436  if (const int64_t extras = payloadSeen - payloadTruncated - clen) {
1437  // server sent more that the advertised content length
1438  debugs(11, 5, "payloadSeen=" << payloadSeen <<
1439  " clen=" << clen << '/' << vrep->content_length <<
1440  " truncated=" << payloadTruncated << '+' << extras);
1441 
1442  inBuf.chop(0, inBuf.length() - extras);
1443  payloadTruncated += extras;
1444  }
1445 }
1446 
1451 void
1453 {
1454  truncateVirginBody(); // if needed
1455  const char *data = inBuf.rawContent();
1456  int len = inBuf.length();
1458  inBuf.consume(len);
1459 }
1460 
1461 bool
1463 {
1464  const char *data = NULL;
1465  int len;
1466  bool wasThereAnException = false;
1467  assert(flags.chunked);
1470  MemBuf decodedData;
1471  decodedData.init();
1472  httpChunkDecoder->setPayloadBuffer(&decodedData);
1473  const bool doneParsing = httpChunkDecoder->parse(inBuf);
1474  inBuf = httpChunkDecoder->remaining(); // sync buffers after parse
1475  len = decodedData.contentSize();
1476  data=decodedData.content();
1478  if (doneParsing) {
1479  lastChunk = 1;
1480  flags.do_next_read = false;
1481  }
1482  SQUID_EXIT_THROWING_CODE(wasThereAnException);
1483  return wasThereAnException;
1484 }
1485 
1493 void
1495 {
1496  if (!flags.headers_parsed) {
1497  flags.do_next_read = true;
1499  return;
1500  }
1501 
1502 #if USE_ADAPTATION
1503  debugs(11,5, HERE << "adaptationAccessCheckPending=" << adaptationAccessCheckPending);
1505  return;
1506 
1507 #endif
1508 
1509  /*
1510  * At this point the reply headers have been parsed and consumed.
1511  * That means header content has been removed from readBuf and
1512  * it contains only body data.
1513  */
1514  if (entry->isAccepting()) {
1515  if (flags.chunked) {
1516  if (!decodeAndWriteReplyBody()) {
1517  flags.do_next_read = false;
1518  serverComplete();
1519  return;
1520  }
1521  } else
1522  writeReplyBody();
1523  }
1524 
1525  // storing/sending methods like earlier adaptOrFinalizeReply() or
1526  // above writeReplyBody() may release/abort the store entry.
1528  // TODO: In some cases (e.g., 304), we should keep persistent conn open.
1529  // Detect end-of-reply (and, hence, pool our idle pconn) earlier (ASAP).
1530  abortTransaction("store entry aborted while storing reply");
1531  return;
1532  } else
1533  switch (persistentConnStatus()) {
1534  case INCOMPLETE_MSG: {
1535  debugs(11, 5, "processReplyBody: INCOMPLETE_MSG from " << serverConnection);
1536  /* Wait for more data or EOF condition */
1538  if (flags.keepalive_broken) {
1540  } else {
1542  }
1543 
1544  flags.do_next_read = true;
1545  }
1546  break;
1547 
1548  case COMPLETE_PERSISTENT_MSG: {
1549  debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG from " << serverConnection);
1550 
1551  // TODO: Remove serverConnectionSaved but preserve exception safety.
1552 
1554  flags.do_next_read = false;
1555 
1557  closeHandler = NULL;
1558 
1559  Ip::Address client_addr; // XXX: Remove as unused. Why was it added?
1561  client_addr = request->client_addr;
1562 
1563  auto serverConnectionSaved = serverConnection;
1565  serverConnection = nullptr;
1566 
1567  bool ispinned = false; // TODO: Rename to isOrShouldBePinned
1568  if (request->flags.pinned) {
1569  ispinned = true;
1570  } else if (request->flags.connectionAuth && request->flags.authSent) {
1571  ispinned = true;
1572  }
1573 
1574  if (ispinned) {
1577  ConnStateData,
1578  notePinnedConnectionBecameIdle,
1579  ConnStateData::PinnedIdleContext(serverConnectionSaved, request));
1580  } else {
1581  // must not pool/share ispinned connections, even orphaned ones
1582  serverConnectionSaved->close();
1583  }
1584  } else {
1585  fwdPconnPool->push(serverConnectionSaved, request->url.host());
1586  }
1587 
1588  serverComplete();
1589  return;
1590  }
1591 
1593  debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG from " << serverConnection);
1594  if (flags.chunked && !lastChunk)
1595  entry->lengthWentBad("missing last-chunk");
1596 
1597  serverComplete();
1598  return;
1599  }
1600 
1602 }
1603 
1604 bool
1606 {
1607  // TODO: Be more precise here. For example, if/when reading trailer, we may
1608  // not be doneWithServer() yet, but we should return false. Similarly, we
1609  // could still be writing the request body after receiving the whole reply.
1610  return !doneWithServer();
1611 }
1612 
1613 void
1615 {
1616  // too late to read
1618  return;
1619 
1620  if (!maybeMakeSpaceAvailable(false))
1621  return;
1622 
1623  // XXX: get rid of the do_next_read flag
1624  // check for the proper reasons preventing read(2)
1625  if (!flags.do_next_read)
1626  return;
1627 
1628  flags.do_next_read = false;
1629 
1630  // must not already be waiting for read(2) ...
1632 
1633  // wait for read(2) to be possible.
1635  AsyncCall::Pointer call = JobCallback(11, 5, Dialer, this, HttpStateData::readReply);
1637 }
1638 
1639 bool
1641 {
1642  // how much we are allowed to buffer
1643  const int limitBuffer = (flags.headers_parsed ? Config.readAheadGap : Config.maxReplyHeaderSize);
1644 
1645  if (limitBuffer < 0 || inBuf.length() >= (SBuf::size_type)limitBuffer) {
1646  // when buffer is at or over limit already
1647  debugs(11, 7, "will not read up to " << limitBuffer << ". buffer has (" << inBuf.length() << "/" << inBuf.spaceSize() << ") from " << serverConnection);
1648  debugs(11, DBG_DATA, "buffer has {" << inBuf << "}");
1649  // Process next response from buffer
1650  processReply();
1651  return false;
1652  }
1653 
1654  // how much we want to read
1655  const size_t read_size = calcBufferSpaceToReserve(inBuf.spaceSize(), (limitBuffer - inBuf.length()));
1656 
1657  if (!read_size) {
1658  debugs(11, 7, "will not read up to " << read_size << " into buffer (" << inBuf.length() << "/" << inBuf.spaceSize() << ") from " << serverConnection);
1659  return false;
1660  }
1661 
1662  // just report whether we could grow or not, do not actually do it
1663  if (doGrow)
1664  return (read_size >= 2);
1665 
1666  // we may need to grow the buffer
1667  inBuf.reserveSpace(read_size);
1668  debugs(11, 8, (!flags.do_next_read ? "will not" : "may") <<
1669  " read up to " << read_size << " bytes info buf(" << inBuf.length() << "/" << inBuf.spaceSize() <<
1670  ") from " << serverConnection);
1671 
1672  return (inBuf.spaceSize() >= 2); // only read if there is 1+ bytes of space available
1673 }
1674 
1676 void
1678 {
1679  debugs(11, 5, HERE << serverConnection << ": size " << io.size << ": errflag " << io.flag << ".");
1680 #if URL_CHECKSUM_DEBUG
1681 
1682  entry->mem_obj->checkUrlChecksum();
1683 #endif
1684 
1685  // XXX: Keep in sync with Client::sentRequestBody().
1686  // TODO: Extract common parts.
1687 
1688  if (io.size > 0) {
1689  fd_bytes(io.fd, io.size, FD_WRITE);
1690  statCounter.server.all.kbytes_out += io.size;
1691  statCounter.server.http.kbytes_out += io.size;
1692  }
1693 
1694  if (io.flag == Comm::ERR_CLOSING)
1695  return;
1696 
1697  // both successful and failed writes affect response times
1699 
1700  if (io.flag) {
1701  const auto err = new ErrorState(ERR_WRITE_ERROR, Http::scBadGateway, fwd->request, fwd->al);
1702  err->xerrno = io.xerrno;
1703  fwd->fail(err);
1704  closeServer();
1705  mustStop("HttpStateData::wroteLast");
1706  return;
1707  }
1708 
1709  sendComplete();
1710 }
1711 
1713 void
1715 {
1716  /*
1717  * Set the read timeout here because it hasn't been set yet.
1718  * We only set the read timeout after the request has been
1719  * fully written to the peer. If we start the timeout
1720  * after connection establishment, then we are likely to hit
1721  * the timeout for POST/PUT requests that have very large
1722  * request bodies.
1723  */
1725  AsyncCall::Pointer timeoutCall = JobCallback(11, 5,
1726  TimeoutDialer, this, HttpStateData::httpTimeout);
1727 
1729  flags.request_sent = true;
1730 }
1731 
1732 void
1734 {
1735  debugs(11,5, HERE << "closing HTTP server " << serverConnection << " this " << this);
1736 
1740  closeHandler = NULL;
1742  }
1743 }
1744 
1745 bool
1747 {
1749 }
1750 
1751 /*
1752  * Fixup authentication request headers for special cases
1753  */
1754 static void
1756 {
1757  /* Nothing to do unless we are forwarding to a peer */
1758  if (!flags.peering)
1759  return;
1760 
1761  // This request is going "through" rather than "to" our _peer.
1762  if (flags.tunneling)
1763  return;
1764 
1765  /* Needs to be explicitly enabled */
1766  if (!request->peer_login)
1767  return;
1768 
1770  /* Maybe already dealt with? */
1771  if (hdr_out->has(header))
1772  return;
1773 
1774  /* Nothing to do here for PASSTHRU */
1775  if (strcmp(request->peer_login, "PASSTHRU") == 0)
1776  return;
1777 
1778  // Dangerous and undocumented PROXYPASS is a single-signon to servers with
1779  // the proxy password. Only Basic Authentication can work this way. This
1780  // statement forwards a "basic" Proxy-Authorization value from our client
1781  // to an originserver peer. Other PROXYPASS cases are handled lower.
1782  if (flags.toOrigin &&
1783  strcmp(request->peer_login, "PROXYPASS") == 0 &&
1785 
1786  const char *auth = hdr_in->getStr(Http::HdrType::PROXY_AUTHORIZATION);
1787 
1788  if (auth && strncasecmp(auth, "basic ", 6) == 0) {
1789  hdr_out->putStr(header, auth);
1790  return;
1791  }
1792  }
1793 
1794  char loginbuf[base64_encode_len(MAX_LOGIN_SZ)];
1795  size_t blen;
1796  struct base64_encode_ctx ctx;
1797  base64_encode_init(&ctx);
1798 
1799  /* Special mode to pass the username to the upstream cache */
1800  if (*request->peer_login == '*') {
1801  const char *username = "-";
1802 
1803  if (request->extacl_user.size())
1804  username = request->extacl_user.termedBuf();
1805 #if USE_AUTH
1806  else if (request->auth_user_request != NULL)
1807  username = request->auth_user_request->username();
1808 #endif
1809 
1810  blen = base64_encode_update(&ctx, loginbuf, strlen(username), reinterpret_cast<const uint8_t*>(username));
1811  blen += base64_encode_update(&ctx, loginbuf+blen, strlen(request->peer_login +1), reinterpret_cast<const uint8_t*>(request->peer_login +1));
1812  blen += base64_encode_final(&ctx, loginbuf+blen);
1813  httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf);
1814  return;
1815  }
1816 
1817  /* external_acl provided credentials */
1818  if (request->extacl_user.size() && request->extacl_passwd.size() &&
1819  (strcmp(request->peer_login, "PASS") == 0 ||
1820  strcmp(request->peer_login, "PROXYPASS") == 0)) {
1821 
1822  blen = base64_encode_update(&ctx, loginbuf, request->extacl_user.size(), reinterpret_cast<const uint8_t*>(request->extacl_user.rawBuf()));
1823  blen += base64_encode_update(&ctx, loginbuf+blen, 1, reinterpret_cast<const uint8_t*>(":"));
1824  blen += base64_encode_update(&ctx, loginbuf+blen, request->extacl_passwd.size(), reinterpret_cast<const uint8_t*>(request->extacl_passwd.rawBuf()));
1825  blen += base64_encode_final(&ctx, loginbuf+blen);
1826  httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf);
1827  return;
1828  }
1829  // if no external user credentials are available to fake authentication with PASS acts like PASSTHRU
1830  if (strcmp(request->peer_login, "PASS") == 0)
1831  return;
1832 
1833  /* Kerberos login to peer */
1834 #if HAVE_AUTH_MODULE_NEGOTIATE && HAVE_KRB5 && HAVE_GSSAPI
1835  if (strncmp(request->peer_login, "NEGOTIATE",strlen("NEGOTIATE")) == 0) {
1836  char *Token=NULL;
1837  char *PrincipalName=NULL,*p;
1838  int negotiate_flags = 0;
1839 
1840  if ((p=strchr(request->peer_login,':')) != NULL ) {
1841  PrincipalName=++p;
1842  }
1843  if (request->flags.auth_no_keytab) {
1844  negotiate_flags |= PEER_PROXY_NEGOTIATE_NOKEYTAB;
1845  }
1846  Token = peer_proxy_negotiate_auth(PrincipalName, request->peer_host, negotiate_flags);
1847  if (Token) {
1848  httpHeaderPutStrf(hdr_out, header, "Negotiate %s",Token);
1849  }
1850  return;
1851  }
1852 #endif /* HAVE_KRB5 && HAVE_GSSAPI */
1853 
1854  blen = base64_encode_update(&ctx, loginbuf, strlen(request->peer_login), reinterpret_cast<const uint8_t*>(request->peer_login));
1855  blen += base64_encode_final(&ctx, loginbuf+blen);
1856  httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf);
1857  return;
1858 }
1859 
1860 /*
1861  * build request headers and append them to a given MemBuf
1862  * used by buildRequestPrefix()
1863  * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
1864  */
1865 void
1867  StoreEntry * entry,
1868  const AccessLogEntryPointer &al,
1869  HttpHeader * hdr_out,
1870  const Http::StateFlags &flags)
1871 {
1872  /* building buffer for complex strings */
1873 #define BBUF_SZ (MAX_URL+32)
1874  LOCAL_ARRAY(char, bbuf, BBUF_SZ);
1875  LOCAL_ARRAY(char, ntoabuf, MAX_IPSTRLEN);
1876  const HttpHeader *hdr_in = &request->header;
1877  const HttpHeaderEntry *e = NULL;
1879  assert (hdr_out->owner == hoRequest);
1880 
1881  /* use our IMS header if the cached entry has Last-Modified time */
1882  if (request->lastmod > -1)
1884 
1885  // Add our own If-None-Match field if the cached entry has a strong ETag.
1886  // copyOneHeaderFromClientsideRequestToUpstreamRequest() adds client ones.
1887  if (request->etag.size() > 0) {
1889  request->etag.termedBuf()));
1890  }
1891 
1892  bool we_do_ranges = decideIfWeDoRanges (request);
1893 
1894  String strConnection (hdr_in->getList(Http::HdrType::CONNECTION));
1895 
1896  while ((e = hdr_in->getEntry(&pos)))
1897  copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, hdr_out, we_do_ranges, flags);
1898 
1899  /* Abstraction break: We should interpret multipart/byterange responses
1900  * into offset-length data, and this works around our inability to do so.
1901  */
1902  if (!we_do_ranges && request->multipartRangeRequest()) {
1903  /* don't cache the result */
1904  request->flags.cachable = false;
1905  /* pretend it's not a range request */
1906  request->ignoreRange("want to request the whole object");
1907  request->flags.isRanged = false;
1908  }
1909 
1910  hdr_out->addVia(request->http_ver, hdr_in);
1911 
1912  if (request->flags.accelerated) {
1913  /* Append Surrogate-Capabilities */
1914  String strSurrogate(hdr_in->getList(Http::HdrType::SURROGATE_CAPABILITY));
1915 #if USE_SQUID_ESI
1916  snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"", Config.Accel.surrogate_id);
1917 #else
1918  snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0\"", Config.Accel.surrogate_id);
1919 #endif
1920  strListAdd(&strSurrogate, bbuf, ',');
1921  hdr_out->putStr(Http::HdrType::SURROGATE_CAPABILITY, strSurrogate.termedBuf());
1922  }
1923 
1925  if (strcmp(opt_forwarded_for, "delete") != 0) {
1926 
1927  String strFwd = hdr_in->getList(Http::HdrType::X_FORWARDED_FOR);
1928 
1929  // if we cannot double strFwd size, then it grew past 50% of the limit
1930  if (!strFwd.canGrowBy(strFwd.size())) {
1931  // There is probably a forwarding loop with Via detection disabled.
1932  // If we do nothing, String will assert on overflow soon.
1933  // TODO: Terminate all transactions with huge XFF?
1934  strFwd = "error";
1935 
1936  static int warnedCount = 0;
1937  if (warnedCount++ < 100) {
1938  const SBuf url(entry ? SBuf(entry->url()) : request->effectiveRequestUri());
1939  debugs(11, DBG_IMPORTANT, "Warning: likely forwarding loop with " << url);
1940  }
1941  }
1942 
1943  if (strcmp(opt_forwarded_for, "on") == 0) {
1945  if ( request->client_addr.isNoAddr() )
1946  strListAdd(&strFwd, "unknown", ',');
1947  else
1948  strListAdd(&strFwd, request->client_addr.toStr(ntoabuf, MAX_IPSTRLEN), ',');
1949  } else if (strcmp(opt_forwarded_for, "off") == 0) {
1951  strListAdd(&strFwd, "unknown", ',');
1952  } else if (strcmp(opt_forwarded_for, "transparent") == 0) {
1954  } else if (strcmp(opt_forwarded_for, "truncate") == 0) {
1956  if ( request->client_addr.isNoAddr() )
1957  strFwd = "unknown";
1958  else
1959  strFwd = request->client_addr.toStr(ntoabuf, MAX_IPSTRLEN);
1960  }
1961  if (strFwd.size() > 0)
1962  hdr_out->putStr(Http::HdrType::X_FORWARDED_FOR, strFwd.termedBuf());
1963  }
1966  /* append Host if not there already */
1967  if (!hdr_out->has(Http::HdrType::HOST)) {
1968  if (request->peer_domain) {
1970  } else {
1971  SBuf authority = request->url.authority();
1972  hdr_out->putStr(Http::HdrType::HOST, authority.c_str());
1973  }
1974  }
1975 
1976  /* append Authorization if known in URL, not in header and going direct */
1977  if (!hdr_out->has(Http::HdrType::AUTHORIZATION)) {
1978  if (flags.toOrigin && !request->url.userInfo().isEmpty()) {
1979  static char result[base64_encode_len(MAX_URL*2)]; // should be big enough for a single URI segment
1980  struct base64_encode_ctx ctx;
1981  base64_encode_init(&ctx);
1982  size_t blen = base64_encode_update(&ctx, result, request->url.userInfo().length(), reinterpret_cast<const uint8_t*>(request->url.userInfo().rawContent()));
1983  blen += base64_encode_final(&ctx, result+blen);
1984  result[blen] = '\0';
1985  if (blen)
1986  httpHeaderPutStrf(hdr_out, Http::HdrType::AUTHORIZATION, "Basic %.*s", (int)blen, result);
1987  }
1988  }
1989 
1990  /* Fixup (Proxy-)Authorization special cases. Plain relaying dealt with above */
1991  httpFixupAuthentication(request, hdr_in, hdr_out, flags);
1992 
1993  /* append Cache-Control, add max-age if not there already */
1994  {
1995  HttpHdrCc *cc = hdr_in->getCc();
1996 
1997  if (!cc)
1998  cc = new HttpHdrCc();
1999 
2000 #if 0 /* see bug 2330 */
2001  /* Set no-cache if determined needed but not found */
2002  if (request->flags.nocache)
2004 #endif
2005 
2006  /* Add max-age only without no-cache */
2007  if (!cc->hasMaxAge() && !cc->hasNoCache()) {
2008  // XXX: performance regression. c_str() reallocates
2010  cc->maxAge(getMaxAge(entry ? entry->url() : tmp.c_str()));
2011  }
2012 
2013  /* Enforce sibling relations */
2014  if (flags.only_if_cached)
2015  cc->onlyIfCached(true);
2016 
2017  hdr_out->putCc(cc);
2018 
2019  delete cc;
2020  }
2021 
2022  // Always send Connection because HTTP/1.0 servers need explicit
2023  // "keep-alive", HTTP/1.1 servers need explicit "close", Upgrade recipients
2024  // need bare "upgrade", and we do not always know the server expectations.
2025  if (!hdr_out->has(Http::HdrType::CONNECTION)) // forwardUpgrade() may add it
2026  hdr_out->putStr(Http::HdrType::CONNECTION, flags.keepalive ? "keep-alive" : "close");
2027 
2028  /* append Front-End-Https */
2029  if (flags.front_end_https) {
2031  hdr_out->putStr(Http::HdrType::FRONT_END_HTTPS, "On");
2032  }
2033 
2034  if (flags.chunked_request) {
2035  // Do not just copy the original value so that if the client-side
2036  // starts decode other encodings, this code may remain valid.
2037  hdr_out->putStr(Http::HdrType::TRANSFER_ENCODING, "chunked");
2038  }
2039 
2040  /* Now mangle the headers. */
2041  httpHdrMangleList(hdr_out, request, al, ROR_REQUEST);
2042 
2043  strConnection.clean();
2044 }
2045 
2048 void
2050 {
2052  return; // forward nothing by default
2053 
2054  /* RFC 7230 section 6.7 paragraph 10:
2055  * A server MUST ignore an Upgrade header field that is received in
2056  * an HTTP/1.0 request.
2057  */
2058  if (request->http_ver == Http::ProtocolVersion(1,0))
2059  return;
2060 
2061  const auto &hdrIn = request->header;
2062  if (!hdrIn.has(Http::HdrType::UPGRADE))
2063  return;
2064  const auto upgradeIn = hdrIn.getList(Http::HdrType::UPGRADE);
2065 
2066  String upgradeOut;
2067 
2068  ACLFilledChecklist ch(nullptr, request.getRaw());
2069  ch.al = fwd->al;
2070  const char *pos = nullptr;
2071  const char *offeredStr = nullptr;
2072  int offeredStrLen = 0;
2073  while (strListGetItem(&upgradeIn, ',', &offeredStr, &offeredStrLen, &pos)) {
2074  const ProtocolView offeredProto(offeredStr, offeredStrLen);
2075  debugs(11, 5, "checks all rules applicable to " << offeredProto);
2076  Config.http_upgrade_request_protocols->forApplicable(offeredProto, [&ch, offeredStr, offeredStrLen, &upgradeOut] (const SBuf &cfgProto, const acl_access *guard) {
2077  debugs(11, 5, "checks " << cfgProto << " rule(s)");
2078  ch.changeAcl(guard);
2079  const auto answer = ch.fastCheck();
2080  if (answer.implicit)
2081  return false; // keep looking for an explicit rule match
2082  if (answer.allowed())
2083  strListAdd(upgradeOut, offeredStr, offeredStrLen);
2084  // else drop the offer (explicitly denied cases and ACL errors)
2085  return true; // stop after an explicit rule match or an error
2086  });
2087  }
2088 
2089  if (upgradeOut.size()) {
2090  hdrOut.putStr(Http::HdrType::UPGRADE, upgradeOut.termedBuf());
2091 
2092  /* RFC 7230 section 6.7 paragraph 10:
2093  * When Upgrade is sent, the sender MUST also send a Connection header
2094  * field that contains an "upgrade" connection option, in
2095  * order to prevent Upgrade from being accidentally forwarded by
2096  * intermediaries that might not implement the listed protocols.
2097  *
2098  * NP: Squid does not truly implement the protocol(s) in this Upgrade.
2099  * For now we are treating an explicit blind tunnel as "implemented"
2100  * regardless of the security implications.
2101  */
2102  hdrOut.putStr(Http::HdrType::CONNECTION, "upgrade");
2103 
2104  // Connection:close and Connection:keepalive confuse some Upgrade
2105  // recipients, so we do not send those headers. Our Upgrade request
2106  // implicitly offers connection persistency per HTTP/1.1 defaults.
2107  // Update the keepalive flag to reflect that offer.
2108  // * If the server upgrades, then we would not be talking HTTP past the
2109  // HTTP 101 control message, and HTTP persistence would be irrelevant.
2110  // * Otherwise, our request will contradict onoff.server_pconns=off or
2111  // other no-keepalive conditions (if any). We compensate by copying
2112  // the original no-keepalive decision now and honoring it later.
2114  flags.keepalive = true; // should already be true in most cases
2115  }
2116 }
2117 
2122 void
2123 copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request, HttpHeader * hdr_out, const int we_do_ranges, const Http::StateFlags &flags)
2124 {
2125  debugs(11, 5, "httpBuildRequestHeader: " << e->name << ": " << e->value );
2126 
2127  switch (e->id) {
2128 
2136  if (!flags.toOrigin && request->peer_login &&
2137  (strcmp(request->peer_login, "PASS") == 0 ||
2138  strcmp(request->peer_login, "PROXYPASS") == 0 ||
2139  strcmp(request->peer_login, "PASSTHRU") == 0)) {
2140  hdr_out->addEntry(e->clone());
2141  }
2142  break;
2143 
2147  case Http::HdrType::TE:
2150  case Http::HdrType::TRAILER:
2152  break;
2153 
2156  break;
2157 
2164  if (!flags.toOriginPeer()) {
2165  hdr_out->addEntry(e->clone());
2166  } else {
2171  if (request->peer_login &&
2172  (strcmp(request->peer_login, "PASS") == 0 ||
2173  strcmp(request->peer_login, "PASSTHRU") == 0 ||
2174  strcmp(request->peer_login, "PROXYPASS") == 0)) {
2175  hdr_out->addEntry(e->clone());
2176  }
2177  }
2178 
2179  break;
2180 
2181  case Http::HdrType::HOST:
2188  if (request->peer_domain)
2189  hdr_out->putStr(Http::HdrType::HOST, request->peer_domain);
2190  else if (request->flags.redirected && !Config.onoff.redir_rewrites_host)
2191  hdr_out->addEntry(e->clone());
2192  else {
2193  SBuf authority = request->url.authority();
2194  hdr_out->putStr(Http::HdrType::HOST, authority.c_str());
2195  }
2196 
2197  break;
2198 
2207  // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
2208  if (hdr_out->has(Http::HdrType::IF_MODIFIED_SINCE))
2209  break;
2210  else if (Config.onoff.cache_miss_revalidate || !request->flags.cachable || request->flags.auth)
2211  hdr_out->addEntry(e->clone());
2212  break;
2213 
2222  // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
2223  if (hdr_out->hasListMember(Http::HdrType::IF_MATCH, "*", ',') || Config.onoff.cache_miss_revalidate || !request->flags.cachable || request->flags.auth)
2224  hdr_out->addEntry(e->clone());
2225  break;
2226 
2231  const int64_t hops = e->getInt64();
2232 
2233  if (hops > 0)
2234  hdr_out->putInt64(Http::HdrType::MAX_FORWARDS, hops - 1);
2235  }
2236 
2237  break;
2238 
2239  case Http::HdrType::VIA:
2244  if (!Config.onoff.via)
2245  hdr_out->addEntry(e->clone());
2246 
2247  break;
2248 
2249  case Http::HdrType::RANGE:
2250 
2252 
2256  if (!we_do_ranges)
2257  hdr_out->addEntry(e->clone());
2258 
2259  break;
2260 
2261  case Http::HdrType::PROXY_CONNECTION: // SHOULD ignore. But doing so breaks things.
2262  break;
2263 
2265  // pass through unless we chunk; also, keeping this away from default
2266  // prevents request smuggling via Connection: Content-Length tricks
2267  if (!flags.chunked_request)
2268  hdr_out->addEntry(e->clone());
2269  break;
2270 
2272 
2277  break;
2278 
2282  if (!flags.front_end_https)
2283  hdr_out->addEntry(e->clone());
2284 
2285  break;
2286 
2287  default:
2291  if (strConnection.size()>0 && strListIsMember(&strConnection, e->name, ',')) {
2292  debugs(11, 2, "'" << e->name << "' header cropped by Connection: definition");
2293  return;
2294  }
2295 
2296  hdr_out->addEntry(e->clone());
2297  }
2298 }
2299 
2300 bool
2302 {
2303  bool result = true;
2304  /* decide if we want to do Ranges ourselves
2305  * and fetch the whole object now)
2306  * We want to handle Ranges ourselves iff
2307  * - we can actually parse client Range specs
2308  * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
2309  * - reply will be cachable
2310  * (If the reply will be uncachable we have to throw it away after
2311  * serving this request, so it is better to forward ranges to
2312  * the server and fetch only the requested content)
2313  */
2314 
2315  int64_t roffLimit = request->getRangeOffsetLimit();
2316 
2317  if (NULL == request->range || !request->flags.cachable
2319  result = false;
2320 
2321  debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
2322  request->range << ", cachable: " <<
2323  request->flags.cachable << "; we_do_ranges: " << result);
2324 
2325  return result;
2326 }
2327 
2328 /* build request prefix and append it to a given MemBuf;
2329  * return the length of the prefix */
2330 mb_size_t
2332 {
2333  const int offset = mb->size;
2334  /* Uses a local httpver variable to print the HTTP label
2335  * since the HttpRequest may have an older version label.
2336  * XXX: This could create protocol bugs as the headers sent and
2337  * flow control should all be based on the HttpRequest version
2338  * not the one we are sending. Needs checking.
2339  */
2340  const AnyP::ProtocolVersion httpver = Http::ProtocolVersion();
2342  mb->appendf(SQUIDSBUFPH " " SQUIDSBUFPH " %s/%d.%d\r\n",
2344  SQUIDSBUFPRINT(url),
2346  httpver.major,httpver.minor);
2347  /* build and pack headers */
2348  {
2349  HttpHeader hdr(hoRequest);
2350  forwardUpgrade(hdr); // before httpBuildRequestHeader() for CONNECTION
2352 
2354  request->flags.authSent = true;
2355  else if (hdr.has(Http::HdrType::AUTHORIZATION))
2356  request->flags.authSent = true;
2357 
2358  // The late placement of this check supports reply_header_add mangling,
2359  // but also complicates optimizing upgradeHeaderOut-like lookups.
2360  if (hdr.has(Http::HdrType::UPGRADE)) {
2363  }
2364 
2365  hdr.packInto(mb);
2366  hdr.clean();
2367  }
2368  /* append header terminator */
2369  mb->append(crlf, 2);
2370  return mb->size - offset;
2371 }
2372 
2373 /* This will be called when connect completes. Write request. */
2374 bool
2376 {
2377  MemBuf mb;
2378 
2379  debugs(11, 5, HERE << serverConnection << ", request " << request << ", this " << this << ".");
2380 
2382  debugs(11,3, HERE << "cannot send request to closing " << serverConnection);
2383  assert(closeHandler != NULL);
2384  return false;
2385  }
2386 
2388  AsyncCall::Pointer timeoutCall = JobCallback(11, 5,
2389  TimeoutDialer, this, HttpStateData::httpTimeout);
2391  flags.do_next_read = true;
2393 
2394  if (request->body_pipe != NULL) {
2395  if (!startRequestBodyFlow()) // register to receive body data
2396  return false;
2398  requestSender = JobCallback(11,5,
2399  Dialer, this, HttpStateData::sentRequestBody);
2400 
2402  // use chunked encoding if we do not know the length
2403  if (request->content_length < 0)
2404  flags.chunked_request = true;
2405  } else {
2408  requestSender = JobCallback(11,5,
2409  Dialer, this, HttpStateData::wroteLast);
2410  }
2411 
2412  /*
2413  * Is keep-alive okay for all request methods?
2414  */
2416  flags.keepalive = true;
2417  else if (request->flags.pinned)
2419  else if (!Config.onoff.server_pconns)
2420  flags.keepalive = false;
2421  else if (flags.tunneling)
2422  // tunneled non pinned bumped requests must not keepalive
2424  else if (_peer == NULL)
2425  flags.keepalive = true;
2426  else if (_peer->stats.n_keepalives_sent < 10)
2427  flags.keepalive = true;
2428  else if ((double) _peer->stats.n_keepalives_recv /
2429  (double) _peer->stats.n_keepalives_sent > 0.50)
2430  flags.keepalive = true;
2431 
2432  if (_peer && !flags.tunneling) {
2433  /*The old code here was
2434  if (neighborType(_peer, request->url) == PEER_SIBLING && ...
2435  which is equivalent to:
2436  if (neighborType(_peer, URL()) == PEER_SIBLING && ...
2437  or better:
2438  if (((_peer->type == PEER_MULTICAST && p->options.mcast_siblings) ||
2439  _peer->type == PEER_SIBLINGS ) && _peer->options.allow_miss)
2440  flags.only_if_cached = 1;
2441 
2442  But I suppose it was a bug
2443  */
2445  flags.only_if_cached = true;
2446 
2448  }
2449 
2450  mb.init();
2452  buildRequestPrefix(&mb);
2453 
2454  debugs(11, 2, "HTTP Server " << serverConnection);
2455  debugs(11, 2, "HTTP Server REQUEST:\n---------\n" << mb.buf << "\n----------");
2456 
2458  return true;
2459 }
2460 
2461 bool
2463 {
2464  // parent's implementation can handle the no-encoding case
2465  if (!flags.chunked_request)
2467 
2468  MemBuf raw;
2469 
2471  if (!requestBodySource->getMoreData(raw))
2472  return false; // no request body bytes to chunk yet
2473 
2474  // optimization: pre-allocate buffer size that should be enough
2475  const mb_size_t rawDataSize = raw.contentSize();
2476  // we may need to send: hex-chunk-size CRLF raw-data CRLF last-chunk
2477  buf.init(16 + 2 + rawDataSize + 2 + 5, raw.max_capacity);
2478 
2479  buf.appendf("%x\r\n", static_cast<unsigned int>(rawDataSize));
2480  buf.append(raw.content(), rawDataSize);
2481  buf.append("\r\n", 2);
2482 
2483  Must(rawDataSize > 0); // we did not accidentally created last-chunk above
2484 
2485  // Do not send last-chunk unless we successfully received everything
2488  flags.sentLastChunk = true;
2489  buf.append("0\r\n\r\n", 5);
2490  }
2491 
2492  return true;
2493 }
2494 
2495 void
2497 {
2498  debugs(11, 3, fwd->request->method << ' ' << fwd->entry->url());
2499  AsyncJob::Start(new HttpStateData(fwd));
2500 }
2501 
2502 void
2504 {
2505  if (!sendRequest()) {
2506  debugs(11, 3, "httpStart: aborted");
2507  mustStop("HttpStateData::start failed");
2508  return;
2509  }
2510 
2511  ++ statCounter.server.all.requests;
2512  ++ statCounter.server.http.requests;
2513 
2514  /*
2515  * We used to set the read timeout here, but not any more.
2516  * Now its set in httpSendComplete() after the full request,
2517  * including request body, has been written to the server.
2518  */
2519 }
2520 
2522 bool
2524 {
2525 #if USE_HTTP_VIOLATIONS
2526  if (!Config.accessList.brokenPosts) {
2527  debugs(11, 5, HERE << "No brokenPosts list");
2528  return false;
2529  }
2530 
2532  ch.al = fwd->al;
2533  ch.syncAle(originalRequest().getRaw(), nullptr);
2534  if (!ch.fastCheck().allowed()) {
2535  debugs(11, 5, HERE << "didn't match brokenPosts");
2536  return false;
2537  }
2538 
2540  debugs(11, 3, HERE << "ignoring broken POST for closed " << serverConnection);
2541  assert(closeHandler != NULL);
2542  return true; // prevent caller from proceeding as if nothing happened
2543  }
2544 
2545  debugs(11, 3, "finishingBrokenPost: fixing broken POST");
2547  requestSender = JobCallback(11,5,
2548  Dialer, this, HttpStateData::wroteLast);
2550  return true;
2551 #else
2552  return false;
2553 #endif /* USE_HTTP_VIOLATIONS */
2554 }
2555 
2557 bool
2559 {
2560  if (flags.sentLastChunk) {
2561  debugs(11, 5, HERE << "already sent last-chunk");
2562  return false;
2563  }
2564 
2565  Must(receivedWholeRequestBody); // or we should not be sending last-chunk
2566  flags.sentLastChunk = true;
2567 
2569  requestSender = JobCallback(11,5, Dialer, this, HttpStateData::wroteLast);
2570  Comm::Write(serverConnection, "0\r\n\r\n", 5, requestSender, NULL);
2571  return true;
2572 }
2573 
2574 void
2576 {
2578  debugs(11,5, HERE << serverConnection);
2579 
2580  // do we need to write something after the last body byte?
2582  return;
2584  return;
2585 
2586  sendComplete();
2587 }
2588 
2589 // more origin request body data is available
2590 void
2592 {
2594  // XXX: we should check this condition in other callbacks then!
2595  // TODO: Check whether this can actually happen: We should unsubscribe
2596  // as a body consumer when the above condition(s) are detected.
2597  debugs(11, DBG_IMPORTANT, HERE << "Transaction aborted while reading HTTP body");
2598  return;
2599  }
2600 
2602 
2603  if (requestBodySource->buf().hasContent()) {
2604  // XXX: why does not this trigger a debug message on every request?
2605 
2607  flags.abuse_detected = true;
2608  debugs(11, DBG_IMPORTANT, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << request->client_addr << "' -> '" << entry->url() << "'" );
2609 
2610  if (virginReply()->sline.status() == Http::scInvalidHeader) {
2611  closeServer();
2612  mustStop("HttpStateData::handleMoreRequestBodyAvailable");
2613  return;
2614  }
2615  }
2616  }
2617 
2619 }
2620 
2621 // premature end of the request body
2622 void
2624 {
2626  if (entry->isEmpty()) {
2627  debugs(11, 3, "request body aborted: " << serverConnection);
2628  // We usually get here when ICAP REQMOD aborts during body processing.
2629  // We might also get here if client-side aborts, but then our response
2630  // should not matter because either client-side will provide its own or
2631  // there will be no response at all (e.g., if the the client has left).
2633  static const auto d = MakeNamedErrorDetail("SRV_REQMOD_REQ_BODY");
2634  err->detailError(d);
2635  fwd->fail(err);
2636  }
2637 
2638  abortTransaction("request body producer aborted");
2639 }
2640 
2641 // called when we wrote request headers(!) or a part of the body
2642 void
2644 {
2645  if (io.size > 0)
2646  statCounter.server.http.kbytes_out += io.size;
2647 
2649 }
2650 
2651 void
2652 HttpStateData::abortAll(const char *reason)
2653 {
2654  debugs(11,5, HERE << "aborting transaction for " << reason <<
2655  "; " << serverConnection << ", this " << this);
2656  mustStop(reason);
2657 }
2658 
2660  : answer(HttpStateData::ReuseDecision::reuseNot), reason(nullptr), entry(e), statusCode(code) {}
2661 
2664 {
2665  answer = ans;
2666  reason = why;
2667  return answer;
2668 }
2669 
2670 std::ostream &operator <<(std::ostream &os, const HttpStateData::ReuseDecision &d)
2671 {
2672  static const char *ReuseMessages[] = {
2673  "do not cache and do not share", // reuseNot
2674  "cache positively and share", // cachePositively
2675  "cache negatively and share", // cacheNegatively
2676  "do not cache but share" // doNotCacheButShare
2677  };
2678 
2681  return os << ReuseMessages[d.answer] << " because " << d.reason <<
2682  "; HTTP status " << d.statusCode << " " << *(d.entry);
2683 }
2684 
const MemBuf & buf() const
Definition: BodyPipe.h:137
void drop1xx(const char *reason)
Definition: http.cc:852
void Read(const Comm::ConnectionPointer &conn, AsyncCall::Pointer &callback)
Definition: Read.cc:40
bool proxy_only
Definition: CachePeer.h:82
virtual void haveParsedReplyHeaders()
called when we have final (possibly adapted) reply headers; kids extend
Definition: http.cc:984
const char * xstrerr(int error)
Definition: xstrerror.cc:83
void makePrivate(const bool shareable)
Definition: store.cc:172
bool handling1xx
Whether we are processing an HTTP 1xx control message.
Definition: StateFlags.h:30
char method[16]
Definition: tcp-banger2.c:115
bool hasProxyRevalidate() const
Definition: HttpHdrCc.h:117
bool maybeMakeSpaceAvailable(bool grow)
Definition: http.cc:1640
char * buf
Definition: MemBuf.h:134
AsyncCall::Pointer comm_add_close_handler(int fd, CLCB *handler, void *data)
Definition: comm.cc:983
int connection_auth
0 - off, 1 - on, 2 - auto
Definition: CachePeer.h:195
virtual bool getMoreRequestBody(MemBuf &buf)
either fill buf with available [encoded] request body bytes or return false
Definition: Client.cc:418
void truncateVirginBody()
Definition: http.cc:1424
char * peer_host
Definition: HttpRequest.h:165
bool keepalive_broken
Definition: StateFlags.h:58
unsigned int major
major version number
StoreEntry * entry
Definition: Client.h:164
bool keepalive
whether the Squid-sent request offers to keep the connection persistent
Definition: StateFlags.h:21
@ scMethodNotAllowed
Definition: StatusCode.h:49
bool hasPrivate(const String **val=nullptr) const
Definition: HttpHdrCc.h:74
@ scNonAuthoritativeInformation
Definition: StatusCode.h:29
AnyP::ProtocolVersion http_ver
Definition: Message.h:73
void userInfo(const SBuf &s)
Definition: Uri.h:79
#define base64_encode_len(length)
Definition: base64.h:169
@ HDR_X_ACCELERATOR_VARY
void ignoreRange(const char *reason)
forgets about the cached Range header (for a reason)
Definition: HttpRequest.cc:629
void appendf(const char *fmt,...) PRINTF_FORMAT_ARG2
Append operation with printf-style arguments.
Definition: Packable.h:61
@ scUnauthorized
Definition: StatusCode.h:45
@ scPayloadTooLarge
Definition: StatusCode.h:57
@ METHOD_HEAD
Definition: MethodType.h:28
AnyP::Uri url
the request URI
Definition: HttpRequest.h:115
http_hdr_owner_type owner
Definition: HttpHeader.h:173
bool ignoreCacheControl
Definition: http.h:70
Definition: Client.h:35
@ ERR_READ_ERROR
Definition: forward.h:28
Cbc * valid() const
was set and is valid
Definition: CbcPointer.h:41
struct CachePeer::@31 options
BodyPipe::Pointer body_pipe
optional pipeline to receive message body
Definition: Message.h:98
bool spoofClientIp
Definition: RequestFlags.h:70
const char * storeId() const
Definition: MemObject.cc:54
void releaseRequest(const bool shareable=false)
Definition: store.cc:472
@ ENTRY_REVALIDATE_STALE
Definition: enums.h:100
int Ctx
Definition: Debug.h:37
@ FD_WRITE
Definition: enums.h:24
struct StatCounters::@131 server
@ scBadRequest
Definition: StatusCode.h:44
bool chunked
reading a chunked response; TODO: rename
Definition: StateFlags.h:62
const char * getStr(Http::HdrType id) const
Definition: HttpHeader.cc:1208
#define LOCAL_ARRAY(type, name, size)
Definition: squid.h:75
mb_size_t size
Definition: MemBuf.h:135
virtual bool getMoreRequestBody(MemBuf &buf)
either fill buf with available [encoded] request body bytes or return false
Definition: http.cc:2462
int reads
Definition: IoStats.h:19
bool makePublic(const KeyScope keyScope=ksDefault)
Definition: store.cc:165
HttpHeader header
Definition: Message.h:75
bool offsetLimitExceeded(const int64_t limit) const
#define EBIT_SET(flag, bit)
Definition: defines.h:105
int hasListMember(Http::HdrType id, const char *member, const char separator) const
Definition: HttpHeader.cc:1709
Http::StateFlags flags
Definition: http.h:67
@ scMisdirectedRequest
Definition: StatusCode.h:62
Http::StatusCode peer_reply_status
last HTTP status code received
bool MonitorsRead(int fd)
whether the FD socket is being monitored for read
Definition: Read.cc:29
Answers make(const Answers ans, const char *why)
stores the corresponding decision
Definition: http.cc:2663
bool isEmpty() const
Definition: SBuf.h:420
MemObject * mem_obj
Definition: Store.h:213
AsyncCall::Pointer requestSender
Definition: Client.h:170
RequestFlags flags
Definition: HttpRequest.h:141
String * upgradeHeaderOut
Upgrade header value sent to the origin server or cache peer.
Definition: http.h:74
void checkDateSkew(HttpReply *)
Definition: http.cc:651
ssize_t HttpHeaderPos
Definition: HttpHeader.h:45
int64_t payloadTruncated
positive when we read more than we wanted
Definition: http.h:155
virtual void abortAll(const char *reason)
abnormal transaction termination; reason is for debugging only
Definition: http.cc:2652
void reserveSpace(size_type minSpace)
Definition: SBuf.h:429
@ scLengthRequired
Definition: StatusCode.h:55
const Http::StatusCode statusCode
HTTP status for debugging.
Definition: http.h:41
virtual bool mayReadVirginReplyBody() const
whether we may receive more virgin response body bytes
Definition: http.cc:1605
bool surrogateNoStore
Definition: http.h:71
const char * url() const
Definition: store.cc:1601
a reference to a protocol name[/version] string; no 0-termination is assumed
int lastChunk
Definition: http.h:66
Comm::Flag ReadNow(CommIoCbParams &params, SBuf &buf)
Definition: Read.cc:81
size_t base64_encode_final(struct base64_encode_ctx *ctx, char *dst)
Definition: base64.c:308
struct StatCounters::@131::@141 all
static void httpFixupAuthentication(HttpRequest *request, const HttpHeader *hdr_in, HttpHeader *hdr_out, const Http::StateFlags &flags)
Definition: http.cc:1755
int64_t getRangeOffsetLimit()
Definition: HttpRequest.cc:602
MemObject & mem()
Definition: Store.h:52
#define HttpHeaderInitPos
Definition: HttpHeader.h:48
#define ScheduleCallHere(call)
Definition: AsyncCall.h:166
virtual void handleRequestBodyProducerAborted()=0
Definition: Client.cc:331
void error(char *format,...)
AccessLogEntryPointer al
info for the future access.log entry
Definition: FwdState.h:166
unsigned int minor
minor version number
@ PROXY_CONNECTION
#define PEER_PROXY_NEGOTIATE_NOKEYTAB
bool finishingBrokenPost()
if broken posts are enabled for the request, try to fix and return true
Definition: http.cc:2523
CachePeer * _peer
Definition: http.h:64
bool connectionAuth
Definition: RequestFlags.h:76
@ scUnsupportedMediaType
Definition: StatusCode.h:59
void httpHdrMangleList(HttpHeader *l, HttpRequest *request, const AccessLogEntryPointer &al, req_or_rep_t req_or_rep)
bool hasContent() const
Definition: MemBuf.h:54
HttpReplyPointer reply
int64_t bodySize(const HttpRequestMethod &) const
Definition: HttpReply.cc:375
void init(mb_size_t szInit, mb_size_t szMax)
Definition: MemBuf.cc:96
const char * ProtocolType_str[]
@ KEY_PRIVATE
Definition: enums.h:102
@ INPROGRESS
Definition: Flag.h:22
Definition: SBuf.h:87
virtual void sendControlMsg(HttpControlMsg)
called to send the 1xx message and notify the Source
mb_size_t buildRequestPrefix(MemBuf *mb)
Definition: http.cc:2331
size_t maxReplyHeaderSize
Definition: SquidConfig.h:134
ConnectionStatus statusIfComplete() const
Definition: http.cc:1117
AsyncCall::Pointer closeHandler
Definition: http.h:91
char * opt_forwarded_for
ConnectionStatus
Definition: http.h:92
@ scUseProxy
Definition: StatusCode.h:41
int commSetConnTimeout(const Comm::ConnectionPointer &conn, int timeout, AsyncCall::Pointer &callback)
Definition: comm.cc:567
HttpStateData(FwdState *)
Definition: http.cc:87
@ scMovedPermanently
Definition: StatusCode.h:37
void noStoreRemote(bool v)
static void assembleVaryKey(String &vary, SBuf &vstr, const HttpRequest &request)
assemble a variant key (vary-mark) from the given Vary header and HTTP request
Definition: http.cc:576
#define SQUID_ENTER_THROWING_CODE()
Definition: http.cc:70
DelayId mostBytesAllowed() const
Definition: MemObject.cc:478
@ ERR_INVALID_RESP
Definition: forward.h:41
bool peering
Whether the next TCP hop is a cache_peer, including originserver.
Definition: StateFlags.h:40
BodyPipe::Pointer requestBodySource
Definition: Client.h:169
a representation of a refresh pattern.
const char * blockSwitchingProtocols(const HttpReply &) const
Definition: http.cc:870
PconnPool * fwdPconnPool
a collection of previously used persistent Squid-to-peer HTTP(S) connections
Definition: FwdState.cc:78
String getList(Http::HdrType id) const
Definition: HttpHeader.cc:858
bool sendRequest()
Definition: http.cc:2375
int fd
FD which the call was about. Set by the async call creator.
Definition: CommCalls.h:90
bool chunked_request
writing a chunked request
Definition: StateFlags.h:63
int detect_broken_server_pconns
Definition: SquidConfig.h:320
C * getRaw() const
Definition: RefCount.h:80
size_type spaceSize() const
Definition: SBuf.h:382
virtual void append(const char *c, int sz)
Definition: MemBuf.cc:216
uint16_t flags
Definition: Store.h:224
AccessLogEntry::Pointer al
info for the future access.log, and external ACL
const SBuf & image() const
Acl::Answer const & fastCheck()
Definition: Checklist.cc:336
void processReplyBody()
Definition: http.cc:1494
void toLower()
converts all characters to lower case;
Definition: SBuf.cc:818
bool IsConnOpen(const Comm::ConnectionPointer &conn)
Definition: Connection.cc:26
bool allow_miss
Definition: CachePeer.h:103
IoStats IOStats
@ OK
Definition: Flag.h:16
bool isAccepting() const
Definition: store.cc:2029
#define SQUID_EXIT_THROWING_CODE(status)
Definition: http.cc:71
Http::StatusLine sline
Definition: HttpReply.h:60
time_t getMaxAge(const char *url)
Definition: refresh.cc:642
@ ENDFILE
Definition: Flag.h:27
Comm::ConnectionPointer serverConnection
Definition: http.h:90
@ ERR_NONE
Definition: forward.h:15
int surrogate_is_remote
Definition: SquidConfig.h:318
StatusCode
Definition: StatusCode.h:20
static const char *const crlf
Definition: http.cc:81
err_type
Definition: forward.h:14
void adaptOrFinalizeReply()
Definition: Client.cc:962
void unregister(Comm::ConnectionPointer &conn)
Definition: FwdState.cc:502
bool multipartRangeRequest() const
Definition: HttpRequest.cc:435
void fail(ErrorState *err)
Definition: FwdState.cc:470
void keepaliveAccounting(HttpReply *)
Definition: http.cc:631
bool startRequestBodyFlow()
Definition: Client.cc:219
@ scRequestedRangeNotSatisfied
Definition: StatusCode.h:60
@ ERR_CLOSING
Definition: Flag.h:25
virtual void haveParsedReplyHeaders()
called when we have final (possibly adapted) reply headers; kids extend
Definition: Client.cc:517
bool Is1xx(const int sc)
whether this is an informational 1xx response status code
Definition: StatusCode.h:92
#define cbdataReference(var)
Definition: cbdata.h:341
int front_end_https
0 - off, 1 - on, 2 - auto
Definition: CachePeer.h:194
#define PROF_stop(probename)
Definition: Profiler.h:63
bool connectionAuthDisabled
Definition: RequestFlags.h:78
void reset()
Definition: store.cc:1656
@ IF_MODIFIED_SINCE
#define DBG_IMPORTANT
Definition: Debug.h:46
bool decodeAndWriteReplyBody()
Definition: http.cc:1462
int xerrno
The last errno to occur. non-zero if flag is Comm::COMM_ERROR.
Definition: CommCalls.h:88
void httpHeaderPutStrf(HttpHeader *hdr, Http::HdrType id, const char *fmt,...)
StoreEntry * storeGetPublicByRequest(HttpRequest *req, const KeyScope keyScope)
Definition: store.cc:533
int32_t mask
Definition: HttpHdrCc.h:173
ProtocolType protocol
which protocol this version is for
void readReply(const CommIoCbParams &io)
Definition: http.cc:1226
static bool decideIfWeDoRanges(HttpRequest *orig_request)
Definition: http.cc:2301
size_t getMoreData(MemBuf &buf)
Definition: BodyPipe.cc:294
@ scSeeOther
Definition: StatusCode.h:39
SBuf httpMakeVaryMark(HttpRequest *request, HttpReply const *reply)
Definition: http.cc:612
StoreEntry * storeGetPublicByRequestMethod(HttpRequest *req, const HttpRequestMethod &method, const KeyScope keyScope)
Definition: store.cc:527
char * toStr(char *buf, const unsigned int blen, int force=AF_UNSPEC) const
Definition: Address.cc:802
AnyP::UriScheme const & getScheme() const
Definition: Uri.h:67
AnyP::ProtocolType protocol
Definition: StatusLine.h:68
void serverComplete()
Definition: Client.cc:160
@ METHOD_OPTIONS
Definition: MethodType.h:31
@ CONTENT_LENGTH
SBuf & chop(size_type pos, size_type n=npos)
Definition: SBuf.cc:537
bool chunked() const
Definition: HttpHeader.h:165
mb_size_t max_capacity
Definition: MemBuf.h:142
peer_t neighborType(const CachePeer *p, const AnyP::Uri &url)
Definition: neighbors.cc:115
#define MAX_IPSTRLEN
Length of buffer that needs to be allocated to old a null-terminated IP-string.
Definition: forward.h:23
@ scNotAcceptable
Definition: StatusCode.h:50
@ COMPLETE_NONPERSISTENT_MSG
Definition: http.h:95
Definition: Range.h:19
@ scGatewayTimeout
Definition: StatusCode.h:75
Definition: Debug.h:189
@ ENTRY_FWD_HDR_WAIT
Definition: enums.h:111
#define MAX_URL
Definition: defines.h:118
bool persistent() const
Definition: Message.cc:261
void sendComplete()
successfully wrote the entire request (including body, last-chunk, etc.)
Definition: http.cc:1714
time_t lastmod
Definition: HttpRequest.h:167
void strListAdd(String &str, const char *item, const size_t itemSize, const char delimiter)
Appends the given item of a given size to a delimiter-separated list in str.
Definition: StrList.cc:18
bool canGrowBy(const size_type growthLen) const
whether appending growthLen characters is safe (i.e., unlikely to assert)
Definition: SquidString.h:123
@ ERR_ICAP_FAILURE
Definition: forward.h:64
@ HTCP_CLR_INVALIDATION
Definition: enums.h:243
struct SquidConfig::@113 onoff
void bytesIn(int qty)
Definition: DelayId.cc:154
HttpHdrScTarget * getMergedTarget(const char *ourtarget)
Definition: HttpHdrSc.cc:296
String etag
A strong etag of the cached entry. Used for refreshing that entry.
Definition: HttpRequest.h:191
void processReplyHeader()
Definition: http.cc:668
ReuseDecision(const StoreEntry *e, const Http::StatusCode code)
Definition: http.cc:2659
virtual bool expectingBody(const HttpRequestMethod &, int64_t &) const
Definition: HttpReply.cc:488
bool httpHeaderHasConnDir(const HttpHeader *hdr, const SBuf &directive)
static void httpMaybeRemovePublic(StoreEntry *, Http::StatusCode)
Definition: http.cc:184
time_t expires
Definition: HttpReply.h:48
mb_size_t contentSize() const
available data size
Definition: MemBuf.h:47
int64_t getInt64() const
Definition: HttpHeader.cc:1582
@ scTemporaryRedirect
Definition: StatusCode.h:42
parameters for the async notePinnedConnectionBecameIdle() call
Definition: client_side.h:179
unsigned int front_end_https
send "Front-End-Https: On" header (off/on/auto=2)
Definition: StateFlags.h:18
#define NULL
Definition: types.h:166
@ COMPLETE_PERSISTENT_MSG
Definition: http.h:94
struct StatCounters::@131::@141 http
const char * rawContent() const
Definition: SBuf.cc:516
SBuf consume(size_type n=npos)
Definition: SBuf.cc:488
int n_keepalives_sent
Definition: CachePeer.h:51
@ scFailedDependency
Definition: StatusCode.h:65
void maxAge(int32_t v)
Definition: HttpHdrCc.h:123
@ scSwitchingProtocols
Definition: StatusCode.h:23
int strListIsMember(const String *list, const SBuf &m, char del)
Definition: StrList.cc:46
virtual void doneSendingRequestBody()=0
Definition: Client.cc:320
time_t read
Definition: SquidConfig.h:109
@ scForbidden
Definition: StatusCode.h:47
@ ROR_REQUEST
#define SQUIDSBUFPRINT(s)
Definition: SBuf.h:32
bool dontRetry()
Definition: FwdState.h:94
void mustStop(const char *aReason)
Definition: AsyncJob.cc:69
#define debugs(SECTION, LEVEL, CONTENT)
Definition: Debug.h:128
const HttpReply * virginReply() const
Definition: Client.cc:110
SBuf inBuf
I/O buffer for receiving server responses.
Definition: http.h:69
bundles HTTP 1xx reply and the "successfully forwarded" callback
@ scInsufficientStorage
Definition: StatusCode.h:78
SBuf vary_headers
Definition: MemObject.h:204
@ scPreconditionFailed
Definition: StatusCode.h:56
@ scNotImplemented
Definition: StatusCode.h:72
Http::StatusCode status() const
retrieve the status code for this status line
Definition: StatusLine.h:45
MemBlob::size_type size_type
Definition: SBuf.h:89
#define MAX_LOGIN_SZ
Definition: defines.h:119
bool hasNoCacheWithParameters() const
Definition: HttpHdrCc.h:87
struct IoStats::@81 Http
void forApplicable(const ProtocolView &, const Visitor &) const
bool hasNoStore() const
virtual void handleMoreRequestBodyAvailable()
Definition: http.cc:2591
void handle1xx(HttpReply *msg)
ignore or start forwarding the 1xx response (a.k.a., control message)
Definition: http.cc:793
@ ENTRY_REVALIDATE_ALWAYS
Definition: enums.h:85
@ srcHttp
http_port or HTTP server
Definition: Message.h:39
static Pointer Start(AsyncJob *job)
starts a freshly created job (i.e., makes the job asynchronous)
Definition: AsyncJob.cc:23
@ scBadGateway
Definition: StatusCode.h:73
const StoreEntry * entry
entry for debugging
Definition: http.h:40
Definition: MemBuf.h:24
void doneSendingRequestBody()
Definition: http.cc:2575
bool toOriginPeer() const
Whether the next TCP/HTTP hop is an originserver cache_peer.
Definition: StateFlags.h:56
#define EBIT_TEST(flag, bit)
Definition: defines.h:107
CachePeer * getPeer() const
Definition: Connection.cc:105
void push(const Comm::ConnectionPointer &serverConn, const char *domain)
Definition: pconn.cc:412
unsigned char code
Definition: html_quote.c:20
bool canHandle1xx() const
whether the client is likely to be able to handle a 1xx reply
Definition: HttpRequest.cc:643
std::ostream & HERE(std::ostream &s)
Definition: Debug.h:157
virtual void handleRequestBodyProducerAborted()
Definition: http.cc:2623
@ scPartialContent
Definition: StatusCode.h:32
@ scGone
Definition: StatusCode.h:54
Http::HdrType id
Definition: HttpHeader.h:63
void proceedAfter1xx()
restores state and resumes processing after 1xx is ignored or forwarded
Definition: http.cc:897
ConnectionStatus persistentConnStatus() const
Definition: http.cc:1168
bool hasSMaxAge(int32_t *val=nullptr) const
Definition: HttpHdrCc.h:127
void const char HLPCB void * data
Definition: stub_helper.cc:16
@ INCOMPLETE_MSG
Definition: http.h:93
#define CallJobHere(debugSection, debugLevel, job, Class, method)
Definition: AsyncJobCalls.h:58
char * peer_domain
Definition: HttpRequest.h:172
@ scUnprocessableEntity
Definition: StatusCode.h:63
#define BBUF_SZ
void httpTimeout(const CommTimeoutCbParams &params)
Definition: http.cc:161
Comm::ConnectionPointer conn
Definition: CommCalls.h:85
Answers answer
the decision id
Definition: http.h:38
void addEntry(HttpHeaderEntry *e)
Definition: HttpHeader.cc:781
bool hasNoCache(const String **val=nullptr) const
Definition: HttpHdrCc.h:89
HttpRequestMethod method
Definition: MemObject.h:137
virtual bool doneWithServer() const
Definition: http.cc:1746
store_status_t store_status
Definition: Store.h:236
@ scPermanentRedirect
Definition: StatusCode.h:43
void putTime(Http::HdrType id, time_t htime)
Definition: HttpHeader.cc:1059
struct SquidConfig::@106 Accel
int neighbors_do_private_keys
@ ERR_ZERO_SIZE_OBJECT
Definition: forward.h:46
HttpUpgradeProtocolAccess * http_upgrade_request_protocols
http_upgrade_request_protocols
Definition: SquidConfig.h:483
#define assert(EX)
Definition: assert.h:19
@ scUriTooLong
Definition: StatusCode.h:58
char const * termedBuf() const
Definition: SquidString.h:91
void setPayloadBuffer(MemBuf *parsedContent)
set the buffer to be used to store decoded chunk data
@ scContinue
Definition: StatusCode.h:22
HttpHdrCc * cache_control
Definition: Message.h:77
FwdState::Pointer fwd
Definition: Client.h:165
HierarchyLogEntry hier
Definition: HttpRequest.h:157
acl_access * brokenPosts
Definition: SquidConfig.h:379
void HTTPMSGLOCK(Http::Message *a)
Definition: Message.h:160
virtual void syncAle(HttpRequest *adaptedRequest, const char *logUri) const
assigns uninitialized adapted_request and url ALE components
void neighborsHtcpClear(StoreEntry *e, HttpRequest *req, const HttpRequestMethod &method, htcp_clr_reason reason)
Definition: neighbors.cc:1807
struct SquidConfig::@99 Timeout
virtual HttpRequestPointer originalRequest()
a hack to reach HttpStateData::orignal_request
Definition: Client.cc:547
Comm::Flag flag
comm layer result status.
Definition: CommCalls.h:87
const SBuf & remaining() const
the remaining unprocessed section of buffer
Definition: Parser.h:98
void abortTransaction(const char *reason)
Definition: http.h:113
@ TRANSFER_ENCODING
bool no_delay
Definition: CachePeer.h:101
@ scServiceUnavailable
Definition: StatusCode.h:74
@ METHOD_TRACE
Definition: MethodType.h:30
#define cbdataReferenceDone(var)
Definition: cbdata.h:350
bool adaptationAccessCheckPending
Definition: Client.h:177
void onlyIfCached(bool v)
Definition: HttpHdrCc.h:146
void writeReplyBody()
Definition: http.cc:1452
#define JobCallback(dbgSection, dbgLevel, Dialer, job, method)
Convenience macro to create a Dialer-based job callback.
Definition: AsyncJobCalls.h:69
@ scInternalServerError
Definition: StatusCode.h:71
HttpHdrRange * range
Definition: HttpRequest.h:143
HttpReply * setVirginReply(HttpReply *r)
Definition: Client.cc:117
void httpStateConnClosed(const CommCloseCbParams &params)
Definition: http.cc:153
void packInto(Packable *p, bool mask_sensitive_info=false) const
Definition: HttpHeader.cc:584
bool sentLastChunk
do not try to write last-chunk again
Definition: StateFlags.h:64
bool cacheNegatively()
Definition: store.cc:186
const char * c_str()
Definition: SBuf.cc:523
void Write(const Comm::ConnectionPointer &conn, const char *buf, int size, AsyncCall::Pointer &callback, FREE *free_func)
Definition: Write.cc:35
int commUnsetConnTimeout(const Comm::ConnectionPointer &conn)
Definition: comm.cc:593
virtual const Comm::ConnectionPointer & dataConnection() const
Definition: http.cc:147
bool olderThan(const HttpReply *them) const
Definition: HttpReply.cc:664
SBuf & authority(bool requirePort=false) const
Definition: Uri.cc:574
void base64_encode_init(struct base64_encode_ctx *ctx)
Definition: base64.c:232
bool receivedWholeRequestBody
handleRequestBodyProductionEnded called
Definition: Client.h:180
#define CBDATA_CLASS_INIT(type)
Definition: cbdata.h:318
size_type length() const
Returns the number of bytes stored in SBuf.
Definition: SBuf.h:404
time_t squid_curtime
Definition: stub_time.cc:17
size_t bytesWanted(Range< size_t > const aRange, bool ignoreDelayPool=false) const
Definition: store.cc:249
SBuf & append(const SBuf &S)
Definition: SBuf.cc:192
bool isNoAddr() const
Definition: Address.cc:284
int64_t content_length
Definition: Message.h:84
time_t date
Definition: HttpReply.h:44
HttpReply * finalReply()
Definition: Client.cc:130
void putCc(const HttpHdrCc *cc)
Definition: HttpHeader.cc:1084
void fd_bytes(int fd, int len, unsigned int type)
Definition: fd.cc:256
bool parseHeader(Http1::Parser &hp)
parses reply header using Parser
Definition: HttpReply.cc:467
@ scNotModified
Definition: StatusCode.h:40
ReuseDecision::Answers reusableReply(ReuseDecision &decision)
Definition: http.cc:321
uint32_t sources
The message sources.
Definition: Message.h:100
const Acl::Tree * changeAcl(const Acl::Tree *t)
Definition: Checklist.h:176
bool mustKeepalive
Definition: RequestFlags.h:74
Http1::TeChunkedParser * httpChunkDecoder
Definition: http.h:150
Ctx ctx_enter(const char *descr)
Definition: debug.cc:721
void wroteLast(const CommIoCbParams &io)
called after writing the very last request byte (body, last-chunk, etc)
Definition: http.cc:1677
#define fd_table
Definition: fde.h:189
Http1::ResponseParserPointer hp
Parser being used at present to parse the HTTP/ICY server response.
Definition: http.h:149
@ ERR_READ_TIMEOUT
Definition: forward.h:26
assists in making and relaying entry caching/sharing decision
Definition: http.h:30
@ scFound
Definition: StatusCode.h:38
virtual bool parse(const SBuf &)
@ PROTO_HTTPS
Definition: ProtocolType.h:27
size_t calcBufferSpaceToReserve(const size_t space, const size_t wantSpace) const
determine how much space the buffer needs to reserve
Definition: Client.cc:1020
@ scRequestTimeout
Definition: StatusCode.h:52
bool accelerated
Definition: RequestFlags.h:58
void maxAge(int v)
HttpRequestMethod method
Definition: HttpRequest.h:114
void path(const char *p)
Definition: Uri.h:99
const char * reason
the decision reason
Definition: http.h:39
@ scNotFound
Definition: StatusCode.h:48
acl_access * reply
Definition: SquidConfig.h:383
noteTakeServerConnectionControl() callback parameter
Definition: client_side.h:209
@ ENTRY_ABORTED
Definition: enums.h:115
@ PROTO_HTTP
Definition: ProtocolType.h:25
char * host
Definition: CachePeer.h:40
int eof
Definition: http.h:65
bool allowed() const
Definition: Acl.h:143
int cache_miss_revalidate
Definition: SquidConfig.h:325
bool sawDateGoBack
Definition: http.h:159
void addVirginReplyBody(const char *buf, ssize_t len)
Definition: Client.cc:995
int server_pconns
Definition: SquidConfig.h:310
struct SquidConfig::@114 accessList
AnyP::ProtocolVersion version
breakdown of protocol version label: (HTTP/ICY) and (0.9/1.0/1.1)
Definition: StatusLine.h:70
const char * doneWithFwd
Definition: Client.h:184
void delayRead(DeferredRead const &)
Definition: MemObject.cc:457
virtual void sentRequestBody(const CommIoCbParams &io)=0
Definition: Client.cc:344
bool peerSupportsConnectionPinning() const
Definition: http.cc:926
bool timestampsSet()
Definition: store.cc:1428
@ scNoContent
Definition: StatusCode.h:30
@ PROXY_AUTHENTICATE
@ ERR_TOO_BIG
Definition: forward.h:40
bool forcedBodyContinuation
whether we have responded with HTTP 100 or FTP 150 already
Definition: HttpRequest.h:194
virtual void maybeReadVirginBody()
read response data from the network
Definition: http.cc:1614
int has(Http::HdrType id) const
Definition: HttpHeader.cc:1007
void processReply()
Definition: http.cc:1324
char * content()
start of the added data
Definition: MemBuf.h:41
#define acl_access
Definition: forward.h:44
bool hasMaxAge(int32_t *val=nullptr) const
Definition: HttpHdrCc.h:122
void putStr(Http::HdrType id, const char *str)
Definition: HttpHeader.cc:1068
@ ERR_WRITE_ERROR
Definition: forward.h:29
void set(const AnyP::ProtocolVersion &newVersion, Http::StatusCode newStatus, const char *newReason=NULL)
Definition: StatusLine.cc:35
bool finishingChunkedRequest()
if needed, write last-chunk to end the request body and return true
Definition: http.cc:2558
size_type size() const
Definition: SquidString.h:72
char * url
Definition: tcp-banger2.c:114
bool isEmpty() const
Definition: Store.h:67
bool refreshIsCachable(const StoreEntry *entry)
Definition: refresh.cc:528
bool reforwardableStatus(const Http::StatusCode s) const
Definition: FwdState.cc:1322
#define Must(condition)
Like assert() but throws an exception instead of aborting the process.
Definition: TextException.h:72
int redir_rewrites_host
Definition: SquidConfig.h:302
@ SURROGATE_CAPABILITY
@ scProxyAuthenticationRequired
Definition: StatusCode.h:51
AsyncCall * asyncCall(int aDebugSection, int aDebugLevel, const char *aName, const Dialer &aDialer)
Definition: AsyncCall.h:156
void Controller::create() STUB void Controller Controller nil
size_t base64_encode_update(struct base64_encode_ctx *ctx, char *dst, size_t length, const uint8_t *src)
Definition: base64.c:265
char * surrogate_id
Definition: SquidConfig.h:216
int unsigned int const char *desc STUB void int len
Definition: stub_fd.cc:20
StoreEntry * entry
Definition: FwdState.h:164
StoreEntry * storeGetPublic(const char *uri, const HttpRequestMethod &method)
Definition: store.cc:521
void release(const bool shareable=false)
Definition: store.cc:1175
virtual void start()
called by AsyncStart; do not call directly
Definition: http.cc:2503
const HttpReply & freshestReply() const
Definition: MemObject.h:67
ssize_t mb_size_t
Definition: MemBuf.h:17
HttpHdrSc * surrogate_control
Definition: HttpReply.h:52
@ scInvalidHeader
Definition: StatusCode.h:86
@ scPaymentRequired
Definition: StatusCode.h:46
@ scLocked
Definition: StatusCode.h:64
static StoreEntry * findPreviouslyCachedEntry(StoreEntry *newEntry)
Definition: http.cc:174
@ scConflict
Definition: StatusCode.h:53
int n_keepalives_recv
Definition: CachePeer.h:52
@ RELEASE_REQUEST
prohibits making the key public
Definition: enums.h:98
#define REFRESH_OVERRIDE(flag)
static void httpBuildRequestHeader(HttpRequest *request, StoreEntry *entry, const AccessLogEntryPointer &al, HttpHeader *hdr_out, const Http::StateFlags &flags)
Definition: http.cc:1866
@ srcHttps
https_port or bumped http_port tunnel; HTTPS server
Definition: Message.h:33
virtual void sentRequestBody(const CommIoCbParams &io)
Definition: http.cc:2643
int64_t readAheadGap
Definition: SquidConfig.h:95
void setNoDelay(bool const)
Definition: store.cc:273
bool hasNoCacheWithoutParameters() const
Definition: HttpHdrCc.h:88
bool hasMustRevalidate() const
Definition: HttpHdrCc.h:112
void processSurrogateControl(HttpReply *)
Definition: http.cc:283
int64_t payloadSeen
amount of message payload/body received so far.
Definition: http.h:153
bool continueAfterParsingHeader()
Definition: http.cc:1354
static void readDelayed(void *context, CommRead const &)
Definition: http.cc:1218
@ scMultipleChoices
Definition: StatusCode.h:36
const char * urlXXX() const
Definition: MemObject.h:128
bool serverSwitchedProtocols
Definition: StateFlags.h:35
@ scOkay
Definition: StatusCode.h:26
std::ostream & operator<<(std::ostream &os, const HttpStateData::ReuseDecision &d)
Definition: http.cc:2670
HttpHeaderEntry * getEntry(HttpHeaderPos *pos) const
Definition: HttpHeader.cc:628
void lengthWentBad(const char *reason)
flags [truncated or too big] entry with ENTRY_BAD_LENGTH and releases it
Definition: store.cc:1049
@ scHeaderTooLarge
Definition: StatusCode.h:87
#define rfc1738_escape_part(x)
Definition: rfc1738.h:55
@ CC_NO_CACHE
Definition: HttpHdrCc.h:23
time_t lifetime
Definition: SquidConfig.h:111
virtual void closeServer()
Definition: http.cc:1733
#define false
Definition: GnuRegex.c:233
const SBuf & effectiveRequestUri() const
RFC 7230 section 5.5 - Effective Request URI.
Definition: HttpRequest.cc:688
static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest *request, HttpHeader *hdr_out, const int we_do_ranges, const Http::StateFlags &)
Definition: http.cc:2123
void addVia(const AnyP::ProtocolVersion &ver, const HttpHeader *from=0)
Definition: HttpHeader.cc:1015
HttpRequest * request
Definition: FwdState.h:165
Ip::Address client_addr
Definition: HttpRequest.h:149
bool hasNoStore() const
Definition: HttpHdrCc.h:102
void host(const char *src)
Definition: Uri.cc:98
void forwardUpgrade(HttpHeader &)
Definition: http.cc:2049
@ PEER_SIBLING
Definition: enums.h:29
@ scExpectationFailed
Definition: StatusCode.h:61
HttpRequestPointer request
Definition: Client.h:166
int read_hist[histSize]
Definition: IoStats.h:21
struct _request * request(char *urlin)
Definition: tcp-banger2.c:291
virtual void noteTakeServerConnectionControl(ServerConnectionContext)
Definition: client_side.h:225
short int keep_alive
Definition: HttpReply.h:57
@ hoRequest
Definition: HttpHeader.h:36
HttpRequestPointer request
Definition: MemObject.h:188
void clean()
Definition: HttpHeader.cc:190
struct CachePeer::@29 stats
void comm_remove_close_handler(int fd, CLCB *handler, void *data)
Definition: comm.cc:1010
Comm::ConnectionPointer const & serverConnection() const
Definition: FwdState.h:102
const char * getMD5Text() const
Definition: store.cc:205
void const char * buf
Definition: stub_helper.cc:16
~HttpStateData()
Definition: http.cc:130
bool originserver
Definition: CachePeer.h:117
time_t negativeTtl
Definition: SquidConfig.h:99
void ctx_exit(Ctx ctx)
Definition: debug.cc:737
HttpHdrCc * getCc() const
Definition: HttpHeader.cc:1239
#define SQUIDSBUFPH
Definition: SBuf.h:31
void putInt64(Http::HdrType id, int64_t number)
Definition: HttpHeader.cc:1050
HttpHeaderEntry * clone() const
Definition: HttpHeader.cc:1554
CbcPointer< ConnStateData > clientConnectionManager
Definition: HttpRequest.h:232
#define PROF_start(probename)
Definition: Profiler.h:62
bool hasMaxAge() const
bool hasPublic() const
Definition: HttpHdrCc.h:69
class SquidConfig Config
Definition: SquidConfig.cc:12
void httpStart(FwdState *fwd)
Definition: http.cc:2496
int strListGetItem(const String *str, char del, const char **item, int *ilen, const char **pos)
Definition: StrList.cc:86
ErrorDetail::Pointer MakeNamedErrorDetail(const char *name)
Definition: Detail.cc:54
StatCounters statCounter
Definition: StatCounters.cc:12
void removeStaleWarnings()
Remove Warnings with warn-date different from Date value.
Definition: HttpReply.cc:599
void clean()
Definition: String.cc:125
AnyP::ProtocolVersion ProtocolVersion(unsigned int aMajor, unsigned int aMinor)
HTTP version label information.
@ PROXY_AUTHORIZATION
void maxStale(int v)
#define DBG_DATA
Definition: Debug.h:48
#define CallJobHere1(debugSection, debugLevel, job, Class, method, arg1)
Definition: AsyncJobCalls.h:63
@ STORE_PENDING
Definition: enums.h:51

 

Introduction

Documentation

Support

Miscellaneous

Web Site Translations

Mirrors