2 * Copyright (C) 1996-2019 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 "err_detail_type.h"
28 #include "http/ContentLengthInterpreter.h"
29 #include "HttpHeaderTools.h"
30 #include "HttpReply.h"
31 #include "MasterXaction.h"
32 #include "parser/Tokenizer.h"
33 #include "sbuf/Stream.h"
34 #include "SquidTime.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 const size_t 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, HERE
<< "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, HERE
<< "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, HERE
<< "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 // connection with the ICAP service established
190 void Adaptation::Icap::ModXact::handleCommConnected()
192 Must(state
.writing
== State::writingConnect
);
194 startReading(); // wait for early errors from the ICAP server
199 makeRequestHeaders(requestBuf
);
200 debugs(93, 9, HERE
<< "will write" << status() << ":\n" <<
201 (requestBuf
.terminate(), requestBuf
.content()));
204 state
.writing
= State::writingHeaders
;
205 icap_tio_start
= current_time
;
206 scheduleWrite(requestBuf
);
209 void Adaptation::Icap::ModXact::handleCommWrote(size_t sz
)
211 debugs(93, 5, HERE
<< "Wrote " << sz
<< " bytes");
213 if (state
.writing
== State::writingHeaders
)
214 handleCommWroteHeaders();
216 handleCommWroteBody();
219 void Adaptation::Icap::ModXact::handleCommWroteHeaders()
221 Must(state
.writing
== State::writingHeaders
);
223 // determine next step
224 if (preview
.enabled()) {
226 decideWritingAfterPreview("zero-size");
228 state
.writing
= State::writingPreview
;
229 } else if (virginBody
.expected()) {
230 state
.writing
= State::writingPrime
;
239 void Adaptation::Icap::ModXact::writeMore()
241 debugs(93, 5, HERE
<< "checking whether to write more" << status());
243 if (writer
!= NULL
) // already writing something
246 switch (state
.writing
) {
248 case State::writingInit
: // waiting for service OPTIONS
249 Must(state
.serviceWaiting
);
251 case State::writingConnect
: // waiting for the connection to establish
253 case State::writingHeaders
: // waiting for the headers to be written
255 case State::writingPaused
: // waiting for the ICAP server response
257 case State::writingReallyDone
: // nothing more to write
260 case State::writingAlmostDone
: // was waiting for the last write
264 case State::writingPreview
:
268 case State::writingPrime
:
273 throw TexcHere("Adaptation::Icap::ModXact in bad writing state");
277 void Adaptation::Icap::ModXact::writePreviewBody()
279 debugs(93, 8, HERE
<< "will write Preview body from " <<
280 virgin
.body_pipe
<< status());
281 Must(state
.writing
== State::writingPreview
);
282 Must(virgin
.body_pipe
!= NULL
);
284 const size_t sizeMax
= (size_t)virgin
.body_pipe
->buf().contentSize();
285 const size_t size
= min(preview
.debt(), sizeMax
);
286 writeSomeBody("preview body", size
);
288 // change state once preview is written
291 decideWritingAfterPreview("body");
294 /// determine state.writing after we wrote the entire preview
295 void Adaptation::Icap::ModXact::decideWritingAfterPreview(const char *kind
)
297 if (preview
.ieof()) // nothing more to write
299 else if (state
.parsing
== State::psIcapHeader
) // did not get a reply yet
300 state
.writing
= State::writingPaused
; // wait for the ICAP server reply
302 stopWriting(true); // ICAP server reply implies no post-preview writing
304 debugs(93, 6, HERE
<< "decided on writing after " << kind
<< " preview" <<
308 void Adaptation::Icap::ModXact::writePrimeBody()
310 Must(state
.writing
== State::writingPrime
);
311 Must(virginBodyWriting
.active());
313 const size_t size
= (size_t)virgin
.body_pipe
->buf().contentSize();
314 writeSomeBody("prime virgin body", size
);
316 if (virginBodyEndReached(virginBodyWriting
)) {
317 debugs(93, 5, HERE
<< "wrote entire body");
322 void Adaptation::Icap::ModXact::writeSomeBody(const char *label
, size_t size
)
324 Must(!writer
&& state
.writing
< state
.writingAlmostDone
);
325 Must(virgin
.body_pipe
!= NULL
);
326 debugs(93, 8, HERE
<< "will write up to " << size
<< " bytes of " <<
329 MemBuf writeBuf
; // TODO: suggest a min size based on size and lastChunk
331 writeBuf
.init(); // note: we assume that last-chunk will fit
333 const size_t writableSize
= virginContentSize(virginBodyWriting
);
334 const size_t chunkSize
= min(writableSize
, size
);
337 debugs(93, 7, HERE
<< "will write " << chunkSize
<<
338 "-byte chunk of " << label
);
340 openChunk(writeBuf
, chunkSize
, false);
341 writeBuf
.append(virginContentData(virginBodyWriting
), chunkSize
);
342 closeChunk(writeBuf
);
344 virginBodyWriting
.progress(chunkSize
);
347 debugs(93, 7, HERE
<< "has no writable " << label
<< " content");
350 const bool wroteEof
= virginBodyEndReached(virginBodyWriting
);
351 bool lastChunk
= wroteEof
;
352 if (state
.writing
== State::writingPreview
) {
353 preview
.wrote(chunkSize
, wroteEof
); // even if wrote nothing
354 lastChunk
= lastChunk
|| preview
.done();
358 debugs(93, 8, HERE
<< "will write last-chunk of " << label
);
359 addLastRequestChunk(writeBuf
);
362 debugs(93, 7, HERE
<< "will write " << writeBuf
.contentSize()
363 << " raw bytes of " << label
);
365 if (writeBuf
.hasContent()) {
366 scheduleWrite(writeBuf
); // comm will free the chunk
372 void Adaptation::Icap::ModXact::addLastRequestChunk(MemBuf
&buf
)
374 const bool ieof
= state
.writing
== State::writingPreview
&& preview
.ieof();
375 openChunk(buf
, 0, ieof
);
379 void Adaptation::Icap::ModXact::openChunk(MemBuf
&buf
, size_t chunkSize
, bool ieof
)
381 buf
.appendf((ieof
? "%x; ieof\r\n" : "%x\r\n"), (int) chunkSize
);
384 void Adaptation::Icap::ModXact::closeChunk(MemBuf
&buf
)
386 buf
.append(ICAP::crlf
, 2); // chunk-terminating CRLF
389 const HttpRequest
&Adaptation::Icap::ModXact::virginRequest() const
391 const HttpRequest
*request
= virgin
.cause
?
392 virgin
.cause
: dynamic_cast<const HttpRequest
*>(virgin
.header
);
397 // did the activity reached the end of the virgin body?
398 bool Adaptation::Icap::ModXact::virginBodyEndReached(const Adaptation::Icap::VirginBodyAct
&act
) const
401 !act
.active() || // did all (assuming it was originally planned)
402 !virgin
.body_pipe
->expectMoreAfter(act
.offset()); // will not have more
405 // the size of buffered virgin body data available for the specified activity
406 // if this size is zero, we may be done or may be waiting for more data
407 size_t Adaptation::Icap::ModXact::virginContentSize(const Adaptation::Icap::VirginBodyAct
&act
) const
410 // asbolute start of unprocessed data
411 const uint64_t dataStart
= act
.offset();
412 // absolute end of buffered data
413 const uint64_t dataEnd
= virginConsumed
+ virgin
.body_pipe
->buf().contentSize();
414 Must(virginConsumed
<= dataStart
&& dataStart
<= dataEnd
);
415 return static_cast<size_t>(dataEnd
- dataStart
);
418 // pointer to buffered virgin body data available for the specified activity
419 const char *Adaptation::Icap::ModXact::virginContentData(const Adaptation::Icap::VirginBodyAct
&act
) const
422 const uint64_t dataStart
= act
.offset();
423 Must(virginConsumed
<= dataStart
);
424 return virgin
.body_pipe
->buf().content() + static_cast<size_t>(dataStart
-virginConsumed
);
427 void Adaptation::Icap::ModXact::virginConsume()
429 debugs(93, 9, HERE
<< "consumption guards: " << !virgin
.body_pipe
<< isRetriable
<<
430 isRepeatable
<< canStartBypass
<< protectGroupBypass
);
432 if (!virgin
.body_pipe
)
433 return; // nothing to consume
436 return; // do not consume if we may have to retry later
438 BodyPipe
&bp
= *virgin
.body_pipe
;
439 const bool wantToPostpone
= isRepeatable
|| canStartBypass
|| protectGroupBypass
;
441 // Why > 2? HttpState does not use the last bytes in the buffer
442 // because delayAwareRead() is arguably broken. See
443 // HttpStateData::maybeReadVirginBody for more details.
444 if (wantToPostpone
&& bp
.buf().spaceSize() > 2) {
445 // Postponing may increase memory footprint and slow the HTTP side
446 // down. Not postponing may increase the number of ICAP errors
447 // if the ICAP service fails. We may also use "potential" space to
448 // postpone more aggressively. Should the trade-off be configurable?
449 debugs(93, 8, HERE
<< "postponing consumption from " << bp
.status());
453 const size_t have
= static_cast<size_t>(bp
.buf().contentSize());
454 const uint64_t end
= virginConsumed
+ have
;
455 uint64_t offset
= end
;
457 debugs(93, 9, HERE
<< "max virgin consumption offset=" << offset
<<
458 " acts " << virginBodyWriting
.active() << virginBodySending
.active() <<
459 " consumed=" << virginConsumed
<<
460 " from " << virgin
.body_pipe
->status());
462 if (virginBodyWriting
.active())
463 offset
= min(virginBodyWriting
.offset(), offset
);
465 if (virginBodySending
.active())
466 offset
= min(virginBodySending
.offset(), offset
);
468 Must(virginConsumed
<= offset
&& offset
<= end
);
470 if (const size_t size
= static_cast<size_t>(offset
- virginConsumed
)) {
471 debugs(93, 8, HERE
<< "consuming " << size
<< " out of " << have
<<
472 " virgin body bytes");
474 virginConsumed
+= size
;
475 Must(!isRetriable
); // or we should not be consuming
476 disableRepeats("consumed content");
477 disableBypass("consumed content", true);
481 void Adaptation::Icap::ModXact::handleCommWroteBody()
486 // Called when we do not expect to call comm_write anymore.
487 // We may have a pending write though.
488 // If stopping nicely, we will just wait for that pending write, if any.
489 void Adaptation::Icap::ModXact::stopWriting(bool nicely
)
491 if (state
.writing
== State::writingReallyDone
)
494 if (writer
!= NULL
) {
496 debugs(93, 7, HERE
<< "will wait for the last write" << status());
497 state
.writing
= State::writingAlmostDone
; // may already be set
501 debugs(93, 3, HERE
<< "will NOT wait for the last write" << status());
503 // Comm does not have an interface to clear the writer callback nicely,
504 // but without clearing the writer we cannot recycle the connection.
505 // We prevent connection reuse and hope that we can handle a callback
506 // call at any time, usually in the middle of the destruction sequence!
507 // Somebody should add comm_remove_write_handler() to comm API.
508 reuseConnection
= false;
509 ignoreLastWrite
= true;
512 debugs(93, 7, HERE
<< "will no longer write" << status());
513 if (virginBodyWriting
.active()) {
514 virginBodyWriting
.disable();
517 state
.writing
= State::writingReallyDone
;
521 void Adaptation::Icap::ModXact::stopBackup()
523 if (!virginBodySending
.active())
526 debugs(93, 7, HERE
<< "will no longer backup" << status());
527 virginBodySending
.disable();
531 bool Adaptation::Icap::ModXact::doneAll() const
533 return Adaptation::Icap::Xaction::doneAll() && !state
.serviceWaiting
&&
535 doneReading() && state
.doneWriting();
538 void Adaptation::Icap::ModXact::startReading()
540 Must(haveConnection());
542 Must(!adapted
.header
);
543 Must(!adapted
.body_pipe
);
545 // we use the same buffer for headers and body and then consume headers
549 void Adaptation::Icap::ModXact::readMore()
551 if (reader
!= NULL
|| doneReading()) {
552 debugs(93,3,HERE
<< "returning from readMore because reader or doneReading()");
556 // do not fill readBuf if we have no space to store the result
557 if (adapted
.body_pipe
!= NULL
&&
558 !adapted
.body_pipe
->buf().hasPotentialSpace()) {
559 debugs(93,3,HERE
<< "not reading because ICAP reply pipe is full");
563 if (readBuf
.length() < SQUID_TCP_SO_RCVBUF
)
566 debugs(93,3,HERE
<< "cannot read with a full buffer");
569 // comm module read a portion of the ICAP response for us
570 void Adaptation::Icap::ModXact::handleCommRead(size_t)
572 Must(!state
.doneParsing());
573 icap_tio_finish
= current_time
;
578 void Adaptation::Icap::ModXact::echoMore()
580 Must(state
.sending
== State::sendingVirgin
);
581 Must(adapted
.body_pipe
!= NULL
);
582 Must(virginBodySending
.active());
584 const size_t sizeMax
= virginContentSize(virginBodySending
);
585 debugs(93,5, HERE
<< "will echo up to " << sizeMax
<< " bytes from " <<
586 virgin
.body_pipe
->status());
587 debugs(93,5, HERE
<< "will echo up to " << sizeMax
<< " bytes to " <<
588 adapted
.body_pipe
->status());
591 const size_t size
= adapted
.body_pipe
->putMoreData(virginContentData(virginBodySending
), sizeMax
);
592 debugs(93,5, HERE
<< "echoed " << size
<< " out of " << sizeMax
<<
594 virginBodySending
.progress(size
);
595 disableRepeats("echoed content");
596 disableBypass("echoed content", true);
600 if (virginBodyEndReached(virginBodySending
)) {
601 debugs(93, 5, HERE
<< "echoed all" << status());
604 debugs(93, 5, HERE
<< "has " <<
605 virgin
.body_pipe
->buf().contentSize() << " bytes " <<
606 "and expects more to echo" << status());
607 // TODO: timeout if virgin or adapted pipes are broken
611 bool Adaptation::Icap::ModXact::doneSending() const
613 return state
.sending
== State::sendingDone
;
616 // stop (or do not start) sending adapted message body
617 void Adaptation::Icap::ModXact::stopSending(bool nicely
)
619 debugs(93, 7, HERE
<< "Enter stop sending ");
622 debugs(93, 7, HERE
<< "Proceed with stop sending ");
624 if (state
.sending
!= State::sendingUndecided
) {
625 debugs(93, 7, HERE
<< "will no longer send" << status());
626 if (adapted
.body_pipe
!= NULL
) {
627 virginBodySending
.disable();
628 // we may leave debts if we were echoing and the virgin
629 // body_pipe got exhausted before we echoed all planned bytes
630 const bool leftDebts
= adapted
.body_pipe
->needsMoreData();
631 stopProducingFor(adapted
.body_pipe
, nicely
&& !leftDebts
);
634 debugs(93, 7, HERE
<< "will not start sending" << status());
635 Must(!adapted
.body_pipe
);
638 state
.sending
= State::sendingDone
;
642 // should be called after certain state.writing or state.sending changes
643 void Adaptation::Icap::ModXact::checkConsuming()
645 // quit if we already stopped or are still using the pipe
646 if (!virgin
.body_pipe
|| !state
.doneConsumingVirgin())
649 debugs(93, 7, HERE
<< "will stop consuming" << status());
650 stopConsumingFrom(virgin
.body_pipe
);
653 void Adaptation::Icap::ModXact::parseMore()
655 debugs(93, 5, "have " << readBuf
.length() << " bytes to parse" << status());
656 debugs(93, 5, "\n" << readBuf
);
658 if (state
.parsingHeaders())
661 if (state
.parsing
== State::psBody
)
664 if (state
.parsing
== State::psIcapTrailer
)
668 void Adaptation::Icap::ModXact::callException(const std::exception
&e
)
670 if (!canStartBypass
|| isRetriable
) {
672 if (const TextException
*te
= dynamic_cast<const TextException
*>(&e
))
673 detailError(ERR_DETAIL_EXCEPTION_START
+ te
->id());
675 detailError(ERR_DETAIL_EXCEPTION_OTHER
);
677 Adaptation::Icap::Xaction::callException(e
);
682 debugs(93, 3, HERE
<< "bypassing " << inCall
<< " exception: " <<
683 e
.what() << ' ' << status());
685 } catch (const TextException
&bypassTe
) {
686 detailError(ERR_DETAIL_EXCEPTION_START
+ bypassTe
.id());
687 Adaptation::Icap::Xaction::callException(bypassTe
);
688 } catch (const std::exception
&bypassE
) {
689 detailError(ERR_DETAIL_EXCEPTION_OTHER
);
690 Adaptation::Icap::Xaction::callException(bypassE
);
694 void Adaptation::Icap::ModXact::bypassFailure()
696 disableBypass("already started to bypass", false);
698 Must(!isRetriable
); // or we should not be bypassing
699 // TODO: should the same be enforced for isRepeatable? Check icap_repeat??
705 // end all activities associated with the ICAP server
709 stopWriting(true); // or should we force it?
710 if (haveConnection()) {
711 reuseConnection
= false; // be conservative
712 cancelRead(); // may not work; and we cannot stop connecting either
714 debugs(93, 7, HERE
<< "Warning: bypass failed to stop I/O" << status());
717 service().noteFailure(); // we are bypassing, but this is still a failure
720 void Adaptation::Icap::ModXact::disableBypass(const char *reason
, bool includingGroupBypass
)
722 if (canStartBypass
) {
723 debugs(93,7, HERE
<< "will never start bypass because " << reason
);
724 canStartBypass
= false;
726 if (protectGroupBypass
&& includingGroupBypass
) {
727 debugs(93,7, HERE
<< "not protecting group bypass because " << reason
);
728 protectGroupBypass
= false;
732 // note that allocation for echoing is done in handle204NoContent()
733 void Adaptation::Icap::ModXact::maybeAllocateHttpMsg()
735 if (adapted
.header
) // already allocated
738 if (gotEncapsulated("res-hdr")) {
739 adapted
.setHeader(new HttpReply
);
740 setOutcome(service().cfg().method
== ICAP::methodReqmod
?
741 xoSatisfied
: xoModified
);
742 } else if (gotEncapsulated("req-hdr")) {
743 adapted
.setHeader(new HttpRequest(virginRequest().masterXaction
));
744 setOutcome(xoModified
);
746 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
749 void Adaptation::Icap::ModXact::parseHeaders()
751 Must(state
.parsingHeaders());
753 if (state
.parsing
== State::psIcapHeader
) {
754 debugs(93, 5, HERE
<< "parse ICAP headers");
758 if (state
.parsing
== State::psHttpHeader
) {
759 debugs(93, 5, HERE
<< "parse HTTP headers");
763 if (state
.parsingHeaders()) { // need more data
771 // called after parsing all headers or when bypassing an exception
772 void Adaptation::Icap::ModXact::startSending()
774 disableRepeats("sent headers");
775 disableBypass("sent headers", true);
776 sendAnswer(Answer::Forward(adapted
.header
));
778 if (state
.sending
== State::sendingVirgin
)
781 // If we are not using the virgin HTTP object update the
782 // Http::Message::sources flag.
783 // The state.sending may set to State::sendingVirgin in the case
784 // of 206 responses too, where we do not want to update Http::Message::sources
785 // flag. However even for 206 responses the state.sending is
786 // not set yet to sendingVirgin. This is done in later step
787 // after the parseBody method called.
792 void Adaptation::Icap::ModXact::parseIcapHead()
794 Must(state
.sending
== State::sendingUndecided
);
796 if (!parseHead(icapReply
.getRaw()))
799 if (expectIcapTrailers()) {
800 Must(!trailerParser
);
801 trailerParser
= new TrailerParser
;
804 static SBuf
close("close", 5);
805 if (httpHeaderHasConnDir(&icapReply
->header
, close
)) {
806 debugs(93, 5, HERE
<< "found connection close");
807 reuseConnection
= false;
810 switch (icapReply
->sline
.status()) {
812 case Http::scContinue
:
817 case Http::scCreated
: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
819 if (!validate200Ok()) {
820 throw TexcHere("Invalid ICAP Response");
827 case Http::scNoContent
:
828 handle204NoContent();
831 case Http::scPartialContent
:
832 handle206PartialContent();
836 debugs(93, 5, "ICAP status " << icapReply
->sline
.status());
837 handleUnknownScode();
841 const HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
843 request
= &virginRequest();
845 // update the cross-transactional database if needed (all status codes!)
846 if (const char *xxName
= Adaptation::Config::masterx_shared_name
) {
847 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
848 if (ah
!= NULL
) { // TODO: reorder checks to avoid creating history
849 const String val
= icapReply
->header
.getByName(xxName
);
850 if (val
.size() > 0) // XXX: HttpHeader lacks empty value detection
851 ah
->updateXxRecord(xxName
, val
);
855 // update the adaptation plan if needed (all status codes!)
856 if (service().cfg().routing
) {
858 if (icapReply
->header
.getList(Http::HdrType::X_NEXT_SERVICES
, &services
)) {
859 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
861 ah
->updateNextServices(services
);
863 } // TODO: else warn (occasionally!) if we got Http::HdrType::X_NEXT_SERVICES
865 // We need to store received ICAP headers for <icapLastHeader logformat option.
866 // If we already have stored headers from previous ICAP transaction related to this
867 // request, old headers will be replaced with the new one.
869 Adaptation::History::Pointer ah
= request
->adaptLogHistory();
871 ah
->recordMeta(&icapReply
->header
);
873 // handle100Continue() manages state.writing on its own.
874 // Non-100 status means the server needs no postPreview data from us.
875 if (state
.writing
== State::writingPaused
)
879 /// Parses ICAP trailers and stops parsing, if all trailer data
880 /// have been received.
881 void Adaptation::Icap::ModXact::parseIcapTrailer() {
883 if (parsePart(trailerParser
, "trailer")) {
884 for (const auto &e
: trailerParser
->trailer
.entries
)
885 debugs(93, 5, "ICAP trailer: " << e
->name
<< ": " << e
->value
);
890 bool Adaptation::Icap::ModXact::validate200Ok()
892 if (service().cfg().method
== ICAP::methodRespmod
)
893 return gotEncapsulated("res-hdr");
895 return service().cfg().method
== ICAP::methodReqmod
&&
899 void Adaptation::Icap::ModXact::handle100Continue()
901 Must(state
.writing
== State::writingPaused
);
902 // server must not respond before the end of preview: we may send ieof
903 Must(preview
.enabled() && preview
.done() && !preview
.ieof());
905 // 100 "Continue" cancels our Preview commitment,
906 // but not commitment to handle 204 or 206 outside Preview
907 if (!state
.allowedPostview204
&& !state
.allowedPostview206
)
910 state
.parsing
= State::psIcapHeader
; // eventually
913 state
.writing
= State::writingPrime
;
918 void Adaptation::Icap::ModXact::handle200Ok()
920 state
.parsing
= State::psHttpHeader
;
921 state
.sending
= State::sendingAdapted
;
926 void Adaptation::Icap::ModXact::handle204NoContent()
932 void Adaptation::Icap::ModXact::handle206PartialContent()
934 if (state
.writing
== State::writingPaused
) {
935 Must(preview
.enabled());
936 Must(state
.allowedPreview206
);
937 debugs(93, 7, HERE
<< "206 inside preview");
939 Must(state
.writing
> State::writingPaused
);
940 Must(state
.allowedPostview206
);
941 debugs(93, 7, HERE
<< "206 outside preview");
943 state
.parsing
= State::psHttpHeader
;
944 state
.sending
= State::sendingAdapted
;
945 state
.readyForUob
= true;
949 // Called when we receive a 204 No Content response and
950 // when we are trying to bypass a service failure.
951 // We actually start sending (echoig or not) in startSending.
952 void Adaptation::Icap::ModXact::prepEchoing()
954 disableRepeats("preparing to echo content");
955 disableBypass("preparing to echo content", true);
958 // We want to clone the HTTP message, but we do not want
959 // to copy some non-HTTP state parts that Http::Message kids carry in them.
960 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
961 // Instead, we simply write the HTTP message and "clone" it by parsing.
962 // TODO: use Http::Message::clone()!
964 Http::Message
*oldHead
= virgin
.header
;
965 debugs(93, 7, HERE
<< "cloning virgin message " << oldHead
);
969 // write the virgin message into a memory buffer
971 packHead(httpBuf
, oldHead
);
973 // allocate the adapted message and copy metainfo
974 Must(!adapted
.header
);
976 Http::MessagePointer newHead
;
977 if (const HttpRequest
*r
= dynamic_cast<const HttpRequest
*>(oldHead
)) {
978 newHead
= new HttpRequest(r
->masterXaction
);
979 } else if (dynamic_cast<const HttpReply
*>(oldHead
)) {
980 newHead
= new HttpReply
;
984 newHead
->inheritProperties(oldHead
);
986 adapted
.setHeader(newHead
.getRaw());
989 // parse the buffer back
990 Http::StatusCode error
= Http::scNone
;
992 httpBuf
.terminate(); // Http::Message::parse requires nil-terminated buffer
993 Must(adapted
.header
->parse(httpBuf
.content(), httpBuf
.contentSize(), true, &error
));
994 Must(adapted
.header
->hdr_sz
== httpBuf
.contentSize()); // no leftovers
998 debugs(93, 7, HERE
<< "cloned virgin message " << oldHead
<< " to " <<
1001 // setup adapted body pipe if needed
1002 if (oldHead
->body_pipe
!= NULL
) {
1003 debugs(93, 7, HERE
<< "will echo virgin body from " <<
1004 oldHead
->body_pipe
);
1005 if (!virginBodySending
.active())
1006 virginBodySending
.plan(); // will throw if not possible
1007 state
.sending
= State::sendingVirgin
;
1010 // TODO: optimize: is it possible to just use the oldHead pipe and
1011 // remove ICAP from the loop? This echoing is probably a common case!
1012 makeAdaptedBodyPipe("echoed virgin response");
1013 if (oldHead
->body_pipe
->bodySizeKnown())
1014 adapted
.body_pipe
->setBodySize(oldHead
->body_pipe
->bodySize());
1015 debugs(93, 7, HERE
<< "will echo virgin body to " <<
1018 debugs(93, 7, HERE
<< "no virgin body to echo");
1023 /// Called when we received use-original-body chunk extension in 206 response.
1024 /// We actually start sending (echoing or not) in startSending().
1025 void Adaptation::Icap::ModXact::prepPartialBodyEchoing(uint64_t pos
)
1027 Must(virginBodySending
.active());
1028 Must(virgin
.header
->body_pipe
!= NULL
);
1030 setOutcome(xoPartEcho
);
1032 debugs(93, 7, HERE
<< "will echo virgin body suffix from " <<
1033 virgin
.header
->body_pipe
<< " offset " << pos
);
1035 // check that use-original-body=N does not point beyond buffered data
1036 const uint64_t virginDataEnd
= virginConsumed
+
1037 virgin
.body_pipe
->buf().contentSize();
1038 Must(pos
<= virginDataEnd
);
1039 virginBodySending
.progress(static_cast<size_t>(pos
));
1041 state
.sending
= State::sendingVirgin
;
1044 if (virgin
.header
->body_pipe
->bodySizeKnown())
1045 adapted
.body_pipe
->expectProductionEndAfter(virgin
.header
->body_pipe
->bodySize() - pos
);
1047 debugs(93, 7, HERE
<< "will echo virgin body suffix to " <<
1050 // Start echoing data
1054 void Adaptation::Icap::ModXact::handleUnknownScode()
1058 // TODO: mark connection as "bad"
1060 // Terminate the transaction; we do not know how to handle this response.
1061 throw TexcHere("Unsupported ICAP status code");
1064 void Adaptation::Icap::ModXact::parseHttpHead()
1066 if (expectHttpHeader()) {
1067 replyHttpHeaderSize
= 0;
1068 maybeAllocateHttpMsg();
1070 if (!parseHead(adapted
.header
))
1071 return; // need more header data
1074 replyHttpHeaderSize
= adapted
.header
->hdr_sz
;
1076 if (dynamic_cast<HttpRequest
*>(adapted
.header
)) {
1077 const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(virgin
.header
);
1079 // TODO: the adapted request did not really originate from the
1080 // client; give proxy admin an option to prevent copying of
1081 // sensitive client information here. See the following thread:
1082 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
1085 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
1087 adapted
.header
->inheritProperties(virgin
.header
);
1090 decideOnParsingBody();
1093 template<class Part
>
1094 bool Adaptation::Icap::ModXact::parsePart(Part
*part
, const char *description
)
1097 debugs(93, 5, "have " << readBuf
.length() << ' ' << description
<< " bytes to parse; state: " << state
.parsing
);
1098 Http::StatusCode error
= Http::scNone
;
1099 // XXX: performance regression. c_str() data copies
1100 // XXX: Http::Message::parse requires a terminated string buffer
1101 const char *tmpBuf
= readBuf
.c_str();
1102 const bool parsed
= part
->parse(tmpBuf
, readBuf
.length(), commEof
, &error
);
1103 debugs(93, (!parsed
&& error
) ? 2 : 5, description
<< " parsing result: " << parsed
<< " detail: " << error
);
1104 Must(parsed
|| !error
);
1106 readBuf
.consume(part
->hdr_sz
);
1110 // parses both HTTP and ICAP headers
1112 Adaptation::Icap::ModXact::parseHead(Http::Message
*head
)
1114 if (!parsePart(head
, "head")) {
1121 bool Adaptation::Icap::ModXact::expectHttpHeader() const
1123 return gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr");
1126 bool Adaptation::Icap::ModXact::expectHttpBody() const
1128 return gotEncapsulated("res-body") || gotEncapsulated("req-body");
1131 bool Adaptation::Icap::ModXact::expectIcapTrailers() const
1134 const bool promisesToSendTrailer
= icapReply
->header
.getByIdIfPresent(Http::HdrType::TRAILER
, &trailers
);
1135 const bool supportsTrailers
= icapReply
->header
.hasListMember(Http::HdrType::ALLOW
, "trailers", ',');
1136 // ICAP Trailer specs require us to reject transactions having either Trailer
1137 // header or Allow:trailers
1138 Must((promisesToSendTrailer
== supportsTrailers
) || (!promisesToSendTrailer
&& supportsTrailers
));
1139 if (promisesToSendTrailer
&& !trailers
.size())
1140 debugs(93, DBG_IMPORTANT
, "ERROR: ICAP Trailer response header field must not be empty (salvaged)");
1141 return promisesToSendTrailer
;
1144 void Adaptation::Icap::ModXact::decideOnParsingBody()
1146 if (expectHttpBody()) {
1147 debugs(93, 5, HERE
<< "expecting a body");
1148 state
.parsing
= State::psBody
;
1149 replyHttpBodySize
= 0;
1150 bodyParser
= new Http1::TeChunkedParser
;
1151 bodyParser
->parseExtensionValuesWith(&extensionParser
);
1152 makeAdaptedBodyPipe("adapted response from the ICAP server");
1153 Must(state
.sending
== State::sendingAdapted
);
1155 debugs(93, 5, HERE
<< "not expecting a body");
1157 state
.parsing
= State::psIcapTrailer
;
1164 void Adaptation::Icap::ModXact::parseBody()
1166 Must(state
.parsing
== State::psBody
);
1169 debugs(93, 5, "have " << readBuf
.length() << " body bytes to parse");
1171 // the parser will throw on errors
1172 BodyPipeCheckout
bpc(*adapted
.body_pipe
);
1173 bodyParser
->setPayloadBuffer(&bpc
.buf
);
1174 const bool parsed
= bodyParser
->parse(readBuf
);
1175 readBuf
= bodyParser
->remaining(); // sync buffers after parse
1178 debugs(93, 5, "have " << readBuf
.length() << " body bytes after parsed all: " << parsed
);
1179 replyHttpBodySize
+= adapted
.body_pipe
->buf().contentSize();
1181 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
1182 // TODO: do we really need this if we disable when sending headers?
1183 if (adapted
.body_pipe
->buf().contentSize() > 0) { // parsed something sometime
1184 disableRepeats("sent adapted content");
1185 disableBypass("sent adapted content", true);
1189 if (state
.readyForUob
&& extensionParser
.sawUseOriginalBody())
1190 prepPartialBodyEchoing(extensionParser
.useOriginalBody());
1192 stopSending(true); // the parser succeeds only if all parsed data fits
1194 state
.parsing
= State::psIcapTrailer
;
1200 debugs(93,3,HERE
<< this << " needsMoreData = " << bodyParser
->needsMoreData());
1202 if (bodyParser
->needsMoreData()) {
1203 debugs(93,3,HERE
<< this);
1204 Must(mayReadMore());
1208 if (bodyParser
->needsMoreSpace()) {
1209 Must(!doneSending()); // can hope for more space
1210 Must(adapted
.body_pipe
->buf().contentSize() > 0); // paranoid
1211 // TODO: there should be a timeout in case the sink is broken
1212 // or cannot consume partial content (while we need more space)
1216 void Adaptation::Icap::ModXact::stopParsing(const bool checkUnparsedData
)
1218 if (state
.parsing
== State::psDone
)
1221 if (checkUnparsedData
)
1222 Must(readBuf
.isEmpty());
1224 debugs(93, 7, "will no longer parse" << status());
1227 bodyParser
= nullptr;
1229 delete trailerParser
;
1230 trailerParser
= nullptr;
1232 state
.parsing
= State::psDone
;
1235 // HTTP side added virgin body data
1236 void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer
)
1240 if (state
.sending
== State::sendingVirgin
)
1244 // HTTP side sent us all virgin info
1245 void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer
)
1247 Must(virgin
.body_pipe
->productionEnded());
1249 // push writer and sender in case we were waiting for the last-chunk
1252 if (state
.sending
== State::sendingVirgin
)
1256 // body producer aborted, but the initiator may still want to know
1257 // the answer, even though the HTTP message has been truncated
1258 void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer
)
1260 Must(virgin
.body_pipe
->productionEnded());
1262 // push writer and sender in case we were waiting for the last-chunk
1265 if (state
.sending
== State::sendingVirgin
)
1269 // adapted body consumer wants more adapted data and
1270 // possibly freed some buffer space
1271 void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
1273 if (state
.sending
== State::sendingVirgin
)
1275 else if (state
.sending
== State::sendingAdapted
)
1278 Must(state
.sending
== State::sendingUndecided
);
1281 // adapted body consumer aborted
1282 void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer
)
1284 detailError(ERR_DETAIL_ICAP_XACT_BODY_CONSUMER_ABORT
);
1285 mustStop("adapted body consumer aborted");
1288 Adaptation::Icap::ModXact::~ModXact()
1291 delete trailerParser
;
1295 void Adaptation::Icap::ModXact::swanSong()
1297 debugs(93, 5, HERE
<< "swan sings" << status());
1302 if (theInitiator
.set()) // we have not sent the answer to the initiator
1303 detailError(ERR_DETAIL_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
!= NULL
&& adaptHistoryId
>= 0)
1308 ah
->recordXactFinish(adaptHistoryId
);
1310 Adaptation::Icap::Xaction::swanSong();
1313 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
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
!= NULL
); // 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 if (adapted_reply_
) {
1342 al
.reply
= adapted_reply_
;
1343 HTTPMSGLOCK(al
.reply
);
1347 if (h
->rfc931
.size())
1348 al
.cache
.rfc931
= h
->rfc931
.termedBuf();
1351 if (h
->ssluser
.size())
1352 al
.cache
.ssluser
= h
->ssluser
.termedBuf();
1354 al
.cache
.code
= h
->logType
;
1356 const Http::Message
*virgin_msg
= dynamic_cast<HttpReply
*>(virgin
.header
);
1358 virgin_msg
= virgin_request_
;
1359 assert(virgin_msg
!= virgin
.cause
);
1360 al
.http
.clientRequestSz
.header
= virgin_msg
->hdr_sz
;
1361 if (virgin_msg
->body_pipe
!= NULL
)
1362 al
.http
.clientRequestSz
.payloadData
= virgin_msg
->body_pipe
->producedSize();
1364 // leave al.icap.bodyBytesRead negative if no body
1365 if (replyHttpHeaderSize
>= 0 || replyHttpBodySize
>= 0) {
1366 const int64_t zero
= 0; // to make max() argument types the same
1367 const uint64_t headerSize
= max(zero
, replyHttpHeaderSize
);
1368 const uint64_t bodySize
= max(zero
, replyHttpBodySize
);
1369 al
.icap
.bodyBytesRead
= headerSize
+ bodySize
;
1370 al
.http
.clientReplySz
.header
= headerSize
;
1371 al
.http
.clientReplySz
.payloadData
= bodySize
;
1374 if (adapted_reply_
) {
1375 al
.http
.code
= adapted_reply_
->sline
.status();
1376 al
.http
.content_type
= adapted_reply_
->content_type
.termedBuf();
1377 if (replyHttpBodySize
>= 0)
1378 al
.cache
.highOffset
= replyHttpBodySize
;
1379 //don't set al.cache.objectSize because it hasn't exist yet
1383 adapted_reply_
->header
.packInto(&mb
);
1384 al
.headers
.reply
= xstrdup(mb
.buf
);
1387 prepareLogWithRequestDetails(adapted_request_
, alep
);
1388 Xaction::finalizeLogInfo();
1391 void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf
&buf
)
1393 char ntoabuf
[MAX_IPSTRLEN
];
1395 * XXX These should use HttpHdr interfaces instead of Printfs
1397 const Adaptation::ServiceConfig
&s
= service().cfg();
1398 buf
.appendf("%s " SQUIDSTRINGPH
" ICAP/1.0\r\n", s
.methodStr(), SQUIDSTRINGPRINT(s
.uri
));
1399 buf
.appendf("Host: " SQUIDSTRINGPH
":%d\r\n", SQUIDSTRINGPRINT(s
.host
), s
.port
);
1400 buf
.appendf("Date: %s\r\n", mkrfc1123(squid_curtime
));
1402 if (!TheConfig
.reuse_connections
)
1403 buf
.appendf("Connection: close\r\n");
1405 const HttpRequest
*request
= &virginRequest();
1407 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1409 if (virgin
.header
->header
.has(Http::HdrType::PROXY_AUTHENTICATE
)) {
1410 String vh
=virgin
.header
->header
.getById(Http::HdrType::PROXY_AUTHENTICATE
);
1411 buf
.appendf("Proxy-Authenticate: " SQUIDSTRINGPH
"\r\n",SQUIDSTRINGPRINT(vh
));
1414 if (virgin
.header
->header
.has(Http::HdrType::PROXY_AUTHORIZATION
)) {
1415 String vh
=virgin
.header
->header
.getById(Http::HdrType::PROXY_AUTHORIZATION
);
1416 buf
.appendf("Proxy-Authorization: " SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(vh
));
1417 } else if (request
->extacl_user
.size() > 0 && request
->extacl_passwd
.size() > 0) {
1418 struct base64_encode_ctx ctx
;
1419 base64_encode_init(&ctx
);
1420 char base64buf
[base64_encode_len(MAX_LOGIN_SZ
)];
1421 size_t resultLen
= base64_encode_update(&ctx
, base64buf
, request
->extacl_user
.size(), reinterpret_cast<const uint8_t*>(request
->extacl_user
.rawBuf()));
1422 resultLen
+= base64_encode_update(&ctx
, base64buf
+resultLen
, 1, reinterpret_cast<const uint8_t*>(":"));
1423 resultLen
+= base64_encode_update(&ctx
, base64buf
+resultLen
, request
->extacl_passwd
.size(), reinterpret_cast<const uint8_t*>(request
->extacl_passwd
.rawBuf()));
1424 resultLen
+= base64_encode_final(&ctx
, base64buf
+resultLen
);
1425 buf
.appendf("Proxy-Authorization: Basic %.*s\r\n", (int)resultLen
, base64buf
);
1428 // share the cross-transactional database records if needed
1429 if (Adaptation::Config::masterx_shared_name
) {
1430 Adaptation::History::Pointer ah
= request
->adaptHistory(false);
1433 if (ah
->getXxRecord(name
, value
)) {
1434 buf
.appendf(SQUIDSTRINGPH
": " SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(name
), SQUIDSTRINGPRINT(value
));
1439 buf
.append("Encapsulated: ", 14);
1445 // build HTTP request header, if any
1446 ICAP::Method m
= s
.method
;
1448 // to simplify, we could assume that request is always available
1451 if (ICAP::methodRespmod
== m
)
1452 encapsulateHead(buf
, "req-hdr", httpBuf
, request
);
1453 else if (ICAP::methodReqmod
== m
)
1454 encapsulateHead(buf
, "req-hdr", httpBuf
, virgin
.header
);
1457 if (ICAP::methodRespmod
== m
)
1458 if (const Http::Message
*prime
= virgin
.header
)
1459 encapsulateHead(buf
, "res-hdr", httpBuf
, prime
);
1461 if (!virginBody
.expected())
1462 buf
.appendf("null-body=%d", (int) httpBuf
.contentSize());
1463 else if (ICAP::methodReqmod
== m
)
1464 buf
.appendf("req-body=%d", (int) httpBuf
.contentSize());
1466 buf
.appendf("res-body=%d", (int) httpBuf
.contentSize());
1468 buf
.append(ICAP::crlf
, 2); // terminate Encapsulated line
1470 if (preview
.enabled()) {
1471 buf
.appendf("Preview: %d\r\n", (int)preview
.ad());
1472 if (!virginBody
.expected()) // there is no body to preview
1473 finishNullOrEmptyBodyPreview(httpBuf
);
1476 makeAllowHeader(buf
);
1478 if (TheConfig
.send_client_ip
&& request
) {
1479 Ip::Address client_addr
;
1480 #if FOLLOW_X_FORWARDED_FOR
1481 if (TheConfig
.use_indirect_client
) {
1482 client_addr
= request
->indirect_client_addr
;
1485 client_addr
= request
->client_addr
;
1486 if (!client_addr
.isAnyAddr() && !client_addr
.isNoAddr())
1487 buf
.appendf("X-Client-IP: %s\r\n", client_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
1490 if (TheConfig
.send_username
&& request
)
1491 makeUsernameHeader(request
, buf
);
1493 // Adaptation::Config::metaHeaders
1494 for (auto h
: Adaptation::Config::metaHeaders
) {
1495 HttpRequest
*r
= virgin
.cause
?
1496 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
1499 HttpReply
*reply
= dynamic_cast<HttpReply
*>(virgin
.header
);
1502 if (h
->match(r
, reply
, alMaster
, matched
)) {
1503 buf
.append(h
->key().rawContent(), h
->key().length());
1504 buf
.append(": ", 2);
1505 buf
.append(matched
.rawContent(), matched
.length());
1506 buf
.append("\r\n", 2);
1507 Adaptation::History::Pointer ah
= request
->adaptHistory(false);
1509 if (ah
->metaHeaders
== NULL
)
1510 ah
->metaHeaders
= new NotePairs
;
1511 if (!ah
->metaHeaders
->hasPair(h
->key(), matched
))
1512 ah
->metaHeaders
->add(h
->key(), matched
);
1517 // fprintf(stderr, "%s\n", buf.content());
1519 buf
.append(ICAP::crlf
, 2); // terminate ICAP header
1521 // fill icapRequest for logging
1522 Must(icapRequest
->parseCharBuf(buf
.content(), buf
.contentSize()));
1524 // start ICAP request body with encapsulated HTTP headers
1525 buf
.append(httpBuf
.content(), httpBuf
.contentSize());
1530 // decides which Allow values to write and updates the request buffer
1531 void Adaptation::Icap::ModXact::makeAllowHeader(MemBuf
&buf
)
1533 const bool allow204in
= preview
.enabled(); // TODO: add shouldAllow204in()
1534 const bool allow204out
= state
.allowedPostview204
= shouldAllow204();
1535 const bool allow206in
= state
.allowedPreview206
= shouldAllow206in();
1536 const bool allow206out
= state
.allowedPostview206
= shouldAllow206out();
1537 const bool allowTrailers
= true; // TODO: make configurable
1539 debugs(93, 9, "Allows: " << allow204in
<< allow204out
<<
1540 allow206in
<< allow206out
<< allowTrailers
);
1542 const bool allow204
= allow204in
|| allow204out
;
1543 const bool allow206
= allow206in
|| allow206out
;
1545 if ((allow204
|| allow206
) && virginBody
.expected())
1546 virginBodySending
.plan(); // if there is a virgin body, plan to send it
1548 // writing Preview:... means we will honor 204 inside preview
1549 // writing Allow/204 means we will honor 204 outside preview
1550 // writing Allow:206 means we will honor 206 inside preview
1551 // writing Allow:204,206 means we will honor 206 outside preview
1552 if (allow204
|| allow206
|| allowTrailers
) {
1553 buf
.appendf("Allow: ");
1555 buf
.appendf("204, ");
1557 buf
.appendf("206, ");
1559 buf
.appendf("trailers");
1560 buf
.appendf("\r\n");
1564 void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest
*request
, MemBuf
&buf
)
1567 struct base64_encode_ctx ctx
;
1568 base64_encode_init(&ctx
);
1570 const char *value
= NULL
;
1571 if (request
->auth_user_request
!= NULL
) {
1572 value
= request
->auth_user_request
->username();
1573 } else if (request
->extacl_user
.size() > 0) {
1574 value
= request
->extacl_user
.termedBuf();
1578 if (TheConfig
.client_username_encode
) {
1579 char base64buf
[base64_encode_len(MAX_LOGIN_SZ
)];
1580 size_t resultLen
= base64_encode_update(&ctx
, base64buf
, strlen(value
), reinterpret_cast<const uint8_t*>(value
));
1581 resultLen
+= base64_encode_final(&ctx
, base64buf
+resultLen
);
1582 buf
.appendf("%s: %.*s\r\n", TheConfig
.client_username_header
, (int)resultLen
, base64buf
);
1584 buf
.appendf("%s: %s\r\n", TheConfig
.client_username_header
, value
);
1590 Adaptation::Icap::ModXact::encapsulateHead(MemBuf
&icapBuf
, const char *section
, MemBuf
&httpBuf
, const Http::Message
*head
)
1592 // update ICAP header
1593 icapBuf
.appendf("%s=%d, ", section
, (int) httpBuf
.contentSize());
1596 Http::MessagePointer headClone
;
1598 if (const HttpRequest
* old_request
= dynamic_cast<const HttpRequest
*>(head
)) {
1599 HttpRequest::Pointer
new_request(new HttpRequest(old_request
->masterXaction
));
1600 // copy the request-line details
1601 new_request
->method
= old_request
->method
;
1602 new_request
->url
= old_request
->url
;
1603 new_request
->http_ver
= old_request
->http_ver
;
1604 headClone
= new_request
.getRaw();
1605 } else if (const HttpReply
*old_reply
= dynamic_cast<const HttpReply
*>(head
)) {
1606 HttpReply::Pointer
new_reply(new HttpReply
);
1607 new_reply
->sline
= old_reply
->sline
;
1608 headClone
= new_reply
.getRaw();
1611 headClone
->inheritProperties(head
);
1613 HttpHeaderPos pos
= HttpHeaderInitPos
;
1614 while (HttpHeaderEntry
* p_head_entry
= head
->header
.getEntry(&pos
))
1615 headClone
->header
.addEntry(p_head_entry
->clone());
1619 // remove all hop-by-hop headers from the clone
1620 headClone
->header
.delById(Http::HdrType::PROXY_AUTHENTICATE
);
1621 headClone
->header
.removeHopByHopEntries();
1623 // pack polished HTTP header
1624 packHead(httpBuf
, headClone
.getRaw());
1626 // headClone unlocks and, hence, deletes the message we packed
1630 Adaptation::Icap::ModXact::packHead(MemBuf
&httpBuf
, const Http::Message
*head
)
1632 head
->packInto(&httpBuf
, true);
1635 // decides whether to offer a preview and calculates its size
1636 void Adaptation::Icap::ModXact::decideOnPreview()
1638 if (!TheConfig
.preview_enable
) {
1639 debugs(93, 5, HERE
<< "preview disabled by squid.conf");
1643 const SBuf
urlPath(virginRequest().url
.path());
1645 if (!service().wantsPreview(urlPath
, wantedSize
)) {
1646 debugs(93, 5, "should not offer preview for " << urlPath
);
1650 // we decided to do preview, now compute its size
1652 // cannot preview more than we can backup
1653 size_t ad
= min(wantedSize
, TheBackupLimit
);
1655 if (!virginBody
.expected())
1657 else if (virginBody
.knownSize())
1658 ad
= min(static_cast<uint64_t>(ad
), virginBody
.size()); // not more than we have
1660 debugs(93, 5, HERE
<< "should offer " << ad
<< "-byte preview " <<
1661 "(service wanted " << wantedSize
<< ")");
1664 Must(preview
.enabled());
1667 // decides whether to allow 204 responses
1668 bool Adaptation::Icap::ModXact::shouldAllow204()
1670 if (!service().allows204())
1673 return canBackupEverything();
1676 // decides whether to allow 206 responses in some mode
1677 bool Adaptation::Icap::ModXact::shouldAllow206any()
1679 return TheConfig
.allow206_enable
&& service().allows206() &&
1680 virginBody
.expected(); // no need for 206 without a body
1683 // decides whether to allow 206 responses in preview mode
1684 bool Adaptation::Icap::ModXact::shouldAllow206in()
1686 return shouldAllow206any() && preview
.enabled();
1689 // decides whether to allow 206 responses outside of preview
1690 bool Adaptation::Icap::ModXact::shouldAllow206out()
1692 return shouldAllow206any() && canBackupEverything();
1695 // used by shouldAllow204 and decideOnRetries
1696 bool Adaptation::Icap::ModXact::canBackupEverything() const
1698 if (!virginBody
.expected())
1699 return true; // no body means no problems with backup
1701 // if there is a body, check whether we can backup it all
1703 if (!virginBody
.knownSize())
1706 // or should we have a different backup limit?
1707 // note that '<' allows for 0-termination of the "full" backup buffer
1708 return virginBody
.size() < TheBackupLimit
;
1711 // Decide whether this transaction can be retried if pconn fails
1712 // Must be called after decideOnPreview and before openConnection()
1713 void Adaptation::Icap::ModXact::decideOnRetries()
1716 return; // no, already decided
1718 if (preview
.enabled())
1719 return; // yes, because preview provides enough guarantees
1721 if (canBackupEverything())
1722 return; // yes, because we can back everything up
1724 disableRetries(); // no, because we cannot back everything up
1727 // Normally, the body-writing code handles preview body. It can deal with
1728 // bodies of unexpected size, including those that turn out to be empty.
1729 // However, that code assumes that the body was expected and body control
1730 // structures were initialized. This is not the case when there is no body
1731 // or the body is known to be empty, because the virgin message will lack a
1732 // body_pipe. So we handle preview of null-body and zero-size bodies here.
1733 void Adaptation::Icap::ModXact::finishNullOrEmptyBodyPreview(MemBuf
&)
1735 Must(!virginBodyWriting
.active()); // one reason we handle it here
1736 Must(!virgin
.body_pipe
); // another reason we handle it here
1737 Must(!preview
.ad());
1739 // do not add last-chunk because our Encapsulated header says null-body
1740 // addLastRequestChunk(buf);
1741 preview
.wrote(0, true);
1743 Must(preview
.done());
1744 Must(preview
.ieof());
1747 void Adaptation::Icap::ModXact::fillPendingStatus(MemBuf
&buf
) const
1749 Adaptation::Icap::Xaction::fillPendingStatus(buf
);
1751 if (state
.serviceWaiting
)
1754 if (virgin
.body_pipe
!= NULL
)
1757 if (haveConnection() && !doneReading())
1760 if (!state
.doneWriting() && state
.writing
!= State::writingInit
)
1761 buf
.appendf("w(%d)", state
.writing
);
1763 if (preview
.enabled()) {
1764 if (!preview
.done())
1765 buf
.appendf("P(%d)", (int) preview
.debt());
1768 if (virginBodySending
.active())
1771 if (!state
.doneParsing() && state
.parsing
!= State::psIcapHeader
)
1772 buf
.appendf("p(%d)", state
.parsing
);
1774 if (!doneSending() && state
.sending
!= State::sendingUndecided
)
1775 buf
.appendf("S(%d)", state
.sending
);
1777 if (state
.readyForUob
)
1783 if (protectGroupBypass
)
1787 void Adaptation::Icap::ModXact::fillDoneStatus(MemBuf
&buf
) const
1789 Adaptation::Icap::Xaction::fillDoneStatus(buf
);
1791 if (!virgin
.body_pipe
)
1794 if (state
.doneWriting())
1797 if (preview
.enabled()) {
1799 buf
.appendf("P%s", preview
.ieof() ? "(ieof)" : "");
1805 if (state
.doneParsing())
1812 bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section
) const
1814 return !icapReply
->header
.getByNameListMember("Encapsulated",
1815 section
, ',').isEmpty();
1818 // calculate whether there is a virgin HTTP body and
1819 // whether its expected size is known
1820 // TODO: rename because we do not just estimate
1821 void Adaptation::Icap::ModXact::estimateVirginBody()
1823 // note: lack of size info may disable previews and 204s
1825 Http::Message
*msg
= virgin
.header
;
1828 HttpRequestMethod method
;
1831 method
= virgin
.cause
->method
;
1832 else if (HttpRequest
*req
= dynamic_cast<HttpRequest
*>(msg
))
1833 method
= req
->method
;
1835 method
= Http::METHOD_NONE
;
1838 // expectingBody returns true for zero-sized bodies, but we will not
1839 // get a pipe for that body, so we treat the message as bodyless
1840 if (method
!= Http::METHOD_NONE
&& msg
->expectingBody(method
, size
) && size
) {
1841 debugs(93, 6, HERE
<< "expects virgin body from " <<
1842 virgin
.body_pipe
<< "; size: " << size
);
1844 virginBody
.expect(size
);
1845 virginBodyWriting
.plan();
1847 // sign up as a body consumer
1848 Must(msg
->body_pipe
!= NULL
);
1849 Must(msg
->body_pipe
== virgin
.body_pipe
);
1850 Must(virgin
.body_pipe
->setConsumerIfNotLate(this));
1852 // make sure TheBackupLimit is in-sync with the buffer size
1853 Must(TheBackupLimit
<= static_cast<size_t>(msg
->body_pipe
->buf().max_capacity
));
1855 debugs(93, 6, HERE
<< "does not expect virgin body");
1856 Must(msg
->body_pipe
== NULL
);
1861 void Adaptation::Icap::ModXact::makeAdaptedBodyPipe(const char *what
)
1863 Must(!adapted
.body_pipe
);
1864 Must(!adapted
.header
->body_pipe
);
1865 adapted
.header
->body_pipe
= new BodyPipe(this);
1866 adapted
.body_pipe
= adapted
.header
->body_pipe
;
1867 debugs(93, 7, HERE
<< "will supply " << what
<< " via " <<
1868 adapted
.body_pipe
<< " pipe");
1871 // TODO: Move SizedEstimate and Preview elsewhere
1873 Adaptation::Icap::SizedEstimate::SizedEstimate()
1874 : theData(dtUnexpected
)
1877 void Adaptation::Icap::SizedEstimate::expect(int64_t aSize
)
1879 theData
= (aSize
>= 0) ? aSize
: (int64_t)dtUnknown
;
1882 bool Adaptation::Icap::SizedEstimate::expected() const
1884 return theData
!= dtUnexpected
;
1887 bool Adaptation::Icap::SizedEstimate::knownSize() const
1890 return theData
!= dtUnknown
;
1893 uint64_t Adaptation::Icap::SizedEstimate::size() const
1896 return static_cast<uint64_t>(theData
);
1899 Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided
)
1902 void Adaptation::Icap::VirginBodyAct::plan()
1905 Must(!theStart
); // not started
1906 theState
= stActive
;
1909 void Adaptation::Icap::VirginBodyAct::disable()
1911 theState
= stDisabled
;
1914 void Adaptation::Icap::VirginBodyAct::progress(size_t size
)
1917 #if SIZEOF_SIZE_T > 4
1918 /* always true for smaller size_t's */
1919 Must(static_cast<int64_t>(size
) >= 0);
1921 theStart
+= static_cast<int64_t>(size
);
1924 uint64_t Adaptation::Icap::VirginBodyAct::offset() const
1927 return static_cast<uint64_t>(theStart
);
1930 Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled
)
1933 void Adaptation::Icap::Preview::enable(size_t anAd
)
1935 // TODO: check for anAd not exceeding preview size limit
1938 theState
= stWriting
;
1941 bool Adaptation::Icap::Preview::enabled() const
1943 return theState
!= stDisabled
;
1946 size_t Adaptation::Icap::Preview::ad() const
1952 bool Adaptation::Icap::Preview::done() const
1955 return theState
>= stIeof
;
1958 bool Adaptation::Icap::Preview::ieof() const
1961 return theState
== stIeof
;
1964 size_t Adaptation::Icap::Preview::debt() const
1967 return done() ? 0 : (theAd
- theWritten
);
1970 void Adaptation::Icap::Preview::wrote(size_t size
, bool wroteEof
)
1976 Must(theWritten
<= theAd
);
1979 theState
= stIeof
; // written size is irrelevant
1980 else if (theWritten
>= theAd
)
1984 bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf
&mb
) const
1986 if (virgin
.header
== NULL
)
1989 virgin
.header
->firstLineBuf(mb
);
1994 void Adaptation::Icap::ModXact::detailError(int errDetail
)
1996 HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
1997 // if no adapted request, update virgin (and inherit its properties later)
1998 // TODO: make this and HttpRequest::detailError constant, like adaptHistory
2000 request
= const_cast<HttpRequest
*>(&virginRequest());
2003 request
->detailError(ERR_ICAP_FAILURE
, errDetail
);
2006 void Adaptation::Icap::ModXact::clearError()
2008 HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
2009 // if no adapted request, update virgin (and inherit its properties later)
2011 request
= const_cast<HttpRequest
*>(&virginRequest());
2014 request
->clearError();
2017 void Adaptation::Icap::ModXact::updateSources()
2019 Must(adapted
.header
);
2020 adapted
.header
->sources
|= (service().cfg().connectionEncryption
? Http::Message::srcIcaps
: Http::Message::srcIcap
);
2023 /* Adaptation::Icap::ModXactLauncher */
2025 Adaptation::Icap::ModXactLauncher::ModXactLauncher(Http::Message
*virginHeader
, HttpRequest
*virginCause
, AccessLogEntry::Pointer
&alp
, Adaptation::ServicePointer aService
):
2026 AsyncJob("Adaptation::Icap::ModXactLauncher"),
2027 Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", aService
),
2030 virgin
.setHeader(virginHeader
);
2031 virgin
.setCause(virginCause
);
2032 updateHistory(true);
2035 Adaptation::Icap::Xaction
*Adaptation::Icap::ModXactLauncher::createXaction()
2037 Adaptation::Icap::ServiceRep::Pointer s
=
2038 dynamic_cast<Adaptation::Icap::ServiceRep
*>(theService
.getRaw());
2040 return new Adaptation::Icap::ModXact(virgin
.header
, virgin
.cause
, al
, s
);
2043 void Adaptation::Icap::ModXactLauncher::swanSong()
2045 debugs(93, 5, HERE
<< "swan sings");
2046 updateHistory(false);
2047 Adaptation::Icap::Launcher::swanSong();
2050 void Adaptation::Icap::ModXactLauncher::updateHistory(bool doStart
)
2052 HttpRequest
*r
= virgin
.cause
?
2053 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
2055 // r should never be NULL but we play safe; TODO: add Should()
2057 Adaptation::Icap::History::Pointer h
= r
->icapHistory();
2060 h
->start("ICAPModXactLauncher");
2062 h
->stop("ICAPModXactLauncher");
2067 bool Adaptation::Icap::TrailerParser::parse(const char *buf
, int len
, int atEnd
, Http::StatusCode
*error
) {
2068 Http::ContentLengthInterpreter clen
;
2069 // RFC 7230 section 4.1.2: MUST NOT generate a trailer that contains
2070 // a field necessary for message framing (e.g., Transfer-Encoding and Content-Length)
2071 clen
.applyTrailerRules();
2072 const int parsed
= trailer
.parse(buf
, len
, atEnd
, hdr_sz
, clen
);
2074 *error
= Http::scInvalidHeader
; // TODO: should we add a new Http::scInvalidTrailer?
2079 Adaptation::Icap::ChunkExtensionValueParser::parse(Tokenizer
&tok
, const SBuf
&extName
)
2081 if (extName
== UseOriginalBodyName
) {
2082 useOriginalBody_
= tok
.udec64("use-original-body");
2083 assert(useOriginalBody_
>= 0);
2085 Ignore(tok
, extName
);