Client.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 #include "squid.h"
10 #include "acl/FilledChecklist.h"
11 #include "acl/Gadgets.h"
12 #include "base/TextException.h"
13 #include "clients/Client.h"
14 #include "comm/Connection.h"
15 #include "comm/forward.h"
16 #include "comm/Write.h"
17 #include "error/Detail.h"
18 #include "errorpage.h"
19 #include "fd.h"
20 #include "HttpHdrContRange.h"
21 #include "HttpReply.h"
22 #include "HttpRequest.h"
23 #include "SquidConfig.h"
24 #include "StatCounters.h"
25 #include "Store.h"
26 #include "tools.h"
27 
28 #if USE_ADAPTATION
29 #include "adaptation/AccessCheck.h"
30 #include "adaptation/Answer.h"
31 #include "adaptation/Iterator.h"
32 #include "base/AsyncCall.h"
33 #endif
34 
35 // implemented in client_side_reply.cc until sides have a common parent
36 void purgeEntriesByUrl(HttpRequest * req, const char *url);
37 
38 Client::Client(FwdState *theFwdState) :
39  AsyncJob("Client"),
40  fwd(theFwdState),
41  request(fwd->request)
42 {
43  entry = fwd->entry;
44  entry->lock("Client");
45 }
46 
48 {
49  // paranoid: check that swanSong has been called
51 #if USE_ADAPTATION
54 #endif
55 
56  entry->unlock("Client");
57 
60 
61  if (responseBodyBuffer != nullptr) {
62  delete responseBodyBuffer;
63  responseBodyBuffer = nullptr;
64  }
65 }
66 
67 void
69 {
70  // get rid of our piping obligations
71  if (requestBodySource != nullptr)
73 
74 #if USE_ADAPTATION
76 #endif
77 
78  if (!doneWithServer())
79  closeServer();
80 
81  if (!doneWithFwd) {
82  doneWithFwd = "swanSong()";
84  }
85 
87 #if USE_ADAPTATION
88  Initiator::swanSong();
90 #endif
91 
92  // paranoid: check that swanSong has been called
93  // extra paranoid: yeah, I really mean it. they MUST pass here.
95 #if USE_ADAPTATION
98 #endif
99 }
100 
101 HttpReply *
103 {
105  return theVirginReply;
106 }
107 
108 const HttpReply *
109 Client::virginReply() const
110 {
112  return theVirginReply;
113 }
114 
115 HttpReply *
117 {
118  debugs(11,5, this << " setting virgin reply to " << rep);
120  assert(rep);
121  theVirginReply = rep;
123  if (fwd->al)
125  return theVirginReply;
126 }
127 
128 HttpReply *
130 {
132  return theFinalReply;
133 }
134 
135 HttpReply *
137 {
138  debugs(11,5, this << " setting final reply to " << rep);
139 
141  assert(rep);
142  theFinalReply = rep;
144  if (fwd->al)
146 
147  // give entry the reply because haveParsedReplyHeaders() expects it there
148  entry->replaceHttpReply(theFinalReply, false); // but do not write yet
149  haveParsedReplyHeaders(); // update the entry/reply (e.g., set timestamps)
151  entry->release();
152  entry->startWriting(); // write the updated entry to store
153 
154  return theFinalReply;
155 }
156 
157 void
158 Client::markParsedVirginReplyAsWhole(const char *reasonWeAreSure)
159 {
160  assert(reasonWeAreSure);
161  debugs(11, 3, reasonWeAreSure);
162 
163  // The code storing adapted reply takes care of markStoredReplyAsWhole().
164  // We need to take care of the remaining regular network-to-store case.
165 #if USE_ADAPTATION
166  if (startedAdaptation) {
167  debugs(11, 5, "adaptation handles markStoredReplyAsWhole()");
168  return;
169  }
170 #endif
171 
172  // Convert the "parsed whole virgin reply" event into the "stored..." event
173  // because, without adaptation, we store everything we parse: There is no
174  // buffer for parsed content; addVirginReplyBody() stores every parsed byte.
175  fwd->markStoredReplyAsWhole(reasonWeAreSure);
176 }
177 
178 // called when no more server communication is expected; may quit
179 void
181 {
182  debugs(11,5, "serverComplete " << this);
183 
184  if (!doneWithServer()) {
185  closeServer();
187  }
188 
189  completed = true;
190 
191  if (requestBodySource != nullptr)
193 
194  if (responseBodyBuffer != nullptr)
195  return;
196 
197  serverComplete2();
198 }
199 
200 void
202 {
203  debugs(11,5, "serverComplete2 " << this);
204 
205 #if USE_ADAPTATION
206  if (virginBodyDestination != nullptr)
208 
209  if (!doneWithAdaptation())
210  return;
211 #endif
212 
214 }
215 
216 bool Client::doneAll() const
217 {
218  return doneWithServer() &&
219 #if USE_ADAPTATION
220  doneWithAdaptation() &&
223 #endif
225 }
226 
227 // FTP side overloads this to work around multiple calls to fwd->complete
228 void
230 {
231  debugs(11,5, "completing forwarding for " << fwd);
232  assert(fwd != nullptr);
233  doneWithFwd = "completeForwarding()";
234  fwd->complete();
235 }
236 
237 // Register to receive request body
239 {
241  assert(r->body_pipe != nullptr);
244  debugs(11,3, "expecting request body from " <<
246  return true;
247  }
248 
249  debugs(11,3, "aborting on partially consumed request body: " <<
251  requestBodySource = nullptr;
252  return false;
253 }
254 
255 // Entry-dependent callbacks use this check to quit if the entry went bad
256 bool
257 Client::abortOnBadEntry(const char *abortReason)
258 {
259  if (entry->isAccepting())
260  return false;
261 
262  debugs(11,5, "entry is not Accepting!");
263  abortOnData(abortReason);
264  return true;
265 }
266 
267 // more request or adapted response body is available
268 void
270 {
271 #if USE_ADAPTATION
272  if (adaptedBodySource == bp) {
274  return;
275  }
276 #endif
277  if (requestBodySource == bp)
279 }
280 
281 // the entire request or adapted response body was provided, successfully
282 void
284 {
285 #if USE_ADAPTATION
286  if (adaptedBodySource == bp) {
288  return;
289  }
290 #endif
291  if (requestBodySource == bp)
293 }
294 
295 // premature end of the request or adapted response body production
296 void
298 {
299 #if USE_ADAPTATION
300  if (adaptedBodySource == bp) {
302  return;
303  }
304 #endif
305  if (requestBodySource == bp)
307 }
308 
309 bool
310 Client::abortOnData(const char *reason)
311 {
312  abortAll(reason);
313  return true;
314 }
315 
316 // more origin request body data is available
317 void
319 {
320  if (!requestSender)
322  else
323  debugs(9,3, "waiting for request body write to complete");
324 }
325 
326 // there will be no more handleMoreRequestBodyAvailable calls
327 void
329 {
331  if (!requestSender)
333  else
334  debugs(9,3, "waiting for request body write to complete");
335 }
336 
337 // called when we are done sending request body; kids extend this
338 void
340 {
341  debugs(9,3, "done sending request body");
342  assert(requestBodySource != nullptr);
344 
345  // kids extend this
346 }
347 
348 // called when body producers aborts; kids extend this
349 void
351 {
352  if (requestSender != nullptr)
353  debugs(9,3, "fyi: request body aborted while we were sending");
354 
355  fwd->dontRetry(true); // the problem is not with the server
356  stopConsumingFrom(requestBodySource); // requestSender, if any, will notice
357 
358  // kids extend this
359 }
360 
361 // called when we wrote request headers(!) or a part of the body
362 void
364 {
365  debugs(11, 5, "sentRequestBody: FD " << io.fd << ": size " << io.size << ": errflag " << io.flag << ".");
366  debugs(32,3, "sentRequestBody called");
367 
368  requestSender = nullptr;
369 
370  if (io.size > 0) {
372  statCounter.server.all.kbytes_out += io.size;
373  // kids should increment their counters
374  }
375 
376  if (io.flag == Comm::ERR_CLOSING)
377  return;
378 
379  if (!requestBodySource) {
380  debugs(9,3, "detected while-we-were-sending abort");
381  return; // do nothing;
382  }
383 
384  // both successful and failed writes affect response times
386 
387  if (io.flag) {
388  debugs(11, DBG_IMPORTANT, "ERROR: sentRequestBody failure: FD " << io.fd << ": " << xstrerr(io.xerrno));
389  ErrorState *err;
391  err->xerrno = io.xerrno;
392  fwd->fail(err);
393  abortOnData("I/O error while sending request body");
394  return;
395  }
396 
398  abortOnData("store entry aborted while sending request body");
399  return;
400  }
401 
404  else if (receivedWholeRequestBody)
406  else
407  debugs(9,3, "waiting for body production end or abort");
408 }
409 
410 void
412 {
413  assert(requestBodySource != nullptr);
415 
417 
418  if (!Comm::IsConnOpen(conn)) {
419  debugs(9,3, "cannot send request body to closing " << conn);
420  return; // wait for the kid's close handler; TODO: assert(closer);
421  }
422 
423  MemBuf buf;
424  if (getMoreRequestBody(buf) && buf.contentSize() > 0) {
425  debugs(9,3, "will write " << buf.contentSize() << " request body bytes");
427  requestSender = JobCallback(93,3, Dialer, this, Client::sentRequestBody);
428  Comm::Write(conn, &buf, requestSender);
429  } else {
430  debugs(9,3, "will wait for more request body bytes or eof");
431  requestSender = nullptr;
432  }
433 }
434 
436 bool
438 {
439  // default implementation does not encode request body content
440  Must(requestBodySource != nullptr);
441  return requestBodySource->getMoreData(buf);
442 }
443 
444 // Compares hosts in urls, returns false if different, no sheme, or no host.
445 static bool
446 sameUrlHosts(const char *url1, const char *url2)
447 {
448  // XXX: Want AnyP::Uri::parse() here, but it uses static storage and copying
449  const char *host1 = strchr(url1, ':');
450  const char *host2 = strchr(url2, ':');
451 
452  if (host1 && host2) {
453  // skip scheme slashes
454  do {
455  ++host1;
456  ++host2;
457  } while (*host1 == '/' && *host2 == '/');
458 
459  if (!*host1)
460  return false; // no host
461 
462  // increment while the same until we reach the end of the URL/host
463  while (*host1 && *host1 != '/' && *host1 == *host2) {
464  ++host1;
465  ++host2;
466  }
467  return *host1 == *host2;
468  }
469 
470  return false; // no URL scheme
471 }
472 
473 // purges entries that match the value of a given HTTP [response] header
474 static void
475 purgeEntriesByHeader(HttpRequest *req, const char *reqUrl, Http::Message *rep, Http::HdrType hdr)
476 {
477  const auto hdrUrl = rep->header.getStr(hdr);
478  if (!hdrUrl)
479  return;
480 
481  /*
482  * If the URL is relative, make it absolute so we can find it.
483  * If it's absolute, make sure the host parts match to avoid DOS attacks
484  * as per RFC 2616 13.10.
485  */
486  SBuf absUrlMaker;
487  const char *absUrl = nullptr;
488  if (urlIsRelative(hdrUrl)) {
489  if (req->method.id() == Http::METHOD_CONNECT)
490  absUrl = hdrUrl; // TODO: merge authority-uri and hdrUrl
491  else if (req->url.getScheme() == AnyP::PROTO_URN)
492  absUrl = req->url.absolute().c_str();
493  else {
494  AnyP::Uri tmpUrl = req->url;
495  if (*hdrUrl == '/') {
496  // RFC 3986 section 4.2: absolute-path reference
497  // for this logic replace the entire request-target URI path
498  tmpUrl.path(hdrUrl);
499  } else {
500  tmpUrl.addRelativePath(reqUrl);
501  }
502  absUrlMaker = tmpUrl.absolute();
503  absUrl = absUrlMaker.c_str();
504  }
505  } else if (!sameUrlHosts(reqUrl, hdrUrl)) {
506  return;
507  } else
508  absUrl = hdrUrl;
509 
510  purgeEntriesByUrl(req, absUrl);
511 }
512 
513 // some HTTP methods should purge matching cache entries
514 void
516 {
517  // only some HTTP methods should purge matching cache entries
518  if (!request->method.purgesOthers())
519  return;
520 
521  // and probably only if the response was successful
522  if (theFinalReply->sline.status() >= 400)
523  return;
524 
525  // XXX: should we use originalRequest() here?
527  const char *reqUrl = tmp.c_str();
528  debugs(88, 5, "maybe purging due to " << request->method << ' ' << tmp);
529  purgeEntriesByUrl(request.getRaw(), reqUrl);
532 }
533 
535 void
537 {
540 
541  // adaptation may overwrite old offset computed using the virgin response
542  currentOffset = 0;
543  if (const auto cr = theFinalReply->contentRange()) {
544  if (cr->spec.offset != HttpHdrRangeSpec::UnknownPosition)
545  currentOffset = cr->spec.offset;
546  }
547 }
548 
550 bool
552 {
553  if (const auto acl = Config.accessList.storeMiss) {
554  // This relatively expensive check is not in StoreEntry::checkCachable:
555  // That method lacks HttpRequest and may be called too many times.
556  ACLFilledChecklist ch(acl, originalRequest().getRaw());
557  ch.updateAle(fwd->al);
559  if (!ch.fastCheck().allowed()) { // when in doubt, block
560  debugs(20, 3, "store_miss prohibits caching");
561  return true;
562  }
563  }
564  return false;
565 }
566 
569 {
570  return request;
571 }
572 
573 #if USE_ADAPTATION
574 void
577 {
578  debugs(11, 5, "Client::startAdaptation() called");
579  // check whether we should be sending a body as well
580  // start body pipe to feed ICAP transaction if needed
582  HttpReply *vrep = virginReply();
583  assert(!vrep->body_pipe);
584  int64_t size = 0;
585  if (vrep->expectingBody(cause->method, size) && size) {
586  virginBodyDestination = new BodyPipe(this);
588  debugs(93, 6, "will send virgin reply body to " <<
589  virginBodyDestination << "; size: " << size);
590  if (size > 0)
592  }
593 
595  new Adaptation::Iterator(vrep, cause, fwd->al, group));
598 }
599 
600 // properly cleans up ICAP-related state
601 // may be called multiple times
603 {
604  debugs(11,5, "cleaning ICAP; ACL: " << adaptationAccessCheckPending);
605 
606  if (virginBodyDestination != nullptr)
608 
610 
611  if (adaptedBodySource != nullptr)
613 
614  if (!adaptationAccessCheckPending) // we cannot cancel a pending callback
615  assert(doneWithAdaptation()); // make sure the two methods are in sync
616 }
617 
618 bool
620 {
623 }
624 
625 // sends virgin reply body to ICAP, buffering excesses if needed
626 void
627 Client::adaptVirginReplyBody(const char *data, ssize_t len)
628 {
630 
631  if (!virginBodyDestination) {
632  debugs(11,3, "ICAP does not want more virgin body");
633  return;
634  }
635 
636  // grow overflow area if already overflowed
637  if (responseBodyBuffer) {
638  responseBodyBuffer->append(data, len);
639  data = responseBodyBuffer->content();
641  }
642 
643  const ssize_t putSize = virginBodyDestination->putMoreData(data, len);
644  data += putSize;
645  len -= putSize;
646 
647  // if we had overflow area, shrink it as necessary
648  if (responseBodyBuffer) {
649  if (putSize == responseBodyBuffer->contentSize()) {
650  delete responseBodyBuffer;
651  responseBodyBuffer = nullptr;
652  } else {
653  responseBodyBuffer->consume(putSize);
654  }
655  return;
656  }
657 
658  // if we did not have an overflow area, create it as needed
659  if (len > 0) {
662  responseBodyBuffer->init(4096, SQUID_TCP_SO_RCVBUF * 10);
663  responseBodyBuffer->append(data, len);
664  }
665 }
666 
667 // can supply more virgin response body data
668 void
670 {
671  if (responseBodyBuffer) {
672  addVirginReplyBody(nullptr, 0); // kick the buffered fragment alive again
673  if (completed && !responseBodyBuffer) {
674  serverComplete2();
675  return;
676  }
677  }
679 }
680 
681 // the consumer of our virgin response body aborted
682 void
684 {
686 
687  // do not force closeServer here in case we need to bypass AdaptationQueryAbort
688 
689  if (doneWithAdaptation()) // we may still be receiving adapted response
691 }
692 
693 // received adapted response headers (body may follow)
694 void
696 {
697  clearAdaptation(adaptedHeadSource); // we do not expect more messages
698 
699  switch (answer.kind) {
701  handleAdaptedHeader(const_cast<Http::Message*>(answer.message.getRaw()));
702  break;
703 
705  handleAdaptationBlocked(answer);
706  break;
707 
710  break;
711  }
712 }
713 
714 void
716 {
717  if (abortOnBadEntry("entry went bad while waiting for adapted headers")) {
718  // If the adapted response has a body, the ICAP side needs to know
719  // that nobody will consume that body. We will be destroyed upon
720  // return. Tell the ICAP side that it is on its own.
721  HttpReply *rep = dynamic_cast<HttpReply*>(msg);
722  assert(rep);
723  if (rep->body_pipe != nullptr)
725 
726  return;
727  }
728 
729  HttpReply *rep = dynamic_cast<HttpReply*>(msg);
730  assert(rep);
731  debugs(11,5, this << " setting adapted reply to " << rep);
732  setFinalReply(rep);
733 
735  if (rep->body_pipe != nullptr) {
736  // subscribe to receive adapted body
738  // assume that ICAP does not auto-consume on failures
739  const bool result = adaptedBodySource->setConsumerIfNotLate(this);
740  assert(result);
741  } else {
742  // no body
743  fwd->markStoredReplyAsWhole("setFinalReply() stored header-only adapted reply");
744  if (doneWithAdaptation()) // we may still be sending virgin response
746  }
747 }
748 
749 void
751 {
752  if (abortOnBadEntry("store entry aborted while kick producer callback"))
753  return;
754 
755  if (!adaptedBodySource)
756  return;
757 
759 
760  if (adaptedBodySource != nullptr && adaptedBodySource->exhausted())
762 }
763 
764 // more adapted response body is available
765 void
767 {
768  if (abortOnBadEntry("entry refuses adapted body"))
769  return;
770 
771  assert(entry);
772 
773  size_t contentSize = adaptedBodySource->buf().contentSize();
774 
775  if (!contentSize)
776  return; // XXX: bytesWanted asserts on zero-size ranges
777 
778  const size_t spaceAvailable = entry->bytesWanted(Range<size_t>(0, contentSize), true);
779 
780  if (spaceAvailable < contentSize ) {
781  // No or partial body data consuming
782  typedef NullaryMemFunT<Client> Dialer;
783  AsyncCall::Pointer call = asyncCall(93, 5, "Client::resumeBodyStorage",
784  Dialer(this, &Client::resumeBodyStorage));
785  entry->deferProducer(call);
786  }
787 
788  if (!spaceAvailable) {
789  debugs(11, 5, "NOT storing " << contentSize << " bytes of adapted " <<
790  "response body at offset " << adaptedBodySource->consumedSize());
791  return;
792  }
793 
794  if (spaceAvailable < contentSize ) {
795  debugs(11, 5, "postponing storage of " <<
796  (contentSize - spaceAvailable) << " body bytes");
797  contentSize = spaceAvailable;
798  }
799 
800  debugs(11,5, "storing " << contentSize << " bytes of adapted " <<
801  "response body at offset " << adaptedBodySource->consumedSize());
802 
804  const StoreIOBuffer ioBuf(&bpc.buf, currentOffset, contentSize);
805  currentOffset += ioBuf.length;
806  entry->write(ioBuf);
807  bpc.buf.consume(contentSize);
808  bpc.checkIn();
809 }
810 
811 // the entire adapted response body was produced, successfully
812 void
814 {
815  if (abortOnBadEntry("entry went bad while waiting for adapted body eof"))
816  return;
817 
818  // distinguish this code path from handleAdaptedBodyProducerAborted()
820 
821  // end consumption if we consumed everything
822  if (adaptedBodySource != nullptr && adaptedBodySource->exhausted())
824  // else resumeBodyStorage() will eventually consume the rest
825 }
826 
827 void
829 {
831 
833  // We received the entire adapted reply per receivedWholeAdaptedReply.
834  // We are called when we consumed everything received (per our callers).
835  // We consume only what we store per handleMoreAdaptedBodyAvailable().
836  fwd->markStoredReplyAsWhole("received,consumed=>stored the entire RESPMOD reply");
837  }
838 
840 }
841 
842 // premature end of the adapted response body
844 {
845  if (abortOnBadEntry("entry went bad while waiting for the now-aborted adapted body"))
846  return;
847 
848  Must(adaptedBodySource != nullptr);
849  if (!adaptedBodySource->exhausted()) {
850  debugs(11,5, "waiting to consume the remainder of the aborted adapted body");
851  return; // resumeBodyStorage() should eventually consume the rest
852  }
853 
855 
857  return;
858 
859  handleAdaptationCompleted(); // the user should get a truncated response
860 }
861 
862 // common part of noteAdaptationAnswer and handleAdaptedBodyProductionEnded
863 void
865 {
866  debugs(11,5, "handleAdaptationCompleted");
867  cleanAdaptation();
868 
869  // We stop reading origin response because we have no place to put it(*) and
870  // cannot use it. If some origin servers do not like that or if we want to
871  // reuse more pconns, we can add code to discard unneeded origin responses.
872  // (*) TODO: Is it possible that the adaptation xaction is still running?
873  if (mayReadVirginReplyBody()) {
874  debugs(11,3, "closing origin conn due to ICAP completion");
875  closeServer();
876  }
877 
879 }
880 
881 // common part of noteAdaptation*Aborted and noteBodyConsumerAborted methods
882 void
884 {
885  debugs(11,5, "handleAdaptationAborted; bypassable: " << bypassable <<
886  ", entry empty: " << entry->isEmpty());
887 
888  if (abortOnBadEntry("entry went bad while ICAP aborted"))
889  return;
890 
891  // TODO: bypass if possible
893  abortAll("adaptation failure with a filled entry");
894 }
895 
898 bool
900 {
901  if (entry->isEmpty()) {
902  debugs(11,8, "adaptation failure with an empty entry: " << *entry);
904  static const auto d = MakeNamedErrorDetail("ICAP_RESPMOD_EARLY");
905  err->detailError(d);
906  fwd->fail(err);
907  fwd->dontRetry(true);
908  abortAll("adaptation failure with an empty entry");
909  return true; // handled
910  }
911 
912  if (request) { // update logged info directly
913  static const auto d = MakeNamedErrorDetail("ICAP_RESPMOD_LATE");
915  }
916 
917  return false; // the caller must handle
918 }
919 
920 // adaptation service wants us to deny HTTP client access to this response
921 void
923 {
924  const auto blockedAnswer = answer.blockedToChecklistAnswer();
925 
926  debugs(11,5, blockedAnswer.lastCheckDescription());
927 
928  if (abortOnBadEntry("entry went bad while ICAP aborted"))
929  return;
930 
931  if (!entry->isEmpty()) { // too late to block (should not really happen)
932  if (request) {
933  static const auto d = MakeNamedErrorDetail("RESPMOD_BLOCK_LATE");
935  }
936  abortAll("late adaptation block");
937  return;
938  }
939 
940  debugs(11,7, "creating adaptation block response");
941 
942  auto page_id = FindDenyInfoPage(blockedAnswer, true);
943  if (page_id == ERR_NONE)
944  page_id = ERR_ACCESS_DENIED;
945 
946  const auto err = new ErrorState(page_id, Http::scForbidden, request.getRaw(), fwd->al);
947  static const auto d = MakeNamedErrorDetail("RESPMOD_BLOCK_EARLY");
948  err->detailError(d);
949  fwd->fail(err);
950  fwd->dontRetry(true);
951 
952  abortOnData("timely adaptation block");
953 }
954 
955 void
957 {
959 
960  if (abortOnBadEntry("entry went bad while waiting for ICAP ACL check"))
961  return;
962 
963  // TODO: Should non-ICAP and ICAP REPMOD pre-cache paths check this?
964  // That check now only happens on REQMOD pre-cache and REPMOD post-cache, in processReplyAccess().
965  if (virginReply()->expectedBodyTooLarge(*request)) {
967  return;
968  }
969  // TODO: Should we check receivedBodyTooLarge as well?
970 
971  if (!group) {
972  debugs(11,3, "no adapation needed");
975  return;
976  }
977 
978  startAdaptation(group, originalRequest().getRaw());
980 }
981 #endif
982 
983 void
985 {
986  const auto err = new ErrorState(ERR_TOO_BIG, Http::scForbidden, request.getRaw(), fwd->al);
987  fwd->fail(err);
988  fwd->dontRetry(true);
989  abortOnData("Virgin body too large.");
990 }
991 
992 // TODO: when HttpStateData sends all errors to ICAP,
993 // we should be able to move this at the end of setVirginReply().
994 void
996 {
997 #if USE_ADAPTATION
998  // TODO: merge with client side and return void to hide the on/off logic?
999  // The callback can be called with a NULL service if adaptation is off.
1002  originalRequest().getRaw(), virginReply(), fwd->al, this);
1003  debugs(11,5, "adaptationAccessCheckPending=" << adaptationAccessCheckPending);
1005  return;
1006 #endif
1007 
1009 }
1010 
1012 void
1013 Client::adjustBodyBytesRead(const int64_t delta)
1014 {
1015  int64_t &bodyBytesRead = originalRequest()->hier.bodyBytesRead;
1016 
1017  // if we got here, do not log a dash even if we got nothing from the server
1018  if (bodyBytesRead < 0)
1019  bodyBytesRead = 0;
1020 
1021  bodyBytesRead += delta; // supports negative and zero deltas
1022 
1023  // check for overflows ("infinite" response?) and underflows (a bug)
1024  Must(bodyBytesRead >= 0);
1025 }
1026 
1027 void
1029 {
1032 
1033  using DeferredReadDialer = NullaryMemFunT<Client>;
1034  AsyncCall::Pointer call = asyncCall(11, 5, "Client::noteDelayAwareReadChance",
1035  DeferredReadDialer(this, &Client::noteDelayAwareReadChance));
1036  entry->mem().delayRead(call);
1037 }
1038 
1039 void
1040 Client::addVirginReplyBody(const char *data, ssize_t len)
1041 {
1042  adjustBodyBytesRead(len);
1043 
1044 #if USE_ADAPTATION
1045  assert(!adaptationAccessCheckPending); // or would need to buffer while waiting
1046  if (startedAdaptation) {
1047  adaptVirginReplyBody(data, len);
1048  return;
1049  }
1050 #endif
1051  storeReplyBody(data, len);
1052 }
1053 
1054 // writes virgin or adapted reply body to store
1055 void
1056 Client::storeReplyBody(const char *data, ssize_t len)
1057 {
1058  // write even if len is zero to push headers towards the client side
1059  entry->write (StoreIOBuffer(len, currentOffset, (char*)data));
1060 
1061  currentOffset += len;
1062 }
1063 
1064 size_t
1065 Client::calcBufferSpaceToReserve(size_t space, const size_t wantSpace) const
1066 {
1067  if (space < wantSpace) {
1068  const size_t maxSpace = SBuf::maxSize; // absolute best
1069  space = min(wantSpace, maxSpace); // do not promise more than asked
1070  }
1071 
1072 #if USE_ADAPTATION
1073  if (responseBodyBuffer) {
1074  return 0; // Stop reading if already overflowed waiting for ICAP to catch up
1075  }
1076 
1077  if (virginBodyDestination != nullptr) {
1078  /*
1079  * BodyPipe buffer has a finite size limit. We
1080  * should not read more data from the network than will fit
1081  * into the pipe buffer or we _lose_ what did not fit if
1082  * the response ends sooner that BodyPipe frees up space:
1083  * There is no code to keep pumping data into the pipe once
1084  * response ends and serverComplete() is called.
1085  */
1086  const size_t adaptor_space = virginBodyDestination->buf().potentialSpaceSize();
1087 
1088  debugs(11,9, "Client may read up to min(" <<
1089  adaptor_space << ", " << space << ") bytes");
1090 
1091  if (adaptor_space < space)
1092  space = adaptor_space;
1093  }
1094 #endif
1095 
1096  return space;
1097 }
1098 
1099 size_t
1100 Client::replyBodySpace(const MemBuf &readBuf, const size_t minSpace) const
1101 {
1102  size_t space = readBuf.spaceSize(); // available space w/o heroic measures
1103  if (space < minSpace) {
1104  const size_t maxSpace = readBuf.potentialSpaceSize(); // absolute best
1105  space = min(minSpace, maxSpace); // do not promise more than asked
1106  }
1107 
1108 #if USE_ADAPTATION
1109  if (responseBodyBuffer) {
1110  return 0; // Stop reading if already overflowed waiting for ICAP to catch up
1111  }
1112 
1113  if (virginBodyDestination != nullptr) {
1114  /*
1115  * BodyPipe buffer has a finite size limit. We
1116  * should not read more data from the network than will fit
1117  * into the pipe buffer or we _lose_ what did not fit if
1118  * the response ends sooner that BodyPipe frees up space:
1119  * There is no code to keep pumping data into the pipe once
1120  * response ends and serverComplete() is called.
1121  *
1122  * If the pipe is totally full, don't register the read handler.
1123  * The BodyPipe will call our noteMoreBodySpaceAvailable() method
1124  * when it has free space again.
1125  */
1126  size_t adaptation_space =
1128 
1129  debugs(11,9, "Client may read up to min(" <<
1130  adaptation_space << ", " << space << ") bytes");
1131 
1132  if (adaptation_space < space)
1133  space = adaptation_space;
1134  }
1135 #endif
1136 
1137  return space;
1138 }
1139 
const MemBuf & buf() const
Definition: BodyPipe.h:137
const char * xstrerr(int error)
Definition: xstrerror.cc:83
void handleMoreRequestBodyAvailable()
Definition: Client.cc:318
static bool sameUrlHosts(const char *url1, const char *url2)
Definition: Client.cc:446
void storeReplyBody(const char *buf, ssize_t len)
Definition: Client.cc:1056
HttpReply * theVirginReply
Definition: Client.h:208
virtual bool getMoreRequestBody(MemBuf &buf)
either fill buf with available [encoded] request body bytes or return false
Definition: Client.cc:437
void noteAdaptationAnswer(const Adaptation::Answer &answer) override
Definition: Client.cc:695
bool expectingBody(const HttpRequestMethod &, int64_t &) const override
Definition: HttpReply.cc:528
StoreEntry * entry
Definition: Client.h:176
void noteAdaptationAclCheckDone(Adaptation::ServiceGroupPointer group) override
Definition: Client.cc:956
bool initiated(const CbcPointer< AsyncJob > &job) const
Must(initiated(initiate)) instead of Must(initiate.set()), for clarity.
Definition: Initiator.h:52
void delayRead()
Definition: Client.cc:1028
AnyP::Uri url
the request URI
Definition: HttpRequest.h:115
common parts of HttpRequest and HttpReply
Definition: Message.h:25
bool doneAll() const override
whether positive goal has been reached
Definition: Client.cc:216
void fd_bytes(const int fd, const int len, const IoDirection direction)
Definition: fd.cc:226
BodyPipe::Pointer body_pipe
optional pipeline to receive message body
Definition: Message.h:97
void endAdaptedBodyConsumption()
called when the entire adapted response body is consumed
Definition: Client.cc:828
Definition: Uri.h:31
void adaptVirginReplyBody(const char *buf, ssize_t len)
Definition: Client.cc:627
bool waitingForDelayAwareReadChance
whether we are waiting for MemObject::delayRead() to call us back
Definition: Client.h:198
struct SquidConfig::@98 accessList
bool completed
Definition: Client.h:90
const char * getStr(Http::HdrType id) const
Definition: HttpHeader.cc:1163
HttpHeader header
Definition: Message.h:74
AsyncCall::Pointer requestSender
Definition: Client.h:182
void noteMoreBodyDataAvailable(BodyPipe::Pointer) override
Definition: Client.cc:269
virtual void swanSong()
Definition: AsyncJob.h:61
bool final
whether the error, if any, cannot be bypassed
Definition: Answer.h:46
Client(FwdState *)
Definition: Client.cc:38
void setBodySize(uint64_t aSize)
Definition: BodyPipe.cc:147
MemObject & mem()
Definition: Store.h:47
void handleAdaptationCompleted()
Definition: Client.cc:864
void noteBodyConsumerAborted(BodyPipe::Pointer) override
Definition: Client.cc:683
struct StatCounters::@112::@122 all
void lock(const char *context)
Definition: store.cc:445
virtual void handleRequestBodyProducerAborted()=0
Definition: Client.cc:350
@ ENTRY_ABORTED
Definition: enums.h:110
AccessLogEntryPointer al
info for the future access.log entry
Definition: FwdState.h:204
HttpReplyPointer reply
virtual void abortAll(const char *reason)=0
abnormal transaction termination; reason is for debugging only
void init(mb_size_t szInit, mb_size_t szMax)
Definition: MemBuf.cc:93
Definition: SBuf.h:93
void maybePurgeOthers()
Definition: Client.cc:515
void serverComplete2()
Definition: Client.cc:201
bool purgesOthers() const
BodyPipe::Pointer requestBodySource
Definition: Client.h:181
static void purgeEntriesByHeader(HttpRequest *req, const char *reqUrl, Http::Message *rep, Http::HdrType hdr)
Definition: Client.cc:475
int fd
FD which the call was about. Set by the async call creator.
Definition: CommCalls.h:85
struct StatCounters::@112 server
C * getRaw() const
Definition: RefCount.h:89
uint16_t flags
Definition: Store.h:231
virtual const Comm::ConnectionPointer & dataConnection() const =0
void cleanAdaptation()
Definition: Client.cc:602
bool IsConnOpen(const Comm::ConnectionPointer &conn)
Definition: Connection.cc:27
void adjustBodyBytesRead(const int64_t delta)
initializes bodyBytesRead stats if needed and applies delta
Definition: Client.cc:1013
bool isAccepting() const
Definition: store.cc:1988
Http::StatusLine sline
Definition: HttpReply.h:56
void HTTPMSGUNLOCK(M *&a)
Definition: Message.h:150
@ ERR_NONE
Definition: forward.h:15
void replaceHttpReply(const HttpReplyPointer &, const bool andStartWriting=true)
Definition: store.cc:1705
void adaptOrFinalizeReply()
Definition: Client.cc:995
MemBuf * responseBodyBuffer
Definition: Client.h:173
void fail(ErrorState *err)
Definition: FwdState.cc:458
BodyPipe::Pointer virginBodyDestination
Definition: Client.h:185
bool startRequestBodyFlow()
Definition: Client.cc:238
@ akForward
forward the supplied adapted HTTP message
Definition: Answer.h:29
void startWriting()
Definition: store.cc:1721
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
CbcPointer< Initiate > initiateAdaptation(Initiate *x)
< starts freshly created initiate and returns a safe pointer to it
Definition: Initiator.cc:23
virtual void haveParsedReplyHeaders()
called when we have final (possibly adapted) reply headers; kids extend
Definition: Client.cc:536
int64_t currentOffset
Definition: Client.h:172
bool setConsumerIfNotLate(const Consumer::Pointer &aConsumer)
Definition: BodyPipe.cc:228
int xerrno
The last errno to occur. non-zero if flag is Comm::COMM_ERROR.
Definition: CommCalls.h:83
static const size_type maxSize
Maximum size of a SBuf. By design it MUST be < MAX(size_type)/2. Currently 256Mb.
Definition: SBuf.h:103
RefCount< AsyncCallT< Dialer > > asyncCall(int aDebugSection, int aDebugLevel, const char *aName, const Dialer &aDialer)
Definition: AsyncCall.h:156
virtual bool mayReadVirginReplyBody() const =0
whether we may receive more virgin response body bytes
size_t getMoreData(MemBuf &buf)
Definition: BodyPipe.cc:294
bool exhausted() const
Definition: BodyPipe.cc:174
void serverComplete()
Definition: Client.cc:180
void updateReply(const HttpReply::Pointer &)
virtual void completeForwarding()
Definition: Client.cc:229
err_type FindDenyInfoPage(const Acl::Answer &answer, const bool redirect_allowed)
Definition: Gadgets.cc:34
Definition: Range.h:18
@ ERR_ACCESS_DENIED
Definition: forward.h:18
@ PROTO_URN
Definition: ProtocolType.h:35
void handleMoreAdaptedBodyAvailable()
Definition: Client.cc:766
MemBuf & buf
Definition: BodyPipe.h:74
void handleAdaptedHeader(Http::Message *msg)
Definition: Client.cc:715
@ ERR_ICAP_FAILURE
Definition: forward.h:64
Http::MethodType id() const
Definition: RequestMethod.h:70
mb_size_t contentSize() const
available data size
Definition: MemBuf.h:47
int size
Definition: ModDevPoll.cc:69
void append(const char *c, int sz) override
Definition: MemBuf.cc:209
virtual bool doneAll() const
whether positive goal has been reached
Definition: AsyncJob.cc:112
void noteBodyProductionEnded(BodyPipe::Pointer) override
Definition: Client.cc:283
virtual void doneSendingRequestBody()=0
Definition: Client.cc:339
@ scForbidden
Definition: StatusCode.h:48
bool dontRetry()
Definition: FwdState.h:130
void resumeBodyStorage()
called by StoreEntry when it has more buffer space available
Definition: Client.cc:750
const HttpReply * virginReply() const
Definition: Client.cc:102
void stopConsumingFrom(RefCount< BodyPipe > &)
Definition: BodyPipe.cc:118
Http::StatusCode status() const
retrieve the status code for this status line
Definition: StatusLine.h:45
iterates services in ServiceGroup, starting adaptation launchers
Definition: Iterator.h:31
HttpReply * theFinalReply
Definition: Client.h:209
bool blockCaching()
whether to prevent caching of an otherwise cachable response
Definition: Client.cc:551
@ RELEASE_REQUEST
prohibits making the key public
Definition: enums.h:93
virtual void processReplyBody()=0
const Acl::Answer & fastCheck()
Definition: Checklist.cc:298
void clearAdaptation(CbcPointer< Initiate > &x)
clears the pointer (does not call announceInitiatorAbort)
Definition: Initiator.cc:32
@ scBadGateway
Definition: StatusCode.h:75
Definition: MemBuf.h:23
@ CONTENT_LOCATION
#define EBIT_TEST(flag, bit)
Definition: defines.h:67
void swanSong() override
Definition: Client.cc:68
Kind kind
the type of the answer
Definition: Answer.h:47
@ METHOD_CONNECT
Definition: MethodType.h:29
void handleAdaptedBodyProducerAborted()
Definition: Client.cc:843
int unlock(const char *context)
Definition: store.cc:469
#define assert(EX)
Definition: assert.h:17
void sendMoreRequestBody()
Definition: Client.cc:411
FwdState::Pointer fwd
Definition: Client.h:177
HierarchyLogEntry hier
Definition: HttpRequest.h:157
void purgeEntriesByUrl(HttpRequest *req, const char *url)
bool handledEarlyAdaptationAbort()
Definition: Client.cc:899
HttpReply * setFinalReply(HttpReply *r)
Definition: Client.cc:136
void HTTPMSGLOCK(Http::Message *a)
Definition: Message.h:161
virtual HttpRequestPointer originalRequest()
a hack to reach HttpStateData::orignal_request
Definition: Client.cc:568
Comm::Flag flag
comm layer result status.
Definition: CommCalls.h:82
const AnyP::UriScheme & getScheme() const
Definition: Uri.h:58
bool adaptationAccessCheckPending
Definition: Client.h:189
void write(StoreIOBuffer)
Definition: store.cc:780
#define Assure(condition)
Definition: Assure.h:35
#define JobCallback(dbgSection, dbgLevel, Dialer, job, method)
Convenience macro to create a Dialer-based job callback.
Definition: AsyncJobCalls.h:70
@ scInternalServerError
Definition: StatusCode.h:73
HttpReply * setVirginReply(HttpReply *r)
Definition: Client.cc:116
static const int64_t UnknownPosition
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
void delayRead(const AsyncCallPointer &)
Definition: MemObject.cc:445
bool receivedWholeRequestBody
handleRequestBodyProductionEnded called
Definition: Client.h:195
size_t bytesWanted(Range< size_t > const aRange, bool ignoreDelayPool=false) const
Definition: store.cc:213
void addRelativePath(const char *relUrl)
Definition: Uri.cc:836
HttpReply * finalReply()
Definition: Client.cc:129
int xerrno
Definition: errorpage.h:179
virtual void noteDelayAwareReadChance()=0
bool abortOnBadEntry(const char *abortReason)
Entry-dependent callbacks use this check to quit if the entry went bad.
Definition: Client.cc:257
summarizes adaptation service answer for the noteAdaptationAnswer() API
Definition: Answer.h:24
void markParsedVirginReplyAsWhole(const char *reasonWeAreSure)
Definition: Client.cc:158
BodyPipe::Pointer adaptedBodySource
Definition: Client.h:187
virtual bool doneWithAdaptation() const
Definition: Client.cc:619
void sendBodyIsTooLargeError()
Definition: Client.cc:984
int64_t bodyBytesRead
number of body bytes received from the next hop or -1
SBuf & absolute() const
Definition: Uri.cc:711
size_t calcBufferSpaceToReserve(const size_t space, const size_t wantSpace) const
determine how much space the buffer needs to reserve
Definition: Client.cc:1065
void startAdaptation(const Adaptation::ServiceGroupPointer &group, HttpRequest *cause)
Initiate an asynchronous adaptation transaction which will call us back.
Definition: Client.cc:576
@ pointPreCache
Definition: Elements.h:18
void handleAdaptationAborted(bool bypassable=false)
Definition: Client.cc:883
HttpRequestMethod method
Definition: HttpRequest.h:114
void path(const char *p)
Definition: Uri.h:96
Http::MessagePointer message
HTTP request or response to forward.
Definition: Answer.h:44
@ methodRespmod
Definition: Elements.h:17
bool allowed() const
Definition: Acl.h:82
size_t putMoreData(const char *buf, size_t size)
Definition: BodyPipe.cc:213
void addVirginReplyBody(const char *buf, ssize_t len)
Definition: Client.cc:1040
const char * status() const
Definition: BodyPipe.cc:446
const char * doneWithFwd
Definition: Client.h:202
void complete()
Definition: FwdState.cc:526
virtual void sentRequestBody(const CommIoCbParams &io)=0
Definition: Client.cc:363
mb_size_t potentialSpaceSize() const
Definition: MemBuf.cc:161
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
@ ERR_TOO_BIG
Definition: forward.h:40
const HttpHdrContRange * contentRange() const
Definition: HttpReply.cc:345
char * content()
start of the added data
Definition: MemBuf.h:41
mb_size_t spaceSize() const
Definition: MemBuf.cc:155
void expectNoConsumption()
there will be no more setConsumer() calls
Definition: BodyPipe.cc:267
@ ERR_WRITE_ERROR
Definition: forward.h:29
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
void noteBodyProducerAborted(BodyPipe::Pointer) override
Definition: Client.cc:297
#define Must(condition)
Definition: TextException.h:75
acl_access * storeMiss
Definition: SquidConfig.h:368
void handleRequestBodyProductionEnded()
Definition: Client.cc:328
void stopProducingFor(RefCount< BodyPipe > &, bool atEof)
Definition: BodyPipe.cc:107
#define DBG_IMPORTANT
Definition: Stream.h:38
virtual void maybeReadVirginBody()=0
read response data from the network
StoreEntry * entry
Definition: FwdState.h:202
bool urlIsRelative(const char *url)
Definition: Uri.cc:803
~Client() override
Definition: Client.cc:47
void release(const bool shareable=false)
Definition: store.cc:1146
virtual void closeServer()=0
virtual bool abortOnData(const char *reason)
Definition: Client.cc:310
const HttpReply & freshestReply() const
Definition: MemObject.h:68
void handleAdaptedBodyProductionEnded()
Definition: Client.cc:813
bool startedAdaptation
Definition: Client.h:190
bool receivedWholeAdaptedReply
handleAdaptedBodyProductionEnded() was called
Definition: Client.h:193
void deferProducer(const AsyncCall::Pointer &producer)
call back producer when more buffer space is available
Definition: store.cc:366
void markStoredReplyAsWhole(const char *whyWeAreSure)
Definition: FwdState.cc:575
@ akBlock
block or deny the master xaction; see authority
Definition: Answer.h:30
void consume(mb_size_t sz)
removes sz bytes and "packs" by moving content left
Definition: MemBuf.cc:168
CbcPointer< Adaptation::Initiate > adaptedHeadSource
Definition: Client.h:186
size_t replyBodySpace(const MemBuf &readBuf, const size_t minSpace) const
Definition: Client.cc:1100
const SBuf & effectiveRequestUri() const
RFC 7230 section 5.5 - Effective Request URI.
Definition: HttpRequest.cc:744
void handleAdaptationBlocked(const Adaptation::Answer &answer)
Definition: Client.cc:922
HttpRequest * request
Definition: FwdState.h:203
HttpRequestPointer request
Definition: Client.h:178
#define debugs(SECTION, LEVEL, CONTENT)
Definition: Stream.h:192
const A & min(A const &lhs, A const &rhs)
void updateAle(const AccessLogEntry::Pointer &)
uint64_t consumedSize() const
Definition: BodyPipe.h:111
void noteMoreBodySpaceAvailable(BodyPipe::Pointer) override
Definition: Client.cc:669
static bool Start(Method method, VectPoint vp, HttpRequest *req, HttpReply *, const AccessLogEntryPointer &, Adaptation::Initiator *)
Definition: AccessCheck.cc:30
void handleUnregisteredServerEnd()
Definition: FwdState.cc:804
class SquidConfig Config
Definition: SquidConfig.cc:12
ErrorDetail::Pointer MakeNamedErrorDetail(const char *name)
Definition: Detail.cc:54
StatCounters statCounter
Definition: StatCounters.cc:12
virtual bool doneWithServer() const =0

 

Introduction

Documentation

Support

Miscellaneous