2 * Copyright (C) 1996-2025 The Squid Software Foundation and contributors
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.
9 /* DEBUG: section 93 ICAP (RFC 3507) Client */
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"
17 #include "adaptation/icap/History.h"
18 #include "adaptation/icap/Launcher.h"
19 #include "adaptation/icap/ModXact.h"
20 #include "adaptation/icap/ServiceRep.h"
21 #include "adaptation/Initiator.h"
22 #include "auth/UserRequest.h"
23 #include "base/TextException.h"
26 #include "comm/Connection.h"
27 #include "error/Detail.h"
28 #include "error/ExceptionErrorDetail.h"
29 #include "http/ContentLengthInterpreter.h"
30 #include "HttpHeaderTools.h"
31 #include "HttpReply.h"
32 #include "MasterXaction.h"
33 #include "parser/Tokenizer.h"
34 #include "sbuf/Stream.h"
36 // flow and terminology:
37 // HTTP| --> receive --> encode --> write --> |network
38 // end | <-- send <-- parse <-- read <-- |end
40 // TODO: replace gotEncapsulated() with something faster; we call it often
42 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXact
);
43 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXactLauncher
);
45 static constexpr auto TheBackupLimit
= BodyPipe::MaxCapacity
;
47 const SBuf
Adaptation::Icap::ChunkExtensionValueParser::UseOriginalBodyName("use-original-body");
49 Adaptation::Icap::ModXact::State::State()
51 memset(this, 0, sizeof(*this));
54 Adaptation::Icap::ModXact::ModXact(Http::Message
*virginHeader
,
55 HttpRequest
*virginCause
, AccessLogEntry::Pointer
&alp
, Adaptation::Icap::ServiceRep::Pointer
&aService
):
56 AsyncJob("Adaptation::Icap::ModXact"),
57 Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", aService
),
60 canStartBypass(false), // too early
61 protectGroupBypass(true),
62 replyHttpHeaderSize(-1),
63 replyHttpBodySize(-1),
65 trailerParser(nullptr),
70 virgin
.setHeader(virginHeader
); // sets virgin.body_pipe if needed
71 virgin
.setCause(virginCause
); // may be NULL
73 // adapted header and body are initialized when we parse them
75 // writing and reading ends are handled by Adaptation::Icap::Xaction
78 // nothing to do because we are using temporary buffers
80 // parsing; TODO: do not set until we parse, see ICAPOptXact
81 icapReply
= new HttpReply
;
82 icapReply
->protoPrefix
= "ICAP/"; // TODO: make an IcapReply class?
84 debugs(93,7, "initialized." << status());
87 // initiator wants us to start
88 void Adaptation::Icap::ModXact::start()
90 Adaptation::Icap::Xaction::start();
92 // reserve an adaptation history slot (attempts are known at this time)
93 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
95 adaptHistoryId
= ah
->recordXactStart(service().cfg().key
, icap_tr_start
, attempts
> 1);
97 estimateVirginBody(); // before virgin disappears!
99 canStartBypass
= service().cfg().bypass
;
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())
109 void Adaptation::Icap::ModXact::waitForService()
112 Must(!state
.serviceWaiting
);
114 if (!service().up()) {
115 AsyncCall::Pointer call
= JobCallback(93,5,
116 ConnWaiterDialer
, this, Adaptation::Icap::ModXact::noteServiceReady
);
118 service().callWhenReady(call
);
119 comment
= "to be up";
121 //The service is unavailable because of max-connection or other reason
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;
132 disableRepeats("ICAP service is not available");
134 debugs(93, 7, "will not wait for the service to be available" <<
137 throw TexcHere("ICAP service is not available");
140 AsyncCall::Pointer call
= JobCallback(93,5,
141 ConnWaiterDialer
, this, Adaptation::Icap::ModXact::noteServiceAvailable
);
142 service().callWhenAvailable(call
, state
.waitedForService
);
143 comment
= "to be available";
146 debugs(93, 7, "will wait for the service " << comment
<< status());
147 state
.serviceWaiting
= true; // after callWhenReady() which may throw
148 state
.waitedForService
= true;
151 void Adaptation::Icap::ModXact::noteServiceReady()
153 Must(state
.serviceWaiting
);
154 state
.serviceWaiting
= false;
156 if (!service().up()) {
158 disableRepeats("ICAP service is unusable");
159 throw TexcHere("ICAP service is unusable");
162 if (service().availableForOld())
168 void Adaptation::Icap::ModXact::noteServiceAvailable()
170 Must(state
.serviceWaiting
);
171 state
.serviceWaiting
= false;
173 if (service().up() && service().availableForOld())
179 void Adaptation::Icap::ModXact::startWriting()
181 state
.writing
= State::writingConnect
;
183 decideOnPreview(); // must be decided before we decideOnRetries
189 void Adaptation::Icap::ModXact::startShoveling()
191 Must(state
.writing
== State::writingConnect
);
193 startReading(); // wait for early errors from the ICAP server
198 makeRequestHeaders(requestBuf
);
199 debugs(93, 9, "will write" << status() << ":\n" <<
200 (requestBuf
.terminate(), requestBuf
.content()));
203 state
.writing
= State::writingHeaders
;
204 icap_tio_start
= current_time
;
205 scheduleWrite(requestBuf
);
208 void Adaptation::Icap::ModXact::handleCommWrote(size_t sz
)
210 debugs(93, 5, "Wrote " << sz
<< " bytes");
212 if (state
.writing
== State::writingHeaders
)
213 handleCommWroteHeaders();
215 handleCommWroteBody();
218 void Adaptation::Icap::ModXact::handleCommWroteHeaders()
220 Must(state
.writing
== State::writingHeaders
);
222 // determine next step
223 if (preview
.enabled()) {
225 decideWritingAfterPreview("zero-size");
227 state
.writing
= State::writingPreview
;
228 } else if (virginBody
.expected()) {
229 state
.writing
= State::writingPrime
;
238 void Adaptation::Icap::ModXact::writeMore()
240 debugs(93, 5, "checking whether to write more" << status());
242 if (writer
!= nullptr) // already writing something
245 switch (state
.writing
) {
247 case State::writingInit
: // waiting for service OPTIONS
248 Must(state
.serviceWaiting
);
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
257 case State::writingAlmostDone
: // was waiting for the last write
261 case State::writingPreview
:
265 case State::writingPrime
:
270 throw TexcHere("Adaptation::Icap::ModXact in bad writing state");
274 void Adaptation::Icap::ModXact::writePreviewBody()
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);
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
);
285 // change state once preview is written
288 decideWritingAfterPreview("body");
291 /// determine state.writing after we wrote the entire preview
292 void Adaptation::Icap::ModXact::decideWritingAfterPreview(const char *kind
)
294 if (preview
.ieof()) // nothing more to write
296 else if (state
.parsing
== State::psIcapHeader
) // did not get a reply yet
297 state
.writing
= State::writingPaused
; // wait for the ICAP server reply
299 stopWriting(true); // ICAP server reply implies no post-preview writing
301 debugs(93, 6, "decided on writing after " << kind
<< " preview" <<
305 void Adaptation::Icap::ModXact::writePrimeBody()
307 Must(state
.writing
== State::writingPrime
);
308 Must(virginBodyWriting
.active());
310 const size_t size
= (size_t)virgin
.body_pipe
->buf().contentSize();
311 writeSomeBody("prime virgin body", size
);
313 if (virginBodyEndReached(virginBodyWriting
)) {
314 debugs(93, 5, "wrote entire body");
319 void Adaptation::Icap::ModXact::writeSomeBody(const char *label
, size_t size
)
321 Must(!writer
&& state
.writing
< state
.writingAlmostDone
);
322 Must(virgin
.body_pipe
!= nullptr);
323 debugs(93, 8, "will write up to " << size
<< " bytes of " <<
326 MemBuf writeBuf
; // TODO: suggest a min size based on size and lastChunk
328 writeBuf
.init(); // note: we assume that last-chunk will fit
330 const size_t writableSize
= virginContentSize(virginBodyWriting
);
331 const size_t chunkSize
= min(writableSize
, size
);
334 debugs(93, 7, "will write " << chunkSize
<<
335 "-byte chunk of " << label
);
337 openChunk(writeBuf
, chunkSize
, false);
338 writeBuf
.append(virginContentData(virginBodyWriting
), chunkSize
);
339 closeChunk(writeBuf
);
341 virginBodyWriting
.progress(chunkSize
);
344 debugs(93, 7, "has no writable " << label
<< " content");
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();
355 debugs(93, 8, "will write last-chunk of " << label
);
356 addLastRequestChunk(writeBuf
);
359 debugs(93, 7, "will write " << writeBuf
.contentSize()
360 << " raw bytes of " << label
);
362 if (writeBuf
.hasContent()) {
363 scheduleWrite(writeBuf
); // comm will free the chunk
369 void Adaptation::Icap::ModXact::addLastRequestChunk(MemBuf
&buf
)
371 const bool ieof
= state
.writing
== State::writingPreview
&& preview
.ieof();
372 openChunk(buf
, 0, ieof
);
376 void Adaptation::Icap::ModXact::openChunk(MemBuf
&buf
, size_t chunkSize
, bool ieof
)
378 buf
.appendf((ieof
? "%x; ieof\r\n" : "%x\r\n"), (int) chunkSize
);
381 void Adaptation::Icap::ModXact::closeChunk(MemBuf
&buf
)
383 buf
.append(ICAP::crlf
, 2); // chunk-terminating CRLF
386 const HttpRequest
&Adaptation::Icap::ModXact::virginRequest() const
388 const HttpRequest
*request
= virgin
.cause
?
389 virgin
.cause
: dynamic_cast<const HttpRequest
*>(virgin
.header
);
394 // did the activity reached the end of the virgin body?
395 bool Adaptation::Icap::ModXact::virginBodyEndReached(const Adaptation::Icap::VirginBodyAct
&act
) const
398 !act
.active() || // did all (assuming it was originally planned)
399 !virgin
.body_pipe
->expectMoreAfter(act
.offset()); // will not have more
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
404 size_t Adaptation::Icap::ModXact::virginContentSize(const Adaptation::Icap::VirginBodyAct
&act
) const
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
);
415 // pointer to buffered virgin body data available for the specified activity
416 const char *Adaptation::Icap::ModXact::virginContentData(const Adaptation::Icap::VirginBodyAct
&act
) const
419 const uint64_t dataStart
= act
.offset();
420 Must(virginConsumed
<= dataStart
);
421 return virgin
.body_pipe
->buf().content() + static_cast<size_t>(dataStart
-virginConsumed
);
424 void Adaptation::Icap::ModXact::virginConsume()
426 debugs(93, 9, "consumption guards: " << !virgin
.body_pipe
<< isRetriable
<<
427 isRepeatable
<< canStartBypass
<< protectGroupBypass
);
429 if (!virgin
.body_pipe
)
430 return; // nothing to consume
433 return; // do not consume if we may have to retry later
435 BodyPipe
&bp
= *virgin
.body_pipe
;
436 const bool wantToPostpone
= isRepeatable
|| canStartBypass
|| protectGroupBypass
;
438 if (wantToPostpone
&& bp
.buf().potentialSpaceSize() > 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. Should the trade-off be configurable?
442 debugs(93, 8, "postponing consumption from " << bp
.status());
446 const size_t have
= static_cast<size_t>(bp
.buf().contentSize());
447 const uint64_t end
= virginConsumed
+ have
;
448 uint64_t offset
= end
;
450 debugs(93, 9, "max virgin consumption offset=" << offset
<<
451 " acts " << virginBodyWriting
.active() << virginBodySending
.active() <<
452 " consumed=" << virginConsumed
<<
453 " from " << virgin
.body_pipe
->status());
455 if (virginBodyWriting
.active())
456 offset
= min(virginBodyWriting
.offset(), offset
);
458 if (virginBodySending
.active())
459 offset
= min(virginBodySending
.offset(), offset
);
461 Must(virginConsumed
<= offset
&& offset
<= end
);
463 if (const size_t size
= static_cast<size_t>(offset
- virginConsumed
)) {
464 debugs(93, 8, "consuming " << size
<< " out of " << have
<<
465 " virgin body bytes");
467 virginConsumed
+= size
;
468 Must(!isRetriable
); // or we should not be consuming
469 disableRepeats("consumed content");
470 disableBypass("consumed content", true);
474 void Adaptation::Icap::ModXact::handleCommWroteBody()
479 // Called when we do not expect to call comm_write anymore.
480 // We may have a pending write though.
481 // If stopping nicely, we will just wait for that pending write, if any.
482 void Adaptation::Icap::ModXact::stopWriting(bool nicely
)
484 if (state
.writing
== State::writingReallyDone
)
487 if (writer
!= nullptr) {
489 debugs(93, 7, "will wait for the last write" << status());
490 state
.writing
= State::writingAlmostDone
; // may already be set
494 debugs(93, 3, "will NOT wait for the last write" << status());
496 // Comm does not have an interface to clear the writer callback nicely,
497 // but without clearing the writer we cannot recycle the connection.
498 // We prevent connection reuse and hope that we can handle a callback
499 // call at any time, usually in the middle of the destruction sequence!
500 // Somebody should add comm_remove_write_handler() to comm API.
501 reuseConnection
= false;
502 ignoreLastWrite
= true;
505 debugs(93, 7, "will no longer write" << status());
506 if (virginBodyWriting
.active()) {
507 virginBodyWriting
.disable();
510 state
.writing
= State::writingReallyDone
;
514 void Adaptation::Icap::ModXact::stopBackup()
516 if (!virginBodySending
.active())
519 debugs(93, 7, "will no longer backup" << status());
520 virginBodySending
.disable();
524 bool Adaptation::Icap::ModXact::doneAll() const
526 return Adaptation::Icap::Xaction::doneAll() && !state
.serviceWaiting
&&
528 doneReading() && state
.doneWriting();
531 void Adaptation::Icap::ModXact::startReading()
533 Must(haveConnection());
535 Must(!adapted
.header
);
536 Must(!adapted
.body_pipe
);
538 // we use the same buffer for headers and body and then consume headers
542 void Adaptation::Icap::ModXact::readMore()
544 if (reader
!= nullptr || doneReading()) {
545 debugs(93,3, "returning from readMore because reader or doneReading()");
549 // do not fill readBuf if we have no space to store the result
550 if (adapted
.body_pipe
!= nullptr &&
551 !adapted
.body_pipe
->buf().hasPotentialSpace()) {
552 debugs(93,3, "not reading because ICAP reply pipe is full");
556 if (readBuf
.length() < SQUID_TCP_SO_RCVBUF
)
559 debugs(93,3, "cannot read with a full buffer");
562 // comm module read a portion of the ICAP response for us
563 void Adaptation::Icap::ModXact::handleCommRead(size_t)
565 Must(!state
.doneParsing());
566 icap_tio_finish
= current_time
;
571 void Adaptation::Icap::ModXact::echoMore()
573 Must(state
.sending
== State::sendingVirgin
);
574 Must(adapted
.body_pipe
!= nullptr);
575 Must(virginBodySending
.active());
577 const size_t sizeMax
= virginContentSize(virginBodySending
);
578 debugs(93,5, "will echo up to " << sizeMax
<< " bytes from " <<
579 virgin
.body_pipe
->status());
580 debugs(93,5, "will echo up to " << sizeMax
<< " bytes to " <<
581 adapted
.body_pipe
->status());
584 const size_t size
= adapted
.body_pipe
->putMoreData(virginContentData(virginBodySending
), sizeMax
);
585 debugs(93,5, "echoed " << size
<< " out of " << sizeMax
<<
587 virginBodySending
.progress(size
);
588 disableRepeats("echoed content");
589 disableBypass("echoed content", true);
593 if (virginBodyEndReached(virginBodySending
)) {
594 debugs(93, 5, "echoed all" << status());
597 debugs(93, 5, "has " <<
598 virgin
.body_pipe
->buf().contentSize() << " bytes " <<
599 "and expects more to echo" << status());
600 // TODO: timeout if virgin or adapted pipes are broken
604 bool Adaptation::Icap::ModXact::doneSending() const
606 return state
.sending
== State::sendingDone
;
609 // stop (or do not start) sending adapted message body
610 void Adaptation::Icap::ModXact::stopSending(bool nicely
)
612 debugs(93, 7, "Enter stop sending ");
615 debugs(93, 7, "Proceed with stop sending ");
617 if (state
.sending
!= State::sendingUndecided
) {
618 debugs(93, 7, "will no longer send" << status());
619 if (adapted
.body_pipe
!= nullptr) {
620 virginBodySending
.disable();
621 // we may leave debts if we were echoing and the virgin
622 // body_pipe got exhausted before we echoed all planned bytes
623 const bool leftDebts
= adapted
.body_pipe
->needsMoreData();
624 stopProducingFor(adapted
.body_pipe
, nicely
&& !leftDebts
);
627 debugs(93, 7, "will not start sending" << status());
628 Must(!adapted
.body_pipe
);
631 state
.sending
= State::sendingDone
;
635 // should be called after certain state.writing or state.sending changes
636 void Adaptation::Icap::ModXact::checkConsuming()
638 // quit if we already stopped or are still using the pipe
639 if (!virgin
.body_pipe
|| !state
.doneConsumingVirgin())
642 debugs(93, 7, "will stop consuming" << status());
643 stopConsumingFrom(virgin
.body_pipe
);
646 void Adaptation::Icap::ModXact::parseMore()
648 debugs(93, 5, "have " << readBuf
.length() << " bytes to parse" << status());
649 debugs(93, 5, "\n" << readBuf
);
651 if (state
.parsingHeaders())
654 if (state
.parsing
== State::psBody
)
657 if (state
.parsing
== State::psIcapTrailer
)
661 void Adaptation::Icap::ModXact::callException(const std::exception
&e
)
663 if (!canStartBypass
|| isRetriable
) {
665 if (const TextException
*te
= dynamic_cast<const TextException
*>(&e
))
666 detailError(new ExceptionErrorDetail(te
->id()));
668 detailError(new ExceptionErrorDetail(Here().id()));
670 Adaptation::Icap::Xaction::callException(e
);
675 debugs(93, 3, "bypassing " << inCall
<< " exception: " <<
676 e
.what() << ' ' << status());
678 } catch (const TextException
&bypassTe
) {
679 detailError(new ExceptionErrorDetail(bypassTe
.id()));
680 Adaptation::Icap::Xaction::callException(bypassTe
);
681 } catch (const std::exception
&bypassE
) {
682 detailError(new ExceptionErrorDetail(Here().id()));
683 Adaptation::Icap::Xaction::callException(bypassE
);
687 void Adaptation::Icap::ModXact::bypassFailure()
689 disableBypass("already started to bypass", false);
691 Must(!isRetriable
); // or we should not be bypassing
692 // TODO: should the same be enforced for isRepeatable? Check icap_repeat??
698 // end all activities associated with the ICAP server
702 stopWriting(true); // or should we force it?
703 if (haveConnection()) {
704 reuseConnection
= false; // be conservative
705 cancelRead(); // may not work; and we cannot stop connecting either
707 debugs(93, 7, "Warning: bypass failed to stop I/O" << status());
710 service().noteFailure(); // we are bypassing, but this is still a failure
713 void Adaptation::Icap::ModXact::disableBypass(const char *reason
, bool includingGroupBypass
)
715 if (canStartBypass
) {
716 debugs(93,7, "will never start bypass because " << reason
);
717 canStartBypass
= false;
719 if (protectGroupBypass
&& includingGroupBypass
) {
720 debugs(93,7, "not protecting group bypass because " << reason
);
721 protectGroupBypass
= false;
725 // note that allocation for echoing is done in handle204NoContent()
726 void Adaptation::Icap::ModXact::maybeAllocateHttpMsg()
728 if (adapted
.header
) // already allocated
731 if (gotEncapsulated("res-hdr")) {
732 adapted
.setHeader(new HttpReply
);
733 setOutcome(service().cfg().method
== ICAP::methodReqmod
?
734 xoSatisfied
: xoModified
);
735 } else if (gotEncapsulated("req-hdr")) {
736 adapted
.setHeader(new HttpRequest(virginRequest().masterXaction
));
737 setOutcome(xoModified
);
739 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
742 void Adaptation::Icap::ModXact::parseHeaders()
744 Must(state
.parsingHeaders());
746 if (state
.parsing
== State::psIcapHeader
) {
747 debugs(93, 5, "parse ICAP headers");
751 if (state
.parsing
== State::psHttpHeader
) {
752 debugs(93, 5, "parse HTTP headers");
756 if (state
.parsingHeaders()) { // need more data
764 // called after parsing all headers or when bypassing an exception
765 void Adaptation::Icap::ModXact::startSending()
767 disableRepeats("sent headers");
768 disableBypass("sent headers", true);
769 sendAnswer(Answer::Forward(adapted
.header
));
771 if (state
.sending
== State::sendingVirgin
)
774 // If we are not using the virgin HTTP object update the
775 // Http::Message::sources flag.
776 // The state.sending may set to State::sendingVirgin in the case
777 // of 206 responses too, where we do not want to update Http::Message::sources
778 // flag. However even for 206 responses the state.sending is
779 // not set yet to sendingVirgin. This is done in later step
780 // after the parseBody method called.
785 void Adaptation::Icap::ModXact::parseIcapHead()
787 Must(state
.sending
== State::sendingUndecided
);
789 if (!parseHead(icapReply
.getRaw()))
792 if (expectIcapTrailers()) {
793 Must(!trailerParser
);
794 trailerParser
= new TrailerParser
;
797 static SBuf
close("close", 5);
798 if (httpHeaderHasConnDir(&icapReply
->header
, close
)) {
799 debugs(93, 5, "found connection close");
800 reuseConnection
= false;
803 switch (icapReply
->sline
.status()) {
805 case Http::scContinue
:
810 case Http::scCreated
: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
812 if (!validate200Ok()) {
813 throw TexcHere("Invalid ICAP Response");
820 case Http::scNoContent
:
821 handle204NoContent();
824 case Http::scPartialContent
:
825 handle206PartialContent();
829 debugs(93, 5, "ICAP status " << icapReply
->sline
.status());
830 handleUnknownScode();
834 const HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
836 request
= &virginRequest();
838 // update the cross-transactional database if needed (all status codes!)
839 if (const char *xxName
= Adaptation::Config::masterx_shared_name
) {
840 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
841 if (ah
!= nullptr) { // TODO: reorder checks to avoid creating history
842 const String val
= icapReply
->header
.getByName(xxName
);
843 if (val
.size() > 0) // XXX: HttpHeader lacks empty value detection
844 ah
->updateXxRecord(xxName
, val
);
848 // update the adaptation plan if needed (all status codes!)
849 if (service().cfg().routing
) {
851 if (icapReply
->header
.getList(Http::HdrType::X_NEXT_SERVICES
, &services
)) {
852 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
854 ah
->updateNextServices(services
);
856 } // TODO: else warn (occasionally!) if we got Http::HdrType::X_NEXT_SERVICES
858 // We need to store received ICAP headers for <icapLastHeader logformat option.
859 // If we already have stored headers from previous ICAP transaction related to this
860 // request, old headers will be replaced with the new one.
862 Adaptation::History::Pointer ah
= request
->adaptLogHistory();
864 ah
->recordMeta(&icapReply
->header
);
866 // handle100Continue() manages state.writing on its own.
867 // Non-100 status means the server needs no postPreview data from us.
868 if (state
.writing
== State::writingPaused
)
872 /// Parses ICAP trailers and stops parsing, if all trailer data
873 /// have been received.
874 void Adaptation::Icap::ModXact::parseIcapTrailer() {
876 if (parsePart(trailerParser
, "trailer")) {
877 for (const auto &e
: trailerParser
->trailer
.entries
)
878 debugs(93, 5, "ICAP trailer: " << e
->name
<< ": " << e
->value
);
883 bool Adaptation::Icap::ModXact::validate200Ok()
885 if (service().cfg().method
== ICAP::methodRespmod
)
886 return gotEncapsulated("res-hdr");
888 return service().cfg().method
== ICAP::methodReqmod
&&
892 void Adaptation::Icap::ModXact::handle100Continue()
894 Must(state
.writing
== State::writingPaused
);
895 // server must not respond before the end of preview: we may send ieof
896 Must(preview
.enabled() && preview
.done() && !preview
.ieof());
898 // 100 "Continue" cancels our Preview commitment,
899 // but not commitment to handle 204 or 206 outside Preview
900 if (!state
.allowedPostview204
&& !state
.allowedPostview206
)
903 state
.parsing
= State::psIcapHeader
; // eventually
906 state
.writing
= State::writingPrime
;
911 void Adaptation::Icap::ModXact::handle200Ok()
913 state
.parsing
= State::psHttpHeader
;
914 state
.sending
= State::sendingAdapted
;
919 void Adaptation::Icap::ModXact::handle204NoContent()
925 void Adaptation::Icap::ModXact::handle206PartialContent()
927 if (state
.writing
== State::writingPaused
) {
928 Must(preview
.enabled());
929 Must(state
.allowedPreview206
);
930 debugs(93, 7, "206 inside preview");
932 Must(state
.writing
> State::writingPaused
);
933 Must(state
.allowedPostview206
);
934 debugs(93, 7, "206 outside preview");
936 state
.parsing
= State::psHttpHeader
;
937 state
.sending
= State::sendingAdapted
;
938 state
.readyForUob
= true;
942 // Called when we receive a 204 No Content response and
943 // when we are trying to bypass a service failure.
944 // We actually start sending (echoig or not) in startSending.
945 void Adaptation::Icap::ModXact::prepEchoing()
947 disableRepeats("preparing to echo content");
948 disableBypass("preparing to echo content", true);
951 // We want to clone the HTTP message, but we do not want
952 // to copy some non-HTTP state parts that Http::Message kids carry in them.
953 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
954 // Instead, we simply write the HTTP message and "clone" it by parsing.
955 // TODO: use Http::Message::clone()!
957 Http::Message
*oldHead
= virgin
.header
;
958 debugs(93, 7, "cloning virgin message " << oldHead
);
962 // write the virgin message into a memory buffer
964 packHead(httpBuf
, oldHead
);
966 // allocate the adapted message and copy metainfo
967 Must(!adapted
.header
);
969 Http::MessagePointer newHead
;
970 if (const HttpRequest
*r
= dynamic_cast<const HttpRequest
*>(oldHead
)) {
971 newHead
= new HttpRequest(r
->masterXaction
);
972 } else if (dynamic_cast<const HttpReply
*>(oldHead
)) {
973 newHead
= new HttpReply
;
977 newHead
->inheritProperties(oldHead
);
979 adapted
.setHeader(newHead
.getRaw());
982 // parse the buffer back
983 Http::StatusCode error
= Http::scNone
;
985 httpBuf
.terminate(); // Http::Message::parse requires nil-terminated buffer
986 Must(adapted
.header
->parse(httpBuf
.content(), httpBuf
.contentSize(), true, &error
));
987 Must(adapted
.header
->hdr_sz
== httpBuf
.contentSize()); // no leftovers
991 debugs(93, 7, "cloned virgin message " << oldHead
<< " to " <<
994 // setup adapted body pipe if needed
995 if (oldHead
->body_pipe
!= nullptr) {
996 debugs(93, 7, "will echo virgin body from " <<
998 if (!virginBodySending
.active())
999 virginBodySending
.plan(); // will throw if not possible
1000 state
.sending
= State::sendingVirgin
;
1003 // TODO: optimize: is it possible to just use the oldHead pipe and
1004 // remove ICAP from the loop? This echoing is probably a common case!
1005 makeAdaptedBodyPipe("echoed virgin response");
1006 if (oldHead
->body_pipe
->bodySizeKnown())
1007 adapted
.body_pipe
->setBodySize(oldHead
->body_pipe
->bodySize());
1008 debugs(93, 7, "will echo virgin body to " <<
1011 debugs(93, 7, "no virgin body to echo");
1016 /// Called when we received use-original-body chunk extension in 206 response.
1017 /// We actually start sending (echoing or not) in startSending().
1018 void Adaptation::Icap::ModXact::prepPartialBodyEchoing(uint64_t pos
)
1020 Must(virginBodySending
.active());
1021 Must(virgin
.header
->body_pipe
!= nullptr);
1023 setOutcome(xoPartEcho
);
1025 debugs(93, 7, "will echo virgin body suffix from " <<
1026 virgin
.header
->body_pipe
<< " offset " << pos
);
1028 // check that use-original-body=N does not point beyond buffered data
1029 const uint64_t virginDataEnd
= virginConsumed
+
1030 virgin
.body_pipe
->buf().contentSize();
1031 Must(pos
<= virginDataEnd
);
1032 virginBodySending
.progress(static_cast<size_t>(pos
));
1034 state
.sending
= State::sendingVirgin
;
1037 if (virgin
.header
->body_pipe
->bodySizeKnown())
1038 adapted
.body_pipe
->expectProductionEndAfter(virgin
.header
->body_pipe
->bodySize() - pos
);
1040 debugs(93, 7, "will echo virgin body suffix to " <<
1043 // Start echoing data
1047 void Adaptation::Icap::ModXact::handleUnknownScode()
1051 // TODO: mark connection as "bad"
1053 // Terminate the transaction; we do not know how to handle this response.
1054 throw TexcHere("Unsupported ICAP status code");
1057 void Adaptation::Icap::ModXact::parseHttpHead()
1059 if (expectHttpHeader()) {
1060 replyHttpHeaderSize
= 0;
1061 maybeAllocateHttpMsg();
1063 if (!parseHead(adapted
.header
))
1064 return; // need more header data
1067 replyHttpHeaderSize
= adapted
.header
->hdr_sz
;
1069 if (dynamic_cast<HttpRequest
*>(adapted
.header
)) {
1070 const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(virgin
.header
);
1072 // TODO: the adapted request did not really originate from the
1073 // client; give proxy admin an option to prevent copying of
1074 // sensitive client information here. See the following thread:
1075 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
1078 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
1080 adapted
.header
->inheritProperties(virgin
.header
);
1083 decideOnParsingBody();
1086 template<class Part
>
1087 bool Adaptation::Icap::ModXact::parsePart(Part
*part
, const char *description
)
1090 debugs(93, 5, "have " << readBuf
.length() << ' ' << description
<< " bytes to parse; state: " << state
.parsing
);
1091 Http::StatusCode error
= Http::scNone
;
1092 // XXX: performance regression. c_str() data copies
1093 // XXX: Http::Message::parse requires a terminated string buffer
1094 const char *tmpBuf
= readBuf
.c_str();
1095 const bool parsed
= part
->parse(tmpBuf
, readBuf
.length(), commEof
, &error
);
1096 debugs(93, (!parsed
&& error
) ? 2 : 5, description
<< " parsing result: " << parsed
<< " detail: " << error
);
1097 Must(parsed
|| !error
);
1099 readBuf
.consume(part
->hdr_sz
);
1103 // parses both HTTP and ICAP headers
1105 Adaptation::Icap::ModXact::parseHead(Http::Message
*head
)
1107 if (!parsePart(head
, "head")) {
1114 bool Adaptation::Icap::ModXact::expectHttpHeader() const
1116 return gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr");
1119 bool Adaptation::Icap::ModXact::expectHttpBody() const
1121 return gotEncapsulated("res-body") || gotEncapsulated("req-body");
1124 bool Adaptation::Icap::ModXact::expectIcapTrailers() const
1127 const bool promisesToSendTrailer
= icapReply
->header
.getByIdIfPresent(Http::HdrType::TRAILER
, &trailers
);
1128 const bool supportsTrailers
= icapReply
->header
.hasListMember(Http::HdrType::ALLOW
, "trailers", ',');
1129 // ICAP Trailer specs require us to reject transactions having either Trailer
1130 // header or Allow:trailers
1131 Must((promisesToSendTrailer
== supportsTrailers
) || (!promisesToSendTrailer
&& supportsTrailers
));
1132 if (promisesToSendTrailer
&& !trailers
.size())
1133 debugs(93, DBG_IMPORTANT
, "ERROR: ICAP Trailer response header field must not be empty (salvaged)");
1134 return promisesToSendTrailer
;
1137 void Adaptation::Icap::ModXact::decideOnParsingBody()
1139 if (expectHttpBody()) {
1140 debugs(93, 5, "expecting a body");
1141 state
.parsing
= State::psBody
;
1142 replyHttpBodySize
= 0;
1143 bodyParser
= new Http1::TeChunkedParser
;
1144 bodyParser
->parseExtensionValuesWith(&extensionParser
);
1145 makeAdaptedBodyPipe("adapted response from the ICAP server");
1146 Must(state
.sending
== State::sendingAdapted
);
1148 debugs(93, 5, "not expecting a body");
1150 state
.parsing
= State::psIcapTrailer
;
1157 void Adaptation::Icap::ModXact::parseBody()
1159 Must(state
.parsing
== State::psBody
);
1162 debugs(93, 5, "have " << readBuf
.length() << " body bytes to parse");
1164 // the parser will throw on errors
1165 BodyPipeCheckout
bpc(*adapted
.body_pipe
);
1166 bodyParser
->setPayloadBuffer(&bpc
.buf
);
1167 const bool parsed
= bodyParser
->parse(readBuf
);
1168 readBuf
= bodyParser
->remaining(); // sync buffers after parse
1171 debugs(93, 5, "have " << readBuf
.length() << " body bytes after parsed all: " << parsed
);
1172 replyHttpBodySize
+= adapted
.body_pipe
->buf().contentSize();
1174 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
1175 // TODO: do we really need this if we disable when sending headers?
1176 if (adapted
.body_pipe
->buf().contentSize() > 0) { // parsed something sometime
1177 disableRepeats("sent adapted content");
1178 disableBypass("sent adapted content", true);
1182 if (state
.readyForUob
&& extensionParser
.sawUseOriginalBody())
1183 prepPartialBodyEchoing(extensionParser
.useOriginalBody());
1185 stopSending(true); // the parser succeeds only if all parsed data fits
1187 state
.parsing
= State::psIcapTrailer
;
1193 debugs(93,3, this << " needsMoreData = " << bodyParser
->needsMoreData());
1195 if (bodyParser
->needsMoreData()) {
1197 Must(mayReadMore());
1201 if (bodyParser
->needsMoreSpace()) {
1202 Must(!doneSending()); // can hope for more space
1203 Must(adapted
.body_pipe
->buf().contentSize() > 0); // paranoid
1204 // TODO: there should be a timeout in case the sink is broken
1205 // or cannot consume partial content (while we need more space)
1209 void Adaptation::Icap::ModXact::stopParsing(const bool checkUnparsedData
)
1211 if (state
.parsing
== State::psDone
)
1214 if (checkUnparsedData
)
1215 Must(readBuf
.isEmpty());
1217 debugs(93, 7, "will no longer parse" << status());
1220 bodyParser
= nullptr;
1222 delete trailerParser
;
1223 trailerParser
= nullptr;
1225 state
.parsing
= State::psDone
;
1228 // HTTP side added virgin body data
1229 void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer
)
1233 if (state
.sending
== State::sendingVirgin
)
1237 // HTTP side sent us all virgin info
1238 void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer
)
1240 Must(virgin
.body_pipe
->productionEnded());
1242 // push writer and sender in case we were waiting for the last-chunk
1245 if (state
.sending
== State::sendingVirgin
)
1249 // body producer aborted, but the initiator may still want to know
1250 // the answer, even though the HTTP message has been truncated
1251 void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer
)
1253 Must(virgin
.body_pipe
->productionEnded());
1255 // push writer and sender in case we were waiting for the last-chunk
1258 if (state
.sending
== State::sendingVirgin
)
1262 // adapted body consumer wants more adapted data and
1263 // possibly freed some buffer space
1264 void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
1266 if (state
.sending
== State::sendingVirgin
)
1268 else if (state
.sending
== State::sendingAdapted
)
1271 Must(state
.sending
== State::sendingUndecided
);
1274 // adapted body consumer aborted
1275 void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer
)
1277 static const auto d
= MakeNamedErrorDetail("ICAP_XACT_BODY_CONSUMER_ABORT");
1279 mustStop("adapted body consumer aborted");
1282 Adaptation::Icap::ModXact::~ModXact()
1285 delete trailerParser
;
1289 void Adaptation::Icap::ModXact::swanSong()
1291 debugs(93, 5, "swan sings" << status());
1296 if (theInitiator
.set()) { // we have not sent the answer to the initiator
1297 static const auto d
= MakeNamedErrorDetail("ICAP_XACT_OTHER");
1301 // update adaptation history if start was called and we reserved a slot
1302 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
1303 if (ah
!= nullptr && adaptHistoryId
>= 0)
1304 ah
->recordXactFinish(adaptHistoryId
);
1306 Adaptation::Icap::Xaction::swanSong();
1309 void prepareLogWithRequestDetails(HttpRequest
*, const AccessLogEntryPointer
&);
1311 void Adaptation::Icap::ModXact::finalizeLogInfo()
1313 HttpRequest
*adapted_request_
= nullptr;
1314 HttpReply
*adapted_reply_
= nullptr;
1315 HttpRequest
*virgin_request_
= const_cast<HttpRequest
*>(&virginRequest());
1316 if (!(adapted_request_
= dynamic_cast<HttpRequest
*>(adapted
.header
))) {
1317 // if the request was not adapted, use virgin request to simplify
1318 // the code further below
1319 adapted_request_
= virgin_request_
;
1320 adapted_reply_
= dynamic_cast<HttpReply
*>(adapted
.header
);
1323 Adaptation::Icap::History::Pointer h
= virgin_request_
->icapHistory();
1324 Must(h
!= nullptr); // ICAPXaction::maybeLog calls only if there is a log
1325 al
.icp
.opcode
= ICP_INVALID
;
1326 al
.url
= h
->log_uri
.termedBuf();
1327 const Adaptation::Icap::ServiceRep
&s
= service();
1328 al
.icap
.reqMethod
= s
.cfg().method
;
1330 al
.cache
.caddr
= virgin_request_
->client_addr
;
1332 al
.request
= virgin_request_
;
1333 HTTPMSGLOCK(al
.request
);
1334 al
.adapted_request
= adapted_request_
;
1335 HTTPMSGLOCK(al
.adapted_request
);
1337 // XXX: This reply (and other ALE members!) may have been needed earlier.
1338 al
.reply
= adapted_reply_
;
1341 if (h
->ssluser
.size())
1342 al
.cache
.ssluser
= h
->ssluser
.termedBuf();
1344 al
.cache
.code
= h
->logType
;
1346 const Http::Message
*virgin_msg
= dynamic_cast<HttpReply
*>(virgin
.header
);
1348 virgin_msg
= virgin_request_
;
1349 assert(virgin_msg
!= virgin
.cause
);
1350 al
.http
.clientRequestSz
.header
= virgin_msg
->hdr_sz
;
1351 if (virgin_msg
->body_pipe
!= nullptr)
1352 al
.http
.clientRequestSz
.payloadData
= virgin_msg
->body_pipe
->producedSize();
1354 // leave al.icap.bodyBytesRead negative if no body
1355 if (replyHttpHeaderSize
>= 0 || replyHttpBodySize
>= 0) {
1356 const int64_t zero
= 0; // to make max() argument types the same
1357 const uint64_t headerSize
= max(zero
, replyHttpHeaderSize
);
1358 const uint64_t bodySize
= max(zero
, replyHttpBodySize
);
1359 al
.icap
.bodyBytesRead
= headerSize
+ bodySize
;
1360 al
.http
.clientReplySz
.header
= headerSize
;
1361 al
.http
.clientReplySz
.payloadData
= bodySize
;
1364 if (adapted_reply_
) {
1365 al
.http
.code
= adapted_reply_
->sline
.status();
1366 al
.http
.content_type
= adapted_reply_
->content_type
.termedBuf();
1367 if (replyHttpBodySize
>= 0)
1368 al
.cache
.highOffset
= replyHttpBodySize
;
1369 //don't set al.cache.objectSize because it hasn't exist yet
1371 prepareLogWithRequestDetails(adapted_request_
, alep
);
1372 Xaction::finalizeLogInfo();
1375 void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf
&buf
)
1377 char ntoabuf
[MAX_IPSTRLEN
];
1379 * XXX These should use HttpHdr interfaces instead of Printfs
1381 const Adaptation::ServiceConfig
&s
= service().cfg();
1382 buf
.appendf("%s " SQUIDSTRINGPH
" ICAP/1.0\r\n", s
.methodStr(), SQUIDSTRINGPRINT(s
.uri
));
1383 buf
.appendf("Host: " SQUIDSTRINGPH
":%d\r\n", SQUIDSTRINGPRINT(s
.host
), s
.port
);
1384 buf
.appendf("Date: %s\r\n", Time::FormatRfc1123(squid_curtime
));
1386 if (!TheConfig
.reuse_connections
)
1387 buf
.appendf("Connection: close\r\n");
1389 const HttpRequest
*request
= &virginRequest();
1391 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1393 if (virgin
.header
->header
.has(Http::HdrType::PROXY_AUTHENTICATE
)) {
1394 String vh
=virgin
.header
->header
.getById(Http::HdrType::PROXY_AUTHENTICATE
);
1395 buf
.appendf("Proxy-Authenticate: " SQUIDSTRINGPH
"\r\n",SQUIDSTRINGPRINT(vh
));
1398 if (virgin
.header
->header
.has(Http::HdrType::PROXY_AUTHORIZATION
)) {
1399 String vh
=virgin
.header
->header
.getById(Http::HdrType::PROXY_AUTHORIZATION
);
1400 buf
.appendf("Proxy-Authorization: " SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(vh
));
1401 } else if (request
->extacl_user
.size() > 0 && request
->extacl_passwd
.size() > 0) {
1402 struct base64_encode_ctx ctx
;
1403 base64_encode_init(&ctx
);
1404 char base64buf
[base64_encode_len(MAX_LOGIN_SZ
)];
1405 size_t resultLen
= base64_encode_update(&ctx
, base64buf
, request
->extacl_user
.size(), reinterpret_cast<const uint8_t*>(request
->extacl_user
.rawBuf()));
1406 resultLen
+= base64_encode_update(&ctx
, base64buf
+resultLen
, 1, reinterpret_cast<const uint8_t*>(":"));
1407 resultLen
+= base64_encode_update(&ctx
, base64buf
+resultLen
, request
->extacl_passwd
.size(), reinterpret_cast<const uint8_t*>(request
->extacl_passwd
.rawBuf()));
1408 resultLen
+= base64_encode_final(&ctx
, base64buf
+resultLen
);
1409 buf
.appendf("Proxy-Authorization: Basic %.*s\r\n", (int)resultLen
, base64buf
);
1412 // share the cross-transactional database records if needed
1413 if (Adaptation::Config::masterx_shared_name
) {
1414 Adaptation::History::Pointer ah
= request
->adaptHistory(false);
1415 if (ah
!= nullptr) {
1417 if (ah
->getXxRecord(name
, value
)) {
1418 buf
.appendf(SQUIDSTRINGPH
": " SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(name
), SQUIDSTRINGPRINT(value
));
1423 buf
.append("Encapsulated: ", 14);
1429 // build HTTP request header, if any
1430 ICAP::Method m
= s
.method
;
1432 // to simplify, we could assume that request is always available
1435 if (ICAP::methodRespmod
== m
)
1436 encapsulateHead(buf
, "req-hdr", httpBuf
, request
);
1437 else if (ICAP::methodReqmod
== m
)
1438 encapsulateHead(buf
, "req-hdr", httpBuf
, virgin
.header
);
1441 if (ICAP::methodRespmod
== m
)
1442 if (const Http::Message
*prime
= virgin
.header
)
1443 encapsulateHead(buf
, "res-hdr", httpBuf
, prime
);
1445 if (!virginBody
.expected())
1446 buf
.appendf("null-body=%d", (int) httpBuf
.contentSize());
1447 else if (ICAP::methodReqmod
== m
)
1448 buf
.appendf("req-body=%d", (int) httpBuf
.contentSize());
1450 buf
.appendf("res-body=%d", (int) httpBuf
.contentSize());
1452 buf
.append(ICAP::crlf
, 2); // terminate Encapsulated line
1454 if (preview
.enabled()) {
1455 buf
.appendf("Preview: %d\r\n", (int)preview
.ad());
1456 if (!virginBody
.expected()) // there is no body to preview
1457 finishNullOrEmptyBodyPreview(httpBuf
);
1460 makeAllowHeader(buf
);
1462 if (TheConfig
.send_client_ip
&& request
) {
1463 Ip::Address client_addr
;
1464 #if FOLLOW_X_FORWARDED_FOR
1465 if (TheConfig
.use_indirect_client
) {
1466 client_addr
= request
->indirect_client_addr
;
1469 client_addr
= request
->client_addr
;
1470 if (!client_addr
.isAnyAddr() && !client_addr
.isNoAddr())
1471 buf
.appendf("X-Client-IP: %s\r\n", client_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
1474 if (TheConfig
.send_username
&& request
)
1475 makeUsernameHeader(request
, buf
);
1477 // Adaptation::Config::metaHeaders
1478 for (const auto &h
: Adaptation::Config::metaHeaders()) {
1479 HttpRequest
*r
= virgin
.cause
?
1480 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
1483 HttpReply
*reply
= dynamic_cast<HttpReply
*>(virgin
.header
);
1486 if (h
->match(r
, reply
, alMaster
, matched
)) {
1487 buf
.append(h
->key().rawContent(), h
->key().length());
1488 buf
.append(": ", 2);
1489 buf
.append(matched
.rawContent(), matched
.length());
1490 buf
.append("\r\n", 2);
1491 Adaptation::History::Pointer ah
= request
->adaptHistory(false);
1492 if (ah
!= nullptr) {
1493 if (ah
->metaHeaders
== nullptr)
1494 ah
->metaHeaders
= new NotePairs
;
1495 if (!ah
->metaHeaders
->hasPair(h
->key(), matched
))
1496 ah
->metaHeaders
->add(h
->key(), matched
);
1501 // fprintf(stderr, "%s\n", buf.content());
1503 buf
.append(ICAP::crlf
, 2); // terminate ICAP header
1505 // fill icapRequest for logging
1506 Must(icapRequest
->parseCharBuf(buf
.content(), buf
.contentSize()));
1508 // start ICAP request body with encapsulated HTTP headers
1509 buf
.append(httpBuf
.content(), httpBuf
.contentSize());
1514 // decides which Allow values to write and updates the request buffer
1515 void Adaptation::Icap::ModXact::makeAllowHeader(MemBuf
&buf
)
1517 const bool allow204in
= preview
.enabled(); // TODO: add shouldAllow204in()
1518 const bool allow204out
= state
.allowedPostview204
= shouldAllow204();
1519 const bool allow206in
= state
.allowedPreview206
= shouldAllow206in();
1520 const bool allow206out
= state
.allowedPostview206
= shouldAllow206out();
1521 const bool allowTrailers
= true; // TODO: make configurable
1523 debugs(93, 9, "Allows: " << allow204in
<< allow204out
<<
1524 allow206in
<< allow206out
<< allowTrailers
);
1526 const bool allow204
= allow204in
|| allow204out
;
1527 const bool allow206
= allow206in
|| allow206out
;
1529 if ((allow204
|| allow206
) && virginBody
.expected())
1530 virginBodySending
.plan(); // if there is a virgin body, plan to send it
1532 // writing Preview:... means we will honor 204 inside preview
1533 // writing Allow/204 means we will honor 204 outside preview
1534 // writing Allow:206 means we will honor 206 inside preview
1535 // writing Allow:204,206 means we will honor 206 outside preview
1536 if (allow204
|| allow206
|| allowTrailers
) {
1537 buf
.appendf("Allow: ");
1539 buf
.appendf("204, ");
1541 buf
.appendf("206, ");
1543 buf
.appendf("trailers");
1544 buf
.appendf("\r\n");
1548 void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest
*request
, MemBuf
&buf
)
1551 struct base64_encode_ctx ctx
;
1552 base64_encode_init(&ctx
);
1554 const char *value
= nullptr;
1555 if (request
->auth_user_request
!= nullptr) {
1556 value
= request
->auth_user_request
->username();
1557 } else if (request
->extacl_user
.size() > 0) {
1558 value
= request
->extacl_user
.termedBuf();
1562 if (TheConfig
.client_username_encode
) {
1563 char base64buf
[base64_encode_len(MAX_LOGIN_SZ
)];
1564 size_t resultLen
= base64_encode_update(&ctx
, base64buf
, strlen(value
), reinterpret_cast<const uint8_t*>(value
));
1565 resultLen
+= base64_encode_final(&ctx
, base64buf
+resultLen
);
1566 buf
.appendf("%s: %.*s\r\n", TheConfig
.client_username_header
, (int)resultLen
, base64buf
);
1568 buf
.appendf("%s: %s\r\n", TheConfig
.client_username_header
, value
);
1577 Adaptation::Icap::ModXact::encapsulateHead(MemBuf
&icapBuf
, const char *section
, MemBuf
&httpBuf
, const Http::Message
*head
)
1579 // update ICAP header
1580 icapBuf
.appendf("%s=%d, ", section
, (int) httpBuf
.contentSize());
1583 Http::MessagePointer headClone
;
1585 if (const HttpRequest
* old_request
= dynamic_cast<const HttpRequest
*>(head
)) {
1586 HttpRequest::Pointer
new_request(new HttpRequest(old_request
->masterXaction
));
1587 // copy the request-line details
1588 new_request
->method
= old_request
->method
;
1589 new_request
->url
= old_request
->url
;
1590 new_request
->http_ver
= old_request
->http_ver
;
1591 headClone
= new_request
.getRaw();
1592 } else if (const HttpReply
*old_reply
= dynamic_cast<const HttpReply
*>(head
)) {
1593 HttpReply::Pointer
new_reply(new HttpReply
);
1594 new_reply
->sline
= old_reply
->sline
;
1595 headClone
= new_reply
.getRaw();
1598 headClone
->inheritProperties(head
);
1600 HttpHeaderPos pos
= HttpHeaderInitPos
;
1601 while (HttpHeaderEntry
* p_head_entry
= head
->header
.getEntry(&pos
))
1602 headClone
->header
.addEntry(p_head_entry
->clone());
1606 // remove all hop-by-hop headers from the clone
1607 headClone
->header
.delById(Http::HdrType::PROXY_AUTHENTICATE
);
1608 headClone
->header
.removeHopByHopEntries();
1610 // TODO: modify HttpHeader::removeHopByHopEntries to accept a list of
1611 // excluded hop-by-hop headers
1612 if (head
->header
.has(Http::HdrType::UPGRADE
)) {
1613 const auto upgrade
= head
->header
.getList(Http::HdrType::UPGRADE
);
1614 headClone
->header
.putStr(Http::HdrType::UPGRADE
, upgrade
.termedBuf());
1617 // pack polished HTTP header
1618 packHead(httpBuf
, headClone
.getRaw());
1620 // headClone unlocks and, hence, deletes the message we packed
1624 Adaptation::Icap::ModXact::packHead(MemBuf
&httpBuf
, const Http::Message
*head
)
1626 head
->packInto(&httpBuf
, true);
1629 // decides whether to offer a preview and calculates its size
1630 void Adaptation::Icap::ModXact::decideOnPreview()
1632 if (!TheConfig
.preview_enable
) {
1633 debugs(93, 5, "preview disabled by squid.conf");
1637 const SBuf
urlPath(virginRequest().url
.path());
1639 if (!service().wantsPreview(urlPath
, wantedSize
)) {
1640 debugs(93, 5, "should not offer preview for " << urlPath
);
1644 // we decided to do preview, now compute its size
1646 // cannot preview more than we can backup
1647 size_t ad
= min(wantedSize
, TheBackupLimit
);
1649 if (!virginBody
.expected())
1651 else if (virginBody
.knownSize())
1652 ad
= min(static_cast<uint64_t>(ad
), virginBody
.size()); // not more than we have
1654 debugs(93, 5, "should offer " << ad
<< "-byte preview " <<
1655 "(service wanted " << wantedSize
<< ")");
1658 Must(preview
.enabled());
1661 // decides whether to allow 204 responses
1662 bool Adaptation::Icap::ModXact::shouldAllow204()
1664 if (!service().allows204())
1667 return canBackupEverything();
1670 // decides whether to allow 206 responses in some mode
1671 bool Adaptation::Icap::ModXact::shouldAllow206any()
1673 return TheConfig
.allow206_enable
&& service().allows206() &&
1674 virginBody
.expected(); // no need for 206 without a body
1677 // decides whether to allow 206 responses in preview mode
1678 bool Adaptation::Icap::ModXact::shouldAllow206in()
1680 return shouldAllow206any() && preview
.enabled();
1683 // decides whether to allow 206 responses outside of preview
1684 bool Adaptation::Icap::ModXact::shouldAllow206out()
1686 return shouldAllow206any() && canBackupEverything();
1689 // used by shouldAllow204 and decideOnRetries
1690 bool Adaptation::Icap::ModXact::canBackupEverything() const
1692 if (!virginBody
.expected())
1693 return true; // no body means no problems with backup
1695 // if there is a body, check whether we can backup it all
1697 if (!virginBody
.knownSize())
1700 // or should we have a different backup limit?
1701 // note that '<' allows for 0-termination of the "full" backup buffer
1702 return virginBody
.size() < TheBackupLimit
;
1705 // Decide whether this transaction can be retried if pconn fails
1706 // Must be called after decideOnPreview and before openConnection()
1707 void Adaptation::Icap::ModXact::decideOnRetries()
1710 return; // no, already decided
1712 if (preview
.enabled())
1713 return; // yes, because preview provides enough guarantees
1715 if (canBackupEverything())
1716 return; // yes, because we can back everything up
1718 disableRetries(); // no, because we cannot back everything up
1721 // Normally, the body-writing code handles preview body. It can deal with
1722 // bodies of unexpected size, including those that turn out to be empty.
1723 // However, that code assumes that the body was expected and body control
1724 // structures were initialized. This is not the case when there is no body
1725 // or the body is known to be empty, because the virgin message will lack a
1726 // body_pipe. So we handle preview of null-body and zero-size bodies here.
1727 void Adaptation::Icap::ModXact::finishNullOrEmptyBodyPreview(MemBuf
&)
1729 Must(!virginBodyWriting
.active()); // one reason we handle it here
1730 Must(!virgin
.body_pipe
); // another reason we handle it here
1731 Must(!preview
.ad());
1733 // do not add last-chunk because our Encapsulated header says null-body
1734 // addLastRequestChunk(buf);
1735 preview
.wrote(0, true);
1737 Must(preview
.done());
1738 Must(preview
.ieof());
1741 void Adaptation::Icap::ModXact::fillPendingStatus(MemBuf
&buf
) const
1743 Adaptation::Icap::Xaction::fillPendingStatus(buf
);
1745 if (state
.serviceWaiting
)
1748 if (virgin
.body_pipe
!= nullptr)
1751 if (haveConnection() && !doneReading())
1754 if (!state
.doneWriting() && state
.writing
!= State::writingInit
)
1755 buf
.appendf("w(%d)", state
.writing
);
1757 if (preview
.enabled()) {
1758 if (!preview
.done())
1759 buf
.appendf("P(%d)", (int) preview
.debt());
1762 if (virginBodySending
.active())
1765 if (!state
.doneParsing() && state
.parsing
!= State::psIcapHeader
)
1766 buf
.appendf("p(%d)", state
.parsing
);
1768 if (!doneSending() && state
.sending
!= State::sendingUndecided
)
1769 buf
.appendf("S(%d)", state
.sending
);
1771 if (state
.readyForUob
)
1777 if (protectGroupBypass
)
1781 void Adaptation::Icap::ModXact::fillDoneStatus(MemBuf
&buf
) const
1783 Adaptation::Icap::Xaction::fillDoneStatus(buf
);
1785 if (!virgin
.body_pipe
)
1788 if (state
.doneWriting())
1791 if (preview
.enabled()) {
1793 buf
.appendf("P%s", preview
.ieof() ? "(ieof)" : "");
1799 if (state
.doneParsing())
1806 bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section
) const
1808 return !icapReply
->header
.getByNameListMember("Encapsulated",
1809 section
, ',').isEmpty();
1812 // calculate whether there is a virgin HTTP body and
1813 // whether its expected size is known
1814 // TODO: rename because we do not just estimate
1815 void Adaptation::Icap::ModXact::estimateVirginBody()
1817 // note: lack of size info may disable previews and 204s
1819 Http::Message
*msg
= virgin
.header
;
1822 HttpRequestMethod method
;
1825 method
= virgin
.cause
->method
;
1826 else if (HttpRequest
*req
= dynamic_cast<HttpRequest
*>(msg
))
1827 method
= req
->method
;
1829 method
= Http::METHOD_NONE
;
1832 // expectingBody returns true for zero-sized bodies, but we will not
1833 // get a pipe for that body, so we treat the message as bodyless
1834 if (method
!= Http::METHOD_NONE
&& msg
->expectingBody(method
, size
) && size
) {
1835 debugs(93, 6, "expects virgin body from " <<
1836 virgin
.body_pipe
<< "; size: " << size
);
1838 virginBody
.expect(size
);
1839 virginBodyWriting
.plan();
1841 // sign up as a body consumer
1842 Must(msg
->body_pipe
!= nullptr);
1843 Must(msg
->body_pipe
== virgin
.body_pipe
);
1844 Must(virgin
.body_pipe
->setConsumerIfNotLate(this));
1846 // make sure TheBackupLimit is in-sync with the buffer size
1847 Must(TheBackupLimit
<= static_cast<size_t>(msg
->body_pipe
->buf().max_capacity
));
1849 debugs(93, 6, "does not expect virgin body");
1850 Must(msg
->body_pipe
== nullptr);
1855 void Adaptation::Icap::ModXact::makeAdaptedBodyPipe(const char *what
)
1857 Must(!adapted
.body_pipe
);
1858 Must(!adapted
.header
->body_pipe
);
1859 adapted
.header
->body_pipe
= new BodyPipe(this);
1860 adapted
.body_pipe
= adapted
.header
->body_pipe
;
1861 debugs(93, 7, "will supply " << what
<< " via " <<
1862 adapted
.body_pipe
<< " pipe");
1865 // TODO: Move SizedEstimate and Preview elsewhere
1867 Adaptation::Icap::SizedEstimate::SizedEstimate()
1868 : theData(dtUnexpected
)
1871 void Adaptation::Icap::SizedEstimate::expect(int64_t aSize
)
1873 theData
= (aSize
>= 0) ? aSize
: (int64_t)dtUnknown
;
1876 bool Adaptation::Icap::SizedEstimate::expected() const
1878 return theData
!= dtUnexpected
;
1881 bool Adaptation::Icap::SizedEstimate::knownSize() const
1884 return theData
!= dtUnknown
;
1887 uint64_t Adaptation::Icap::SizedEstimate::size() const
1890 return static_cast<uint64_t>(theData
);
1893 Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided
)
1896 void Adaptation::Icap::VirginBodyAct::plan()
1899 Must(!theStart
); // not started
1900 theState
= stActive
;
1903 void Adaptation::Icap::VirginBodyAct::disable()
1905 theState
= stDisabled
;
1908 void Adaptation::Icap::VirginBodyAct::progress(size_t size
)
1911 #if SIZEOF_SIZE_T > 4
1912 /* always true for smaller size_t's */
1913 Must(static_cast<int64_t>(size
) >= 0);
1915 theStart
+= static_cast<int64_t>(size
);
1918 uint64_t Adaptation::Icap::VirginBodyAct::offset() const
1921 return static_cast<uint64_t>(theStart
);
1924 Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled
)
1927 void Adaptation::Icap::Preview::enable(size_t anAd
)
1929 // TODO: check for anAd not exceeding preview size limit
1932 theState
= stWriting
;
1935 bool Adaptation::Icap::Preview::enabled() const
1937 return theState
!= stDisabled
;
1940 size_t Adaptation::Icap::Preview::ad() const
1946 bool Adaptation::Icap::Preview::done() const
1949 return theState
>= stIeof
;
1952 bool Adaptation::Icap::Preview::ieof() const
1955 return theState
== stIeof
;
1958 size_t Adaptation::Icap::Preview::debt() const
1961 return done() ? 0 : (theAd
- theWritten
);
1964 void Adaptation::Icap::Preview::wrote(size_t size
, bool wroteEof
)
1970 Must(theWritten
<= theAd
);
1973 theState
= stIeof
; // written size is irrelevant
1974 else if (theWritten
>= theAd
)
1978 bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf
&mb
) const
1980 if (virgin
.header
== nullptr)
1983 virgin
.header
->firstLineBuf(mb
);
1988 void Adaptation::Icap::ModXact::detailError(const ErrorDetail::Pointer
&errDetail
)
1990 HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
1991 // if no adapted request, update virgin (and inherit its properties later)
1992 // TODO: make this and HttpRequest::detailError constant, like adaptHistory
1994 request
= const_cast<HttpRequest
*>(&virginRequest());
1997 request
->detailError(ERR_ICAP_FAILURE
, errDetail
);
2000 void Adaptation::Icap::ModXact::clearError()
2002 HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
2003 // if no adapted request, update virgin (and inherit its properties later)
2005 request
= const_cast<HttpRequest
*>(&virginRequest());
2008 request
->clearError();
2011 void Adaptation::Icap::ModXact::updateSources()
2013 Must(adapted
.header
);
2014 adapted
.header
->sources
|= (service().cfg().connectionEncryption
? Http::Message::srcIcaps
: Http::Message::srcIcap
);
2017 /* Adaptation::Icap::ModXactLauncher */
2019 Adaptation::Icap::ModXactLauncher::ModXactLauncher(Http::Message
*virginHeader
, HttpRequest
*virginCause
, AccessLogEntry::Pointer
&alp
, Adaptation::ServicePointer aService
):
2020 AsyncJob("Adaptation::Icap::ModXactLauncher"),
2021 Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", aService
),
2024 virgin
.setHeader(virginHeader
);
2025 virgin
.setCause(virginCause
);
2026 updateHistory(true);
2029 Adaptation::Icap::Xaction
*Adaptation::Icap::ModXactLauncher::createXaction()
2031 Adaptation::Icap::ServiceRep::Pointer s
=
2032 dynamic_cast<Adaptation::Icap::ServiceRep
*>(theService
.getRaw());
2034 return new Adaptation::Icap::ModXact(virgin
.header
, virgin
.cause
, al
, s
);
2037 void Adaptation::Icap::ModXactLauncher::swanSong()
2039 debugs(93, 5, "swan sings");
2040 updateHistory(false);
2041 Adaptation::Icap::Launcher::swanSong();
2044 void Adaptation::Icap::ModXactLauncher::updateHistory(bool doStart
)
2046 HttpRequest
*r
= virgin
.cause
?
2047 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
2049 // r should never be NULL but we play safe; TODO: add Should()
2051 Adaptation::Icap::History::Pointer h
= r
->icapHistory();
2054 h
->start("ICAPModXactLauncher");
2056 h
->stop("ICAPModXactLauncher");
2061 bool Adaptation::Icap::TrailerParser::parse(const char *buf
, int len
, int atEnd
, Http::StatusCode
*error
) {
2062 Http::ContentLengthInterpreter clen
;
2063 // RFC 7230 section 4.1.2: MUST NOT generate a trailer that contains
2064 // a field necessary for message framing (e.g., Transfer-Encoding and Content-Length)
2065 clen
.applyTrailerRules();
2066 const int parsed
= trailer
.parse(buf
, len
, atEnd
, hdr_sz
, clen
);
2068 *error
= Http::scInvalidHeader
; // TODO: should we add a new Http::scInvalidTrailer?
2073 Adaptation::Icap::ChunkExtensionValueParser::parse(Tokenizer
&tok
, const SBuf
&extName
)
2075 if (extName
== UseOriginalBodyName
) {
2076 useOriginalBody_
= tok
.udec64("use-original-body");
2077 assert(useOriginalBody_
>= 0);
2079 Ignore(tok
, extName
);