client_side_request.cc
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1996-2023 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 85 Client-side Request Routines */
10 
11 /*
12  * General logic of request processing:
13  *
14  * We run a series of tests to determine if access will be permitted, and to do
15  * any redirection. Then we call into the result clientStream to retrieve data.
16  * From that point on it's up to reply management.
17  */
18 
19 #include "squid.h"
20 #include "acl/FilledChecklist.h"
21 #include "acl/Gadgets.h"
22 #include "anyp/PortCfg.h"
23 #include "base/AsyncJobCalls.h"
24 #include "client_side.h"
25 #include "client_side_reply.h"
26 #include "client_side_request.h"
27 #include "ClientRequestContext.h"
28 #include "clientStream.h"
29 #include "comm/Connection.h"
30 #include "comm/Write.h"
31 #include "debug/Messages.h"
32 #include "error/Detail.h"
33 #include "errorpage.h"
34 #include "fd.h"
35 #include "fde.h"
36 #include "format/Token.h"
37 #include "FwdState.h"
38 #include "helper.h"
39 #include "helper/Reply.h"
40 #include "http.h"
41 #include "http/Stream.h"
42 #include "HttpHdrCc.h"
43 #include "HttpReply.h"
44 #include "HttpRequest.h"
45 #include "internal.h"
46 #include "ip/NfMarkConfig.h"
47 #include "ip/QosConfig.h"
48 #include "ipcache.h"
49 #include "log/access_log.h"
50 #include "MemObject.h"
51 #include "Parsing.h"
52 #include "proxyp/Header.h"
53 #include "redirect.h"
54 #include "rfc1738.h"
55 #include "sbuf/StringConvert.h"
56 #include "SquidConfig.h"
57 #include "Store.h"
58 #include "StrList.h"
59 #include "tools.h"
60 #include "wordlist.h"
61 #if USE_AUTH
62 #include "auth/UserRequest.h"
63 #endif
64 #if USE_ADAPTATION
65 #include "adaptation/AccessCheck.h"
66 #include "adaptation/Answer.h"
67 #include "adaptation/Iterator.h"
68 #include "adaptation/Service.h"
69 #if ICAP_CLIENT
71 #endif
72 #endif
73 #if USE_OPENSSL
74 #include "ssl/ServerBump.h"
75 #include "ssl/support.h"
76 #endif
77 
78 #if FOLLOW_X_FORWARDED_FOR
79 
80 #if !defined(SQUID_X_FORWARDED_FOR_HOP_MAX)
81 #define SQUID_X_FORWARDED_FOR_HOP_MAX 64
82 #endif
83 
84 static void clientFollowXForwardedForCheck(Acl::Answer answer, void *data);
85 #endif /* FOLLOW_X_FORWARDED_FOR */
86 
88 
90 
91 /* Local functions */
92 /* other */
93 static void clientAccessCheckDoneWrapper(Acl::Answer, void *);
94 #if USE_OPENSSL
95 static void sslBumpAccessCheckDoneWrapper(Acl::Answer, void *);
96 #endif
97 static int clientHierarchical(ClientHttpRequest * http);
101 static void checkNoCacheDoneWrapper(Acl::Answer, void *);
105 static void checkFailureRatio(err_type, hier_code);
106 
108 {
109  /*
110  * Release our "lock" on our parent, ClientHttpRequest, if we
111  * still have one
112  */
113 
115 
116  delete error;
117  debugs(85,3, "ClientRequestContext destructed, this=" << this);
118 }
119 
121  http(cbdataReference(anHttp))
122 {
123  debugs(85, 3, "ClientRequestContext constructed, this=" << this);
124 }
125 
127 
129 #if USE_ADAPTATION
130  AsyncJob("ClientHttpRequest"),
131 #endif
132  al(new AccessLogEntry()),
133  conn_(cbdataReference(aConn))
134 {
136  al->cache.start_time = current_time;
137  if (aConn) {
138  al->tcpClient = aConn->clientConnection;
139  al->cache.port = aConn->port;
140  al->cache.caddr = aConn->log_addr;
141  al->proxyProtocolHeader = aConn->proxyProtocolHeader();
142  al->updateError(aConn->bareError);
143 
144 #if USE_OPENSSL
145  if (aConn->clientConnection != nullptr && aConn->clientConnection->isOpen()) {
146  if (auto ssl = fd_table[aConn->clientConnection->fd].ssl.get())
147  al->cache.sslClientCert.resetWithoutLocking(SSL_get_peer_certificate(ssl));
148  }
149 #endif
150  }
152 }
153 
154 /*
155  * returns true if client specified that the object must come from the cache
156  * without contacting origin server
157  */
158 bool
160 {
161  assert(request);
162  return request->cache_control &&
164 }
165 
178 static void
180 {
181  // Can be set at compile time with -D compiler flag
182 #ifndef FAILURE_MODE_TIME
183 #define FAILURE_MODE_TIME 300
184 #endif
185 
186  if (hcode == HIER_NONE)
187  return;
188 
189  // don't bother when ICP is disabled.
190  if (Config.Port.icp <= 0)
191  return;
192 
193  static double magic_factor = 100.0;
194  double n_good;
195  double n_bad;
196 
197  n_good = magic_factor / (1.0 + request_failure_ratio);
198 
199  n_bad = magic_factor - n_good;
200 
201  switch (etype) {
202 
203  case ERR_DNS_FAIL:
204 
205  case ERR_CONNECT_FAIL:
207 
208  case ERR_READ_ERROR:
209  ++n_bad;
210  break;
211 
212  default:
213  ++n_good;
214  }
215 
216  request_failure_ratio = n_bad / n_good;
217 
219  return;
220 
221  if (request_failure_ratio < 1.0)
222  return;
223 
224  debugs(33, DBG_CRITICAL, "WARNING: Failure Ratio at "<< std::setw(4)<<
225  std::setprecision(3) << request_failure_ratio);
226 
227  debugs(33, DBG_CRITICAL, "WARNING: ICP going into HIT-only mode for " <<
228  FAILURE_MODE_TIME / 60 << " minutes...");
229 
231 
232  request_failure_ratio = 0.8; /* reset to something less than 1.0 */
233 }
234 
236 {
237  debugs(33, 3, "httpRequestFree: " << uri);
238 
239  // Even though freeResources() below may destroy the request,
240  // we no longer set request->body_pipe to NULL here
241  // because we did not initiate that pipe (ConnStateData did)
242 
243  /* the ICP check here was erroneous
244  * - StoreEntry::releaseRequest was always called if entry was valid
245  */
246 
247  logRequest();
248 
249  loggingEntry(nullptr);
250 
251  if (request)
252  checkFailureRatio(request->error.category, al->hier.code);
253 
254  freeResources();
255 
256 #if USE_ADAPTATION
258 
259  if (adaptedBodySource != nullptr)
261 #endif
262 
263  delete calloutContext;
264 
266 
267  /* moving to the next connection is handled by the context free */
269 }
270 
271 bool
273 {
274  ClientHttpRequest *http_ = http;
275 
276  if (cbdataReferenceValid(http_))
277  return true;
278 
279  http = nullptr;
280 
281  cbdataReferenceDone(http_);
282 
283  return false;
284 }
285 
286 #if FOLLOW_X_FORWARDED_FOR
287 
301 static void
303 {
304  ClientRequestContext *calloutContext = (ClientRequestContext *) data;
305 
306  if (!calloutContext->httpStateIsValid())
307  return;
308 
309  ClientHttpRequest *http = calloutContext->http;
310  HttpRequest *request = http->request;
311 
312  if (answer.allowed() && request->x_forwarded_for_iterator.size() != 0) {
313 
314  /*
315  * Remove the last comma-delimited element from the
316  * x_forwarded_for_iterator and use it to repeat the cycle.
317  */
318  const char *p;
319  const char *asciiaddr;
320  int l;
321  Ip::Address addr;
322  p = request->x_forwarded_for_iterator.termedBuf();
323  l = request->x_forwarded_for_iterator.size();
324 
325  /*
326  * XXX x_forwarded_for_iterator should really be a list of
327  * IP addresses, but it's a String instead. We have to
328  * walk backwards through the String, biting off the last
329  * comma-delimited part each time. As long as the data is in
330  * a String, we should probably implement and use a variant of
331  * strListGetItem() that walks backwards instead of forwards
332  * through a comma-separated list. But we don't even do that;
333  * we just do the work in-line here.
334  */
335  /* skip trailing space and commas */
336  while (l > 0 && (p[l-1] == ',' || xisspace(p[l-1])))
337  --l;
338  request->x_forwarded_for_iterator.cut(l);
339  /* look for start of last item in list */
340  while (l > 0 && ! (p[l-1] == ',' || xisspace(p[l-1])))
341  --l;
342  asciiaddr = p+l;
343  if ((addr = asciiaddr)) {
344  request->indirect_client_addr = addr;
345  request->x_forwarded_for_iterator.cut(l);
348  /* override the default src_addr tested if we have to go deeper than one level into XFF */
349  ch->src_addr = request->indirect_client_addr;
350  }
351  if (++calloutContext->currentXffHopNumber < SQUID_X_FORWARDED_FOR_HOP_MAX) {
353  return;
354  }
356  debugs(28, DBG_CRITICAL, "ERROR: Ignoring trailing " << headerName << " addresses" <<
357  Debug::Extra << "addresses allowed by follow_x_forwarded_for: " << calloutContext->currentXffHopNumber <<
358  Debug::Extra << "last/accepted address: " << request->indirect_client_addr <<
359  Debug::Extra << "ignored trailing addresses: " << request->x_forwarded_for_iterator);
360  // fall through to resume clientAccessCheck() processing
361  }
362  }
363 
364  /* clean up, and pass control to clientAccessCheck */
366  /*
367  * Ensure that the access log shows the indirect client
368  * instead of the direct client.
369  */
370  http->al->cache.caddr = request->indirect_client_addr;
371  if (ConnStateData *conn = http->getConn())
372  conn->log_addr = request->indirect_client_addr;
373  }
374  request->x_forwarded_for_iterator.clean();
375  request->flags.done_follow_x_forwarded_for = true;
376 
377  if (answer.conflicted()) {
378  debugs(28, DBG_CRITICAL, "ERROR: Processing X-Forwarded-For. Stopping at IP address: " << request->indirect_client_addr );
379  }
380 
381  /* process actual access ACL as normal. */
382  calloutContext->clientAccessCheck();
383 }
384 #endif /* FOLLOW_X_FORWARDED_FOR */
385 
386 static void
388 {
389  ClientRequestContext *c = static_cast<ClientRequestContext*>(data);
390  c->hostHeaderIpVerify(ia, dns);
391 }
392 
393 void
395 {
397 
398  // note the DNS details for the transaction stats.
399  http->request->recordLookup(dns);
400 
401  // Is the NAT destination IP in DNS?
402  if (ia && ia->have(clientConn->local)) {
403  debugs(85, 3, "validate IP " << clientConn->local << " possible from Host:");
404  http->request->flags.hostVerified = true;
405  http->doCallouts();
406  return;
407  }
408  debugs(85, 3, "FAIL: validate IP " << clientConn->local << " possible from Host:");
409  hostHeaderVerifyFailed("local IP", "any domain IP");
410 }
411 
412 void
414 {
415  // IP address validation for Host: failed. Admin wants to ignore them.
416  // NP: we do not yet handle CONNECT tunnels well, so ignore for them
418  debugs(85, 3, "SECURITY ALERT: Host header forgery detected on " << http->getConn()->clientConnection <<
419  " (" << A << " does not match " << B << ") on URL: " << http->request->effectiveRequestUri());
420 
421  // MUST NOT cache (for now). It is tempting to set flags.noCache, but
422  // that flag is about satisfying _this_ request. We are actually OK with
423  // satisfying this request from the cache, but want to prevent _other_
424  // requests from being satisfied using this response.
426 
427  // XXX: when we have updated the cache key to base on raw-IP + URI this cacheable limit can go.
428  http->request->flags.hierarchical = false; // MUST NOT pass to peers (for now)
429  // XXX: when we have sorted out the best way to relay requests properly to peers this hierarchical limit can go.
430  http->doCallouts();
431  return;
432  }
433 
434  debugs(85, DBG_IMPORTANT, "SECURITY ALERT: Host header forgery detected on " <<
435  http->getConn()->clientConnection << " (" << A << " does not match " << B << ")");
436  if (const char *ua = http->request->header.getStr(Http::HdrType::USER_AGENT))
437  debugs(85, DBG_IMPORTANT, "SECURITY ALERT: By user agent: " << ua);
438  debugs(85, DBG_IMPORTANT, "SECURITY ALERT: on URL: " << http->request->effectiveRequestUri());
439 
440  // IP address validation for Host: failed. reject the connection.
442  clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
443  assert (repContext);
444  repContext->setReplyToError(ERR_CONFLICT_HOST, Http::scConflict,
445  nullptr,
446  http->getConn(),
447  http->request,
448  nullptr,
449 #if USE_AUTH
450  http->getConn() != nullptr && http->getConn()->getAuth() != nullptr ?
452 #else
453  nullptr);
454 #endif
456  clientStreamRead(node, http, node->readBuffer);
457 }
458 
459 void
461 {
462  // Require a Host: header.
463  const char *host = http->request->header.getStr(Http::HdrType::HOST);
464 
465  if (!host) {
466  // TODO: dump out the HTTP/1.1 error about missing host header.
467  // otherwise this is fine, can't forge a header value when its not even set.
468  debugs(85, 3, "validate skipped with no Host: header present.");
469  http->doCallouts();
470  return;
471  }
472 
473  if (http->request->flags.internal) {
474  // TODO: kill this when URL handling allows partial URLs out of accel mode
475  // and we no longer screw with the URL just to add our internal host there
476  debugs(85, 6, "validate skipped due to internal composite URL.");
477  http->doCallouts();
478  return;
479  }
480 
481  // TODO: Unify Host value parsing below with AnyP::Uri authority parsing
482  // Locate if there is a port attached, strip ready for IP lookup
483  char *portStr = nullptr;
484  char *hostB = xstrdup(host);
485  host = hostB;
486  if (host[0] == '[') {
487  // IPv6 literal.
488  portStr = strchr(hostB, ']');
489  if (portStr && *(++portStr) != ':') {
490  portStr = nullptr;
491  }
492  } else {
493  // Domain or IPv4 literal with port
494  portStr = strrchr(hostB, ':');
495  }
496 
497  uint16_t port = 0;
498  if (portStr) {
499  *portStr = '\0'; // strip the ':'
500  if (*(++portStr) != '\0') {
501  char *end = nullptr;
502  int64_t ret = strtoll(portStr, &end, 10);
503  if (end == portStr || *end != '\0' || ret < 1 || ret > 0xFFFF) {
504  // invalid port details. Replace the ':'
505  *(--portStr) = ':';
506  portStr = nullptr;
507  } else
508  port = (ret & 0xFFFF);
509  }
510  }
511 
512  debugs(85, 3, "validate host=" << host << ", port=" << port << ", portStr=" << (portStr?portStr:"NULL"));
514  // verify the Host: port (if any) matches the apparent destination
515  if (portStr && port != http->getConn()->clientConnection->local.port()) {
516  debugs(85, 3, "FAIL on validate port " << http->getConn()->clientConnection->local.port() <<
517  " matches Host: port " << port << " (" << portStr << ")");
518  hostHeaderVerifyFailed("intercepted port", portStr);
519  } else {
520  // XXX: match the scheme default port against the apparent destination
521 
522  // verify the destination DNS is one of the Host: headers IPs
524  }
525  } else if (!Config.onoff.hostStrictVerify) {
526  debugs(85, 3, "validate skipped.");
527  http->doCallouts();
528  } else if (strlen(host) != strlen(http->request->url.host())) {
529  // Verify forward-proxy requested URL domain matches the Host: header
530  debugs(85, 3, "FAIL on validate URL domain length " << http->request->url.host() << " matches Host: " << host);
532  } else if (matchDomainName(host, http->request->url.host()) != 0) {
533  // Verify forward-proxy requested URL domain matches the Host: header
534  debugs(85, 3, "FAIL on validate URL domain " << http->request->url.host() << " matches Host: " << host);
536  } else if (portStr && !http->request->url.port()) {
537  debugs(85, 3, "FAIL on validate portless URI matches Host: " << portStr);
538  hostHeaderVerifyFailed("portless URI", portStr);
539  } else if (portStr && port != *http->request->url.port()) {
540  // Verify forward-proxy requested URL domain matches the Host: header
541  debugs(85, 3, "FAIL on validate URL port " << *http->request->url.port() << " matches Host: port " << portStr);
542  hostHeaderVerifyFailed("URL port", portStr);
543  } else if (!portStr && http->request->method != Http::METHOD_CONNECT && http->request->url.port() != http->request->url.getScheme().defaultPort()) {
544  // Verify forward-proxy requested URL domain matches the Host: header
545  // Special case: we don't have a default-port to check for CONNECT. Assume URL is correct.
546  debugs(85, 3, "FAIL on validate URL port " << http->request->url.port().value_or(0) << " matches Host: default port " << http->request->url.getScheme().defaultPort().value_or(0));
547  hostHeaderVerifyFailed("URL port", "default port");
548  } else {
549  // Okay no problem.
550  debugs(85, 3, "validate passed.");
551  http->request->flags.hostVerified = true;
552  http->doCallouts();
553  }
554  safe_free(hostB);
555 }
556 
557 /* This is the entry point for external users of the client_side routines */
558 void
560 {
561 #if FOLLOW_X_FORWARDED_FOR
562  if (!http->request->flags.doneFollowXff() &&
565 
566  /* we always trust the direct client address for actual use */
569 
570  /* setup the XFF iterator for processing */
572 
573  /* begin by checking to see if we trust direct client enough to walk XFF */
576  return;
577  }
578 #endif
579 
580  if (Config.accessList.http) {
581  auto acl_checklist = clientAclChecklistCreate(Config.accessList.http, http);
583  } else {
584  debugs(0, DBG_CRITICAL, "No http_access configuration found. This will block ALL traffic");
586  }
587 }
588 
594 void
596 {
600  } else {
601  debugs(85, 2, "No adapted_http_access configuration. default: ALLOW");
603  }
604 }
605 
606 void
608 {
609  ClientRequestContext *calloutContext = (ClientRequestContext *) data;
610 
611  if (!calloutContext->httpStateIsValid())
612  return;
613 
614  calloutContext->clientAccessCheckDone(answer);
615 }
616 
617 void
619 {
620  Http::StatusCode status;
621  debugs(85, 2, "The request " << http->request->method << ' ' <<
622  http->uri << " is " << answer <<
623  "; last ACL checked: " << answer.lastCheckDescription());
624 
625 #if USE_AUTH
626  char const *proxy_auth_msg = "<null>";
627  if (http->getConn() != nullptr && http->getConn()->getAuth() != nullptr)
628  proxy_auth_msg = http->getConn()->getAuth()->denyMessage("<null>");
629  else if (http->request->auth_user_request != nullptr)
630  proxy_auth_msg = http->request->auth_user_request->denyMessage("<null>");
631 #endif
632 
633  if (!answer.allowed()) {
634  // auth has a grace period where credentials can be expired but okay not to challenge.
635 
636  /* Send an auth challenge or error */
637  // XXX: do we still need aclIsProxyAuth() ?
638  const auto auth_challenge = (answer == ACCESS_AUTH_REQUIRED || aclIsProxyAuth(answer.lastCheckedName));
639  debugs(85, 5, "Access Denied: " << http->uri);
640 #if USE_AUTH
641  if (auth_challenge)
642  debugs(33, 5, "Proxy Auth Message = " << (proxy_auth_msg ? proxy_auth_msg : "<null>"));
643 #endif
644 
645  auto page_id = FindDenyInfoPage(answer, answer != ACCESS_AUTH_REQUIRED);
646 
648 
649  if (auth_challenge) {
650 #if USE_AUTH
651  if (http->request->flags.sslBumped) {
652  /*SSL Bumped request, authentication is not possible*/
653  status = Http::scForbidden;
654  } else if (!http->flags.accel) {
655  /* Proxy authorisation needed */
657  } else {
658  /* WWW authorisation needed */
659  status = Http::scUnauthorized;
660  }
661 #else
662  // need auth, but not possible to do.
663  status = Http::scForbidden;
664 #endif
665  if (page_id == ERR_NONE)
667  } else {
668  status = Http::scForbidden;
669 
670  if (page_id == ERR_NONE)
671  page_id = ERR_ACCESS_DENIED;
672  }
673 
674  error = clientBuildError(page_id, status, nullptr, http->getConn(), http->request, http->al);
675 
676 #if USE_AUTH
678  http->getConn() != nullptr && http->getConn()->getAuth() != nullptr ?
680 #endif
681 
682  readNextRequest = true;
683  }
684 
685  /* ACCESS_ALLOWED continues here ... */
686  xfree(http->uri);
688  http->doCallouts();
689 }
690 
691 #if USE_ADAPTATION
692 void
694 {
695  debugs(93,3, this << " adaptationAclCheckDone called");
696 
697 #if ICAP_CLIENT
699  if (ih != nullptr) {
700  if (getConn() != nullptr && getConn()->clientConnection != nullptr) {
701 #if USE_OPENSSL
702  if (getConn()->clientConnection->isOpen()) {
703  ih->ssluser = sslGetUserEmail(fd_table[getConn()->clientConnection->fd].ssl.get());
704  }
705 #endif
706  }
707  ih->log_uri = log_uri;
708  ih->req_sz = req_sz;
709  }
710 #endif
711 
712  if (!g) {
713  debugs(85,3, "no adaptation needed");
714  doCallouts();
715  return;
716  }
717 
718  startAdaptation(g);
719 }
720 
721 #endif
722 
723 static void
725 {
726  ClientRequestContext *context = (ClientRequestContext *)data;
727  ClientHttpRequest *http = context->http;
728 
729  if (answer.allowed())
731  else {
732  Helper::Reply const nilReply(Helper::Error);
733  context->clientRedirectDone(nilReply);
734  }
735 }
736 
737 void
739 {
740  debugs(33, 5, "'" << http->uri << "'");
741  http->al->syncNotes(http->request);
745  } else
747 }
748 
753 static void
755 {
756  ClientRequestContext *context = static_cast<ClientRequestContext *>(data);
757  ClientHttpRequest *http = context->http;
758 
759  if (answer.allowed())
760  storeIdStart(http, clientStoreIdDoneWrapper, context);
761  else {
762  debugs(85, 3, "access denied expected ERR reply handling: " << answer);
763  Helper::Reply const nilReply(Helper::Error);
764  context->clientStoreIdDone(nilReply);
765  }
766 }
767 
773 void
775 {
776  debugs(33, 5,"'" << http->uri << "'");
777 
778  if (Config.accessList.store_id) {
779  auto acl_checklist = clientAclChecklistCreate(Config.accessList.store_id, http);
781  } else
783 }
784 
785 static int
787 {
788  HttpRequest *request = http->request;
789  HttpRequestMethod method = request->method;
790 
791  // intercepted requests MUST NOT (yet) be sent to peers unless verified
792  if (!request->flags.hostVerified && (request->flags.intercepted || request->flags.interceptTproxy))
793  return 0;
794 
795  /*
796  * IMS needs a private key, so we can use the hierarchy for IMS only if our
797  * neighbors support private keys
798  */
799 
800  if (request->flags.ims && !neighbors_do_private_keys)
801  return 0;
802 
803  /*
804  * This is incorrect: authenticating requests can be sent via a hierarchy
805  * (they can even be cached if the correct headers are set on the reply)
806  */
807  if (request->flags.auth)
808  return 0;
809 
810  if (method == Http::METHOD_TRACE)
811  return 1;
812 
813  if (method != Http::METHOD_GET)
814  return 0;
815 
816  if (request->flags.loopDetected)
817  return 0;
818 
819  if (request->url.getScheme() == AnyP::PROTO_HTTP)
820  return method.respMaybeCacheable();
821 
822  return 1;
823 }
824 
825 static void
827 {
828  HttpRequest *request = http->request;
829  HttpHeader *req_hdr = &request->header;
830  ConnStateData *http_conn = http->getConn();
831 
832  // Internal requests may be without a client connection
833  if (!http_conn)
834  return;
835 
836  request->flags.connectionAuthDisabled = http_conn->port->connection_auth_disabled;
837  if (!request->flags.connectionAuthDisabled) {
838  if (Comm::IsConnOpen(http_conn->pinning.serverConnection)) {
839  if (http_conn->pinning.auth) {
840  request->flags.connectionAuth = true;
841  request->flags.auth = true;
842  } else {
843  request->flags.connectionProxyAuth = true;
844  }
845  // These should already be linked correctly.
846  assert(request->clientConnectionManager == http_conn);
847  }
848  }
849 
850  /* check if connection auth is used, and flag as candidate for pinning
851  * in such case.
852  * Note: we may need to set flags.connectionAuth even if the connection
853  * is already pinned if it was pinned earlier due to proxy auth
854  */
855  if (!request->flags.connectionAuth) {
858  HttpHeaderEntry *e;
859  int may_pin = 0;
860  while ((e = req_hdr->getEntry(&pos))) {
862  const char *value = e->value.rawBuf();
863  if (strncasecmp(value, "NTLM ", 5) == 0
864  ||
865  strncasecmp(value, "Negotiate ", 10) == 0
866  ||
867  strncasecmp(value, "Kerberos ", 9) == 0) {
868  if (e->id == Http::HdrType::AUTHORIZATION) {
869  request->flags.connectionAuth = true;
870  may_pin = 1;
871  } else {
872  request->flags.connectionProxyAuth = true;
873  may_pin = 1;
874  }
875  }
876  }
877  }
878  if (may_pin && !request->pinnedConnection()) {
879  // These should already be linked correctly. Just need the ServerConnection to pinn.
880  assert(request->clientConnectionManager == http_conn);
881  }
882  }
883  }
884 }
885 
886 static void
888 {
889  HttpRequest *request = http->request;
890  HttpHeader *req_hdr = &request->header;
891  bool no_cache = false;
892 
893  request->imslen = -1;
894  request->ims = req_hdr->getTime(Http::HdrType::IF_MODIFIED_SINCE);
895 
896  if (request->ims > 0)
897  request->flags.ims = true;
898 
899  if (!request->flags.ignoreCc) {
900  if (request->cache_control) {
901  if (request->cache_control->hasNoCache())
902  no_cache=true;
903 
904  // RFC 2616: treat Pragma:no-cache as if it was Cache-Control:no-cache when Cache-Control is missing
905  } else if (req_hdr->has(Http::HdrType::PRAGMA))
906  no_cache = req_hdr->hasListMember(Http::HdrType::PRAGMA,"no-cache",',');
907  }
908 
909  if (request->method == Http::METHOD_OTHER) {
910  no_cache=true;
911  }
912 
913  if (no_cache) {
914 #if USE_HTTP_VIOLATIONS
915 
917  request->flags.nocacheHack = true;
918  else if (refresh_nocache_hack)
919  request->flags.nocacheHack = true;
920  else
921 #endif
922 
923  request->flags.noCache = true;
924  }
925 
926  /* ignore range header in non-GETs or non-HEADs */
927  if (request->method == Http::METHOD_GET || request->method == Http::METHOD_HEAD) {
928  // XXX: initialize if we got here without HttpRequest::parseHeader()
929  if (!request->range)
930  request->range = req_hdr->getRange();
931 
932  if (request->range) {
933  request->flags.isRanged = true;
935  /* XXX: This is suboptimal. We should give the stream the range set,
936  * and thereby let the top of the stream set the offset when the
937  * size becomes known. As it is, we will end up requesting from 0
938  * for evey -X range specification.
939  * RBC - this may be somewhat wrong. We should probably set the range
940  * iter up at this point.
941  */
942  node->readBuffer.offset = request->range->lowestOffset(0);
943  }
944  }
945 
946  /* Only HEAD and GET requests permit a Range or Request-Range header.
947  * If these headers appear on any other type of request, delete them now.
948  */
949  else {
950  req_hdr->delById(Http::HdrType::RANGE);
952  request->ignoreRange("neither HEAD nor GET");
953  }
954 
955  if (req_hdr->has(Http::HdrType::AUTHORIZATION))
956  request->flags.auth = true;
957 
958  clientCheckPinning(http);
959 
960  if (!request->url.userInfo().isEmpty())
961  request->flags.auth = true;
962 
963  if (req_hdr->has(Http::HdrType::VIA)) {
964  String s = req_hdr->getList(Http::HdrType::VIA);
965  /*
966  * ThisCache cannot be a member of Via header, "1.1 ThisCache" can.
967  * Note ThisCache2 has a space prepended to the hostname so we don't
968  * accidentally match super-domains.
969  */
970 
971  if (strListIsSubstr(&s, ThisCache2, ',')) {
972  request->flags.loopDetected = true;
973  }
974 
975 #if USE_FORW_VIA_DB
977 
978 #endif
979 
980  s.clean();
981  }
982 
983  // headers only relevant to reverse-proxy
984  if (request->flags.accelerated) {
985  // check for a cdn-info member with a cdn-id matching surrogate_id
986  // XXX: HttpHeader::hasListMember() does not handle OWS around ";" yet
988  request->flags.loopDetected = true;
989  }
990 
991  if (request->flags.loopDetected) {
992  debugObj(33, DBG_IMPORTANT, "WARNING: Forwarding loop detected for:\n",
993  request, (ObjPackMethod) & httpRequestPack);
994  }
995 
996 #if USE_FORW_VIA_DB
997 
998  if (req_hdr->has(Http::HdrType::X_FORWARDED_FOR)) {
1001  s.clean();
1002  }
1003 
1004 #endif
1005 
1006  if (http->request->maybeCacheable())
1007  request->flags.cachable.support();
1008  else
1009  request->flags.cachable.veto();
1010 
1011  if (clientHierarchical(http))
1012  request->flags.hierarchical = true;
1013 
1014  debugs(85, 5, "clientInterpretRequestHeaders: REQ_NOCACHE = " <<
1015  (request->flags.noCache ? "SET" : "NOT SET"));
1016  debugs(85, 5, "clientInterpretRequestHeaders: REQ_CACHABLE = " <<
1017  (request->flags.cachable ? "SET" : "NOT SET"));
1018  debugs(85, 5, "clientInterpretRequestHeaders: REQ_HIERARCHICAL = " <<
1019  (request->flags.hierarchical ? "SET" : "NOT SET"));
1020 
1021 }
1022 
1023 void
1024 clientRedirectDoneWrapper(void *data, const Helper::Reply &result)
1025 {
1026  ClientRequestContext *calloutContext = (ClientRequestContext *)data;
1027 
1028  if (!calloutContext->httpStateIsValid())
1029  return;
1030 
1031  calloutContext->clientRedirectDone(result);
1032 }
1033 
1034 void
1035 clientStoreIdDoneWrapper(void *data, const Helper::Reply &result)
1036 {
1037  ClientRequestContext *calloutContext = (ClientRequestContext *)data;
1038 
1039  if (!calloutContext->httpStateIsValid())
1040  return;
1041 
1042  calloutContext->clientStoreIdDone(result);
1043 }
1044 
1045 void
1047 {
1048  HttpRequest *old_request = http->request;
1049  debugs(85, 5, "'" << http->uri << "' result=" << reply);
1052 
1053  // Put helper response Notes into the transaction state record (ALE) eventually
1054  // do it early to ensure that no matter what the outcome the notes are present.
1055  if (http->al)
1056  http->al->syncNotes(old_request);
1057 
1058  UpdateRequestNotes(http->getConn(), *old_request, reply.notes);
1059 
1060  switch (reply.result) {
1061  case Helper::TimedOut:
1063  static const auto d = MakeNamedErrorDetail("REDIRECTOR_TIMEDOUT");
1065  debugs(85, DBG_IMPORTANT, "ERROR: URL rewrite helper: Timedout");
1066  }
1067  break;
1068 
1069  case Helper::Unknown:
1070  case Helper::TT:
1071  // Handler in redirect.cc should have already mapped Unknown
1072  // IF it contained valid entry for the old URL-rewrite helper protocol
1073  debugs(85, DBG_IMPORTANT, "ERROR: URL rewrite helper returned invalid result code. Wrong helper? " << reply);
1074  break;
1075 
1076  case Helper::BrokenHelper:
1077  debugs(85, DBG_IMPORTANT, "ERROR: URL rewrite helper: " << reply);
1078  break;
1079 
1080  case Helper::Error:
1081  // no change to be done.
1082  break;
1083 
1084  case Helper::Okay: {
1085  // #1: redirect with a specific status code OK status=NNN url="..."
1086  // #2: redirect with a default status code OK url="..."
1087  // #3: re-write the URL OK rewrite-url="..."
1088 
1089  const char *statusNote = reply.notes.findFirst("status");
1090  const char *urlNote = reply.notes.findFirst("url");
1091 
1092  if (urlNote != nullptr) {
1093  // HTTP protocol redirect to be done.
1094 
1095  // TODO: change default redirect status for appropriate requests
1096  // Squid defaults to 302 status for now for better compatibility with old clients.
1097  // HTTP/1.0 client should get 302 (Http::scFound)
1098  // HTTP/1.1 client contacting reverse-proxy should get 307 (Http::scTemporaryRedirect)
1099  // HTTP/1.1 client being diverted by forward-proxy should get 303 (Http::scSeeOther)
1101  if (statusNote != nullptr) {
1102  const char * result = statusNote;
1103  status = static_cast<Http::StatusCode>(atoi(result));
1104  }
1105 
1106  if (status == Http::scMovedPermanently
1107  || status == Http::scFound
1108  || status == Http::scSeeOther
1109  || status == Http::scPermanentRedirect
1110  || status == Http::scTemporaryRedirect) {
1111  http->redirect.status = status;
1112  http->redirect.location = xstrdup(urlNote);
1113  // TODO: validate the URL produced here is RFC 2616 compliant absolute URI
1114  } else {
1115  debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid " << status << " redirect Location: " << urlNote);
1116  }
1117  } else {
1118  // URL-rewrite wanted. Ew.
1119  urlNote = reply.notes.findFirst("rewrite-url");
1120 
1121  // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
1122  if (urlNote != nullptr && strcmp(urlNote, http->uri)) {
1123  AnyP::Uri tmpUrl;
1124  if (tmpUrl.parse(old_request->method, SBuf(urlNote))) {
1125  HttpRequest *new_request = old_request->clone();
1126  new_request->url = tmpUrl;
1127  debugs(61, 2, "URL-rewriter diverts URL from " << old_request->effectiveRequestUri() << " to " << new_request->effectiveRequestUri());
1128 
1129  // unlink bodypipe from the old request. Not needed there any longer.
1130  if (old_request->body_pipe != nullptr) {
1131  old_request->body_pipe = nullptr;
1132  debugs(61,2, "URL-rewriter diverts body_pipe " << new_request->body_pipe <<
1133  " from request " << old_request << " to " << new_request);
1134  }
1135 
1136  http->resetRequestXXX(new_request, true);
1137  old_request = nullptr;
1138  } else {
1139  debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid request: " <<
1140  old_request->method << " " << urlNote << " " << old_request->http_ver);
1141  }
1142  }
1143  }
1144  }
1145  break;
1146  }
1147 
1148  /* XXX PIPELINE: This is inaccurate during pipelining */
1149 
1150  if (http->getConn() != nullptr && Comm::IsConnOpen(http->getConn()->clientConnection))
1152 
1153  assert(http->uri);
1154 
1155  http->doCallouts();
1156 }
1157 
1161 void
1163 {
1164  HttpRequest *old_request = http->request;
1165  debugs(85, 5, "'" << http->uri << "' result=" << reply);
1168 
1169  // Put helper response Notes into the transaction state record (ALE) eventually
1170  // do it early to ensure that no matter what the outcome the notes are present.
1171  if (http->al)
1172  http->al->syncNotes(old_request);
1173 
1174  UpdateRequestNotes(http->getConn(), *old_request, reply.notes);
1175 
1176  switch (reply.result) {
1177  case Helper::Unknown:
1178  case Helper::TT:
1179  // Handler in redirect.cc should have already mapped Unknown
1180  // IF it contained valid entry for the old helper protocol
1181  debugs(85, DBG_IMPORTANT, "ERROR: storeID helper returned invalid result code. Wrong helper? " << reply);
1182  break;
1183 
1184  case Helper::TimedOut:
1185  // Timeouts for storeID are not implemented
1186  case Helper::BrokenHelper:
1187  debugs(85, DBG_IMPORTANT, "ERROR: storeID helper: " << reply);
1188  break;
1189 
1190  case Helper::Error:
1191  // no change to be done.
1192  break;
1193 
1194  case Helper::Okay: {
1195  const char *urlNote = reply.notes.findFirst("store-id");
1196 
1197  // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
1198  if (urlNote != nullptr && strcmp(urlNote, http->uri) ) {
1199  // Debug section required for some very specific cases.
1200  debugs(85, 9, "Setting storeID with: " << urlNote );
1201  http->request->store_id = urlNote;
1202  http->store_id = urlNote;
1203  }
1204  }
1205  break;
1206  }
1207 
1208  http->doCallouts();
1209 }
1210 
1212 void
1214 {
1215  if (Config.accessList.noCache) {
1216  auto acl_checklist = clientAclChecklistCreate(Config.accessList.noCache, http);
1217  ACLFilledChecklist::NonBlockingCheck(std::move(acl_checklist), checkNoCacheDoneWrapper, this);
1218  } else {
1219  /* unless otherwise specified, we try to cache. */
1221  }
1222 }
1223 
1224 static void
1226 {
1227  ClientRequestContext *calloutContext = (ClientRequestContext *) data;
1228 
1229  if (!calloutContext->httpStateIsValid())
1230  return;
1231 
1232  calloutContext->checkNoCacheDone(answer);
1233 }
1234 
1235 void
1237 {
1238  if (answer.denied()) {
1239  http->request->flags.disableCacheUse("a cache deny rule matched");
1240  }
1241  http->doCallouts();
1242 }
1243 
1244 #if USE_OPENSSL
1245 bool
1247 {
1248  if (!http->getConn()) {
1249  http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
1250  return false;
1251  }
1252 
1254  if (http->request->flags.forceTunnel) {
1255  debugs(85, 5, "not needed; already decided to tunnel " << http->getConn());
1256  if (bumpMode != Ssl::bumpEnd)
1257  http->al->ssl.bumpMode = bumpMode; // inherited from bumped connection
1258  return false;
1259  }
1260 
1261  // If SSL connection tunneling or bumping decision has been made, obey it.
1262  if (bumpMode != Ssl::bumpEnd) {
1263  debugs(85, 5, "SslBump already decided (" << bumpMode <<
1264  "), " << "ignoring ssl_bump for " << http->getConn());
1265 
1266  // We need the following "if" for transparently bumped TLS connection,
1267  // because in this case we are running ssl_bump access list before
1268  // the doCallouts runs. It can be removed after the bug #4340 fixed.
1269  // We do not want to proceed to bumping steps:
1270  // - if the TLS connection with the client is already established
1271  // because we are accepting normal HTTP requests on TLS port,
1272  // or because of the client-first bumping mode
1273  // - When the bumping is already started
1274  if (!http->getConn()->switchedToHttps() &&
1275  !http->getConn()->serverBump())
1276  http->sslBumpNeed(bumpMode); // for processRequest() to bump if needed and not already bumped
1277  http->al->ssl.bumpMode = bumpMode; // inherited from bumped connection
1278  return false;
1279  }
1280 
1281  // If we have not decided yet, decide whether to bump now.
1282 
1283  // Bumping here can only start with a CONNECT request on a bumping port
1284  // (bumping of intercepted SSL conns is decided before we get 1st request).
1285  // We also do not bump redirected CONNECT requests.
1288  !http->getConn()->port->flags.tunnelSslBumping) {
1289  http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
1290  debugs(85, 5, "cannot SslBump this request");
1291  return false;
1292  }
1293 
1294  // Do not bump during authentication: clients would not proxy-authenticate
1295  // if we delay a 407 response and respond with 200 OK to CONNECT.
1297  http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
1298  debugs(85, 5, "no SslBump during proxy authentication");
1299  return false;
1300  }
1301 
1302  if (error) {
1303  debugs(85, 5, "SslBump applies. Force bump action on error " << errorTypeName(error->type));
1305  http->al->ssl.bumpMode = Ssl::bumpBump;
1306  return false;
1307  }
1308 
1309  debugs(85, 5, "SslBump possible, checking ACL");
1310 
1311  auto aclChecklist = clientAclChecklistCreate(Config.accessList.ssl_bump, http);
1313  return true;
1314 }
1315 
1320 static void
1322 {
1323  ClientRequestContext *calloutContext = static_cast<ClientRequestContext *>(data);
1324 
1325  if (!calloutContext->httpStateIsValid())
1326  return;
1327  calloutContext->sslBumpAccessCheckDone(answer);
1328 }
1329 
1330 void
1332 {
1333  if (!httpStateIsValid())
1334  return;
1335 
1336  const Ssl::BumpMode bumpMode = answer.allowed() ?
1337  static_cast<Ssl::BumpMode>(answer.kind) : Ssl::bumpSplice;
1338  http->sslBumpNeed(bumpMode); // for processRequest() to bump if needed
1339  http->al->ssl.bumpMode = bumpMode; // for logging
1340 
1341  if (bumpMode == Ssl::bumpTerminate) {
1342  const Comm::ConnectionPointer clientConn = http->getConn() ? http->getConn()->clientConnection : nullptr;
1343  if (Comm::IsConnOpen(clientConn)) {
1344  debugs(85, 3, "closing after Ssl::bumpTerminate ");
1345  clientConn->close();
1346  }
1347  return;
1348  }
1349 
1350  http->doCallouts();
1351 }
1352 #endif
1353 
1354 /*
1355  * Identify requests that do not go through the store and client side stream
1356  * and forward them to the appropriate location. All other requests, request
1357  * them.
1358  */
1359 void
1361 {
1362  debugs(85, 4, request->method << ' ' << uri);
1363 
1364  const bool untouchedConnect = request->method == Http::METHOD_CONNECT && !redirect.status;
1365 
1366 #if USE_OPENSSL
1367  if (untouchedConnect && sslBumpNeeded()) {
1369  sslBumpStart();
1370  return;
1371  }
1372 #endif
1373 
1374  if (untouchedConnect || request->flags.forceTunnel) {
1375  getConn()->stopReading(); // tunnels read for themselves
1376  tunnelStart(this);
1377  return;
1378  }
1379 
1380  httpStart();
1381 }
1382 
1383 void
1385 {
1386  // XXX: Re-initializes rather than updates. Should not be needed at all.
1388  debugs(85, 4, loggingTags().c_str() << " for '" << uri << "'");
1389 
1390  /* no one should have touched this */
1391  assert(out.offset == 0);
1392  /* Use the Stream Luke */
1394  clientStreamRead(node, this, node->readBuffer);
1395 }
1396 
1397 #if USE_OPENSSL
1398 
1399 void
1401 {
1402  debugs(83, 3, "sslBump required: "<< Ssl::bumpMode(mode));
1403  sslBumpNeed_ = mode;
1404 }
1405 
1406 // called when comm_write has completed
1407 static void
1408 SslBumpEstablish(const Comm::ConnectionPointer &, char *, size_t, Comm::Flag errflag, int, void *data)
1409 {
1410  ClientHttpRequest *r = static_cast<ClientHttpRequest*>(data);
1411  debugs(85, 5, "responded to CONNECT: " << r << " ? " << errflag);
1412 
1413  assert(r && cbdataReferenceValid(r));
1414  r->sslBumpEstablish(errflag);
1415 }
1416 
1417 void
1419 {
1420  // Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up
1421  if (errflag == Comm::ERR_CLOSING)
1422  return;
1423 
1424  if (errflag) {
1425  debugs(85, 3, "CONNECT response failure in SslBump: " << errflag);
1427  return;
1428  }
1429 
1430 #if USE_AUTH
1431  // Preserve authentication info for the ssl-bumped request
1432  if (request->auth_user_request != nullptr)
1433  getConn()->setAuth(request->auth_user_request, "SSL-bumped CONNECT");
1434 #endif
1435 
1436  assert(sslBumpNeeded());
1438 }
1439 
1440 void
1442 {
1443  debugs(85, 5, "Confirming " << Ssl::bumpMode(sslBumpNeed_) <<
1444  "-bumped CONNECT tunnel on FD " << getConn()->clientConnection);
1446 
1447  AsyncCall::Pointer bumpCall = commCbCall(85, 5, "ClientSocketContext::sslBumpEstablish",
1449 
1451  CommIoCbParams &params = GetCommParams<CommIoCbParams>(bumpCall);
1452  params.flag = Comm::OK;
1453  params.conn = getConn()->clientConnection;
1454  ScheduleCallHere(bumpCall);
1455  return;
1456  }
1457 
1459 
1460  const auto mb = al->reply->pack();
1461  // send an HTTP 200 response to kick client SSL negotiation
1462  // TODO: Unify with tunnel.cc and add a Server(?) header
1463  Comm::Write(getConn()->clientConnection, mb, bumpCall);
1464  delete mb;
1465 }
1466 
1467 #endif
1468 
1469 void
1471 {
1472  if (request)
1474  else
1475  al->updateError(error);
1476 }
1477 
1478 bool
1480 {
1481  // TODO: See also (and unify with) clientReplyContext::storeNotOKTransferDone()
1482  int64_t contentLength =
1484  assert(contentLength >= 0);
1485 
1486  if (out.offset < contentLength)
1487  return false;
1488 
1489  return true;
1490 }
1491 
1492 void
1494 {
1495  entry_ = newEntry;
1496 }
1497 
1498 void
1500 {
1501  if (loggingEntry_)
1502  loggingEntry_->unlock("ClientHttpRequest::loggingEntry");
1503 
1504  loggingEntry_ = newEntry;
1505 
1506  if (loggingEntry_)
1507  loggingEntry_->lock("ClientHttpRequest::loggingEntry");
1508 }
1509 
1510 void
1512 {
1513  assignRequest(aRequest);
1514  if (const auto csd = getConn()) {
1515  if (!csd->notes()->empty())
1516  request->notes()->appendNewOnly(csd->notes().getRaw());
1517  }
1518  // al is created in the constructor
1519  assert(al);
1520  if (!al->request) {
1521  al->request = request;
1522  HTTPMSGLOCK(al->request);
1523  al->syncNotes(request);
1524  }
1525 }
1526 
1527 void
1529 {
1530  const auto uriChanged = request->effectiveRequestUri() != newRequest->effectiveRequestUri();
1531  resetRequestXXX(newRequest, uriChanged);
1532 }
1533 
1534 void
1535 ClientHttpRequest::resetRequestXXX(HttpRequest *newRequest, const bool uriChanged)
1536 {
1537  assert(request != newRequest);
1538  clearRequest();
1539  assignRequest(newRequest);
1540  xfree(uri);
1542 
1543  if (uriChanged) {
1544  request->flags.redirected = true;
1546  }
1547 }
1548 
1549 void
1551 {
1552  if (!internalCheck(request->url.path()))
1553  return;
1554 
1556  debugs(33, 3, "internal URL found: " << request->url.getScheme() << "://" << request->url.authority(true));
1557  request->flags.internal = true;
1559  debugs(33, 3, "internal URL found: " << request->url.getScheme() << "://" << request->url.authority(true) << " (global_internal_static on)");
1562  request->url.port(getMyPort());
1563  request->flags.internal = true;
1565  } else {
1566  debugs(33, 3, "internal URL found: " << request->url.getScheme() << "://" << request->url.authority(true) << " (not this proxy)");
1567  }
1568 
1570  request->flags.disableCacheUse("cache manager URL");
1571 }
1572 
1573 void
1575 {
1576  assert(newRequest);
1577  assert(!request);
1578  const_cast<HttpRequest *&>(request) = newRequest;
1581 }
1582 
1583 void
1585 {
1586  HttpRequest *oldRequest = request;
1587  HTTPMSGUNLOCK(oldRequest);
1588  const_cast<HttpRequest *&>(request) = nullptr;
1589  absorbLogUri(nullptr);
1590 }
1591 
1592 /*
1593  * doCallouts() - This function controls the order of "callout"
1594  * executions, including non-blocking access control checks, the
1595  * redirector, and ICAP. Previously, these callouts were chained
1596  * together such that "clientAccessCheckDone()" would call
1597  * "clientRedirectStart()" and so on.
1598  *
1599  * The ClientRequestContext (aka calloutContext) class holds certain
1600  * state data for the callout/callback operations. Previously
1601  * ClientHttpRequest would sort of hand off control to ClientRequestContext
1602  * for a short time. ClientRequestContext would then delete itself
1603  * and pass control back to ClientHttpRequest when all callouts
1604  * were finished.
1605  *
1606  * This caused some problems for ICAP because we want to make the
1607  * ICAP callout after checking ACLs, but before checking the no_cache
1608  * list. We can't stuff the ICAP state into the ClientRequestContext
1609  * class because we still need the ICAP state after ClientRequestContext
1610  * goes away.
1611  *
1612  * Note that ClientRequestContext is created before the first call
1613  * to doCallouts().
1614  *
1615  * If one of the callouts notices that ClientHttpRequest is no
1616  * longer valid, it should call cbdataReferenceDone() so that
1617  * ClientHttpRequest's reference count goes to zero and it will get
1618  * deleted. ClientHttpRequest will then delete ClientRequestContext.
1619  *
1620  * Note that we set the _done flags here before actually starting
1621  * the callout. This is strictly for convenience.
1622  */
1623 
1624 void
1626 {
1628 
1629  if (!calloutContext->error) {
1630  // CVE-2009-0801: verify the Host: header is consistent with other known details.
1632  debugs(83, 3, "Doing calloutContext->hostHeaderVerify()");
1635  return;
1636  }
1637 
1639  debugs(83, 3, "Doing calloutContext->clientAccessCheck()");
1642  return;
1643  }
1644 
1645 #if USE_ADAPTATION
1650  request, nullptr, calloutContext->http->al, this))
1651  return; // will call callback
1652  }
1653 #endif
1654 
1655  if (!calloutContext->redirect_done) {
1656  calloutContext->redirect_done = true;
1657 
1658  if (Config.Program.redirect) {
1659  debugs(83, 3, "Doing calloutContext->clientRedirectStart()");
1662  return;
1663  }
1664  }
1665 
1667  debugs(83, 3, "Doing calloutContext->clientAccessCheck2()");
1670  return;
1671  }
1672 
1673  if (!calloutContext->store_id_done) {
1674  calloutContext->store_id_done = true;
1675 
1676  if (Config.Program.store_id) {
1677  debugs(83, 3,"Doing calloutContext->clientStoreIdStart()");
1680  return;
1681  }
1682  }
1683 
1685  debugs(83, 3, "Doing clientInterpretRequestHeaders()");
1688  }
1689 
1690  if (!calloutContext->no_cache_done) {
1691  calloutContext->no_cache_done = true;
1692 
1694  debugs(83, 3, "Doing calloutContext->checkNoCache()");
1696  return;
1697  }
1698  }
1699  } // if !calloutContext->error
1700 
1701  // Set appropriate MARKs and CONNMARKs if needed.
1702  if (getConn() && Comm::IsConnOpen(getConn()->clientConnection)) {
1703  ACLFilledChecklist ch(nullptr, request);
1704  ch.al = calloutContext->http->al;
1706  ch.my_addr = request->my_addr;
1707  ch.syncAle(request, log_uri);
1708 
1711  tos_t tos = aclMapTOS(Ip::Qos::TheConfig.tosToClient, &ch);
1712  if (tos)
1713  Ip::Qos::setSockTos(getConn()->clientConnection, tos);
1714 
1715  const auto packetMark = aclFindNfMarkConfig(Ip::Qos::TheConfig.nfmarkToClient, &ch);
1716  if (!packetMark.isEmpty())
1717  Ip::Qos::setSockNfmark(getConn()->clientConnection, packetMark.mark);
1718 
1719  const auto connmark = aclFindNfMarkConfig(Ip::Qos::TheConfig.nfConnmarkToClient, &ch);
1720  if (!connmark.isEmpty())
1721  Ip::Qos::setNfConnmark(getConn()->clientConnection, Ip::Qos::dirAccepted, connmark);
1722  }
1723  }
1724 
1725 #if USE_OPENSSL
1726  // Even with calloutContext->error, we call sslBumpAccessCheck() to decide
1727  // whether SslBump applies to this transaction. If it applies, we will
1728  // attempt to bump the client to serve the error.
1732  return;
1733  /* else no ssl bump required*/
1734  }
1735 #endif
1736 
1737  if (calloutContext->error) {
1738  // XXX: prformance regression. c_str() reallocates
1739  SBuf storeUriBuf(request->storeId());
1740  const char *storeUri = storeUriBuf.c_str();
1741  StoreEntry *e = storeCreateEntry(storeUri, storeUri, request->flags, request->method);
1742 #if USE_OPENSSL
1743  if (sslBumpNeeded()) {
1744  // We have to serve an error, so bump the client first.
1746  // set final error but delay sending until we bump
1747  Ssl::ServerBump *srvBump = new Ssl::ServerBump(this, e, Ssl::bumpClientFirst);
1749  calloutContext->error = nullptr;
1750  getConn()->setServerBump(srvBump);
1751  e->unlock("ClientHttpRequest::doCallouts+sslBumpNeeded");
1752  } else
1753 #endif
1754  {
1755  // send the error to the client now
1757  clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1758  assert (repContext);
1759  repContext->setReplyToStoreEntry(e, "immediate SslBump error");
1761  calloutContext->error = nullptr;
1763  getConn()->flags.readMore = true; // resume any pipeline reads.
1765  clientStreamRead(node, this, node->readBuffer);
1766  e->unlock("ClientHttpRequest::doCallouts-sslBumpNeeded");
1767  return;
1768  }
1769  }
1770 
1772  delete calloutContext;
1773  calloutContext = nullptr;
1774 
1775  debugs(83, 3, "calling processRequest()");
1776  processRequest();
1777 
1778 #if ICAP_CLIENT
1780  if (ih != nullptr)
1781  ih->logType = loggingTags();
1782 #endif
1783 }
1784 
1785 void
1787 {
1788  assert(request);
1789  const auto canonicalUri = request->canonicalCleanUrl();
1790  absorbLogUri(xstrndup(canonicalUri, MAX_URL));
1791 }
1792 
1793 void
1795 {
1796  assert(rawUri);
1797  // Should(!request);
1798 
1799  // TODO: SBuf() performance regression, fix by converting rawUri to SBuf
1800  char *canonicalUri = urlCanonicalCleanWithoutRequest(SBuf(rawUri), method, AnyP::UriScheme());
1801 
1802  absorbLogUri(AnyP::Uri::cleanup(canonicalUri));
1803 
1804  char *cleanedRawUri = AnyP::Uri::cleanup(rawUri);
1805  al->setVirginUrlForMissingRequest(SBuf(cleanedRawUri));
1806  xfree(cleanedRawUri);
1807 }
1808 
1809 void
1811 {
1812  xfree(log_uri);
1813  const_cast<char *&>(log_uri) = aUri;
1814 }
1815 
1816 void
1818 {
1819  assert(!uri);
1820  assert(aUri);
1821  // Should(!request);
1822 
1823  uri = xstrdup(aUri);
1824  // TODO: SBuf() performance regression, fix by converting setErrorUri() parameter to SBuf
1825  const SBuf errorUri(aUri);
1826  const auto canonicalUri = urlCanonicalCleanWithoutRequest(errorUri, HttpRequestMethod(), AnyP::UriScheme());
1827  absorbLogUri(xstrndup(canonicalUri, MAX_URL));
1828 
1829  al->setVirginUrlForMissingRequest(errorUri);
1830 }
1831 
1832 // XXX: This should not be a _request_ method. Move range_iter elsewhere.
1833 int64_t
1835 {
1836  assert(request);
1837  assert(request->range);
1838 
1840  range_iter.end = request->range->end();
1841  range_iter.debt_size = 0;
1842  const auto multipart = request->range->specs.size() > 1;
1843  if (multipart)
1845  range_iter.valid = true; // TODO: Remove.
1846  range_iter.updateSpec(); // TODO: Refactor to initialize rather than update.
1847 
1849  const auto &firstRange = *range_iter.pos;
1850  assert(firstRange);
1851  out.offset = firstRange->offset;
1852 
1853  return multipart ? mRangeCLen() : firstRange->length;
1854 }
1855 
1856 #if USE_ADAPTATION
1857 void
1860 {
1861  debugs(85, 3, "adaptation needed for " << this);
1865  new Adaptation::Iterator(request, nullptr, al, g));
1866 
1867  // we could try to guess whether we can bypass this adaptation
1868  // initiation failure, but it should not really happen
1870 }
1871 
1872 void
1874 {
1875  assert(cbdataReferenceValid(this)); // indicates bug
1878 
1879  switch (answer.kind) {
1881  handleAdaptedHeader(const_cast<Http::Message*>(answer.message.getRaw()));
1882  break;
1883 
1885  handleAdaptationBlock(answer);
1886  break;
1887 
1889  static const auto d = MakeNamedErrorDetail("CLT_REQMOD_ABORT");
1890  handleAdaptationFailure(d, !answer.final);
1891  break;
1892  }
1893  }
1894 }
1895 
1896 void
1898 {
1899  assert(msg);
1900 
1901  if (HttpRequest *new_req = dynamic_cast<HttpRequest*>(msg)) {
1902  resetRequest(new_req);
1903  assert(request->method.id());
1904  } else if (HttpReply *new_rep = dynamic_cast<HttpReply*>(msg)) {
1905  debugs(85,3, "REQMOD reply is HTTP reply");
1906 
1907  // subscribe to receive reply body
1908  if (new_rep->body_pipe != nullptr) {
1909  adaptedBodySource = new_rep->body_pipe;
1910  int consumer_ok = adaptedBodySource->setConsumerIfNotLate(this);
1911  assert(consumer_ok);
1912  }
1913 
1915  clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1916  assert(repContext);
1917  repContext->createStoreEntry(request->method, request->flags);
1918 
1921  storeEntry()->replaceHttpReply(new_rep);
1923 
1924  al->reply = new_rep;
1925 
1926  if (!adaptedBodySource) // no body
1927  storeEntry()->complete();
1928  clientGetMoreData(node, this);
1929  }
1930 
1931  // we are done with getting headers (but may be receiving body)
1933 
1935  doCallouts();
1936 }
1937 
1938 void
1940 {
1941  static const auto d = MakeNamedErrorDetail("REQMOD_BLOCK");
1945 }
1946 
1947 void
1949 {
1950  if (!adaptedBodySource)
1951  return;
1952 
1954 }
1955 
1956 void
1958 {
1960  assert(adaptedBodySource != nullptr);
1961 
1962  if (size_t contentSize = adaptedBodySource->buf().contentSize()) {
1963  const size_t spaceAvailable = storeEntry()->bytesWanted(Range<size_t>(0,contentSize));
1964 
1965  if (spaceAvailable < contentSize ) {
1966  // No or partial body data consuming
1967  typedef NullaryMemFunT<ClientHttpRequest> Dialer;
1968  AsyncCall::Pointer call = asyncCall(93, 5, "ClientHttpRequest::resumeBodyStorage",
1969  Dialer(this, &ClientHttpRequest::resumeBodyStorage));
1970  storeEntry()->deferProducer(call);
1971  }
1972 
1973  if (!spaceAvailable)
1974  return;
1975 
1976  if (spaceAvailable < contentSize )
1977  contentSize = spaceAvailable;
1978 
1980  const StoreIOBuffer ioBuf(&bpc.buf, request_satisfaction_offset, contentSize);
1981  storeEntry()->write(ioBuf);
1982  // assume StoreEntry::write() writes the entire ioBuf
1984  bpc.buf.consume(contentSize);
1985  bpc.checkIn();
1986  }
1987 
1988  if (adaptedBodySource->exhausted()) {
1989  // XXX: Setting receivedWholeAdaptedReply here is a workaround for a
1990  // regression, as described in https://bugs.squid-cache.org/show_bug.cgi?id=5187#c6
1992  debugs(85, Important(72), "WARNING: Squid bug 5187 workaround triggered");
1994  }
1995  // else wait for more body data
1996 }
1997 
1998 void
2000 {
2002 
2003  // distinguish this code path from future noteBodyProducerAborted() that
2004  // would continue storing/delivering (truncated) reply if necessary (TODO)
2006 
2007  // should we end request satisfaction now?
2008  if (adaptedBodySource != nullptr && adaptedBodySource->exhausted())
2010 }
2011 
2012 void
2014 {
2015  debugs(85,4, this << " ends request satisfaction");
2018 
2019  // TODO: anything else needed to end store entry formation correctly?
2021  // We received the entire reply per receivedWholeAdaptedReply.
2022  // We are called when we consumed everything received (per our callers).
2023  // We consume only what we store per noteMoreBodyDataAvailable().
2024  storeEntry()->completeSuccessfully("received, consumed, and, hence, stored the entire REQMOD reply");
2025  } else {
2026  storeEntry()->completeTruncated("REQMOD request satisfaction default");
2027  }
2028 }
2029 
2030 void
2032 {
2035 
2036  debugs(85,3, "REQMOD body production failed");
2037  if (request_satisfaction_mode) { // too late to recover or serve an error
2038  static const auto d = MakeNamedErrorDetail("CLT_REQMOD_RESP_BODY");
2041  Must(Comm::IsConnOpen(c));
2042  c->close(); // drastic, but we may be writing a response already
2043  } else {
2044  static const auto d = MakeNamedErrorDetail("CLT_REQMOD_REQ_BODY");
2046  }
2047 }
2048 
2049 void
2051 {
2052  debugs(85,3, "handleAdaptationFailure(" << bypassable << ")");
2053 
2054  const bool usedStore = storeEntry() && !storeEntry()->isEmpty();
2055  const bool usedPipe = request->body_pipe != nullptr &&
2056  request->body_pipe->consumedSize() > 0;
2057 
2058  if (bypassable && !usedStore && !usedPipe) {
2059  debugs(85,3, "ICAP REQMOD callout failed, bypassing: " << calloutContext);
2060  if (calloutContext)
2061  doCallouts();
2062  return;
2063  }
2064 
2065  debugs(85,3, "ICAP REQMOD callout failed, responding with error");
2066 
2068  clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2069  assert(repContext);
2070 
2071  calloutsError(ERR_ICAP_FAILURE, errDetail);
2072 
2073  if (calloutContext)
2074  doCallouts();
2075 }
2076 
2077 void
2078 ClientHttpRequest::callException(const std::exception &ex)
2079 {
2080  if (const auto clientConn = getConn() ? getConn()->clientConnection : nullptr) {
2081  if (Comm::IsConnOpen(clientConn)) {
2082  debugs(85, 3, "closing after exception: " << ex.what());
2083  clientConn->close(); // initiate orderly top-to-bottom cleanup
2084  return;
2085  }
2086  }
2087  debugs(85, DBG_IMPORTANT, "ClientHttpRequest exception without connection. Ignoring " << ex.what());
2088  // XXX: Normally, we mustStop() but we cannot do that here because it is
2089  // likely to leave Http::Stream and ConnStateData with a dangling http
2090  // pointer. See r13480 or XXX in Http::Stream class description.
2091 }
2092 #endif
2093 
2094 // XXX: modify and use with ClientRequestContext::clientAccessCheckDone too.
2095 void
2097 {
2098  // The original author of the code also wanted to pass an errno to
2099  // setReplyToError, but it seems unlikely that the errno reflects the
2100  // true cause of the error at this point, so I did not pass it.
2101  if (calloutContext) {
2102  ConnStateData * c = getConn();
2104  nullptr, c, request, al);
2105 #if USE_AUTH
2107  c != nullptr && c->getAuth() != nullptr ? c->getAuth() : request->auth_user_request;
2108 #endif
2109  calloutContext->error->detailError(errDetail);
2111  if (c != nullptr)
2112  c->expectNoForwarding();
2113  }
2114  //else if(calloutContext == NULL) is it possible?
2115 }
2116 
const MemBuf & buf() const
Definition: BodyPipe.h:137
static char * cleanup(const char *uri)
Definition: Uri.cc:1033
Definition: parse.c:104
void appendNewOnly(const NotePairs *src)
Definition: Notes.cc:386
void setLogUriToRawUri(const char *, const HttpRequestMethod &)
@ ERR_SECURE_CONNECT_FAIL
Definition: forward.h:31
@ METHOD_OTHER
Definition: MethodType.h:93
void resetRequest(HttpRequest *)
ClientHttpRequest(ConnStateData *)
int getMyPort(void)
Definition: tools.cc:1041
HttpHdrRange * getRange() const
Definition: HttpHeader.cc:1220
static HLPCB clientRedirectDoneWrapper
bool initiated(const CbcPointer< AsyncJob > &job) const
Must(initiated(initiate)) instead of Must(initiate.set()), for clarity.
Definition: Initiator.h:52
AnyP::ProtocolVersion http_ver
Definition: Message.h:72
void userInfo(const SBuf &s)
Definition: Uri.h:70
void ignoreRange(const char *reason)
forgets about the cached Range header (for a reason)
Definition: HttpRequest.cc:621
@ scUnauthorized
Definition: StatusCode.h:46
@ METHOD_HEAD
Definition: MethodType.h:28
#define DBG_CRITICAL
Definition: Stream.h:37
const char * rawBuf() const
Definition: SquidString.h:86
AnyP::Uri url
the request URI
Definition: HttpRequest.h:115
common parts of HttpRequest and HttpReply
Definition: Message.h:25
bool interceptTproxy
Set for requests handled by a "tproxy" port.
Definition: RequestFlags.h:70
@ ERR_READ_ERROR
Definition: forward.h:28
void setServerBump(Ssl::ServerBump *srvBump)
Definition: client_side.h:286
BodyPipe::Pointer body_pipe
optional pipeline to receive message body
Definition: Message.h:97
char * canonicalCleanUrl() const
Definition: HttpRequest.cc:813
const char * findFirst(const char *noteKey) const
Definition: Notes.cc:302
void noteAdaptationAnswer(const Adaptation::Answer &) override
Definition: Uri.h:31
void resetRequestXXX(HttpRequest *, bool uriChanged)
struct SquidConfig::@85 Port
@ ERR_GATEWAY_FAILURE
Definition: forward.h:67
Ip::Address src_addr
struct SquidConfig::@98 accessList
int setSockNfmark(const Comm::ConnectionPointer &conn, nfmark_t mark)
Definition: QosConfig.cc:589
const char * getStr(Http::HdrType id) const
Definition: HttpHeader.cc:1163
@ Error
Definition: ResultCode.h:19
void setAuth(const Auth::UserRequest::Pointer &aur, const char *cause)
Definition: client_side.cc:494
struct ClientHttpRequest::Redirect redirect
SupportOrVeto cachable
whether the response may be stored in the cache
Definition: RequestFlags.h:35
void fd_note(int fd, const char *s)
Definition: fd.cc:216
HttpHeader header
Definition: Message.h:74
int hasListMember(Http::HdrType id, const char *member, const char separator) const
Definition: HttpHeader.cc:1662
void errorAppendEntry(StoreEntry *entry, ErrorState *err)
Definition: errorpage.cc:738
#define FAILURE_MODE_TIME
void initRequest(HttpRequest *)
const ProxyProtocol::HeaderPointer & proxyProtocolHeader() const
Definition: client_side.h:360
RequestFlags flags
Definition: HttpRequest.h:141
@ Unknown
Definition: ResultCode.h:17
HttpHdrRange::iterator pos
ssize_t HttpHeaderPos
Definition: HttpHeader.h:45
void clientStreamRead(clientStreamNode *thisObject, ClientHttpRequest *http, StoreIOBuffer readBuffer)
bool final
whether the error, if any, cannot be bypassed
Definition: Answer.h:46
ConnStateData * getConn() const
String x_forwarded_for_iterator
Definition: HttpRequest.h:187
unsigned short icp
Definition: SquidConfig.h:141
acl_access * noCache
Definition: SquidConfig.h:366
static void clientAccessCheckDoneWrapper(Acl::Answer, void *)
#define HttpHeaderInitPos
Definition: HttpHeader.h:48
acl_access * adapted_http
Definition: SquidConfig.h:360
bool readNextRequest
whether Squid should read after error handling
#define ScheduleCallHere(call)
Definition: AsyncCall.h:166
void lock(const char *context)
Definition: store.cc:445
int hostStrictVerify
Definition: SquidConfig.h:337
const SBuf & lastCheckDescription() const
describes the ACL that was evaluated last while obtaining this answer (for debugging)
Definition: Acl.cc:123
void tunnelStart(ClientHttpRequest *)
Definition: tunnel.cc:1184
void error(char *format,...)
bool loopDetected
Definition: RequestFlags.h:40
void hostHeaderIpVerify(const ipcache_addrs *, const Dns::LookupDetails &)
Ip::Address log_addr
Definition: client_side.h:136
bool sslBumpNeeded() const
returns true if and only if the request needs to be bumped
@ ERR_CACHE_ACCESS_DENIED
Definition: forward.h:19
bool connectionAuth
Definition: RequestFlags.h:85
struct SquidConfig::@90 Program
int64_t bodySize(const HttpRequestMethod &) const
Definition: HttpReply.cc:377
bool parse(const HttpRequestMethod &, const SBuf &url)
Definition: Uri.cc:295
int64_t prepPartialResponseGeneration()
Comm::ConnectionPointer serverConnection
Definition: client_side.h:143
Definition: SBuf.h:93
BumpMode
Definition: support.h:132
@ ERR_CONFLICT_HOST
Definition: forward.h:48
ErrorState * error
saved error page for centralized/delayed processing
void startAdaptation(const Adaptation::ServiceGroupPointer &)
Initiate an asynchronous adaptation transaction which will call us back.
void SBufToCstring(char *d, const SBuf &s)
Definition: SBuf.h:756
void httpRequestPack(void *obj, Packable *p)
Definition: HttpRequest.cc:361
void setErrorUri(const char *)
@ scMovedPermanently
Definition: StatusCode.h:38
void handleAdaptationFailure(const ErrorDetail::Pointer &, bool bypassable=false)
#define xstrdup
bool done_follow_x_forwarded_for
Definition: RequestFlags.h:108
void updateLoggingTags(const LogTags_ot code)
update the code in the transaction processing tags
double request_failure_ratio
bool hostVerified
Definition: RequestFlags.h:68
bool maybeCacheable()
Definition: HttpRequest.cc:538
@ bumpTerminate
Definition: support.h:132
struct ClientHttpRequest::Flags flags
bool have(const Ip::Address &ip, size_t *position=nullptr) const
Definition: ipcache.cc:984
#define REDIRECT_DONE
Definition: defines.h:55
void clientAccessCheckDone(const Acl::Answer &)
String getList(Http::HdrType id) const
Definition: HttpHeader.cc:788
bool hierarchical
Definition: RequestFlags.h:38
static int clientHierarchical(ClientHttpRequest *http)
clientStream_status_t CSS(clientStreamNode *, ClientHttpRequest *)
@ bumpEnd
Definition: support.h:132
struct SquidConfig::@97 onoff
Auth::UserRequest::Pointer auth_user_request
Definition: HttpRequest.h:127
struct ClientHttpRequest::Out out
C * getRaw() const
Definition: RefCount.h:89
unsigned char tos_t
Definition: forward.h:27
void detailError(const ErrorDetail::Pointer &dCode)
set error type-specific detail code
Definition: errorpage.h:111
int cbdataReferenceValid(const void *p)
Definition: cbdata.cc:270
struct ConnStateData::@35 flags
static void clientFollowXForwardedForCheck(Acl::Answer answer, void *data)
ACLFilledChecklist::MakingPointer clientAclChecklistCreate(const acl_access *acl, ClientHttpRequest *http)
AccessLogEntry::Pointer al
info for the future access.log, and external ACL
bool IsConnOpen(const Comm::ConnectionPointer &conn)
Definition: Connection.cc:27
@ OK
Definition: Flag.h:16
const char * sslGetUserEmail(SSL *ssl)
Definition: support.cc:976
int global_internal_static
Definition: SquidConfig.h:322
#define REDIRECT_PENDING
Definition: defines.h:54
void HTTPMSGUNLOCK(M *&a)
Definition: Message.h:150
#define SQUID_X_FORWARDED_FOR_HOP_MAX
@ ERR_NONE
Definition: forward.h:15
void replaceHttpReply(const HttpReplyPointer &, const bool andStartWriting=true)
Definition: store.cc:1705
StatusCode
Definition: StatusCode.h:20
err_type
Definition: forward.h:14
ClientRequestContext(ClientHttpRequest *)
void assignRequest(HttpRequest *)
int matchDomainName(const char *h, const char *d, MatchDomainNameFlags flags)
Definition: Uri.cc:860
bool respMaybeCacheable() const
@ akForward
forward the supplied adapted HTTP message
Definition: Answer.h:29
void detailError(const err_type c, const ErrorDetail::Pointer &d)
sets error detail if no earlier detail was available
Definition: HttpRequest.h:101
@ ERR_CLOSING
Definition: Flag.h:24
time_t hit_only_mode_until
bool internalHostnameIs(const SBuf &arg)
Definition: internal.cc:165
CbcPointer< Initiate > initiateAdaptation(Initiate *x)
< starts freshly created initiate and returns a safe pointer to it
Definition: Initiator.cc:23
CSR clientGetMoreData
#define cbdataReference(var)
Definition: cbdata.h:348
bool setConsumerIfNotLate(const Consumer::Pointer &aConsumer)
Definition: BodyPipe.cc:228
bool connectionAuthDisabled
Definition: RequestFlags.h:87
@ IF_MODIFIED_SINCE
static int port
Definition: ldap_backend.cc:70
Error error
the first transaction problem encountered (or falsy)
Definition: HttpRequest.h:161
void noteBodyProductionEnded(BodyPipe::Pointer) override
RefCount< AsyncCallT< Dialer > > asyncCall(int aDebugSection, int aDebugLevel, const char *aName, const Dialer &aDialer)
Definition: AsyncCall.h:156
@ scSeeOther
Definition: StatusCode.h:40
void checkForInternalAccess()
Checks whether the current request is internal and adjusts it accordingly.
void syncAle(HttpRequest *adaptedRequest, const char *logUri) const override
assigns uninitialized adapted_request and url ALE components
bool exhausted() const
Definition: BodyPipe.cc:174
static void hostHeaderIpVerifyWrapper(const ipcache_addrs *ia, const Dns::LookupDetails &dns, void *data)
ClientHttpRequest * http
void fvdbCountVia(const SBuf &)
HttpHdrRangeIter range_iter
a transaction problem
Definition: Error.h:27
err_type FindDenyInfoPage(const Acl::Answer &answer, const bool redirect_allowed)
Definition: Gadgets.cc:34
bool readMore
needs comm_read (for this request or new requests)
Definition: client_side.h:139
static void Reset()
forgets the current context, setting it to nil/unknown
Definition: CodeContext.cc:77
const char * errorTypeName(err_type err)
Definition: Error.h:77
Definition: Range.h:18
@ ERR_ACCESS_DENIED
Definition: forward.h:18
int acl_uses_indirect_client
Definition: SquidConfig.h:326
void checkNoCache()
applies "cache allow/deny" rules, asynchronously if needed
void callException(const std::exception &) override
called when the job throws during an async call
#define MAX_URL
Definition: defines.h:76
MemBuf & buf
Definition: BodyPipe.h:74
bool ForSomeCacheManager(const SBuf &urlPath)
Definition: internal.cc:86
@ ERR_ICAP_FAILURE
Definition: forward.h:64
@ ACCESS_AUTH_REQUIRED
Definition: Acl.h:46
Http::MethodType id() const
Definition: RequestMethod.h:70
void clientRedirectDone(const Helper::Reply &)
static void checkFailureRatio(err_type, hier_code)
mb_size_t contentSize() const
available data size
Definition: MemBuf.h:47
void clearRequest()
resets the current request and log_uri to nil
@ scTemporaryRedirect
Definition: StatusCode.h:43
void(* ObjPackMethod)(void *obj, Packable *p)
Definition: tools.h:33
struct timeval current_time
the current UNIX time in timeval {seconds, microseconds} format
Definition: gadgets.cc:18
iterator end()
void CSD(clientStreamNode *, ClientHttpRequest *)
client stream detach
void CSR(clientStreamNode *, ClientHttpRequest *)
client stream read
@ scForbidden
Definition: StatusCode.h:48
Ssl::BumpMode sslBumpMode
ssl_bump decision (Ssl::bumpEnd if n/a).
Definition: client_side.h:304
char ThisCache2[RFC2181_MAXHOSTNAMELEN<< 1]
void stopConsumingFrom(RefCount< BodyPipe > &)
Definition: BodyPipe.cc:118
@ HIER_NONE
Definition: hier_code.h:13
const HttpReply & baseReply() const
Definition: MemObject.h:60
iterates services in ServiceGroup, starting adaptation launchers
Definition: Iterator.h:31
wordlist * store_id
Definition: SquidConfig.h:202
acl_access * http
Definition: SquidConfig.h:359
Helper::ResultCode result
The helper response 'result' field.
Definition: Reply.h:59
void recordLookup(const Dns::LookupDetails &detail)
Definition: HttpRequest.cc:580
struct SquidConfig::UrlHelperTimeout onUrlRewriteTimeout
err_type type
Definition: errorpage.h:170
static uint32 A
Definition: md4.c:43
Ip::Address indirect_client_addr
Definition: HttpRequest.h:152
@ LOG_TAG_NONE
Definition: LogTags.h:41
void clearAdaptation(CbcPointer< Initiate > &x)
clears the pointer (does not call announceInitiatorAbort)
Definition: Initiator.cc:32
unsigned short port() const
Definition: Address.cc:798
ConnStateData * pinnedConnection()
Definition: HttpRequest.cc:725
SBuf StringToSBuf(const String &s)
create a new SBuf from a String by copying contents
Definition: StringConvert.h:17
Ip::Address local
Definition: Connection.h:146
void ipcache_nbgethostbyname(const char *name, IPH *handler, void *handlerData)
Definition: ipcache.cc:609
acl_access * ssl_bump
Definition: SquidConfig.h:388
static void NonBlockingCheck(MakingPointer &&p, ACLCB *cb, void *data)
int refresh_nocache_hack
NotePairs notes
Definition: Reply.h:62
Kind kind
the type of the answer
Definition: Answer.h:47
int delById(Http::HdrType id)
Definition: HttpHeader.cc:666
Http::HdrType id
Definition: HttpHeader.h:66
@ METHOD_CONNECT
Definition: MethodType.h:29
Adaptation::Icap::History::Pointer icapHistory() const
Returns possibly nil history, creating it if icap logging is enabled.
Definition: HttpRequest.cc:389
int unlock(const char *context)
Definition: store.cc:469
bool denied() const
Definition: Acl.h:88
Comm::ConnectionPointer conn
Definition: CommCalls.h:80
const char * internalHostname(void)
Definition: internal.cc:149
#define safe_free(x)
Definition: xalloc.h:73
bool hasNoCache(const String **val=nullptr) const
Definition: HttpHdrCc.h:89
time_t getTime(Http::HdrType id) const
Definition: HttpHeader.cc:1146
@ scPermanentRedirect
Definition: StatusCode.h:44
CommCbFunPtrCallT< Dialer > * commCbCall(int debugSection, int debugLevel, const char *callName, const Dialer &dialer)
Definition: CommCalls.h:312
bool hasOnlyIfCached() const
Definition: HttpHdrCc.h:145
int neighbors_do_private_keys
void noteMoreBodyDataAvailable(BodyPipe::Pointer) override
#define assert(EX)
Definition: assert.h:17
@ Okay
Definition: ResultCode.h:18
void clientStoreIdDone(const Helper::Reply &)
bool intercepted
Definition: RequestFlags.h:66
HttpHdrCc * cache_control
Definition: Message.h:76
bool switchedToHttps() const
Definition: client_side.h:284
void HTTPMSGLOCK(Http::Message *a)
Definition: Message.h:161
Comm::Flag flag
comm layer result status.
Definition: CommCalls.h:82
void hostHeaderVerifyFailed(const char *A, const char *B)
encapsulates DNS lookup results
Definition: LookupDetails.h:22
const HeaderTableRecord & lookup(const char *buf, const std::size_t len) const
look record type up by name (C-string and length)
const AnyP::UriScheme & getScheme() const
Definition: Uri.h:58
@ METHOD_TRACE
Definition: MethodType.h:30
Port defaultPort() const
Definition: UriScheme.cc:71
#define cbdataReferenceDone(var)
Definition: cbdata.h:357
@ toutActBypass
Definition: redirect.h:16
void write(StoreIOBuffer)
Definition: store.cc:780
Ip::Address my_addr
Definition: HttpRequest.h:155
@ scInternalServerError
Definition: StatusCode.h:73
HttpHdrRange * range
Definition: HttpRequest.h:143
void port(const Port p)
reset authority port subcomponent
Definition: Uri.h:90
const char * c_str()
Definition: SBuf.cc:516
void Write(const Comm::ConnectionPointer &conn, const char *buf, int size, AsyncCall::Pointer &callback, FREE *free_func)
Definition: Write.cc:33
int64_t strtoll(const char *nptr, char **endptr, int base)
Definition: strtoll.c:61
SBuf & authority(bool requirePort=false) const
Definition: Uri.cc:689
#define CBDATA_CLASS_INIT(type)
Definition: cbdata.h:325
size_t currentXffHopNumber
number of X-Forwarded-For header values processed so far
HttpRequest * clone() const override
Definition: HttpRequest.cc:175
time_t squid_curtime
Definition: stub_libtime.cc:20
@ ERR_DNS_FAIL
Definition: forward.h:35
Comm::ConnectionPointer clientConnection
Definition: Server.h:100
size_t bytesWanted(Range< size_t > const aRange, bool ignoreDelayPool=false) const
Definition: store.cc:213
char * xstrndup(const char *s, size_t n)
Definition: xstring.cc:56
StoreEntry * storeCreateEntry(const char *url, const char *logUrl, const RequestFlags &flags, const HttpRequestMethod &method)
Definition: store.cc:759
static std::ostream & Extra(std::ostream &)
Definition: debug.cc:1316
void noteAdaptationAclCheckDone(Adaptation::ServiceGroupPointer) override
bool connectionProxyAuth
Definition: RequestFlags.h:90
#define xfree
bool doneFollowXff() const
Definition: RequestFlags.h:128
CSD clientReplyDetach
ConnStateData * conn_
void completeSuccessfully(const char *whyWeAreSureWeStoredTheWholeReply)
Definition: store.cc:1017
summarizes adaptation service answer for the noteAdaptationAnswer() API
Definition: Answer.h:24
Flag
Definition: Flag.h:15
const LogTags & loggingTags() const
the processing tags associated with this request transaction.
int strListIsSubstr(const String *list, const char *s, char del)
Definition: StrList.cc:63
void veto()
makes decision() false regardless of past or future support() calls
Definition: SupportOrVeto.h:29
void sslBumpEstablish(Comm::Flag)
struct SquidConfig::@91 Accel
const HeaderLookupTable_t HeaderLookupTable
void sslBumpAccessCheckDone(const Acl::Answer &answer)
The callback function for ssl-bump access check list.
void stopReading()
cancels Comm::Read() if it is scheduled
Definition: Server.cc:60
#define fd_table
Definition: fde.h:189
void complete()
Definition: store.cc:1031
void switchToHttps(ClientHttpRequest *, Ssl::BumpMode bumpServerMode)
void expectNoForwarding()
cleans up virgin request [body] forwarding state
tos_t aclMapTOS(acl_tos *head, ACLChecklist *ch)
Checks for a TOS value to apply depending on the ACL.
Definition: FwdState.cc:1458
const Auth::UserRequest::Pointer & getAuth() const
Definition: client_side.h:123
HttpHdrRange::iterator end
@ scFound
Definition: StatusCode.h:39
struct ConnStateData::@36 pinning
Ssl::BumpMode sslBumpNeed_
whether (and how) the request needs to be bumped
bool accelerated
Definition: RequestFlags.h:62
void checkNoCacheDone(const Acl::Answer &)
static void checkNoCacheDoneWrapper(Acl::Answer, void *)
@ pointPreCache
Definition: Elements.h:18
HttpRequestMethod method
Definition: HttpRequest.h:114
void path(const char *p)
Definition: Uri.h:96
Config TheConfig
Globally available instance of Qos::Config.
Definition: QosConfig.cc:287
void fvdbCountForwarded(const SBuf &)
count occurrences of the given X-Forwarded-For header value
const char * denyMessage(char const *const default_message=nullptr) const
Definition: UserRequest.cc:127
Http::MessagePointer message
HTTP request or response to forward.
Definition: Answer.h:44
bool setNfConnmark(Comm::ConnectionPointer &conn, const ConnectionDirection connDir, const NfMarkConfig &cm)
@ PROTO_HTTP
Definition: ProtocolType.h:25
int log_uses_indirect_client
Definition: SquidConfig.h:328
std::vector< HttpHdrRangeSpec * > specs
const char * termedBuf() const
Definition: SquidString.h:92
@ LOG_TCP_DENIED
Definition: LogTags.h:55
bool allowed() const
Definition: Acl.h:82
static void clientRedirectAccessCheckDone(Acl::Answer answer, void *data)
wordlist * redirect
Definition: SquidConfig.h:201
void noteBodyProducerAborted(BodyPipe::Pointer) override
void handleAdaptedHeader(Http::Message *)
void resumeBodyStorage()
called by StoreEntry when it has more buffer space available
bool timestampsSet()
Definition: store.cc:1387
void cut(size_type newLength)
Definition: String.cc:203
Acl::Answer blockedToChecklistAnswer() const
creates an Acl::Answer from akBlock answer
Definition: Answer.cc:44
@ akError
no adapted message will come; see bypassable
Definition: Answer.h:31
CSS clientReplyStatus
Error bareError
a problem that occurred without a request (e.g., while parsing headers)
Definition: client_side.h:381
int has(Http::HdrType id) const
Definition: HttpHeader.cc:937
const SBuf storeId()
Definition: HttpRequest.cc:733
int reload_into_ims
Definition: SquidConfig.h:293
ErrorState * clientBuildError(err_type, Http::StatusCode, char const *url, const ConnStateData *, HttpRequest *, const AccessLogEntry::Pointer &)
size_type size() const
Definition: SquidString.h:73
void announceInitiatorAbort(CbcPointer< Initiate > &x)
inform the transaction about abnormal termination and clear the pointer
Definition: Initiator.cc:38
bool isEmpty() const
Definition: Store.h:65
@ bumpBump
Definition: support.h:132
@ ERR_CONNECT_FAIL
Definition: forward.h:30
void handleAdaptationBlock(const Adaptation::Answer &)
bool aclIsProxyAuth(const std::optional< SBuf > &name)
Definition: Gadgets.cc:62
#define Must(condition)
Definition: TextException.h:75
Ip::NfMarkConfig aclFindNfMarkConfig(acl_nfmark *head, ACLChecklist *ch)
Checks for a netfilter mark value to apply depending on the ACL.
Definition: FwdState.cc:1470
#define Important(id)
Definition: Messages.h:93
bool auth
pinned for www authentication
Definition: client_side.h:147
@ ACCESS_ALLOWED
Definition: Acl.h:42
size_t req_sz
raw request size on input, not current request size
bool internalCheck(const SBuf &urlPath)
Definition: internal.cc:72
@ ACCESS_DENIED
Definition: Acl.h:41
void redirectStart(ClientHttpRequest *http, HLPCB *handler, void *data)
Definition: redirect.cc:286
#define DBG_IMPORTANT
Definition: Stream.h:38
@ scProxyAuthenticationRequired
Definition: StatusCode.h:52
Ssl::ServerBump * serverBump()
Definition: client_side.h:285
static void clientCheckPinning(ClientHttpRequest *http)
static HttpReplyPointer MakeConnectionEstablished()
construct and return an HTTP/200 (Connection Established) response
Definition: HttpReply.cc:121
char * surrogate_id
Definition: SquidConfig.h:220
AnyP::Port port
destination port of the request that caused serverConnection
Definition: client_side.h:145
hier_code
Definition: hier_code.h:12
acl_access * redirector
Definition: SquidConfig.h:377
time_t ims
Definition: HttpRequest.h:145
String rangeBoundaryStr() const
Definition: client_side.cc:780
const AccessLogEntry::Pointer al
access.log entry
std::optional< SBuf > lastCheckedName
the name of the ACL (if any) that was evaluated last while obtaining this answer
Definition: Acl.h:105
int kind
the matched custom access list verb (or zero)
Definition: Acl.h:99
CbcPointer< Adaptation::Initiate > virginHeadSource
@ methodReqmod
Definition: Elements.h:17
@ BrokenHelper
Definition: ResultCode.h:20
void setLogUriToRequestUri()
sets log_uri when we know the current request
int setSockTos(const Comm::ConnectionPointer &conn, tos_t tos)
Definition: QosConfig.cc:557
bool conflicted() const
whether Squid is uncertain about the allowed() or denied() answer
Definition: Acl.h:91
void calloutsError(const err_type, const ErrorDetail::Pointer &)
Build an error reply. For use with the callouts.
void storeIdStart(ClientHttpRequest *http, HLPCB *handler, void *data)
Definition: redirect.cc:312
bool nocacheHack
Definition: RequestFlags.h:60
void update(const Error &)
if necessary, stores the given error information (if any)
Definition: Error.cc:51
@ dirAccepted
accepted (from a client by Squid)
Definition: QosConfig.h:71
bool receivedWholeAdaptedReply
noteBodyProductionEnded() was called
@ scConflict
Definition: StatusCode.h:54
char * urlCanonicalCleanWithoutRequest(const SBuf &url, const HttpRequestMethod &method, const AnyP::UriScheme &scheme)
Definition: Uri.cc:747
Ssl::BumpMode sslBumpNeed() const
returns raw sslBump mode value
ClientRequestContext * calloutContext
static void SslBumpEstablish(const Comm::ConnectionPointer &, char *, size_t, Comm::Flag errflag, int, void *data)
static void sslBumpAccessCheckDoneWrapper(Acl::Answer, void *)
void HLPCB(void *, const Helper::Reply &)
Definition: forward.h:33
err_type category
primary error classification (or ERR_NONE)
Definition: Error.h:55
void deferProducer(const AsyncCall::Pointer &producer)
call back producer when more buffer space is available
Definition: store.cc:366
void debugObj(int section, int level, const char *label, void *obj, ObjPackMethod pm)
Definition: tools.cc:938
void disableCacheUse(const char *reason)
Definition: RequestFlags.cc:30
#define xisspace(x)
Definition: xis.h:15
static void clientStoreIdAccessCheckDone(Acl::Answer answer, void *data)
StoreEntry * storeEntry() const
bool isOpen() const
Definition: Connection.h:101
StoreEntry * loggingEntry_
StoreEntry * loggingEntry() const
static uint32 B
Definition: md4.c:43
bool isOpen() const
Definition: client_side.cc:640
@ akBlock
block or deny the master xaction; see authority
Definition: Answer.h:30
int64_t lowestOffset(int64_t) const
@ bumpClientFirst
Definition: support.h:132
HttpHeaderEntry * getEntry(HttpHeaderPos *pos) const
Definition: HttpHeader.cc:583
void setScheme(const AnyP::ProtocolType &p, const char *str)
convert the URL scheme to that given
Definition: Uri.h:61
void consume(mb_size_t sz)
removes sz bytes and "packs" by moving content left
Definition: MemBuf.cc:168
@ METHOD_GET
Definition: MethodType.h:25
MemObject * memObject() const
iterator begin()
bool internalStaticCheck(const SBuf &urlPath)
Definition: internal.cc:79
const SBuf & effectiveRequestUri() const
RFC 7230 section 5.5 - Effective Request URI.
Definition: HttpRequest.cc:744
acl_access * followXFF
Definition: SquidConfig.h:391
void updateError(const Error &)
if necessary, stores new error information (if any)
NotePairs::Pointer notes()
Definition: HttpRequest.cc:752
Ip::Address client_addr
Definition: HttpRequest.h:149
void absorbLogUri(char *)
assigns log_uri with aUri without copying the entire C-string
void host(const char *src)
Definition: Uri.cc:123
bool forceTunnel
whether to forward via TunnelStateData (instead of FwdState)
Definition: RequestFlags.h:120
#define debugs(SECTION, LEVEL, CONTENT)
Definition: Stream.h:192
@ TimedOut
Definition: ResultCode.h:21
const char * bumpMode(int bm)
Definition: support.h:144
static void clientInterpretRequestHeaders(ClientHttpRequest *http)
String store_id
Definition: HttpRequest.h:139
static HLPCB clientStoreIdDoneWrapper
void completeTruncated(const char *whyWeConsiderTheReplyTruncated)
Definition: store.cc:1024
uint64_t consumedSize() const
Definition: BodyPipe.h:111
Http::StatusCode httpStatus
Definition: errorpage.h:173
Auth::UserRequest::Pointer auth_user_request
Definition: errorpage.h:175
CbcPointer< ConnStateData > clientConnectionManager
Definition: HttpRequest.h:232
static bool Start(Method method, VectPoint vp, HttpRequest *req, HttpReply *, const AccessLogEntryPointer &, Adaptation::Initiator *)
Definition: AccessCheck.cc:30
class SquidConfig Config
Definition: SquidConfig.cc:12
void UpdateRequestNotes(ConnStateData *csd, HttpRequest &request, NotePairs const &helperNotes)
Definition: HttpRequest.cc:760
HttpRequest *const request
ErrorDetail::Pointer MakeNamedErrorDetail(const char *name)
Definition: Detail.cc:54
void clean()
Definition: String.cc:103
@ PROXY_AUTHORIZATION
int64_t mRangeCLen() const
Definition: client_side.cc:740
@ bumpSplice
Definition: support.h:132
BodyPipe::Pointer adaptedBodySource

 

Introduction

Documentation

Support

Miscellaneous