ModXact.cc
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1996-2025 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 93 ICAP (RFC 3507) Client */
10 
11 #include "squid.h"
12 #include "AccessLogEntry.h"
13 #include "adaptation/Answer.h"
14 #include "adaptation/History.h"
15 #include "adaptation/icap/Client.h"
16 #include "adaptation/icap/Config.h"
21 #include "adaptation/Initiator.h"
22 #include "auth/UserRequest.h"
23 #include "base/TextException.h"
24 #include "base64.h"
25 #include "comm.h"
26 #include "comm/Connection.h"
27 #include "error/Detail.h"
30 #include "HttpHeaderTools.h"
31 #include "HttpReply.h"
32 #include "MasterXaction.h"
33 #include "parser/Tokenizer.h"
34 #include "sbuf/Stream.h"
35 
36 // flow and terminology:
37 // HTTP| --> receive --> encode --> write --> |network
38 // end | <-- send <-- parse <-- read <-- |end
39 
40 // TODO: replace gotEncapsulated() with something faster; we call it often
41 
44 
45 static constexpr auto TheBackupLimit = BodyPipe::MaxCapacity;
46 
48 
50 {
51  memset(this, 0, sizeof(*this));
52 }
53 
56  AsyncJob("Adaptation::Icap::ModXact"),
57  Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", aService),
58  virginConsumed(0),
59  bodyParser(nullptr),
60  canStartBypass(false), // too early
61  protectGroupBypass(true),
64  adaptHistoryId(-1),
65  trailerParser(nullptr),
66  alMaster(alp)
67 {
68  assert(virginHeader);
69 
70  virgin.setHeader(virginHeader); // sets virgin.body_pipe if needed
71  virgin.setCause(virginCause); // may be NULL
72 
73  // adapted header and body are initialized when we parse them
74 
75  // writing and reading ends are handled by Adaptation::Icap::Xaction
76 
77  // encoding
78  // nothing to do because we are using temporary buffers
79 
80  // parsing; TODO: do not set until we parse, see ICAPOptXact
81  icapReply = new HttpReply;
82  icapReply->protoPrefix = "ICAP/"; // TODO: make an IcapReply class?
83 
84  debugs(93,7, "initialized." << status());
85 }
86 
87 // initiator wants us to start
89 {
91 
92  // reserve an adaptation history slot (attempts are known at this time)
93  Adaptation::History::Pointer ah = virginRequest().adaptLogHistory();
94  if (ah != nullptr)
95  adaptHistoryId = ah->recordXactStart(service().cfg().key, icap_tr_start, attempts > 1);
96 
97  estimateVirginBody(); // before virgin disappears!
98 
99  canStartBypass = service().cfg().bypass;
100 
101  // it is an ICAP violation to send request to a service w/o known OPTIONS
102  // and the service may is too busy for us: honor Max-Connections and such
103  if (service().up() && service().availableForNew())
104  startWriting();
105  else
106  waitForService();
107 }
108 
110 {
111  const char *comment;
112  Must(!state.serviceWaiting);
113 
114  if (!service().up()) {
115  AsyncCall::Pointer call = JobCallback(93,5,
117 
118  service().callWhenReady(call);
119  comment = "to be up";
120  } else {
121  //The service is unavailable because of max-connection or other reason
122 
123  if (service().cfg().onOverload != srvWait) {
124  // The service is overloaded, but waiting to be available prohibited by
125  // user configuration (onOverload is set to "block" or "bypass")
126  if (service().cfg().onOverload == srvBlock)
127  disableBypass("not available", true);
128  else //if (service().cfg().onOverload == srvBypass)
129  canStartBypass = true;
130 
131  disableRetries();
132  disableRepeats("ICAP service is not available");
133 
134  debugs(93, 7, "will not wait for the service to be available" <<
135  status());
136 
137  throw TexcHere("ICAP service is not available");
138  }
139 
140  AsyncCall::Pointer call = JobCallback(93,5,
142  service().callWhenAvailable(call, state.waitedForService);
143  comment = "to be available";
144  }
145 
146  debugs(93, 7, "will wait for the service " << comment << status());
147  state.serviceWaiting = true; // after callWhenReady() which may throw
148  state.waitedForService = true;
149 }
150 
152 {
153  Must(state.serviceWaiting);
154  state.serviceWaiting = false;
155 
156  if (!service().up()) {
157  disableRetries();
158  disableRepeats("ICAP service is unusable");
159  throw TexcHere("ICAP service is unusable");
160  }
161 
162  if (service().availableForOld())
163  startWriting();
164  else
165  waitForService();
166 }
167 
169 {
170  Must(state.serviceWaiting);
171  state.serviceWaiting = false;
172 
173  if (service().up() && service().availableForOld())
174  startWriting();
175  else
176  waitForService();
177 }
178 
180 {
181  state.writing = State::writingConnect;
182 
183  decideOnPreview(); // must be decided before we decideOnRetries
184  decideOnRetries();
185 
186  openConnection();
187 }
188 
190 {
191  Must(state.writing == State::writingConnect);
192 
193  startReading(); // wait for early errors from the ICAP server
194 
195  MemBuf requestBuf;
196  requestBuf.init();
197 
198  makeRequestHeaders(requestBuf);
199  debugs(93, 9, "will write" << status() << ":\n" <<
200  (requestBuf.terminate(), requestBuf.content()));
201 
202  // write headers
203  state.writing = State::writingHeaders;
204  icap_tio_start = current_time;
205  scheduleWrite(requestBuf);
206 }
207 
209 {
210  debugs(93, 5, "Wrote " << sz << " bytes");
211 
212  if (state.writing == State::writingHeaders)
213  handleCommWroteHeaders();
214  else
215  handleCommWroteBody();
216 }
217 
219 {
220  Must(state.writing == State::writingHeaders);
221 
222  // determine next step
223  if (preview.enabled()) {
224  if (preview.done())
225  decideWritingAfterPreview("zero-size");
226  else
227  state.writing = State::writingPreview;
228  } else if (virginBody.expected()) {
229  state.writing = State::writingPrime;
230  } else {
231  stopWriting(true);
232  return;
233  }
234 
235  writeMore();
236 }
237 
239 {
240  debugs(93, 5, "checking whether to write more" << status());
241 
242  if (writer != nullptr) // already writing something
243  return;
244 
245  switch (state.writing) {
246 
247  case State::writingInit: // waiting for service OPTIONS
248  Must(state.serviceWaiting);
249  return;
250 
251  case State::writingConnect: // waiting for the connection to establish
252  case State::writingHeaders: // waiting for the headers to be written
253  case State::writingPaused: // waiting for the ICAP server response
254  case State::writingReallyDone: // nothing more to write
255  return;
256 
257  case State::writingAlmostDone: // was waiting for the last write
258  stopWriting(false);
259  return;
260 
261  case State::writingPreview:
262  writePreviewBody();
263  return;
264 
265  case State::writingPrime:
266  writePrimeBody();
267  return;
268 
269  default:
270  throw TexcHere("Adaptation::Icap::ModXact in bad writing state");
271  }
272 }
273 
275 {
276  debugs(93, 8, "will write Preview body from " <<
277  virgin.body_pipe << status());
278  Must(state.writing == State::writingPreview);
279  Must(virgin.body_pipe != nullptr);
280 
281  const size_t sizeMax = (size_t)virgin.body_pipe->buf().contentSize();
282  const size_t size = min(preview.debt(), sizeMax);
283  writeSomeBody("preview body", size);
284 
285  // change state once preview is written
286 
287  if (preview.done())
288  decideWritingAfterPreview("body");
289 }
290 
293 {
294  if (preview.ieof()) // nothing more to write
295  stopWriting(true);
296  else if (state.parsing == State::psIcapHeader) // did not get a reply yet
297  state.writing = State::writingPaused; // wait for the ICAP server reply
298  else
299  stopWriting(true); // ICAP server reply implies no post-preview writing
300 
301  debugs(93, 6, "decided on writing after " << kind << " preview" <<
302  status());
303 }
304 
306 {
307  Must(state.writing == State::writingPrime);
308  Must(virginBodyWriting.active());
309 
310  const size_t size = (size_t)virgin.body_pipe->buf().contentSize();
311  writeSomeBody("prime virgin body", size);
312 
313  if (virginBodyEndReached(virginBodyWriting)) {
314  debugs(93, 5, "wrote entire body");
315  stopWriting(true);
316  }
317 }
318 
319 void Adaptation::Icap::ModXact::writeSomeBody(const char *label, size_t size)
320 {
321  Must(!writer && state.writing < state.writingAlmostDone);
322  Must(virgin.body_pipe != nullptr);
323  debugs(93, 8, "will write up to " << size << " bytes of " <<
324  label);
325 
326  MemBuf writeBuf; // TODO: suggest a min size based on size and lastChunk
327 
328  writeBuf.init(); // note: we assume that last-chunk will fit
329 
330  const size_t writableSize = virginContentSize(virginBodyWriting);
331  const size_t chunkSize = min(writableSize, size);
332 
333  if (chunkSize) {
334  debugs(93, 7, "will write " << chunkSize <<
335  "-byte chunk of " << label);
336 
337  openChunk(writeBuf, chunkSize, false);
338  writeBuf.append(virginContentData(virginBodyWriting), chunkSize);
339  closeChunk(writeBuf);
340 
341  virginBodyWriting.progress(chunkSize);
342  virginConsume();
343  } else {
344  debugs(93, 7, "has no writable " << label << " content");
345  }
346 
347  const bool wroteEof = virginBodyEndReached(virginBodyWriting);
348  bool lastChunk = wroteEof;
349  if (state.writing == State::writingPreview) {
350  preview.wrote(chunkSize, wroteEof); // even if wrote nothing
351  lastChunk = lastChunk || preview.done();
352  }
353 
354  if (lastChunk) {
355  debugs(93, 8, "will write last-chunk of " << label);
356  addLastRequestChunk(writeBuf);
357  }
358 
359  debugs(93, 7, "will write " << writeBuf.contentSize()
360  << " raw bytes of " << label);
361 
362  if (writeBuf.hasContent()) {
363  scheduleWrite(writeBuf); // comm will free the chunk
364  } else {
365  writeBuf.clean();
366  }
367 }
368 
370 {
371  const bool ieof = state.writing == State::writingPreview && preview.ieof();
372  openChunk(buf, 0, ieof);
373  closeChunk(buf);
374 }
375 
376 void Adaptation::Icap::ModXact::openChunk(MemBuf &buf, size_t chunkSize, bool ieof)
377 {
378  buf.appendf((ieof ? "%x; ieof\r\n" : "%x\r\n"), (int) chunkSize);
379 }
380 
382 {
383  buf.append(ICAP::crlf, 2); // chunk-terminating CRLF
384 }
385 
387 {
388  const HttpRequest *request = virgin.cause ?
389  virgin.cause : dynamic_cast<const HttpRequest*>(virgin.header);
390  Must(request);
391  return *request;
392 }
393 
394 // did the activity reached the end of the virgin body?
396 {
397  return
398  !act.active() || // did all (assuming it was originally planned)
399  !virgin.body_pipe->expectMoreAfter(act.offset()); // will not have more
400 }
401 
402 // the size of buffered virgin body data available for the specified activity
403 // if this size is zero, we may be done or may be waiting for more data
405 {
406  Must(act.active());
407  // asbolute start of unprocessed data
408  const uint64_t dataStart = act.offset();
409  // absolute end of buffered data
410  const uint64_t dataEnd = virginConsumed + virgin.body_pipe->buf().contentSize();
411  Must(virginConsumed <= dataStart && dataStart <= dataEnd);
412  return static_cast<size_t>(dataEnd - dataStart);
413 }
414 
415 // pointer to buffered virgin body data available for the specified activity
417 {
418  Must(act.active());
419  const uint64_t dataStart = act.offset();
420  Must(virginConsumed <= dataStart);
421  return virgin.body_pipe->buf().content() + static_cast<size_t>(dataStart-virginConsumed);
422 }
423 
425 {
426  debugs(93, 9, "consumption guards: " << !virgin.body_pipe << isRetriable <<
427  isRepeatable << canStartBypass << protectGroupBypass);
428 
429  if (!virgin.body_pipe)
430  return; // nothing to consume
431 
432  if (isRetriable)
433  return; // do not consume if we may have to retry later
434 
435  BodyPipe &bp = *virgin.body_pipe;
436  const bool wantToPostpone = isRepeatable || canStartBypass || protectGroupBypass;
437 
438  if (wantToPostpone && bp.buf().spaceSize() > 0) {
439  // Postponing may increase memory footprint and slow the HTTP side
440  // down. Not postponing may increase the number of ICAP errors
441  // if the ICAP service fails. We may also use "potential" space to
442  // postpone more aggressively. Should the trade-off be configurable?
443  debugs(93, 8, "postponing consumption from " << bp.status());
444  return;
445  }
446 
447  const size_t have = static_cast<size_t>(bp.buf().contentSize());
448  const uint64_t end = virginConsumed + have;
449  uint64_t offset = end;
450 
451  debugs(93, 9, "max virgin consumption offset=" << offset <<
452  " acts " << virginBodyWriting.active() << virginBodySending.active() <<
453  " consumed=" << virginConsumed <<
454  " from " << virgin.body_pipe->status());
455 
456  if (virginBodyWriting.active())
457  offset = min(virginBodyWriting.offset(), offset);
458 
459  if (virginBodySending.active())
460  offset = min(virginBodySending.offset(), offset);
461 
462  Must(virginConsumed <= offset && offset <= end);
463 
464  if (const size_t size = static_cast<size_t>(offset - virginConsumed)) {
465  debugs(93, 8, "consuming " << size << " out of " << have <<
466  " virgin body bytes");
467  bp.consume(size);
468  virginConsumed += size;
469  Must(!isRetriable); // or we should not be consuming
470  disableRepeats("consumed content");
471  disableBypass("consumed content", true);
472  }
473 }
474 
476 {
477  writeMore();
478 }
479 
480 // Called when we do not expect to call comm_write anymore.
481 // We may have a pending write though.
482 // If stopping nicely, we will just wait for that pending write, if any.
484 {
485  if (state.writing == State::writingReallyDone)
486  return;
487 
488  if (writer != nullptr) {
489  if (nicely) {
490  debugs(93, 7, "will wait for the last write" << status());
491  state.writing = State::writingAlmostDone; // may already be set
492  checkConsuming();
493  return;
494  }
495  debugs(93, 3, "will NOT wait for the last write" << status());
496 
497  // Comm does not have an interface to clear the writer callback nicely,
498  // but without clearing the writer we cannot recycle the connection.
499  // We prevent connection reuse and hope that we can handle a callback
500  // call at any time, usually in the middle of the destruction sequence!
501  // Somebody should add comm_remove_write_handler() to comm API.
502  reuseConnection = false;
503  ignoreLastWrite = true;
504  }
505 
506  debugs(93, 7, "will no longer write" << status());
507  if (virginBodyWriting.active()) {
508  virginBodyWriting.disable();
509  virginConsume();
510  }
511  state.writing = State::writingReallyDone;
512  checkConsuming();
513 }
514 
516 {
517  if (!virginBodySending.active())
518  return;
519 
520  debugs(93, 7, "will no longer backup" << status());
521  virginBodySending.disable();
522  virginConsume();
523 }
524 
526 {
527  return Adaptation::Icap::Xaction::doneAll() && !state.serviceWaiting &&
528  doneSending() &&
529  doneReading() && state.doneWriting();
530 }
531 
533 {
534  Must(haveConnection());
535  Must(!reader);
536  Must(!adapted.header);
537  Must(!adapted.body_pipe);
538 
539  // we use the same buffer for headers and body and then consume headers
540  readMore();
541 }
542 
544 {
545  if (reader != nullptr || doneReading()) {
546  debugs(93,3, "returning from readMore because reader or doneReading()");
547  return;
548  }
549 
550  // do not fill readBuf if we have no space to store the result
551  if (adapted.body_pipe != nullptr &&
552  !adapted.body_pipe->buf().hasPotentialSpace()) {
553  debugs(93,3, "not reading because ICAP reply pipe is full");
554  return;
555  }
556 
557  if (readBuf.length() < SQUID_TCP_SO_RCVBUF)
558  scheduleRead();
559  else
560  debugs(93,3, "cannot read with a full buffer");
561 }
562 
563 // comm module read a portion of the ICAP response for us
565 {
566  Must(!state.doneParsing());
567  icap_tio_finish = current_time;
568  parseMore();
569  readMore();
570 }
571 
573 {
574  Must(state.sending == State::sendingVirgin);
575  Must(adapted.body_pipe != nullptr);
576  Must(virginBodySending.active());
577 
578  const size_t sizeMax = virginContentSize(virginBodySending);
579  debugs(93,5, "will echo up to " << sizeMax << " bytes from " <<
580  virgin.body_pipe->status());
581  debugs(93,5, "will echo up to " << sizeMax << " bytes to " <<
582  adapted.body_pipe->status());
583 
584  if (sizeMax > 0) {
585  const size_t size = adapted.body_pipe->putMoreData(virginContentData(virginBodySending), sizeMax);
586  debugs(93,5, "echoed " << size << " out of " << sizeMax <<
587  " bytes");
588  virginBodySending.progress(size);
589  disableRepeats("echoed content");
590  disableBypass("echoed content", true);
591  virginConsume();
592  }
593 
594  if (virginBodyEndReached(virginBodySending)) {
595  debugs(93, 5, "echoed all" << status());
596  stopSending(true);
597  } else {
598  debugs(93, 5, "has " <<
599  virgin.body_pipe->buf().contentSize() << " bytes " <<
600  "and expects more to echo" << status());
601  // TODO: timeout if virgin or adapted pipes are broken
602  }
603 }
604 
606 {
607  return state.sending == State::sendingDone;
608 }
609 
610 // stop (or do not start) sending adapted message body
612 {
613  debugs(93, 7, "Enter stop sending ");
614  if (doneSending())
615  return;
616  debugs(93, 7, "Proceed with stop sending ");
617 
618  if (state.sending != State::sendingUndecided) {
619  debugs(93, 7, "will no longer send" << status());
620  if (adapted.body_pipe != nullptr) {
621  virginBodySending.disable();
622  // we may leave debts if we were echoing and the virgin
623  // body_pipe got exhausted before we echoed all planned bytes
624  const bool leftDebts = adapted.body_pipe->needsMoreData();
625  stopProducingFor(adapted.body_pipe, nicely && !leftDebts);
626  }
627  } else {
628  debugs(93, 7, "will not start sending" << status());
629  Must(!adapted.body_pipe);
630  }
631 
632  state.sending = State::sendingDone;
633  checkConsuming();
634 }
635 
636 // should be called after certain state.writing or state.sending changes
638 {
639  // quit if we already stopped or are still using the pipe
640  if (!virgin.body_pipe || !state.doneConsumingVirgin())
641  return;
642 
643  debugs(93, 7, "will stop consuming" << status());
644  stopConsumingFrom(virgin.body_pipe);
645 }
646 
648 {
649  debugs(93, 5, "have " << readBuf.length() << " bytes to parse" << status());
650  debugs(93, 5, "\n" << readBuf);
651 
652  if (state.parsingHeaders())
653  parseHeaders();
654 
655  if (state.parsing == State::psBody)
656  parseBody();
657 
658  if (state.parsing == State::psIcapTrailer)
659  parseIcapTrailer();
660 }
661 
662 void Adaptation::Icap::ModXact::callException(const std::exception &e)
663 {
664  if (!canStartBypass || isRetriable) {
665  if (!isRetriable) {
666  if (const TextException *te = dynamic_cast<const TextException *>(&e))
667  detailError(new ExceptionErrorDetail(te->id()));
668  else
669  detailError(new ExceptionErrorDetail(Here().id()));
670  }
672  return;
673  }
674 
675  try {
676  debugs(93, 3, "bypassing " << inCall << " exception: " <<
677  e.what() << ' ' << status());
678  bypassFailure();
679  } catch (const TextException &bypassTe) {
680  detailError(new ExceptionErrorDetail(bypassTe.id()));
682  } catch (const std::exception &bypassE) {
683  detailError(new ExceptionErrorDetail(Here().id()));
685  }
686 }
687 
689 {
690  disableBypass("already started to bypass", false);
691 
692  Must(!isRetriable); // or we should not be bypassing
693  // TODO: should the same be enforced for isRepeatable? Check icap_repeat??
694 
695  prepEchoing();
696 
697  startSending();
698 
699  // end all activities associated with the ICAP server
700 
701  stopParsing(false);
702 
703  stopWriting(true); // or should we force it?
704  if (haveConnection()) {
705  reuseConnection = false; // be conservative
706  cancelRead(); // may not work; and we cannot stop connecting either
707  if (!doneWithIo())
708  debugs(93, 7, "Warning: bypass failed to stop I/O" << status());
709  }
710 
711  service().noteFailure(); // we are bypassing, but this is still a failure
712 }
713 
714 void Adaptation::Icap::ModXact::disableBypass(const char *reason, bool includingGroupBypass)
715 {
716  if (canStartBypass) {
717  debugs(93,7, "will never start bypass because " << reason);
718  canStartBypass = false;
719  }
720  if (protectGroupBypass && includingGroupBypass) {
721  debugs(93,7, "not protecting group bypass because " << reason);
722  protectGroupBypass = false;
723  }
724 }
725 
726 // note that allocation for echoing is done in handle204NoContent()
728 {
729  if (adapted.header) // already allocated
730  return;
731 
732  if (gotEncapsulated("res-hdr")) {
733  adapted.setHeader(new HttpReply);
734  setOutcome(service().cfg().method == ICAP::methodReqmod ?
736  } else if (gotEncapsulated("req-hdr")) {
737  adapted.setHeader(new HttpRequest(virginRequest().masterXaction));
738  setOutcome(xoModified);
739  } else
740  throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
741 }
742 
744 {
745  Must(state.parsingHeaders());
746 
747  if (state.parsing == State::psIcapHeader) {
748  debugs(93, 5, "parse ICAP headers");
749  parseIcapHead();
750  }
751 
752  if (state.parsing == State::psHttpHeader) {
753  debugs(93, 5, "parse HTTP headers");
754  parseHttpHead();
755  }
756 
757  if (state.parsingHeaders()) { // need more data
758  Must(mayReadMore());
759  return;
760  }
761 
762  startSending();
763 }
764 
765 // called after parsing all headers or when bypassing an exception
767 {
768  disableRepeats("sent headers");
769  disableBypass("sent headers", true);
770  sendAnswer(Answer::Forward(adapted.header));
771 
772  if (state.sending == State::sendingVirgin)
773  echoMore();
774  else {
775  // If we are not using the virgin HTTP object update the
776  // Http::Message::sources flag.
777  // The state.sending may set to State::sendingVirgin in the case
778  // of 206 responses too, where we do not want to update Http::Message::sources
779  // flag. However even for 206 responses the state.sending is
780  // not set yet to sendingVirgin. This is done in later step
781  // after the parseBody method called.
782  updateSources();
783  }
784 }
785 
787 {
788  Must(state.sending == State::sendingUndecided);
789 
790  if (!parseHead(icapReply.getRaw()))
791  return;
792 
793  if (expectIcapTrailers()) {
794  Must(!trailerParser);
795  trailerParser = new TrailerParser;
796  }
797 
798  static SBuf close("close", 5);
799  if (httpHeaderHasConnDir(&icapReply->header, close)) {
800  debugs(93, 5, "found connection close");
801  reuseConnection = false;
802  }
803 
804  switch (icapReply->sline.status()) {
805 
806  case Http::scContinue:
807  handle100Continue();
808  break;
809 
810  case Http::scOkay:
811  case Http::scCreated: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
812 
813  if (!validate200Ok()) {
814  throw TexcHere("Invalid ICAP Response");
815  } else {
816  handle200Ok();
817  }
818 
819  break;
820 
821  case Http::scNoContent:
822  handle204NoContent();
823  break;
824 
826  handle206PartialContent();
827  break;
828 
829  default:
830  debugs(93, 5, "ICAP status " << icapReply->sline.status());
831  handleUnknownScode();
832  break;
833  }
834 
835  const HttpRequest *request = dynamic_cast<HttpRequest*>(adapted.header);
836  if (!request)
837  request = &virginRequest();
838 
839  // update the cross-transactional database if needed (all status codes!)
840  if (const char *xxName = Adaptation::Config::masterx_shared_name) {
841  Adaptation::History::Pointer ah = request->adaptHistory(true);
842  if (ah != nullptr) { // TODO: reorder checks to avoid creating history
843  const String val = icapReply->header.getByName(xxName);
844  if (val.size() > 0) // XXX: HttpHeader lacks empty value detection
845  ah->updateXxRecord(xxName, val);
846  }
847  }
848 
849  // update the adaptation plan if needed (all status codes!)
850  if (service().cfg().routing) {
851  String services;
852  if (icapReply->header.getList(Http::HdrType::X_NEXT_SERVICES, &services)) {
853  Adaptation::History::Pointer ah = request->adaptHistory(true);
854  if (ah != nullptr)
855  ah->updateNextServices(services);
856  }
857  } // TODO: else warn (occasionally!) if we got Http::HdrType::X_NEXT_SERVICES
858 
859  // We need to store received ICAP headers for <icapLastHeader logformat option.
860  // If we already have stored headers from previous ICAP transaction related to this
861  // request, old headers will be replaced with the new one.
862 
864  if (ah != nullptr)
865  ah->recordMeta(&icapReply->header);
866 
867  // handle100Continue() manages state.writing on its own.
868  // Non-100 status means the server needs no postPreview data from us.
869  if (state.writing == State::writingPaused)
870  stopWriting(true);
871 }
872 
876 
877  if (parsePart(trailerParser, "trailer")) {
878  for (const auto &e: trailerParser->trailer.entries)
879  debugs(93, 5, "ICAP trailer: " << e->name << ": " << e->value);
880  stopParsing();
881  }
882 }
883 
885 {
886  if (service().cfg().method == ICAP::methodRespmod)
887  return gotEncapsulated("res-hdr");
888 
889  return service().cfg().method == ICAP::methodReqmod &&
890  expectHttpHeader();
891 }
892 
894 {
895  Must(state.writing == State::writingPaused);
896  // server must not respond before the end of preview: we may send ieof
897  Must(preview.enabled() && preview.done() && !preview.ieof());
898 
899  // 100 "Continue" cancels our Preview commitment,
900  // but not commitment to handle 204 or 206 outside Preview
901  if (!state.allowedPostview204 && !state.allowedPostview206)
902  stopBackup();
903 
904  state.parsing = State::psIcapHeader; // eventually
905  icapReply->reset();
906 
907  state.writing = State::writingPrime;
908 
909  writeMore();
910 }
911 
913 {
914  state.parsing = State::psHttpHeader;
915  state.sending = State::sendingAdapted;
916  stopBackup();
917  checkConsuming();
918 }
919 
921 {
922  stopParsing();
923  prepEchoing();
924 }
925 
927 {
928  if (state.writing == State::writingPaused) {
929  Must(preview.enabled());
930  Must(state.allowedPreview206);
931  debugs(93, 7, "206 inside preview");
932  } else {
933  Must(state.writing > State::writingPaused);
934  Must(state.allowedPostview206);
935  debugs(93, 7, "206 outside preview");
936  }
937  state.parsing = State::psHttpHeader;
938  state.sending = State::sendingAdapted;
939  state.readyForUob = true;
940  checkConsuming();
941 }
942 
943 // Called when we receive a 204 No Content response and
944 // when we are trying to bypass a service failure.
945 // We actually start sending (echoig or not) in startSending.
947 {
948  disableRepeats("preparing to echo content");
949  disableBypass("preparing to echo content", true);
950  setOutcome(xoEcho);
951 
952  // We want to clone the HTTP message, but we do not want
953  // to copy some non-HTTP state parts that Http::Message kids carry in them.
954  // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
955  // Instead, we simply write the HTTP message and "clone" it by parsing.
956  // TODO: use Http::Message::clone()!
957 
958  Http::Message *oldHead = virgin.header;
959  debugs(93, 7, "cloning virgin message " << oldHead);
960 
961  MemBuf httpBuf;
962 
963  // write the virgin message into a memory buffer
964  httpBuf.init();
965  packHead(httpBuf, oldHead);
966 
967  // allocate the adapted message and copy metainfo
968  Must(!adapted.header);
969  {
970  Http::MessagePointer newHead;
971  if (const HttpRequest *r = dynamic_cast<const HttpRequest*>(oldHead)) {
972  newHead = new HttpRequest(r->masterXaction);
973  } else if (dynamic_cast<const HttpReply*>(oldHead)) {
974  newHead = new HttpReply;
975  }
976  Must(newHead);
977 
978  newHead->inheritProperties(oldHead);
979 
980  adapted.setHeader(newHead.getRaw());
981  }
982 
983  // parse the buffer back
985 
986  httpBuf.terminate(); // Http::Message::parse requires nil-terminated buffer
987  Must(adapted.header->parse(httpBuf.content(), httpBuf.contentSize(), true, &error));
988  Must(adapted.header->hdr_sz == httpBuf.contentSize()); // no leftovers
989 
990  httpBuf.clean();
991 
992  debugs(93, 7, "cloned virgin message " << oldHead << " to " <<
993  adapted.header);
994 
995  // setup adapted body pipe if needed
996  if (oldHead->body_pipe != nullptr) {
997  debugs(93, 7, "will echo virgin body from " <<
998  oldHead->body_pipe);
999  if (!virginBodySending.active())
1000  virginBodySending.plan(); // will throw if not possible
1001  state.sending = State::sendingVirgin;
1002  checkConsuming();
1003 
1004  // TODO: optimize: is it possible to just use the oldHead pipe and
1005  // remove ICAP from the loop? This echoing is probably a common case!
1006  makeAdaptedBodyPipe("echoed virgin response");
1007  if (oldHead->body_pipe->bodySizeKnown())
1008  adapted.body_pipe->setBodySize(oldHead->body_pipe->bodySize());
1009  debugs(93, 7, "will echo virgin body to " <<
1010  adapted.body_pipe);
1011  } else {
1012  debugs(93, 7, "no virgin body to echo");
1013  stopSending(true);
1014  }
1015 }
1016 
1020 {
1021  Must(virginBodySending.active());
1022  Must(virgin.header->body_pipe != nullptr);
1023 
1024  setOutcome(xoPartEcho);
1025 
1026  debugs(93, 7, "will echo virgin body suffix from " <<
1027  virgin.header->body_pipe << " offset " << pos );
1028 
1029  // check that use-original-body=N does not point beyond buffered data
1030  const uint64_t virginDataEnd = virginConsumed +
1031  virgin.body_pipe->buf().contentSize();
1032  Must(pos <= virginDataEnd);
1033  virginBodySending.progress(static_cast<size_t>(pos));
1034 
1035  state.sending = State::sendingVirgin;
1036  checkConsuming();
1037 
1038  if (virgin.header->body_pipe->bodySizeKnown())
1039  adapted.body_pipe->expectProductionEndAfter(virgin.header->body_pipe->bodySize() - pos);
1040 
1041  debugs(93, 7, "will echo virgin body suffix to " <<
1042  adapted.body_pipe);
1043 
1044  // Start echoing data
1045  echoMore();
1046 }
1047 
1049 {
1050  stopParsing(false);
1051  stopBackup();
1052  // TODO: mark connection as "bad"
1053 
1054  // Terminate the transaction; we do not know how to handle this response.
1055  throw TexcHere("Unsupported ICAP status code");
1056 }
1057 
1059 {
1060  if (expectHttpHeader()) {
1061  replyHttpHeaderSize = 0;
1062  maybeAllocateHttpMsg();
1063 
1064  if (!parseHead(adapted.header))
1065  return; // need more header data
1066 
1067  if (adapted.header)
1068  replyHttpHeaderSize = adapted.header->hdr_sz;
1069 
1070  if (dynamic_cast<HttpRequest*>(adapted.header)) {
1071  const HttpRequest *oldR = dynamic_cast<const HttpRequest*>(virgin.header);
1072  Must(oldR);
1073  // TODO: the adapted request did not really originate from the
1074  // client; give proxy admin an option to prevent copying of
1075  // sensitive client information here. See the following thread:
1076  // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
1077  }
1078 
1079  // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
1080  if (adapted.header)
1081  adapted.header->inheritProperties(virgin.header);
1082  }
1083 
1084  decideOnParsingBody();
1085 }
1086 
1087 template<class Part>
1088 bool Adaptation::Icap::ModXact::parsePart(Part *part, const char *description)
1089 {
1090  Must(part);
1091  debugs(93, 5, "have " << readBuf.length() << ' ' << description << " bytes to parse; state: " << state.parsing);
1093  // XXX: performance regression. c_str() data copies
1094  // XXX: Http::Message::parse requires a terminated string buffer
1095  const char *tmpBuf = readBuf.c_str();
1096  const bool parsed = part->parse(tmpBuf, readBuf.length(), commEof, &error);
1097  debugs(93, (!parsed && error) ? 2 : 5, description << " parsing result: " << parsed << " detail: " << error);
1098  Must(parsed || !error);
1099  if (parsed)
1100  readBuf.consume(part->hdr_sz);
1101  return parsed;
1102 }
1103 
1104 // parses both HTTP and ICAP headers
1105 bool
1107 {
1108  if (!parsePart(head, "head")) {
1109  head->reset();
1110  return false;
1111  }
1112  return true;
1113 }
1114 
1116 {
1117  return gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr");
1118 }
1119 
1121 {
1122  return gotEncapsulated("res-body") || gotEncapsulated("req-body");
1123 }
1124 
1126 {
1127  String trailers;
1128  const bool promisesToSendTrailer = icapReply->header.getByIdIfPresent(Http::HdrType::TRAILER, &trailers);
1129  const bool supportsTrailers = icapReply->header.hasListMember(Http::HdrType::ALLOW, "trailers", ',');
1130  // ICAP Trailer specs require us to reject transactions having either Trailer
1131  // header or Allow:trailers
1132  Must((promisesToSendTrailer == supportsTrailers) || (!promisesToSendTrailer && supportsTrailers));
1133  if (promisesToSendTrailer && !trailers.size())
1134  debugs(93, DBG_IMPORTANT, "ERROR: ICAP Trailer response header field must not be empty (salvaged)");
1135  return promisesToSendTrailer;
1136 }
1137 
1139 {
1140  if (expectHttpBody()) {
1141  debugs(93, 5, "expecting a body");
1142  state.parsing = State::psBody;
1143  replyHttpBodySize = 0;
1144  bodyParser = new Http1::TeChunkedParser;
1145  bodyParser->parseExtensionValuesWith(&extensionParser);
1146  makeAdaptedBodyPipe("adapted response from the ICAP server");
1147  Must(state.sending == State::sendingAdapted);
1148  } else {
1149  debugs(93, 5, "not expecting a body");
1150  if (trailerParser)
1151  state.parsing = State::psIcapTrailer;
1152  else
1153  stopParsing();
1154  stopSending(true);
1155  }
1156 }
1157 
1159 {
1160  Must(state.parsing == State::psBody);
1161  Must(bodyParser);
1162 
1163  debugs(93, 5, "have " << readBuf.length() << " body bytes to parse");
1164 
1165  // the parser will throw on errors
1166  BodyPipeCheckout bpc(*adapted.body_pipe);
1167  bodyParser->setPayloadBuffer(&bpc.buf);
1168  const bool parsed = bodyParser->parse(readBuf);
1169  readBuf = bodyParser->remaining(); // sync buffers after parse
1170  bpc.checkIn();
1171 
1172  debugs(93, 5, "have " << readBuf.length() << " body bytes after parsed all: " << parsed);
1173  replyHttpBodySize += adapted.body_pipe->buf().contentSize();
1174 
1175  // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
1176  // TODO: do we really need this if we disable when sending headers?
1177  if (adapted.body_pipe->buf().contentSize() > 0) { // parsed something sometime
1178  disableRepeats("sent adapted content");
1179  disableBypass("sent adapted content", true);
1180  }
1181 
1182  if (parsed) {
1183  if (state.readyForUob && extensionParser.sawUseOriginalBody())
1184  prepPartialBodyEchoing(extensionParser.useOriginalBody());
1185  else
1186  stopSending(true); // the parser succeeds only if all parsed data fits
1187  if (trailerParser)
1188  state.parsing = State::psIcapTrailer;
1189  else
1190  stopParsing();
1191  return;
1192  }
1193 
1194  debugs(93,3, this << " needsMoreData = " << bodyParser->needsMoreData());
1195 
1196  if (bodyParser->needsMoreData()) {
1197  debugs(93,3, this);
1198  Must(mayReadMore());
1199  readMore();
1200  }
1201 
1202  if (bodyParser->needsMoreSpace()) {
1203  Must(!doneSending()); // can hope for more space
1204  Must(adapted.body_pipe->buf().contentSize() > 0); // paranoid
1205  // TODO: there should be a timeout in case the sink is broken
1206  // or cannot consume partial content (while we need more space)
1207  }
1208 }
1209 
1210 void Adaptation::Icap::ModXact::stopParsing(const bool checkUnparsedData)
1211 {
1212  if (state.parsing == State::psDone)
1213  return;
1214 
1215  if (checkUnparsedData)
1216  Must(readBuf.isEmpty());
1217 
1218  debugs(93, 7, "will no longer parse" << status());
1219 
1220  delete bodyParser;
1221  bodyParser = nullptr;
1222 
1223  delete trailerParser;
1224  trailerParser = nullptr;
1225 
1226  state.parsing = State::psDone;
1227 }
1228 
1229 // HTTP side added virgin body data
1231 {
1232  writeMore();
1233 
1234  if (state.sending == State::sendingVirgin)
1235  echoMore();
1236 }
1237 
1238 // HTTP side sent us all virgin info
1240 {
1241  Must(virgin.body_pipe->productionEnded());
1242 
1243  // push writer and sender in case we were waiting for the last-chunk
1244  writeMore();
1245 
1246  if (state.sending == State::sendingVirgin)
1247  echoMore();
1248 }
1249 
1250 // body producer aborted, but the initiator may still want to know
1251 // the answer, even though the HTTP message has been truncated
1253 {
1254  Must(virgin.body_pipe->productionEnded());
1255 
1256  // push writer and sender in case we were waiting for the last-chunk
1257  writeMore();
1258 
1259  if (state.sending == State::sendingVirgin)
1260  echoMore();
1261 }
1262 
1263 // adapted body consumer wants more adapted data and
1264 // possibly freed some buffer space
1266 {
1267  if (state.sending == State::sendingVirgin)
1268  echoMore();
1269  else if (state.sending == State::sendingAdapted)
1270  parseMore();
1271  else
1272  Must(state.sending == State::sendingUndecided);
1273 }
1274 
1275 // adapted body consumer aborted
1277 {
1278  static const auto d = MakeNamedErrorDetail("ICAP_XACT_BODY_CONSUMER_ABORT");
1279  detailError(d);
1280  mustStop("adapted body consumer aborted");
1281 }
1282 
1284 {
1285  delete bodyParser;
1286  delete trailerParser;
1287 }
1288 
1289 // internal cleanup
1291 {
1292  debugs(93, 5, "swan sings" << status());
1293 
1294  stopWriting(false);
1295  stopSending(false);
1296 
1297  if (theInitiator.set()) { // we have not sent the answer to the initiator
1298  static const auto d = MakeNamedErrorDetail("ICAP_XACT_OTHER");
1299  detailError(d);
1300  }
1301 
1302  // update adaptation history if start was called and we reserved a slot
1303  Adaptation::History::Pointer ah = virginRequest().adaptLogHistory();
1304  if (ah != nullptr && adaptHistoryId >= 0)
1305  ah->recordXactFinish(adaptHistoryId);
1306 
1308 }
1309 
1311 
1313 {
1314  HttpRequest *adapted_request_ = nullptr;
1315  HttpReply *adapted_reply_ = nullptr;
1316  HttpRequest *virgin_request_ = const_cast<HttpRequest*>(&virginRequest());
1317  if (!(adapted_request_ = dynamic_cast<HttpRequest*>(adapted.header))) {
1318  // if the request was not adapted, use virgin request to simplify
1319  // the code further below
1320  adapted_request_ = virgin_request_;
1321  adapted_reply_ = dynamic_cast<HttpReply*>(adapted.header);
1322  }
1323 
1324  Adaptation::Icap::History::Pointer h = virgin_request_->icapHistory();
1325  Must(h != nullptr); // ICAPXaction::maybeLog calls only if there is a log
1326  al.icp.opcode = ICP_INVALID;
1327  al.url = h->log_uri.termedBuf();
1328  const Adaptation::Icap::ServiceRep &s = service();
1329  al.icap.reqMethod = s.cfg().method;
1330 
1331  al.cache.caddr = virgin_request_->client_addr;
1332 
1333  al.request = virgin_request_;
1334  HTTPMSGLOCK(al.request);
1335  al.adapted_request = adapted_request_;
1336  HTTPMSGLOCK(al.adapted_request);
1337 
1338  // XXX: This reply (and other ALE members!) may have been needed earlier.
1339  al.reply = adapted_reply_;
1340 
1341 #if USE_OPENSSL
1342  if (h->ssluser.size())
1343  al.cache.ssluser = h->ssluser.termedBuf();
1344 #endif
1345  al.cache.code = h->logType;
1346 
1347  const Http::Message *virgin_msg = dynamic_cast<HttpReply*>(virgin.header);
1348  if (!virgin_msg)
1349  virgin_msg = virgin_request_;
1350  assert(virgin_msg != virgin.cause);
1351  al.http.clientRequestSz.header = virgin_msg->hdr_sz;
1352  if (virgin_msg->body_pipe != nullptr)
1353  al.http.clientRequestSz.payloadData = virgin_msg->body_pipe->producedSize();
1354 
1355  // leave al.icap.bodyBytesRead negative if no body
1356  if (replyHttpHeaderSize >= 0 || replyHttpBodySize >= 0) {
1357  const int64_t zero = 0; // to make max() argument types the same
1358  const uint64_t headerSize = max(zero, replyHttpHeaderSize);
1359  const uint64_t bodySize = max(zero, replyHttpBodySize);
1360  al.icap.bodyBytesRead = headerSize + bodySize;
1361  al.http.clientReplySz.header = headerSize;
1362  al.http.clientReplySz.payloadData = bodySize;
1363  }
1364 
1365  if (adapted_reply_) {
1366  al.http.code = adapted_reply_->sline.status();
1367  al.http.content_type = adapted_reply_->content_type.termedBuf();
1368  if (replyHttpBodySize >= 0)
1369  al.cache.highOffset = replyHttpBodySize;
1370  //don't set al.cache.objectSize because it hasn't exist yet
1371  }
1372  prepareLogWithRequestDetails(adapted_request_, alep);
1374 }
1375 
1377 {
1378  char ntoabuf[MAX_IPSTRLEN];
1379  /*
1380  * XXX These should use HttpHdr interfaces instead of Printfs
1381  */
1382  const Adaptation::ServiceConfig &s = service().cfg();
1383  buf.appendf("%s " SQUIDSTRINGPH " ICAP/1.0\r\n", s.methodStr(), SQUIDSTRINGPRINT(s.uri));
1384  buf.appendf("Host: " SQUIDSTRINGPH ":%d\r\n", SQUIDSTRINGPRINT(s.host), s.port);
1385  buf.appendf("Date: %s\r\n", Time::FormatRfc1123(squid_curtime));
1386 
1388  buf.appendf("Connection: close\r\n");
1389 
1390  const HttpRequest *request = &virginRequest();
1391 
1392  // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1393  // as ICAP headers.
1394  if (virgin.header->header.has(Http::HdrType::PROXY_AUTHENTICATE)) {
1395  String vh=virgin.header->header.getById(Http::HdrType::PROXY_AUTHENTICATE);
1396  buf.appendf("Proxy-Authenticate: " SQUIDSTRINGPH "\r\n",SQUIDSTRINGPRINT(vh));
1397  }
1398 
1399  if (virgin.header->header.has(Http::HdrType::PROXY_AUTHORIZATION)) {
1400  String vh=virgin.header->header.getById(Http::HdrType::PROXY_AUTHORIZATION);
1401  buf.appendf("Proxy-Authorization: " SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(vh));
1402  } else if (request->extacl_user.size() > 0 && request->extacl_passwd.size() > 0) {
1403  struct base64_encode_ctx ctx;
1404  base64_encode_init(&ctx);
1405  char base64buf[base64_encode_len(MAX_LOGIN_SZ)];
1406  size_t resultLen = base64_encode_update(&ctx, base64buf, request->extacl_user.size(), reinterpret_cast<const uint8_t*>(request->extacl_user.rawBuf()));
1407  resultLen += base64_encode_update(&ctx, base64buf+resultLen, 1, reinterpret_cast<const uint8_t*>(":"));
1408  resultLen += base64_encode_update(&ctx, base64buf+resultLen, request->extacl_passwd.size(), reinterpret_cast<const uint8_t*>(request->extacl_passwd.rawBuf()));
1409  resultLen += base64_encode_final(&ctx, base64buf+resultLen);
1410  buf.appendf("Proxy-Authorization: Basic %.*s\r\n", (int)resultLen, base64buf);
1411  }
1412 
1413  // share the cross-transactional database records if needed
1415  Adaptation::History::Pointer ah = request->adaptHistory(false);
1416  if (ah != nullptr) {
1417  String name, value;
1418  if (ah->getXxRecord(name, value)) {
1419  buf.appendf(SQUIDSTRINGPH ": " SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(name), SQUIDSTRINGPRINT(value));
1420  }
1421  }
1422  }
1423 
1424  buf.append("Encapsulated: ", 14);
1425 
1426  MemBuf httpBuf;
1427 
1428  httpBuf.init();
1429 
1430  // build HTTP request header, if any
1431  ICAP::Method m = s.method;
1432 
1433  // to simplify, we could assume that request is always available
1434 
1435  if (request) {
1436  if (ICAP::methodRespmod == m)
1437  encapsulateHead(buf, "req-hdr", httpBuf, request);
1438  else if (ICAP::methodReqmod == m)
1439  encapsulateHead(buf, "req-hdr", httpBuf, virgin.header);
1440  }
1441 
1442  if (ICAP::methodRespmod == m)
1443  if (const Http::Message *prime = virgin.header)
1444  encapsulateHead(buf, "res-hdr", httpBuf, prime);
1445 
1446  if (!virginBody.expected())
1447  buf.appendf("null-body=%d", (int) httpBuf.contentSize());
1448  else if (ICAP::methodReqmod == m)
1449  buf.appendf("req-body=%d", (int) httpBuf.contentSize());
1450  else
1451  buf.appendf("res-body=%d", (int) httpBuf.contentSize());
1452 
1453  buf.append(ICAP::crlf, 2); // terminate Encapsulated line
1454 
1455  if (preview.enabled()) {
1456  buf.appendf("Preview: %d\r\n", (int)preview.ad());
1457  if (!virginBody.expected()) // there is no body to preview
1458  finishNullOrEmptyBodyPreview(httpBuf);
1459  }
1460 
1461  makeAllowHeader(buf);
1462 
1463  if (TheConfig.send_client_ip && request) {
1464  Ip::Address client_addr;
1465 #if FOLLOW_X_FORWARDED_FOR
1467  client_addr = request->indirect_client_addr;
1468  } else
1469 #endif
1470  client_addr = request->client_addr;
1471  if (!client_addr.isAnyAddr() && !client_addr.isNoAddr())
1472  buf.appendf("X-Client-IP: %s\r\n", client_addr.toStr(ntoabuf,MAX_IPSTRLEN));
1473  }
1474 
1475  if (TheConfig.send_username && request)
1476  makeUsernameHeader(request, buf);
1477 
1478  // Adaptation::Config::metaHeaders
1479  for (const auto &h: Adaptation::Config::metaHeaders()) {
1480  HttpRequest *r = virgin.cause ?
1481  virgin.cause : dynamic_cast<HttpRequest*>(virgin.header);
1482  Must(r);
1483 
1484  HttpReply *reply = dynamic_cast<HttpReply*>(virgin.header);
1485 
1486  SBuf matched;
1487  if (h->match(r, reply, alMaster, matched)) {
1488  buf.append(h->key().rawContent(), h->key().length());
1489  buf.append(": ", 2);
1490  buf.append(matched.rawContent(), matched.length());
1491  buf.append("\r\n", 2);
1492  Adaptation::History::Pointer ah = request->adaptHistory(false);
1493  if (ah != nullptr) {
1494  if (ah->metaHeaders == nullptr)
1495  ah->metaHeaders = new NotePairs;
1496  if (!ah->metaHeaders->hasPair(h->key(), matched))
1497  ah->metaHeaders->add(h->key(), matched);
1498  }
1499  }
1500  }
1501 
1502  // fprintf(stderr, "%s\n", buf.content());
1503 
1504  buf.append(ICAP::crlf, 2); // terminate ICAP header
1505 
1506  // fill icapRequest for logging
1507  Must(icapRequest->parseCharBuf(buf.content(), buf.contentSize()));
1508 
1509  // start ICAP request body with encapsulated HTTP headers
1510  buf.append(httpBuf.content(), httpBuf.contentSize());
1511 
1512  httpBuf.clean();
1513 }
1514 
1515 // decides which Allow values to write and updates the request buffer
1517 {
1518  const bool allow204in = preview.enabled(); // TODO: add shouldAllow204in()
1519  const bool allow204out = state.allowedPostview204 = shouldAllow204();
1520  const bool allow206in = state.allowedPreview206 = shouldAllow206in();
1521  const bool allow206out = state.allowedPostview206 = shouldAllow206out();
1522  const bool allowTrailers = true; // TODO: make configurable
1523 
1524  debugs(93, 9, "Allows: " << allow204in << allow204out <<
1525  allow206in << allow206out << allowTrailers);
1526 
1527  const bool allow204 = allow204in || allow204out;
1528  const bool allow206 = allow206in || allow206out;
1529 
1530  if ((allow204 || allow206) && virginBody.expected())
1531  virginBodySending.plan(); // if there is a virgin body, plan to send it
1532 
1533  // writing Preview:... means we will honor 204 inside preview
1534  // writing Allow/204 means we will honor 204 outside preview
1535  // writing Allow:206 means we will honor 206 inside preview
1536  // writing Allow:204,206 means we will honor 206 outside preview
1537  if (allow204 || allow206 || allowTrailers) {
1538  buf.appendf("Allow: ");
1539  if (allow204out)
1540  buf.appendf("204, ");
1541  if (allow206)
1542  buf.appendf("206, ");
1543  if (allowTrailers)
1544  buf.appendf("trailers");
1545  buf.appendf("\r\n");
1546  }
1547 }
1548 
1550 {
1551 #if USE_AUTH
1552  struct base64_encode_ctx ctx;
1553  base64_encode_init(&ctx);
1554 
1555  const char *value = nullptr;
1556  if (request->auth_user_request != nullptr) {
1557  value = request->auth_user_request->username();
1558  } else if (request->extacl_user.size() > 0) {
1559  value = request->extacl_user.termedBuf();
1560  }
1561 
1562  if (value) {
1564  char base64buf[base64_encode_len(MAX_LOGIN_SZ)];
1565  size_t resultLen = base64_encode_update(&ctx, base64buf, strlen(value), reinterpret_cast<const uint8_t*>(value));
1566  resultLen += base64_encode_final(&ctx, base64buf+resultLen);
1567  buf.appendf("%s: %.*s\r\n", TheConfig.client_username_header, (int)resultLen, base64buf);
1568  } else
1569  buf.appendf("%s: %s\r\n", TheConfig.client_username_header, value);
1570  }
1571 #else
1572  (void)request;
1573  (void)buf;
1574 #endif
1575 }
1576 
1577 void
1578 Adaptation::Icap::ModXact::encapsulateHead(MemBuf &icapBuf, const char *section, MemBuf &httpBuf, const Http::Message *head)
1579 {
1580  // update ICAP header
1581  icapBuf.appendf("%s=%d, ", section, (int) httpBuf.contentSize());
1582 
1583  // begin cloning
1584  Http::MessagePointer headClone;
1585 
1586  if (const HttpRequest* old_request = dynamic_cast<const HttpRequest*>(head)) {
1587  HttpRequest::Pointer new_request(new HttpRequest(old_request->masterXaction));
1588  // copy the request-line details
1589  new_request->method = old_request->method;
1590  new_request->url = old_request->url;
1591  new_request->http_ver = old_request->http_ver;
1592  headClone = new_request.getRaw();
1593  } else if (const HttpReply *old_reply = dynamic_cast<const HttpReply*>(head)) {
1594  HttpReply::Pointer new_reply(new HttpReply);
1595  new_reply->sline = old_reply->sline;
1596  headClone = new_reply.getRaw();
1597  }
1598  Must(headClone);
1599  headClone->inheritProperties(head);
1600 
1602  while (HttpHeaderEntry* p_head_entry = head->header.getEntry(&pos))
1603  headClone->header.addEntry(p_head_entry->clone());
1604 
1605  // end cloning
1606 
1607  // remove all hop-by-hop headers from the clone
1609  headClone->header.removeHopByHopEntries();
1610 
1611  // TODO: modify HttpHeader::removeHopByHopEntries to accept a list of
1612  // excluded hop-by-hop headers
1613  if (head->header.has(Http::HdrType::UPGRADE)) {
1614  const auto upgrade = head->header.getList(Http::HdrType::UPGRADE);
1615  headClone->header.putStr(Http::HdrType::UPGRADE, upgrade.termedBuf());
1616  }
1617 
1618  // pack polished HTTP header
1619  packHead(httpBuf, headClone.getRaw());
1620 
1621  // headClone unlocks and, hence, deletes the message we packed
1622 }
1623 
1624 void
1626 {
1627  head->packInto(&httpBuf, true);
1628 }
1629 
1630 // decides whether to offer a preview and calculates its size
1632 {
1633  if (!TheConfig.preview_enable) {
1634  debugs(93, 5, "preview disabled by squid.conf");
1635  return;
1636  }
1637 
1638  const SBuf urlPath(virginRequest().url.path());
1639  size_t wantedSize;
1640  if (!service().wantsPreview(urlPath, wantedSize)) {
1641  debugs(93, 5, "should not offer preview for " << urlPath);
1642  return;
1643  }
1644 
1645  // we decided to do preview, now compute its size
1646 
1647  // cannot preview more than we can backup
1648  size_t ad = min(wantedSize, TheBackupLimit);
1649 
1650  if (!virginBody.expected())
1651  ad = 0;
1652  else if (virginBody.knownSize())
1653  ad = min(static_cast<uint64_t>(ad), virginBody.size()); // not more than we have
1654 
1655  debugs(93, 5, "should offer " << ad << "-byte preview " <<
1656  "(service wanted " << wantedSize << ")");
1657 
1658  preview.enable(ad);
1659  Must(preview.enabled());
1660 }
1661 
1662 // decides whether to allow 204 responses
1664 {
1665  if (!service().allows204())
1666  return false;
1667 
1668  return canBackupEverything();
1669 }
1670 
1671 // decides whether to allow 206 responses in some mode
1673 {
1674  return TheConfig.allow206_enable && service().allows206() &&
1675  virginBody.expected(); // no need for 206 without a body
1676 }
1677 
1678 // decides whether to allow 206 responses in preview mode
1680 {
1681  return shouldAllow206any() && preview.enabled();
1682 }
1683 
1684 // decides whether to allow 206 responses outside of preview
1686 {
1687  return shouldAllow206any() && canBackupEverything();
1688 }
1689 
1690 // used by shouldAllow204 and decideOnRetries
1692 {
1693  if (!virginBody.expected())
1694  return true; // no body means no problems with backup
1695 
1696  // if there is a body, check whether we can backup it all
1697 
1698  if (!virginBody.knownSize())
1699  return false;
1700 
1701  // or should we have a different backup limit?
1702  // note that '<' allows for 0-termination of the "full" backup buffer
1703  return virginBody.size() < TheBackupLimit;
1704 }
1705 
1706 // Decide whether this transaction can be retried if pconn fails
1707 // Must be called after decideOnPreview and before openConnection()
1709 {
1710  if (!isRetriable)
1711  return; // no, already decided
1712 
1713  if (preview.enabled())
1714  return; // yes, because preview provides enough guarantees
1715 
1716  if (canBackupEverything())
1717  return; // yes, because we can back everything up
1718 
1719  disableRetries(); // no, because we cannot back everything up
1720 }
1721 
1722 // Normally, the body-writing code handles preview body. It can deal with
1723 // bodies of unexpected size, including those that turn out to be empty.
1724 // However, that code assumes that the body was expected and body control
1725 // structures were initialized. This is not the case when there is no body
1726 // or the body is known to be empty, because the virgin message will lack a
1727 // body_pipe. So we handle preview of null-body and zero-size bodies here.
1729 {
1730  Must(!virginBodyWriting.active()); // one reason we handle it here
1731  Must(!virgin.body_pipe); // another reason we handle it here
1732  Must(!preview.ad());
1733 
1734  // do not add last-chunk because our Encapsulated header says null-body
1735  // addLastRequestChunk(buf);
1736  preview.wrote(0, true);
1737 
1738  Must(preview.done());
1739  Must(preview.ieof());
1740 }
1741 
1743 {
1745 
1746  if (state.serviceWaiting)
1747  buf.append("U", 1);
1748 
1749  if (virgin.body_pipe != nullptr)
1750  buf.append("R", 1);
1751 
1752  if (haveConnection() && !doneReading())
1753  buf.append("r", 1);
1754 
1755  if (!state.doneWriting() && state.writing != State::writingInit)
1756  buf.appendf("w(%d)", state.writing);
1757 
1758  if (preview.enabled()) {
1759  if (!preview.done())
1760  buf.appendf("P(%d)", (int) preview.debt());
1761  }
1762 
1763  if (virginBodySending.active())
1764  buf.append("B", 1);
1765 
1766  if (!state.doneParsing() && state.parsing != State::psIcapHeader)
1767  buf.appendf("p(%d)", state.parsing);
1768 
1769  if (!doneSending() && state.sending != State::sendingUndecided)
1770  buf.appendf("S(%d)", state.sending);
1771 
1772  if (state.readyForUob)
1773  buf.append("6", 1);
1774 
1775  if (canStartBypass)
1776  buf.append("Y", 1);
1777 
1778  if (protectGroupBypass)
1779  buf.append("G", 1);
1780 }
1781 
1783 {
1785 
1786  if (!virgin.body_pipe)
1787  buf.append("R", 1);
1788 
1789  if (state.doneWriting())
1790  buf.append("w", 1);
1791 
1792  if (preview.enabled()) {
1793  if (preview.done())
1794  buf.appendf("P%s", preview.ieof() ? "(ieof)" : "");
1795  }
1796 
1797  if (doneReading())
1798  buf.append("r", 1);
1799 
1800  if (state.doneParsing())
1801  buf.append("p", 1);
1802 
1803  if (doneSending())
1804  buf.append("S", 1);
1805 }
1806 
1807 bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section) const
1808 {
1809  return !icapReply->header.getByNameListMember("Encapsulated",
1810  section, ',').isEmpty();
1811 }
1812 
1813 // calculate whether there is a virgin HTTP body and
1814 // whether its expected size is known
1815 // TODO: rename because we do not just estimate
1817 {
1818  // note: lack of size info may disable previews and 204s
1819 
1820  Http::Message *msg = virgin.header;
1821  Must(msg);
1822 
1823  HttpRequestMethod method;
1824 
1825  if (virgin.cause)
1826  method = virgin.cause->method;
1827  else if (HttpRequest *req = dynamic_cast<HttpRequest*>(msg))
1828  method = req->method;
1829  else
1830  method = Http::METHOD_NONE;
1831 
1832  int64_t size;
1833  // expectingBody returns true for zero-sized bodies, but we will not
1834  // get a pipe for that body, so we treat the message as bodyless
1835  if (method != Http::METHOD_NONE && msg->expectingBody(method, size) && size) {
1836  debugs(93, 6, "expects virgin body from " <<
1837  virgin.body_pipe << "; size: " << size);
1838 
1839  virginBody.expect(size);
1840  virginBodyWriting.plan();
1841 
1842  // sign up as a body consumer
1843  Must(msg->body_pipe != nullptr);
1844  Must(msg->body_pipe == virgin.body_pipe);
1845  Must(virgin.body_pipe->setConsumerIfNotLate(this));
1846 
1847  // make sure TheBackupLimit is in-sync with the buffer size
1848  Must(TheBackupLimit <= static_cast<size_t>(msg->body_pipe->buf().max_capacity));
1849  } else {
1850  debugs(93, 6, "does not expect virgin body");
1851  Must(msg->body_pipe == nullptr);
1852  checkConsuming();
1853  }
1854 }
1855 
1857 {
1858  Must(!adapted.body_pipe);
1859  Must(!adapted.header->body_pipe);
1860  adapted.header->body_pipe = new BodyPipe(this);
1861  adapted.body_pipe = adapted.header->body_pipe;
1862  debugs(93, 7, "will supply " << what << " via " <<
1863  adapted.body_pipe << " pipe");
1864 }
1865 
1866 // TODO: Move SizedEstimate and Preview elsewhere
1867 
1869  : theData(dtUnexpected)
1870 {}
1871 
1873 {
1874  theData = (aSize >= 0) ? aSize : (int64_t)dtUnknown;
1875 }
1876 
1878 {
1879  return theData != dtUnexpected;
1880 }
1881 
1883 {
1884  Must(expected());
1885  return theData != dtUnknown;
1886 }
1887 
1889 {
1890  Must(knownSize());
1891  return static_cast<uint64_t>(theData);
1892 }
1893 
1894 Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided)
1895 {}
1896 
1898 {
1899  Must(!disabled());
1900  Must(!theStart); // not started
1901  theState = stActive;
1902 }
1903 
1905 {
1906  theState = stDisabled;
1907 }
1908 
1910 {
1911  Must(active());
1912 #if SIZEOF_SIZE_T > 4
1913  /* always true for smaller size_t's */
1914  Must(static_cast<int64_t>(size) >= 0);
1915 #endif
1916  theStart += static_cast<int64_t>(size);
1917 }
1918 
1920 {
1921  Must(active());
1922  return static_cast<uint64_t>(theStart);
1923 }
1924 
1925 Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled)
1926 {}
1927 
1929 {
1930  // TODO: check for anAd not exceeding preview size limit
1931  Must(!enabled());
1932  theAd = anAd;
1933  theState = stWriting;
1934 }
1935 
1937 {
1938  return theState != stDisabled;
1939 }
1940 
1942 {
1943  Must(enabled());
1944  return theAd;
1945 }
1946 
1948 {
1949  Must(enabled());
1950  return theState >= stIeof;
1951 }
1952 
1954 {
1955  Must(enabled());
1956  return theState == stIeof;
1957 }
1958 
1960 {
1961  Must(enabled());
1962  return done() ? 0 : (theAd - theWritten);
1963 }
1964 
1965 void Adaptation::Icap::Preview::wrote(size_t size, bool wroteEof)
1966 {
1967  Must(enabled());
1968 
1969  theWritten += size;
1970 
1971  Must(theWritten <= theAd);
1972 
1973  if (wroteEof)
1974  theState = stIeof; // written size is irrelevant
1975  else if (theWritten >= theAd)
1976  theState = stDone;
1977 }
1978 
1980 {
1981  if (virgin.header == nullptr)
1982  return false;
1983 
1984  virgin.header->firstLineBuf(mb);
1985 
1986  return true;
1987 }
1988 
1990 {
1991  HttpRequest *request = dynamic_cast<HttpRequest*>(adapted.header);
1992  // if no adapted request, update virgin (and inherit its properties later)
1993  // TODO: make this and HttpRequest::detailError constant, like adaptHistory
1994  if (!request)
1995  request = const_cast<HttpRequest*>(&virginRequest());
1996 
1997  if (request)
1998  request->detailError(ERR_ICAP_FAILURE, errDetail);
1999 }
2000 
2002 {
2003  HttpRequest *request = dynamic_cast<HttpRequest*>(adapted.header);
2004  // if no adapted request, update virgin (and inherit its properties later)
2005  if (!request)
2006  request = const_cast<HttpRequest*>(&virginRequest());
2007 
2008  if (request)
2009  request->clearError();
2010 }
2011 
2013 {
2014  Must(adapted.header);
2015  adapted.header->sources |= (service().cfg().connectionEncryption ? Http::Message::srcIcaps : Http::Message::srcIcap);
2016 }
2017 
2018 /* Adaptation::Icap::ModXactLauncher */
2019 
2021  AsyncJob("Adaptation::Icap::ModXactLauncher"),
2022  Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", aService),
2023  al(alp)
2024 {
2025  virgin.setHeader(virginHeader);
2026  virgin.setCause(virginCause);
2027  updateHistory(true);
2028 }
2029 
2031 {
2033  dynamic_cast<Adaptation::Icap::ServiceRep*>(theService.getRaw());
2034  Must(s != nullptr);
2035  return new Adaptation::Icap::ModXact(virgin.header, virgin.cause, al, s);
2036 }
2037 
2039 {
2040  debugs(93, 5, "swan sings");
2041  updateHistory(false);
2043 }
2044 
2046 {
2047  HttpRequest *r = virgin.cause ?
2048  virgin.cause : dynamic_cast<HttpRequest*>(virgin.header);
2049 
2050  // r should never be NULL but we play safe; TODO: add Should()
2051  if (r) {
2053  if (h != nullptr) {
2054  if (doStart)
2055  h->start("ICAPModXactLauncher");
2056  else
2057  h->stop("ICAPModXactLauncher");
2058  }
2059  }
2060 }
2061 
2062 bool Adaptation::Icap::TrailerParser::parse(const char *buf, int len, int atEnd, Http::StatusCode *error) {
2064  // RFC 7230 section 4.1.2: MUST NOT generate a trailer that contains
2065  // a field necessary for message framing (e.g., Transfer-Encoding and Content-Length)
2066  clen.applyTrailerRules();
2067  const int parsed = trailer.parse(buf, len, atEnd, hdr_sz, clen);
2068  if (parsed < 0)
2069  *error = Http::scInvalidHeader; // TODO: should we add a new Http::scInvalidTrailer?
2070  return parsed > 0;
2071 }
2072 
2073 void
2075 {
2076  if (extName == UseOriginalBodyName) {
2077  useOriginalBody_ = tok.udec64("use-original-body");
2078  assert(useOriginalBody_ >= 0);
2079  } else {
2080  Ignore(tok, extName);
2081  }
2082 }
2083 
void disableBypass(const char *reason, bool includeGroupBypass)
Definition: ModXact.cc:714
const MemBuf & buf() const
Definition: BodyPipe.h:137
void callException(const std::exception &e) override
called when the job throws during an async call
Definition: ModXact.cc:662
int hdr_sz
Definition: Message.h:81
void stop(const char *context)
note the end of an ICAP processing interval
Definition: History.cc:32
void prepPartialBodyEchoing(uint64_t pos)
Definition: ModXact.cc:1019
String content_type
Definition: HttpReply.h:46
SourceLocationId id() const
same-location exceptions have the same ID
Definition: TextException.h:40
#define Here()
source code location of the caller
Definition: Here.h:15
AccessLogEntry::Pointer alMaster
Master transaction AccessLogEntry.
Definition: ModXact.h:373
ModXactLauncher(Http::Message *virginHeader, HttpRequest *virginCause, AccessLogEntry::Pointer &alp, Adaptation::ServicePointer s)
Definition: ModXact.cc:2020
ModXact(Http::Message *virginHeader, HttpRequest *virginCause, AccessLogEntry::Pointer &alp, ServiceRep::Pointer &s)
Definition: ModXact.cc:54
void terminate()
Definition: MemBuf.cc:241
AnyP::ProtocolVersion http_ver
Definition: Message.h:72
#define base64_encode_len(length)
Definition: base64.h:169
void appendf(const char *fmt,...) PRINTF_FORMAT_ARG2
Append operation with printf-style arguments.
Definition: Packable.h:61
@ srvBlock
Definition: Elements.h:19
void openChunk(MemBuf &buf, size_t chunkSize, bool ieof)
Definition: ModXact.cc:376
const char * rawBuf() const
Definition: SquidString.h:86
void applyTrailerRules()
prohibits Content-Length in GET/HEAD requests
AnyP::Uri url
the request URI
Definition: HttpRequest.h:115
common parts of HttpRequest and HttpReply
Definition: Message.h:25
void startShoveling() override
starts sending/receiving ICAP messages
Definition: ModXact.cc:189
void swanSong() override
Definition: ModXact.cc:1290
void progress(size_t size)
Definition: ModXact.cc:1909
BodyPipe::Pointer body_pipe
optional pipeline to receive message body
Definition: Message.h:97
void enable(size_t anAd)
Definition: ModXact.cc:1928
size_t virginContentSize(const VirginBodyAct &act) const
Definition: ModXact.cc:404
virtual bool expectingBody(const HttpRequestMethod &, int64_t &) const =0
void makeRequestHeaders(MemBuf &buf)
Definition: ModXact.cc:1376
virtual void fillDoneStatus(MemBuf &buf) const
Definition: Xaction.cc:667
Config TheConfig
Definition: Config.cc:19
const XactOutcome xoPartEcho
preserved virgin msg part (ICAP 206)
Definition: Elements.cc:24
void packHead(MemBuf &httpBuf, const Http::Message *head)
Definition: ModXact.cc:1625
@ scNone
Definition: StatusCode.h:21
void removeHopByHopEntries()
Definition: HttpHeader.cc:1710
HttpHeader header
Definition: Message.h:74
Http1::TeChunkedParser * bodyParser
Definition: ModXact.h:303
bool virginBodyEndReached(const VirginBodyAct &act) const
Definition: ModXact.cc:395
void noteMoreBodyDataAvailable(BodyPipe::Pointer) override
Definition: ModXact.cc:1230
Parses and stores ICAP trailer header block.
Definition: ModXact.h:110
ssize_t HttpHeaderPos
Definition: HttpHeader.h:45
bool doneAll() const override
whether positive goal has been reached
Definition: ModXact.cc:525
void clearError()
clear error details, useful for retries/repeats
Definition: HttpRequest.cc:464
static int send_client_ip
Definition: Config.h:47
@ srcIcaps
Secure ICAP service.
Definition: Message.h:35
char * client_username_header
Definition: Config.h:36
void updateXxRecord(const char *name, const String &value)
sets or resets a cross-transactional database record
Definition: History.cc:105
size_t base64_encode_final(struct base64_encode_ctx *ctx, char *dst)
Definition: base64.c:308
bool isAnyAddr() const
Definition: Address.cc:190
void updateNextServices(const String &services)
sets or resets next services for the Adaptation::Iterator to notice
Definition: History.cc:121
CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap, ModXact)
#define HttpHeaderInitPos
Definition: HttpHeader.h:48
void error(char *format,...)
bool hasContent() const
Definition: MemBuf.h:54
#define SQUIDSTRINGPRINT(s)
Definition: SquidString.h:22
void init(mb_size_t szInit, mb_size_t szMax)
Definition: MemBuf.cc:93
Definition: SBuf.h:93
void setHeader(Header *h)
Definition: InOut.h:48
static constexpr auto TheBackupLimit
Definition: ModXact.cc:45
virtual void fillPendingStatus(MemBuf &buf) const
Definition: Xaction.cc:649
void stopParsing(const bool checkUnparsedData=true)
Definition: ModXact.cc:1210
void swanSong() override
Definition: Launcher.cc:105
const XactOutcome xoEcho
preserved virgin message (ICAP 204)
Definition: Elements.cc:23
static int send_username
Definition: Config.h:48
const A & max(A const &lhs, A const &rhs)
void closeChunk(MemBuf &buf)
Definition: ModXact.cc:381
static int use_indirect_client
Definition: Config.h:49
Auth::UserRequest::Pointer auth_user_request
Definition: HttpRequest.h:127
C * getRaw() const
Definition: RefCount.h:89
String log_uri
the request uri
Definition: History.h:44
TrailerParser * trailerParser
Definition: ModXact.h:321
void handleCommWrote(size_t size) override
Definition: ModXact.cc:208
Http::StatusLine sline
Definition: HttpReply.h:56
void makeAllowHeader(MemBuf &buf)
Definition: ModXact.cc:1516
bool getXxRecord(String &name, String &value) const
returns true and fills the record fields iff there is a db record
Definition: History.cc:111
bool parsePart(Part *part, const char *description)
Definition: ModXact.cc:1088
StatusCode
Definition: StatusCode.h:20
#define SQUIDSTRINGPH
Definition: SquidString.h:21
void detailError(const err_type c, const ErrorDetail::Pointer &d)
sets error detail if no earlier detail was available
Definition: HttpRequest.h:101
void start() override
called by AsyncStart; do not call directly
Definition: ModXact.cc:88
void fillDoneStatus(MemBuf &buf) const override
Definition: ModXact.cc:1782
String extacl_user
Definition: HttpRequest.h:176
int const char size_t
Definition: stub_liblog.cc:83
void addLastRequestChunk(MemBuf &buf)
Definition: ModXact.cc:369
char * toStr(char *buf, const unsigned int blen, int force=AF_UNSPEC) const
Definition: Address.cc:812
void encapsulateHead(MemBuf &icapBuf, const char *section, MemBuf &httpBuf, const Http::Message *head)
Definition: ModXact.cc:1578
LogTags logType
the squid request status (TCP_MISS etc)
Definition: History.h:42
#define TexcHere(msg)
legacy convenience macro; it is not difficult to type Here() now
Definition: TextException.h:63
virtual bool inheritProperties(const Http::Message *)=0
void consume(size_t size)
Definition: BodyPipe.cc:309
void stopSending(bool nicely)
Definition: ModXact.cc:611
mb_size_t max_capacity
Definition: MemBuf.h:142
#define MAX_IPSTRLEN
Length of buffer that needs to be allocated to old a null-terminated IP-string.
Definition: forward.h:25
void recordXactFinish(int hid)
record the end of a xact identified by its history ID
Definition: History.cc:61
bool bodySizeKnown() const
Definition: BodyPipe.h:109
MemBuf & buf
Definition: BodyPipe.h:74
const char * FormatRfc1123(time_t)
Definition: rfc1123.cc:202
void wrote(size_t size, bool wroteEof)
Definition: ModXact.cc:1965
void handleCommRead(size_t size) override
Definition: ModXact.cc:564
bool doneSending() const
Definition: ModXact.cc:605
@ ERR_ICAP_FAILURE
Definition: forward.h:64
void makeAdaptedBodyPipe(const char *what)
Definition: ModXact.cc:1856
void detailError(const ErrorDetail::Pointer &errDetail) override
record error detail in the virgin request if possible
Definition: ModXact.cc:1989
@ ICP_INVALID
Definition: icp_opcode.h:15
bool httpHeaderHasConnDir(const HttpHeader *hdr, const SBuf &directive)
mb_size_t contentSize() const
available data size
Definition: MemBuf.h:47
uint64_t bodySize() const
Definition: BodyPipe.cc:161
int size
Definition: ModDevPoll.cc:69
struct timeval current_time
the current UNIX time in timeval {seconds, microseconds} format
Definition: gadgets.cc:18
void append(const char *c, int sz) override
Definition: MemBuf.cc:209
void parseExtensionValuesWith(ChunkExtensionValueParser *parser)
const char * rawContent() const
Definition: SBuf.cc:509
static Notes & metaHeaders()
The list of configured meta headers.
Definition: Config.cc:35
void stopWriting(bool nicely)
Definition: ModXact.cc:483
Http::StatusCode status() const
retrieve the status code for this status line
Definition: StatusLine.h:45
void parse(Tokenizer &tok, const SBuf &extName) override
Definition: ModXact.cc:2074
#define MAX_LOGIN_SZ
Definition: defines.h:77
void finalizeLogInfo() override
Definition: ModXact.cc:1312
uint64_t producedSize() const
Definition: BodyPipe.h:112
Ip::Address indirect_client_addr
Definition: HttpRequest.h:152
const char * username() const
Definition: UserRequest.cc:32
void start() override
called by AsyncStart; do not call directly
Definition: Xaction.cc:130
bool expectHttpHeader() const
whether ICAP response header indicates HTTP header presence
Definition: ModXact.cc:1115
Definition: MemBuf.h:23
bool expectHttpBody() const
whether ICAP response header indicates HTTP body presence
Definition: ModXact.cc:1120
const char * status() const override
internal cleanup; do not call directly
Definition: Xaction.cc:635
void clean()
Definition: MemBuf.cc:110
void swanSong() override
Definition: Xaction.cc:573
void clearError() override
clear stored error details, if any; used for retries/repeats
Definition: ModXact.cc:2001
void fillPendingStatus(MemBuf &buf) const override
Definition: ModXact.cc:1742
@ scPartialContent
Definition: StatusCode.h:33
int delById(Http::HdrType id)
Definition: HttpHeader.cc:666
@ srcIcap
traditional ICAP service without encryption
Definition: Message.h:41
Adaptation::Icap::History::Pointer icapHistory() const
Returns possibly nil history, creating it if icap logging is enabled.
Definition: HttpRequest.cc:388
@ scCreated
Definition: StatusCode.h:28
void addEntry(HttpHeaderEntry *e)
Definition: HttpHeader.cc:736
void updateSources()
Update the Http::Message sources.
Definition: ModXact.cc:2012
#define assert(EX)
Definition: assert.h:17
void writeSomeBody(const char *label, size_t size)
Definition: ModXact.cc:319
@ scContinue
Definition: StatusCode.h:22
bool fillVirginHttpHeader(MemBuf &) const override
Definition: ModXact.cc:1979
void HTTPMSGLOCK(Http::Message *a)
Definition: Message.h:161
NotePairs::Pointer metaHeaders
Definition: History.h:66
void noteBodyProducerAborted(BodyPipe::Pointer) override
Definition: ModXact.cc:1252
#define JobCallback(dbgSection, dbgLevel, Dialer, job, method)
Convenience macro to create a Dialer-based job callback.
Definition: AsyncJobCalls.h:70
void prepareLogWithRequestDetails(HttpRequest *, const AccessLogEntryPointer &)
Definition: client_side.cc:322
const char * virginContentData(const VirginBodyAct &act) const
Definition: ModXact.cc:416
void base64_encode_init(struct base64_encode_ctx *ctx)
Definition: base64.c:232
size_type length() const
Returns the number of bytes stored in SBuf.
Definition: SBuf.h:419
time_t squid_curtime
Definition: stub_libtime.cc:20
bool isNoAddr() const
Definition: Address.cc:304
void setCause(HttpRequest *r)
Definition: InOut.h:38
Adaptation::History::Pointer adaptHistory(bool createIfNone=false) const
Returns possibly nil history, creating it if requested.
Definition: HttpRequest.cc:403
Adaptation::History::Pointer adaptLogHistory() const
Returns possibly nil history, creating it if adapt. logging is enabled.
Definition: HttpRequest.cc:414
void callException(const std::exception &e) override
called when the job throws during an async call
Definition: Xaction.cc:372
bool canBackupEverything() const
Definition: ModXact.cc:1691
bool expectIcapTrailers() const
whether ICAP response header indicates ICAP trailers presence
Definition: ModXact.cc:1125
static Answer Forward(Http::Message *aMsg)
create an akForward answer
Definition: Answer.cc:26
virtual void finalizeLogInfo()
Definition: Xaction.cc:612
const HttpRequest & virginRequest() const
locates the request, either as a cause or as a virgin message itself
Definition: ModXact.cc:386
HttpRequestMethod method
Definition: HttpRequest.h:114
Xaction * createXaction() override
Definition: ModXact.cc:2030
const char * termedBuf() const
Definition: SquidString.h:92
void start(const char *context)
record the start of an ICAP processing interval
Definition: History.cc:23
@ methodRespmod
Definition: Elements.h:17
String protoPrefix
Definition: HttpReply.h:60
const char * status() const
Definition: BodyPipe.cc:446
void decideWritingAfterPreview(const char *previewKind)
determine state.writing after we wrote the entire preview
Definition: ModXact.cc:292
Definition: parse.c:160
bool hasPair(const SBuf &key, const SBuf &value) const
Definition: Notes.cc:370
static constexpr size_t MaxCapacity
Definition: BodyPipe.h:100
squidaio_request_t * head
Definition: aiops.cc:127
@ scNoContent
Definition: StatusCode.h:31
@ PROXY_AUTHENTICATE
an std::runtime_error with thrower location info
Definition: TextException.h:20
char * content()
start of the added data
Definition: MemBuf.h:41
void noteMoreBodySpaceAvailable(BodyPipe::Pointer) override
Definition: ModXact.cc:1265
mb_size_t spaceSize() const
Definition: MemBuf.cc:155
void putStr(Http::HdrType id, const char *str)
Definition: HttpHeader.cc:995
size_type size() const
Definition: SquidString.h:73
void noteBodyConsumerAborted(BodyPipe::Pointer) override
Definition: ModXact.cc:1276
@ METHOD_NONE
Definition: MethodType.h:22
#define Must(condition)
Definition: TextException.h:75
const char * methodStr() const
#define DBG_IMPORTANT
Definition: Stream.h:38
size_t base64_encode_update(struct base64_encode_ctx *ctx, char *dst, size_t length, const uint8_t *src)
Definition: base64.c:265
bool gotEncapsulated(const char *section) const
Definition: ModXact.cc:1807
bool doneAll() const override
whether positive goal has been reached
Definition: Xaction.cc:388
void add(const SBuf &key, const SBuf &value)
Definition: Notes.cc:317
@ methodReqmod
Definition: Elements.h:17
static char * masterx_shared_name
Definition: Config.h:45
@ scInvalidHeader
Squid header parsing error.
Definition: StatusCode.h:88
String ssluser
the username from SSL
Definition: History.h:40
const XactOutcome xoSatisfied
request satisfaction
Definition: Elements.cc:26
void finishNullOrEmptyBodyPreview(MemBuf &buf)
Definition: ModXact.cc:1728
void expect(int64_t aSize)
Definition: ModXact.cc:1872
@ scOkay
Definition: StatusCode.h:27
const ServiceConfig & cfg() const
Definition: Service.h:51
HttpReply::Pointer icapReply
received ICAP reply, if any
Definition: Xaction.h:64
void recordMeta(const HttpHeader *lm)
store the last meta header fields received from the adaptation service
Definition: History.cc:140
int recordXactStart(const String &serviceId, const timeval &when, bool retrying)
record the start of a xact, return xact history ID
Definition: History.cc:51
bool parse(const char *buf, int len, int atEnd, Http::StatusCode *error)
Definition: ModXact.cc:2062
bool parseHead(Http::Message *head)
Definition: ModXact.cc:1106
void noteBodyProductionEnded(BodyPipe::Pointer) override
Definition: ModXact.cc:1239
const XactOutcome xoModified
replaced virgin msg with adapted
Definition: Elements.cc:25
int adaptHistoryId
adaptation history slot reservation
Definition: ModXact.h:319
Ip::Address client_addr
Definition: HttpRequest.h:149
void makeUsernameHeader(const HttpRequest *request, MemBuf &buf)
Definition: ModXact.cc:1549
#define debugs(SECTION, LEVEL, CONTENT)
Definition: Stream.h:192
const A & min(A const &lhs, A const &rhs)
String extacl_passwd
Definition: HttpRequest.h:178
size_t debt() const
Definition: ModXact.cc:1959
void updateHistory(bool start)
starts or stops transaction accounting in ICAP history
Definition: ModXact.cc:2045
const CharacterSet crlf("crlf","\r\n")
Definition: Elements.cc:12
ErrorDetail::Pointer MakeNamedErrorDetail(const char *name)
Definition: Detail.cc:54
@ PROXY_AUTHORIZATION

 

Introduction

Documentation

Support

Miscellaneous