2 * Copyright (C) 1996-2023 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 // Why > 2? HttpState does not use the last bytes in the buffer
439 // because Client::delayRead() is arguably broken. See
440 // HttpStateData::maybeReadVirginBody for more details.
441 if (wantToPostpone
&& bp
.buf().spaceSize() > 2) {
442 // Postponing may increase memory footprint and slow the HTTP side
443 // down. Not postponing may increase the number of ICAP errors
444 // if the ICAP service fails. We may also use "potential" space to
445 // postpone more aggressively. Should the trade-off be configurable?
446 debugs(93, 8, "postponing consumption from " << bp
.status());
450 const size_t have
= static_cast<size_t>(bp
.buf().contentSize());
451 const uint64_t end
= virginConsumed
+ have
;
452 uint64_t offset
= end
;
454 debugs(93, 9, "max virgin consumption offset=" << offset
<<
455 " acts " << virginBodyWriting
.active() << virginBodySending
.active() <<
456 " consumed=" << virginConsumed
<<
457 " from " << virgin
.body_pipe
->status());
459 if (virginBodyWriting
.active())
460 offset
= min(virginBodyWriting
.offset(), offset
);
462 if (virginBodySending
.active())
463 offset
= min(virginBodySending
.offset(), offset
);
465 Must(virginConsumed
<= offset
&& offset
<= end
);
467 if (const size_t size
= static_cast<size_t>(offset
- virginConsumed
)) {
468 debugs(93, 8, "consuming " << size
<< " out of " << have
<<
469 " virgin body bytes");
471 virginConsumed
+= size
;
472 Must(!isRetriable
); // or we should not be consuming
473 disableRepeats("consumed content");
474 disableBypass("consumed content", true);
478 void Adaptation::Icap::ModXact::handleCommWroteBody()
483 // Called when we do not expect to call comm_write anymore.
484 // We may have a pending write though.
485 // If stopping nicely, we will just wait for that pending write, if any.
486 void Adaptation::Icap::ModXact::stopWriting(bool nicely
)
488 if (state
.writing
== State::writingReallyDone
)
491 if (writer
!= nullptr) {
493 debugs(93, 7, "will wait for the last write" << status());
494 state
.writing
= State::writingAlmostDone
; // may already be set
498 debugs(93, 3, "will NOT wait for the last write" << status());
500 // Comm does not have an interface to clear the writer callback nicely,
501 // but without clearing the writer we cannot recycle the connection.
502 // We prevent connection reuse and hope that we can handle a callback
503 // call at any time, usually in the middle of the destruction sequence!
504 // Somebody should add comm_remove_write_handler() to comm API.
505 reuseConnection
= false;
506 ignoreLastWrite
= true;
509 debugs(93, 7, "will no longer write" << status());
510 if (virginBodyWriting
.active()) {
511 virginBodyWriting
.disable();
514 state
.writing
= State::writingReallyDone
;
518 void Adaptation::Icap::ModXact::stopBackup()
520 if (!virginBodySending
.active())
523 debugs(93, 7, "will no longer backup" << status());
524 virginBodySending
.disable();
528 bool Adaptation::Icap::ModXact::doneAll() const
530 return Adaptation::Icap::Xaction::doneAll() && !state
.serviceWaiting
&&
532 doneReading() && state
.doneWriting();
535 void Adaptation::Icap::ModXact::startReading()
537 Must(haveConnection());
539 Must(!adapted
.header
);
540 Must(!adapted
.body_pipe
);
542 // we use the same buffer for headers and body and then consume headers
546 void Adaptation::Icap::ModXact::readMore()
548 if (reader
!= nullptr || doneReading()) {
549 debugs(93,3, "returning from readMore because reader or doneReading()");
553 // do not fill readBuf if we have no space to store the result
554 if (adapted
.body_pipe
!= nullptr &&
555 !adapted
.body_pipe
->buf().hasPotentialSpace()) {
556 debugs(93,3, "not reading because ICAP reply pipe is full");
560 if (readBuf
.length() < SQUID_TCP_SO_RCVBUF
)
563 debugs(93,3, "cannot read with a full buffer");
566 // comm module read a portion of the ICAP response for us
567 void Adaptation::Icap::ModXact::handleCommRead(size_t)
569 Must(!state
.doneParsing());
570 icap_tio_finish
= current_time
;
575 void Adaptation::Icap::ModXact::echoMore()
577 Must(state
.sending
== State::sendingVirgin
);
578 Must(adapted
.body_pipe
!= nullptr);
579 Must(virginBodySending
.active());
581 const size_t sizeMax
= virginContentSize(virginBodySending
);
582 debugs(93,5, "will echo up to " << sizeMax
<< " bytes from " <<
583 virgin
.body_pipe
->status());
584 debugs(93,5, "will echo up to " << sizeMax
<< " bytes to " <<
585 adapted
.body_pipe
->status());
588 const size_t size
= adapted
.body_pipe
->putMoreData(virginContentData(virginBodySending
), sizeMax
);
589 debugs(93,5, "echoed " << size
<< " out of " << sizeMax
<<
591 virginBodySending
.progress(size
);
592 disableRepeats("echoed content");
593 disableBypass("echoed content", true);
597 if (virginBodyEndReached(virginBodySending
)) {
598 debugs(93, 5, "echoed all" << status());
601 debugs(93, 5, "has " <<
602 virgin
.body_pipe
->buf().contentSize() << " bytes " <<
603 "and expects more to echo" << status());
604 // TODO: timeout if virgin or adapted pipes are broken
608 bool Adaptation::Icap::ModXact::doneSending() const
610 return state
.sending
== State::sendingDone
;
613 // stop (or do not start) sending adapted message body
614 void Adaptation::Icap::ModXact::stopSending(bool nicely
)
616 debugs(93, 7, "Enter stop sending ");
619 debugs(93, 7, "Proceed with stop sending ");
621 if (state
.sending
!= State::sendingUndecided
) {
622 debugs(93, 7, "will no longer send" << status());
623 if (adapted
.body_pipe
!= nullptr) {
624 virginBodySending
.disable();
625 // we may leave debts if we were echoing and the virgin
626 // body_pipe got exhausted before we echoed all planned bytes
627 const bool leftDebts
= adapted
.body_pipe
->needsMoreData();
628 stopProducingFor(adapted
.body_pipe
, nicely
&& !leftDebts
);
631 debugs(93, 7, "will not start sending" << status());
632 Must(!adapted
.body_pipe
);
635 state
.sending
= State::sendingDone
;
639 // should be called after certain state.writing or state.sending changes
640 void Adaptation::Icap::ModXact::checkConsuming()
642 // quit if we already stopped or are still using the pipe
643 if (!virgin
.body_pipe
|| !state
.doneConsumingVirgin())
646 debugs(93, 7, "will stop consuming" << status());
647 stopConsumingFrom(virgin
.body_pipe
);
650 void Adaptation::Icap::ModXact::parseMore()
652 debugs(93, 5, "have " << readBuf
.length() << " bytes to parse" << status());
653 debugs(93, 5, "\n" << readBuf
);
655 if (state
.parsingHeaders())
658 if (state
.parsing
== State::psBody
)
661 if (state
.parsing
== State::psIcapTrailer
)
665 void Adaptation::Icap::ModXact::callException(const std::exception
&e
)
667 if (!canStartBypass
|| isRetriable
) {
669 if (const TextException
*te
= dynamic_cast<const TextException
*>(&e
))
670 detailError(new ExceptionErrorDetail(te
->id()));
672 detailError(new ExceptionErrorDetail(Here().id()));
674 Adaptation::Icap::Xaction::callException(e
);
679 debugs(93, 3, "bypassing " << inCall
<< " exception: " <<
680 e
.what() << ' ' << status());
682 } catch (const TextException
&bypassTe
) {
683 detailError(new ExceptionErrorDetail(bypassTe
.id()));
684 Adaptation::Icap::Xaction::callException(bypassTe
);
685 } catch (const std::exception
&bypassE
) {
686 detailError(new ExceptionErrorDetail(Here().id()));
687 Adaptation::Icap::Xaction::callException(bypassE
);
691 void Adaptation::Icap::ModXact::bypassFailure()
693 disableBypass("already started to bypass", false);
695 Must(!isRetriable
); // or we should not be bypassing
696 // TODO: should the same be enforced for isRepeatable? Check icap_repeat??
702 // end all activities associated with the ICAP server
706 stopWriting(true); // or should we force it?
707 if (haveConnection()) {
708 reuseConnection
= false; // be conservative
709 cancelRead(); // may not work; and we cannot stop connecting either
711 debugs(93, 7, "Warning: bypass failed to stop I/O" << status());
714 service().noteFailure(); // we are bypassing, but this is still a failure
717 void Adaptation::Icap::ModXact::disableBypass(const char *reason
, bool includingGroupBypass
)
719 if (canStartBypass
) {
720 debugs(93,7, "will never start bypass because " << reason
);
721 canStartBypass
= false;
723 if (protectGroupBypass
&& includingGroupBypass
) {
724 debugs(93,7, "not protecting group bypass because " << reason
);
725 protectGroupBypass
= false;
729 // note that allocation for echoing is done in handle204NoContent()
730 void Adaptation::Icap::ModXact::maybeAllocateHttpMsg()
732 if (adapted
.header
) // already allocated
735 if (gotEncapsulated("res-hdr")) {
736 adapted
.setHeader(new HttpReply
);
737 setOutcome(service().cfg().method
== ICAP::methodReqmod
?
738 xoSatisfied
: xoModified
);
739 } else if (gotEncapsulated("req-hdr")) {
740 adapted
.setHeader(new HttpRequest(virginRequest().masterXaction
));
741 setOutcome(xoModified
);
743 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
746 void Adaptation::Icap::ModXact::parseHeaders()
748 Must(state
.parsingHeaders());
750 if (state
.parsing
== State::psIcapHeader
) {
751 debugs(93, 5, "parse ICAP headers");
755 if (state
.parsing
== State::psHttpHeader
) {
756 debugs(93, 5, "parse HTTP headers");
760 if (state
.parsingHeaders()) { // need more data
768 // called after parsing all headers or when bypassing an exception
769 void Adaptation::Icap::ModXact::startSending()
771 disableRepeats("sent headers");
772 disableBypass("sent headers", true);
773 sendAnswer(Answer::Forward(adapted
.header
));
775 if (state
.sending
== State::sendingVirgin
)
778 // If we are not using the virgin HTTP object update the
779 // Http::Message::sources flag.
780 // The state.sending may set to State::sendingVirgin in the case
781 // of 206 responses too, where we do not want to update Http::Message::sources
782 // flag. However even for 206 responses the state.sending is
783 // not set yet to sendingVirgin. This is done in later step
784 // after the parseBody method called.
789 void Adaptation::Icap::ModXact::parseIcapHead()
791 Must(state
.sending
== State::sendingUndecided
);
793 if (!parseHead(icapReply
.getRaw()))
796 if (expectIcapTrailers()) {
797 Must(!trailerParser
);
798 trailerParser
= new TrailerParser
;
801 static SBuf
close("close", 5);
802 if (httpHeaderHasConnDir(&icapReply
->header
, close
)) {
803 debugs(93, 5, "found connection close");
804 reuseConnection
= false;
807 switch (icapReply
->sline
.status()) {
809 case Http::scContinue
:
814 case Http::scCreated
: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
816 if (!validate200Ok()) {
817 throw TexcHere("Invalid ICAP Response");
824 case Http::scNoContent
:
825 handle204NoContent();
828 case Http::scPartialContent
:
829 handle206PartialContent();
833 debugs(93, 5, "ICAP status " << icapReply
->sline
.status());
834 handleUnknownScode();
838 const HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
840 request
= &virginRequest();
842 // update the cross-transactional database if needed (all status codes!)
843 if (const char *xxName
= Adaptation::Config::masterx_shared_name
) {
844 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
845 if (ah
!= nullptr) { // TODO: reorder checks to avoid creating history
846 const String val
= icapReply
->header
.getByName(xxName
);
847 if (val
.size() > 0) // XXX: HttpHeader lacks empty value detection
848 ah
->updateXxRecord(xxName
, val
);
852 // update the adaptation plan if needed (all status codes!)
853 if (service().cfg().routing
) {
855 if (icapReply
->header
.getList(Http::HdrType::X_NEXT_SERVICES
, &services
)) {
856 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
858 ah
->updateNextServices(services
);
860 } // TODO: else warn (occasionally!) if we got Http::HdrType::X_NEXT_SERVICES
862 // We need to store received ICAP headers for <icapLastHeader logformat option.
863 // If we already have stored headers from previous ICAP transaction related to this
864 // request, old headers will be replaced with the new one.
866 Adaptation::History::Pointer ah
= request
->adaptLogHistory();
868 ah
->recordMeta(&icapReply
->header
);
870 // handle100Continue() manages state.writing on its own.
871 // Non-100 status means the server needs no postPreview data from us.
872 if (state
.writing
== State::writingPaused
)
876 /// Parses ICAP trailers and stops parsing, if all trailer data
877 /// have been received.
878 void Adaptation::Icap::ModXact::parseIcapTrailer() {
880 if (parsePart(trailerParser
, "trailer")) {
881 for (const auto &e
: trailerParser
->trailer
.entries
)
882 debugs(93, 5, "ICAP trailer: " << e
->name
<< ": " << e
->value
);
887 bool Adaptation::Icap::ModXact::validate200Ok()
889 if (service().cfg().method
== ICAP::methodRespmod
)
890 return gotEncapsulated("res-hdr");
892 return service().cfg().method
== ICAP::methodReqmod
&&
896 void Adaptation::Icap::ModXact::handle100Continue()
898 Must(state
.writing
== State::writingPaused
);
899 // server must not respond before the end of preview: we may send ieof
900 Must(preview
.enabled() && preview
.done() && !preview
.ieof());
902 // 100 "Continue" cancels our Preview commitment,
903 // but not commitment to handle 204 or 206 outside Preview
904 if (!state
.allowedPostview204
&& !state
.allowedPostview206
)
907 state
.parsing
= State::psIcapHeader
; // eventually
910 state
.writing
= State::writingPrime
;
915 void Adaptation::Icap::ModXact::handle200Ok()
917 state
.parsing
= State::psHttpHeader
;
918 state
.sending
= State::sendingAdapted
;
923 void Adaptation::Icap::ModXact::handle204NoContent()
929 void Adaptation::Icap::ModXact::handle206PartialContent()
931 if (state
.writing
== State::writingPaused
) {
932 Must(preview
.enabled());
933 Must(state
.allowedPreview206
);
934 debugs(93, 7, "206 inside preview");
936 Must(state
.writing
> State::writingPaused
);
937 Must(state
.allowedPostview206
);
938 debugs(93, 7, "206 outside preview");
940 state
.parsing
= State::psHttpHeader
;
941 state
.sending
= State::sendingAdapted
;
942 state
.readyForUob
= true;
946 // Called when we receive a 204 No Content response and
947 // when we are trying to bypass a service failure.
948 // We actually start sending (echoig or not) in startSending.
949 void Adaptation::Icap::ModXact::prepEchoing()
951 disableRepeats("preparing to echo content");
952 disableBypass("preparing to echo content", true);
955 // We want to clone the HTTP message, but we do not want
956 // to copy some non-HTTP state parts that Http::Message kids carry in them.
957 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
958 // Instead, we simply write the HTTP message and "clone" it by parsing.
959 // TODO: use Http::Message::clone()!
961 Http::Message
*oldHead
= virgin
.header
;
962 debugs(93, 7, "cloning virgin message " << oldHead
);
966 // write the virgin message into a memory buffer
968 packHead(httpBuf
, oldHead
);
970 // allocate the adapted message and copy metainfo
971 Must(!adapted
.header
);
973 Http::MessagePointer newHead
;
974 if (const HttpRequest
*r
= dynamic_cast<const HttpRequest
*>(oldHead
)) {
975 newHead
= new HttpRequest(r
->masterXaction
);
976 } else if (dynamic_cast<const HttpReply
*>(oldHead
)) {
977 newHead
= new HttpReply
;
981 newHead
->inheritProperties(oldHead
);
983 adapted
.setHeader(newHead
.getRaw());
986 // parse the buffer back
987 Http::StatusCode error
= Http::scNone
;
989 httpBuf
.terminate(); // Http::Message::parse requires nil-terminated buffer
990 Must(adapted
.header
->parse(httpBuf
.content(), httpBuf
.contentSize(), true, &error
));
991 Must(adapted
.header
->hdr_sz
== httpBuf
.contentSize()); // no leftovers
995 debugs(93, 7, "cloned virgin message " << oldHead
<< " to " <<
998 // setup adapted body pipe if needed
999 if (oldHead
->body_pipe
!= nullptr) {
1000 debugs(93, 7, "will echo virgin body from " <<
1001 oldHead
->body_pipe
);
1002 if (!virginBodySending
.active())
1003 virginBodySending
.plan(); // will throw if not possible
1004 state
.sending
= State::sendingVirgin
;
1007 // TODO: optimize: is it possible to just use the oldHead pipe and
1008 // remove ICAP from the loop? This echoing is probably a common case!
1009 makeAdaptedBodyPipe("echoed virgin response");
1010 if (oldHead
->body_pipe
->bodySizeKnown())
1011 adapted
.body_pipe
->setBodySize(oldHead
->body_pipe
->bodySize());
1012 debugs(93, 7, "will echo virgin body to " <<
1015 debugs(93, 7, "no virgin body to echo");
1020 /// Called when we received use-original-body chunk extension in 206 response.
1021 /// We actually start sending (echoing or not) in startSending().
1022 void Adaptation::Icap::ModXact::prepPartialBodyEchoing(uint64_t pos
)
1024 Must(virginBodySending
.active());
1025 Must(virgin
.header
->body_pipe
!= nullptr);
1027 setOutcome(xoPartEcho
);
1029 debugs(93, 7, "will echo virgin body suffix from " <<
1030 virgin
.header
->body_pipe
<< " offset " << pos
);
1032 // check that use-original-body=N does not point beyond buffered data
1033 const uint64_t virginDataEnd
= virginConsumed
+
1034 virgin
.body_pipe
->buf().contentSize();
1035 Must(pos
<= virginDataEnd
);
1036 virginBodySending
.progress(static_cast<size_t>(pos
));
1038 state
.sending
= State::sendingVirgin
;
1041 if (virgin
.header
->body_pipe
->bodySizeKnown())
1042 adapted
.body_pipe
->expectProductionEndAfter(virgin
.header
->body_pipe
->bodySize() - pos
);
1044 debugs(93, 7, "will echo virgin body suffix to " <<
1047 // Start echoing data
1051 void Adaptation::Icap::ModXact::handleUnknownScode()
1055 // TODO: mark connection as "bad"
1057 // Terminate the transaction; we do not know how to handle this response.
1058 throw TexcHere("Unsupported ICAP status code");
1061 void Adaptation::Icap::ModXact::parseHttpHead()
1063 if (expectHttpHeader()) {
1064 replyHttpHeaderSize
= 0;
1065 maybeAllocateHttpMsg();
1067 if (!parseHead(adapted
.header
))
1068 return; // need more header data
1071 replyHttpHeaderSize
= adapted
.header
->hdr_sz
;
1073 if (dynamic_cast<HttpRequest
*>(adapted
.header
)) {
1074 const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(virgin
.header
);
1076 // TODO: the adapted request did not really originate from the
1077 // client; give proxy admin an option to prevent copying of
1078 // sensitive client information here. See the following thread:
1079 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
1082 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
1084 adapted
.header
->inheritProperties(virgin
.header
);
1087 decideOnParsingBody();
1090 template<class Part
>
1091 bool Adaptation::Icap::ModXact::parsePart(Part
*part
, const char *description
)
1094 debugs(93, 5, "have " << readBuf
.length() << ' ' << description
<< " bytes to parse; state: " << state
.parsing
);
1095 Http::StatusCode error
= Http::scNone
;
1096 // XXX: performance regression. c_str() data copies
1097 // XXX: Http::Message::parse requires a terminated string buffer
1098 const char *tmpBuf
= readBuf
.c_str();
1099 const bool parsed
= part
->parse(tmpBuf
, readBuf
.length(), commEof
, &error
);
1100 debugs(93, (!parsed
&& error
) ? 2 : 5, description
<< " parsing result: " << parsed
<< " detail: " << error
);
1101 Must(parsed
|| !error
);
1103 readBuf
.consume(part
->hdr_sz
);
1107 // parses both HTTP and ICAP headers
1109 Adaptation::Icap::ModXact::parseHead(Http::Message
*head
)
1111 if (!parsePart(head
, "head")) {
1118 bool Adaptation::Icap::ModXact::expectHttpHeader() const
1120 return gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr");
1123 bool Adaptation::Icap::ModXact::expectHttpBody() const
1125 return gotEncapsulated("res-body") || gotEncapsulated("req-body");
1128 bool Adaptation::Icap::ModXact::expectIcapTrailers() const
1131 const bool promisesToSendTrailer
= icapReply
->header
.getByIdIfPresent(Http::HdrType::TRAILER
, &trailers
);
1132 const bool supportsTrailers
= icapReply
->header
.hasListMember(Http::HdrType::ALLOW
, "trailers", ',');
1133 // ICAP Trailer specs require us to reject transactions having either Trailer
1134 // header or Allow:trailers
1135 Must((promisesToSendTrailer
== supportsTrailers
) || (!promisesToSendTrailer
&& supportsTrailers
));
1136 if (promisesToSendTrailer
&& !trailers
.size())
1137 debugs(93, DBG_IMPORTANT
, "ERROR: ICAP Trailer response header field must not be empty (salvaged)");
1138 return promisesToSendTrailer
;
1141 void Adaptation::Icap::ModXact::decideOnParsingBody()
1143 if (expectHttpBody()) {
1144 debugs(93, 5, "expecting a body");
1145 state
.parsing
= State::psBody
;
1146 replyHttpBodySize
= 0;
1147 bodyParser
= new Http1::TeChunkedParser
;
1148 bodyParser
->parseExtensionValuesWith(&extensionParser
);
1149 makeAdaptedBodyPipe("adapted response from the ICAP server");
1150 Must(state
.sending
== State::sendingAdapted
);
1152 debugs(93, 5, "not expecting a body");
1154 state
.parsing
= State::psIcapTrailer
;
1161 void Adaptation::Icap::ModXact::parseBody()
1163 Must(state
.parsing
== State::psBody
);
1166 debugs(93, 5, "have " << readBuf
.length() << " body bytes to parse");
1168 // the parser will throw on errors
1169 BodyPipeCheckout
bpc(*adapted
.body_pipe
);
1170 bodyParser
->setPayloadBuffer(&bpc
.buf
);
1171 const bool parsed
= bodyParser
->parse(readBuf
);
1172 readBuf
= bodyParser
->remaining(); // sync buffers after parse
1175 debugs(93, 5, "have " << readBuf
.length() << " body bytes after parsed all: " << parsed
);
1176 replyHttpBodySize
+= adapted
.body_pipe
->buf().contentSize();
1178 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
1179 // TODO: do we really need this if we disable when sending headers?
1180 if (adapted
.body_pipe
->buf().contentSize() > 0) { // parsed something sometime
1181 disableRepeats("sent adapted content");
1182 disableBypass("sent adapted content", true);
1186 if (state
.readyForUob
&& extensionParser
.sawUseOriginalBody())
1187 prepPartialBodyEchoing(extensionParser
.useOriginalBody());
1189 stopSending(true); // the parser succeeds only if all parsed data fits
1191 state
.parsing
= State::psIcapTrailer
;
1197 debugs(93,3, this << " needsMoreData = " << bodyParser
->needsMoreData());
1199 if (bodyParser
->needsMoreData()) {
1201 Must(mayReadMore());
1205 if (bodyParser
->needsMoreSpace()) {
1206 Must(!doneSending()); // can hope for more space
1207 Must(adapted
.body_pipe
->buf().contentSize() > 0); // paranoid
1208 // TODO: there should be a timeout in case the sink is broken
1209 // or cannot consume partial content (while we need more space)
1213 void Adaptation::Icap::ModXact::stopParsing(const bool checkUnparsedData
)
1215 if (state
.parsing
== State::psDone
)
1218 if (checkUnparsedData
)
1219 Must(readBuf
.isEmpty());
1221 debugs(93, 7, "will no longer parse" << status());
1224 bodyParser
= nullptr;
1226 delete trailerParser
;
1227 trailerParser
= nullptr;
1229 state
.parsing
= State::psDone
;
1232 // HTTP side added virgin body data
1233 void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer
)
1237 if (state
.sending
== State::sendingVirgin
)
1241 // HTTP side sent us all virgin info
1242 void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer
)
1244 Must(virgin
.body_pipe
->productionEnded());
1246 // push writer and sender in case we were waiting for the last-chunk
1249 if (state
.sending
== State::sendingVirgin
)
1253 // body producer aborted, but the initiator may still want to know
1254 // the answer, even though the HTTP message has been truncated
1255 void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer
)
1257 Must(virgin
.body_pipe
->productionEnded());
1259 // push writer and sender in case we were waiting for the last-chunk
1262 if (state
.sending
== State::sendingVirgin
)
1266 // adapted body consumer wants more adapted data and
1267 // possibly freed some buffer space
1268 void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
1270 if (state
.sending
== State::sendingVirgin
)
1272 else if (state
.sending
== State::sendingAdapted
)
1275 Must(state
.sending
== State::sendingUndecided
);
1278 // adapted body consumer aborted
1279 void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer
)
1281 static const auto d
= MakeNamedErrorDetail("ICAP_XACT_BODY_CONSUMER_ABORT");
1283 mustStop("adapted body consumer aborted");
1286 Adaptation::Icap::ModXact::~ModXact()
1289 delete trailerParser
;
1293 void Adaptation::Icap::ModXact::swanSong()
1295 debugs(93, 5, "swan sings" << status());
1300 if (theInitiator
.set()) { // we have not sent the answer to the initiator
1301 static const auto d
= MakeNamedErrorDetail("ICAP_XACT_OTHER");
1305 // update adaptation history if start was called and we reserved a slot
1306 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
1307 if (ah
!= nullptr && adaptHistoryId
>= 0)
1308 ah
->recordXactFinish(adaptHistoryId
);
1310 Adaptation::Icap::Xaction::swanSong();
1313 void prepareLogWithRequestDetails(HttpRequest
*, const AccessLogEntryPointer
&);
1315 void Adaptation::Icap::ModXact::finalizeLogInfo()
1317 HttpRequest
*adapted_request_
= nullptr;
1318 HttpReply
*adapted_reply_
= nullptr;
1319 HttpRequest
*virgin_request_
= const_cast<HttpRequest
*>(&virginRequest());
1320 if (!(adapted_request_
= dynamic_cast<HttpRequest
*>(adapted
.header
))) {
1321 // if the request was not adapted, use virgin request to simplify
1322 // the code further below
1323 adapted_request_
= virgin_request_
;
1324 adapted_reply_
= dynamic_cast<HttpReply
*>(adapted
.header
);
1327 Adaptation::Icap::History::Pointer h
= virgin_request_
->icapHistory();
1328 Must(h
!= nullptr); // ICAPXaction::maybeLog calls only if there is a log
1329 al
.icp
.opcode
= ICP_INVALID
;
1330 al
.url
= h
->log_uri
.termedBuf();
1331 const Adaptation::Icap::ServiceRep
&s
= service();
1332 al
.icap
.reqMethod
= s
.cfg().method
;
1334 al
.cache
.caddr
= virgin_request_
->client_addr
;
1336 al
.request
= virgin_request_
;
1337 HTTPMSGLOCK(al
.request
);
1338 al
.adapted_request
= adapted_request_
;
1339 HTTPMSGLOCK(al
.adapted_request
);
1341 // XXX: This reply (and other ALE members!) may have been needed earlier.
1342 al
.reply
= adapted_reply_
;
1344 if (h
->rfc931
.size())
1345 al
.cache
.rfc931
= h
->rfc931
.termedBuf();
1348 if (h
->ssluser
.size())
1349 al
.cache
.ssluser
= h
->ssluser
.termedBuf();
1351 al
.cache
.code
= h
->logType
;
1353 const Http::Message
*virgin_msg
= dynamic_cast<HttpReply
*>(virgin
.header
);
1355 virgin_msg
= virgin_request_
;
1356 assert(virgin_msg
!= virgin
.cause
);
1357 al
.http
.clientRequestSz
.header
= virgin_msg
->hdr_sz
;
1358 if (virgin_msg
->body_pipe
!= nullptr)
1359 al
.http
.clientRequestSz
.payloadData
= virgin_msg
->body_pipe
->producedSize();
1361 // leave al.icap.bodyBytesRead negative if no body
1362 if (replyHttpHeaderSize
>= 0 || replyHttpBodySize
>= 0) {
1363 const int64_t zero
= 0; // to make max() argument types the same
1364 const uint64_t headerSize
= max(zero
, replyHttpHeaderSize
);
1365 const uint64_t bodySize
= max(zero
, replyHttpBodySize
);
1366 al
.icap
.bodyBytesRead
= headerSize
+ bodySize
;
1367 al
.http
.clientReplySz
.header
= headerSize
;
1368 al
.http
.clientReplySz
.payloadData
= bodySize
;
1371 if (adapted_reply_
) {
1372 al
.http
.code
= adapted_reply_
->sline
.status();
1373 al
.http
.content_type
= adapted_reply_
->content_type
.termedBuf();
1374 if (replyHttpBodySize
>= 0)
1375 al
.cache
.highOffset
= replyHttpBodySize
;
1376 //don't set al.cache.objectSize because it hasn't exist yet
1378 prepareLogWithRequestDetails(adapted_request_
, alep
);
1379 Xaction::finalizeLogInfo();
1382 void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf
&buf
)
1384 char ntoabuf
[MAX_IPSTRLEN
];
1386 * XXX These should use HttpHdr interfaces instead of Printfs
1388 const Adaptation::ServiceConfig
&s
= service().cfg();
1389 buf
.appendf("%s " SQUIDSTRINGPH
" ICAP/1.0\r\n", s
.methodStr(), SQUIDSTRINGPRINT(s
.uri
));
1390 buf
.appendf("Host: " SQUIDSTRINGPH
":%d\r\n", SQUIDSTRINGPRINT(s
.host
), s
.port
);
1391 buf
.appendf("Date: %s\r\n", Time::FormatRfc1123(squid_curtime
));
1393 if (!TheConfig
.reuse_connections
)
1394 buf
.appendf("Connection: close\r\n");
1396 const HttpRequest
*request
= &virginRequest();
1398 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1400 if (virgin
.header
->header
.has(Http::HdrType::PROXY_AUTHENTICATE
)) {
1401 String vh
=virgin
.header
->header
.getById(Http::HdrType::PROXY_AUTHENTICATE
);
1402 buf
.appendf("Proxy-Authenticate: " SQUIDSTRINGPH
"\r\n",SQUIDSTRINGPRINT(vh
));
1405 if (virgin
.header
->header
.has(Http::HdrType::PROXY_AUTHORIZATION
)) {
1406 String vh
=virgin
.header
->header
.getById(Http::HdrType::PROXY_AUTHORIZATION
);
1407 buf
.appendf("Proxy-Authorization: " SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(vh
));
1408 } else if (request
->extacl_user
.size() > 0 && request
->extacl_passwd
.size() > 0) {
1409 struct base64_encode_ctx ctx
;
1410 base64_encode_init(&ctx
);
1411 char base64buf
[base64_encode_len(MAX_LOGIN_SZ
)];
1412 size_t resultLen
= base64_encode_update(&ctx
, base64buf
, request
->extacl_user
.size(), reinterpret_cast<const uint8_t*>(request
->extacl_user
.rawBuf()));
1413 resultLen
+= base64_encode_update(&ctx
, base64buf
+resultLen
, 1, reinterpret_cast<const uint8_t*>(":"));
1414 resultLen
+= base64_encode_update(&ctx
, base64buf
+resultLen
, request
->extacl_passwd
.size(), reinterpret_cast<const uint8_t*>(request
->extacl_passwd
.rawBuf()));
1415 resultLen
+= base64_encode_final(&ctx
, base64buf
+resultLen
);
1416 buf
.appendf("Proxy-Authorization: Basic %.*s\r\n", (int)resultLen
, base64buf
);
1419 // share the cross-transactional database records if needed
1420 if (Adaptation::Config::masterx_shared_name
) {
1421 Adaptation::History::Pointer ah
= request
->adaptHistory(false);
1422 if (ah
!= nullptr) {
1424 if (ah
->getXxRecord(name
, value
)) {
1425 buf
.appendf(SQUIDSTRINGPH
": " SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(name
), SQUIDSTRINGPRINT(value
));
1430 buf
.append("Encapsulated: ", 14);
1436 // build HTTP request header, if any
1437 ICAP::Method m
= s
.method
;
1439 // to simplify, we could assume that request is always available
1442 if (ICAP::methodRespmod
== m
)
1443 encapsulateHead(buf
, "req-hdr", httpBuf
, request
);
1444 else if (ICAP::methodReqmod
== m
)
1445 encapsulateHead(buf
, "req-hdr", httpBuf
, virgin
.header
);
1448 if (ICAP::methodRespmod
== m
)
1449 if (const Http::Message
*prime
= virgin
.header
)
1450 encapsulateHead(buf
, "res-hdr", httpBuf
, prime
);
1452 if (!virginBody
.expected())
1453 buf
.appendf("null-body=%d", (int) httpBuf
.contentSize());
1454 else if (ICAP::methodReqmod
== m
)
1455 buf
.appendf("req-body=%d", (int) httpBuf
.contentSize());
1457 buf
.appendf("res-body=%d", (int) httpBuf
.contentSize());
1459 buf
.append(ICAP::crlf
, 2); // terminate Encapsulated line
1461 if (preview
.enabled()) {
1462 buf
.appendf("Preview: %d\r\n", (int)preview
.ad());
1463 if (!virginBody
.expected()) // there is no body to preview
1464 finishNullOrEmptyBodyPreview(httpBuf
);
1467 makeAllowHeader(buf
);
1469 if (TheConfig
.send_client_ip
&& request
) {
1470 Ip::Address client_addr
;
1471 #if FOLLOW_X_FORWARDED_FOR
1472 if (TheConfig
.use_indirect_client
) {
1473 client_addr
= request
->indirect_client_addr
;
1476 client_addr
= request
->client_addr
;
1477 if (!client_addr
.isAnyAddr() && !client_addr
.isNoAddr())
1478 buf
.appendf("X-Client-IP: %s\r\n", client_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
1481 if (TheConfig
.send_username
&& request
)
1482 makeUsernameHeader(request
, buf
);
1484 // Adaptation::Config::metaHeaders
1485 for (auto h
: Adaptation::Config::metaHeaders
) {
1486 HttpRequest
*r
= virgin
.cause
?
1487 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
1490 HttpReply
*reply
= dynamic_cast<HttpReply
*>(virgin
.header
);
1493 if (h
->match(r
, reply
, alMaster
, matched
)) {
1494 buf
.append(h
->key().rawContent(), h
->key().length());
1495 buf
.append(": ", 2);
1496 buf
.append(matched
.rawContent(), matched
.length());
1497 buf
.append("\r\n", 2);
1498 Adaptation::History::Pointer ah
= request
->adaptHistory(false);
1499 if (ah
!= nullptr) {
1500 if (ah
->metaHeaders
== nullptr)
1501 ah
->metaHeaders
= new NotePairs
;
1502 if (!ah
->metaHeaders
->hasPair(h
->key(), matched
))
1503 ah
->metaHeaders
->add(h
->key(), matched
);
1508 // fprintf(stderr, "%s\n", buf.content());
1510 buf
.append(ICAP::crlf
, 2); // terminate ICAP header
1512 // fill icapRequest for logging
1513 Must(icapRequest
->parseCharBuf(buf
.content(), buf
.contentSize()));
1515 // start ICAP request body with encapsulated HTTP headers
1516 buf
.append(httpBuf
.content(), httpBuf
.contentSize());
1521 // decides which Allow values to write and updates the request buffer
1522 void Adaptation::Icap::ModXact::makeAllowHeader(MemBuf
&buf
)
1524 const bool allow204in
= preview
.enabled(); // TODO: add shouldAllow204in()
1525 const bool allow204out
= state
.allowedPostview204
= shouldAllow204();
1526 const bool allow206in
= state
.allowedPreview206
= shouldAllow206in();
1527 const bool allow206out
= state
.allowedPostview206
= shouldAllow206out();
1528 const bool allowTrailers
= true; // TODO: make configurable
1530 debugs(93, 9, "Allows: " << allow204in
<< allow204out
<<
1531 allow206in
<< allow206out
<< allowTrailers
);
1533 const bool allow204
= allow204in
|| allow204out
;
1534 const bool allow206
= allow206in
|| allow206out
;
1536 if ((allow204
|| allow206
) && virginBody
.expected())
1537 virginBodySending
.plan(); // if there is a virgin body, plan to send it
1539 // writing Preview:... means we will honor 204 inside preview
1540 // writing Allow/204 means we will honor 204 outside preview
1541 // writing Allow:206 means we will honor 206 inside preview
1542 // writing Allow:204,206 means we will honor 206 outside preview
1543 if (allow204
|| allow206
|| allowTrailers
) {
1544 buf
.appendf("Allow: ");
1546 buf
.appendf("204, ");
1548 buf
.appendf("206, ");
1550 buf
.appendf("trailers");
1551 buf
.appendf("\r\n");
1555 void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest
*request
, MemBuf
&buf
)
1558 struct base64_encode_ctx ctx
;
1559 base64_encode_init(&ctx
);
1561 const char *value
= nullptr;
1562 if (request
->auth_user_request
!= nullptr) {
1563 value
= request
->auth_user_request
->username();
1564 } else if (request
->extacl_user
.size() > 0) {
1565 value
= request
->extacl_user
.termedBuf();
1569 if (TheConfig
.client_username_encode
) {
1570 char base64buf
[base64_encode_len(MAX_LOGIN_SZ
)];
1571 size_t resultLen
= base64_encode_update(&ctx
, base64buf
, strlen(value
), reinterpret_cast<const uint8_t*>(value
));
1572 resultLen
+= base64_encode_final(&ctx
, base64buf
+resultLen
);
1573 buf
.appendf("%s: %.*s\r\n", TheConfig
.client_username_header
, (int)resultLen
, base64buf
);
1575 buf
.appendf("%s: %s\r\n", TheConfig
.client_username_header
, value
);
1584 Adaptation::Icap::ModXact::encapsulateHead(MemBuf
&icapBuf
, const char *section
, MemBuf
&httpBuf
, const Http::Message
*head
)
1586 // update ICAP header
1587 icapBuf
.appendf("%s=%d, ", section
, (int) httpBuf
.contentSize());
1590 Http::MessagePointer headClone
;
1592 if (const HttpRequest
* old_request
= dynamic_cast<const HttpRequest
*>(head
)) {
1593 HttpRequest::Pointer
new_request(new HttpRequest(old_request
->masterXaction
));
1594 // copy the request-line details
1595 new_request
->method
= old_request
->method
;
1596 new_request
->url
= old_request
->url
;
1597 new_request
->http_ver
= old_request
->http_ver
;
1598 headClone
= new_request
.getRaw();
1599 } else if (const HttpReply
*old_reply
= dynamic_cast<const HttpReply
*>(head
)) {
1600 HttpReply::Pointer
new_reply(new HttpReply
);
1601 new_reply
->sline
= old_reply
->sline
;
1602 headClone
= new_reply
.getRaw();
1605 headClone
->inheritProperties(head
);
1607 HttpHeaderPos pos
= HttpHeaderInitPos
;
1608 while (HttpHeaderEntry
* p_head_entry
= head
->header
.getEntry(&pos
))
1609 headClone
->header
.addEntry(p_head_entry
->clone());
1613 // remove all hop-by-hop headers from the clone
1614 headClone
->header
.delById(Http::HdrType::PROXY_AUTHENTICATE
);
1615 headClone
->header
.removeHopByHopEntries();
1617 // TODO: modify HttpHeader::removeHopByHopEntries to accept a list of
1618 // excluded hop-by-hop headers
1619 if (head
->header
.has(Http::HdrType::UPGRADE
)) {
1620 const auto upgrade
= head
->header
.getList(Http::HdrType::UPGRADE
);
1621 headClone
->header
.putStr(Http::HdrType::UPGRADE
, upgrade
.termedBuf());
1624 // pack polished HTTP header
1625 packHead(httpBuf
, headClone
.getRaw());
1627 // headClone unlocks and, hence, deletes the message we packed
1631 Adaptation::Icap::ModXact::packHead(MemBuf
&httpBuf
, const Http::Message
*head
)
1633 head
->packInto(&httpBuf
, true);
1636 // decides whether to offer a preview and calculates its size
1637 void Adaptation::Icap::ModXact::decideOnPreview()
1639 if (!TheConfig
.preview_enable
) {
1640 debugs(93, 5, "preview disabled by squid.conf");
1644 const SBuf
urlPath(virginRequest().url
.path());
1646 if (!service().wantsPreview(urlPath
, wantedSize
)) {
1647 debugs(93, 5, "should not offer preview for " << urlPath
);
1651 // we decided to do preview, now compute its size
1653 // cannot preview more than we can backup
1654 size_t ad
= min(wantedSize
, TheBackupLimit
);
1656 if (!virginBody
.expected())
1658 else if (virginBody
.knownSize())
1659 ad
= min(static_cast<uint64_t>(ad
), virginBody
.size()); // not more than we have
1661 debugs(93, 5, "should offer " << ad
<< "-byte preview " <<
1662 "(service wanted " << wantedSize
<< ")");
1665 Must(preview
.enabled());
1668 // decides whether to allow 204 responses
1669 bool Adaptation::Icap::ModXact::shouldAllow204()
1671 if (!service().allows204())
1674 return canBackupEverything();
1677 // decides whether to allow 206 responses in some mode
1678 bool Adaptation::Icap::ModXact::shouldAllow206any()
1680 return TheConfig
.allow206_enable
&& service().allows206() &&
1681 virginBody
.expected(); // no need for 206 without a body
1684 // decides whether to allow 206 responses in preview mode
1685 bool Adaptation::Icap::ModXact::shouldAllow206in()
1687 return shouldAllow206any() && preview
.enabled();
1690 // decides whether to allow 206 responses outside of preview
1691 bool Adaptation::Icap::ModXact::shouldAllow206out()
1693 return shouldAllow206any() && canBackupEverything();
1696 // used by shouldAllow204 and decideOnRetries
1697 bool Adaptation::Icap::ModXact::canBackupEverything() const
1699 if (!virginBody
.expected())
1700 return true; // no body means no problems with backup
1702 // if there is a body, check whether we can backup it all
1704 if (!virginBody
.knownSize())
1707 // or should we have a different backup limit?
1708 // note that '<' allows for 0-termination of the "full" backup buffer
1709 return virginBody
.size() < TheBackupLimit
;
1712 // Decide whether this transaction can be retried if pconn fails
1713 // Must be called after decideOnPreview and before openConnection()
1714 void Adaptation::Icap::ModXact::decideOnRetries()
1717 return; // no, already decided
1719 if (preview
.enabled())
1720 return; // yes, because preview provides enough guarantees
1722 if (canBackupEverything())
1723 return; // yes, because we can back everything up
1725 disableRetries(); // no, because we cannot back everything up
1728 // Normally, the body-writing code handles preview body. It can deal with
1729 // bodies of unexpected size, including those that turn out to be empty.
1730 // However, that code assumes that the body was expected and body control
1731 // structures were initialized. This is not the case when there is no body
1732 // or the body is known to be empty, because the virgin message will lack a
1733 // body_pipe. So we handle preview of null-body and zero-size bodies here.
1734 void Adaptation::Icap::ModXact::finishNullOrEmptyBodyPreview(MemBuf
&)
1736 Must(!virginBodyWriting
.active()); // one reason we handle it here
1737 Must(!virgin
.body_pipe
); // another reason we handle it here
1738 Must(!preview
.ad());
1740 // do not add last-chunk because our Encapsulated header says null-body
1741 // addLastRequestChunk(buf);
1742 preview
.wrote(0, true);
1744 Must(preview
.done());
1745 Must(preview
.ieof());
1748 void Adaptation::Icap::ModXact::fillPendingStatus(MemBuf
&buf
) const
1750 Adaptation::Icap::Xaction::fillPendingStatus(buf
);
1752 if (state
.serviceWaiting
)
1755 if (virgin
.body_pipe
!= nullptr)
1758 if (haveConnection() && !doneReading())
1761 if (!state
.doneWriting() && state
.writing
!= State::writingInit
)
1762 buf
.appendf("w(%d)", state
.writing
);
1764 if (preview
.enabled()) {
1765 if (!preview
.done())
1766 buf
.appendf("P(%d)", (int) preview
.debt());
1769 if (virginBodySending
.active())
1772 if (!state
.doneParsing() && state
.parsing
!= State::psIcapHeader
)
1773 buf
.appendf("p(%d)", state
.parsing
);
1775 if (!doneSending() && state
.sending
!= State::sendingUndecided
)
1776 buf
.appendf("S(%d)", state
.sending
);
1778 if (state
.readyForUob
)
1784 if (protectGroupBypass
)
1788 void Adaptation::Icap::ModXact::fillDoneStatus(MemBuf
&buf
) const
1790 Adaptation::Icap::Xaction::fillDoneStatus(buf
);
1792 if (!virgin
.body_pipe
)
1795 if (state
.doneWriting())
1798 if (preview
.enabled()) {
1800 buf
.appendf("P%s", preview
.ieof() ? "(ieof)" : "");
1806 if (state
.doneParsing())
1813 bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section
) const
1815 return !icapReply
->header
.getByNameListMember("Encapsulated",
1816 section
, ',').isEmpty();
1819 // calculate whether there is a virgin HTTP body and
1820 // whether its expected size is known
1821 // TODO: rename because we do not just estimate
1822 void Adaptation::Icap::ModXact::estimateVirginBody()
1824 // note: lack of size info may disable previews and 204s
1826 Http::Message
*msg
= virgin
.header
;
1829 HttpRequestMethod method
;
1832 method
= virgin
.cause
->method
;
1833 else if (HttpRequest
*req
= dynamic_cast<HttpRequest
*>(msg
))
1834 method
= req
->method
;
1836 method
= Http::METHOD_NONE
;
1839 // expectingBody returns true for zero-sized bodies, but we will not
1840 // get a pipe for that body, so we treat the message as bodyless
1841 if (method
!= Http::METHOD_NONE
&& msg
->expectingBody(method
, size
) && size
) {
1842 debugs(93, 6, "expects virgin body from " <<
1843 virgin
.body_pipe
<< "; size: " << size
);
1845 virginBody
.expect(size
);
1846 virginBodyWriting
.plan();
1848 // sign up as a body consumer
1849 Must(msg
->body_pipe
!= nullptr);
1850 Must(msg
->body_pipe
== virgin
.body_pipe
);
1851 Must(virgin
.body_pipe
->setConsumerIfNotLate(this));
1853 // make sure TheBackupLimit is in-sync with the buffer size
1854 Must(TheBackupLimit
<= static_cast<size_t>(msg
->body_pipe
->buf().max_capacity
));
1856 debugs(93, 6, "does not expect virgin body");
1857 Must(msg
->body_pipe
== nullptr);
1862 void Adaptation::Icap::ModXact::makeAdaptedBodyPipe(const char *what
)
1864 Must(!adapted
.body_pipe
);
1865 Must(!adapted
.header
->body_pipe
);
1866 adapted
.header
->body_pipe
= new BodyPipe(this);
1867 adapted
.body_pipe
= adapted
.header
->body_pipe
;
1868 debugs(93, 7, "will supply " << what
<< " via " <<
1869 adapted
.body_pipe
<< " pipe");
1872 // TODO: Move SizedEstimate and Preview elsewhere
1874 Adaptation::Icap::SizedEstimate::SizedEstimate()
1875 : theData(dtUnexpected
)
1878 void Adaptation::Icap::SizedEstimate::expect(int64_t aSize
)
1880 theData
= (aSize
>= 0) ? aSize
: (int64_t)dtUnknown
;
1883 bool Adaptation::Icap::SizedEstimate::expected() const
1885 return theData
!= dtUnexpected
;
1888 bool Adaptation::Icap::SizedEstimate::knownSize() const
1891 return theData
!= dtUnknown
;
1894 uint64_t Adaptation::Icap::SizedEstimate::size() const
1897 return static_cast<uint64_t>(theData
);
1900 Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided
)
1903 void Adaptation::Icap::VirginBodyAct::plan()
1906 Must(!theStart
); // not started
1907 theState
= stActive
;
1910 void Adaptation::Icap::VirginBodyAct::disable()
1912 theState
= stDisabled
;
1915 void Adaptation::Icap::VirginBodyAct::progress(size_t size
)
1918 #if SIZEOF_SIZE_T > 4
1919 /* always true for smaller size_t's */
1920 Must(static_cast<int64_t>(size
) >= 0);
1922 theStart
+= static_cast<int64_t>(size
);
1925 uint64_t Adaptation::Icap::VirginBodyAct::offset() const
1928 return static_cast<uint64_t>(theStart
);
1931 Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled
)
1934 void Adaptation::Icap::Preview::enable(size_t anAd
)
1936 // TODO: check for anAd not exceeding preview size limit
1939 theState
= stWriting
;
1942 bool Adaptation::Icap::Preview::enabled() const
1944 return theState
!= stDisabled
;
1947 size_t Adaptation::Icap::Preview::ad() const
1953 bool Adaptation::Icap::Preview::done() const
1956 return theState
>= stIeof
;
1959 bool Adaptation::Icap::Preview::ieof() const
1962 return theState
== stIeof
;
1965 size_t Adaptation::Icap::Preview::debt() const
1968 return done() ? 0 : (theAd
- theWritten
);
1971 void Adaptation::Icap::Preview::wrote(size_t size
, bool wroteEof
)
1977 Must(theWritten
<= theAd
);
1980 theState
= stIeof
; // written size is irrelevant
1981 else if (theWritten
>= theAd
)
1985 bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf
&mb
) const
1987 if (virgin
.header
== nullptr)
1990 virgin
.header
->firstLineBuf(mb
);
1995 void Adaptation::Icap::ModXact::detailError(const ErrorDetail::Pointer
&errDetail
)
1997 HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
1998 // if no adapted request, update virgin (and inherit its properties later)
1999 // TODO: make this and HttpRequest::detailError constant, like adaptHistory
2001 request
= const_cast<HttpRequest
*>(&virginRequest());
2004 request
->detailError(ERR_ICAP_FAILURE
, errDetail
);
2007 void Adaptation::Icap::ModXact::clearError()
2009 HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
2010 // if no adapted request, update virgin (and inherit its properties later)
2012 request
= const_cast<HttpRequest
*>(&virginRequest());
2015 request
->clearError();
2018 void Adaptation::Icap::ModXact::updateSources()
2020 Must(adapted
.header
);
2021 adapted
.header
->sources
|= (service().cfg().connectionEncryption
? Http::Message::srcIcaps
: Http::Message::srcIcap
);
2024 /* Adaptation::Icap::ModXactLauncher */
2026 Adaptation::Icap::ModXactLauncher::ModXactLauncher(Http::Message
*virginHeader
, HttpRequest
*virginCause
, AccessLogEntry::Pointer
&alp
, Adaptation::ServicePointer aService
):
2027 AsyncJob("Adaptation::Icap::ModXactLauncher"),
2028 Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", aService
),
2031 virgin
.setHeader(virginHeader
);
2032 virgin
.setCause(virginCause
);
2033 updateHistory(true);
2036 Adaptation::Icap::Xaction
*Adaptation::Icap::ModXactLauncher::createXaction()
2038 Adaptation::Icap::ServiceRep::Pointer s
=
2039 dynamic_cast<Adaptation::Icap::ServiceRep
*>(theService
.getRaw());
2041 return new Adaptation::Icap::ModXact(virgin
.header
, virgin
.cause
, al
, s
);
2044 void Adaptation::Icap::ModXactLauncher::swanSong()
2046 debugs(93, 5, "swan sings");
2047 updateHistory(false);
2048 Adaptation::Icap::Launcher::swanSong();
2051 void Adaptation::Icap::ModXactLauncher::updateHistory(bool doStart
)
2053 HttpRequest
*r
= virgin
.cause
?
2054 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
2056 // r should never be NULL but we play safe; TODO: add Should()
2058 Adaptation::Icap::History::Pointer h
= r
->icapHistory();
2061 h
->start("ICAPModXactLauncher");
2063 h
->stop("ICAPModXactLauncher");
2068 bool Adaptation::Icap::TrailerParser::parse(const char *buf
, int len
, int atEnd
, Http::StatusCode
*error
) {
2069 Http::ContentLengthInterpreter clen
;
2070 // RFC 7230 section 4.1.2: MUST NOT generate a trailer that contains
2071 // a field necessary for message framing (e.g., Transfer-Encoding and Content-Length)
2072 clen
.applyTrailerRules();
2073 const int parsed
= trailer
.parse(buf
, len
, atEnd
, hdr_sz
, clen
);
2075 *error
= Http::scInvalidHeader
; // TODO: should we add a new Http::scInvalidTrailer?
2080 Adaptation::Icap::ChunkExtensionValueParser::parse(Tokenizer
&tok
, const SBuf
&extName
)
2082 if (extName
== UseOriginalBodyName
) {
2083 useOriginalBody_
= tok
.udec64("use-original-body");
2084 assert(useOriginalBody_
>= 0);
2086 Ignore(tok
, extName
);