2 * DEBUG: section 93 ICAP (RFC 3507) Client
6 #include "AccessLogEntry.h"
7 #include "adaptation/Answer.h"
8 #include "adaptation/History.h"
9 #include "adaptation/icap/Client.h"
10 #include "adaptation/icap/Config.h"
11 #include "adaptation/icap/History.h"
12 #include "adaptation/icap/Launcher.h"
13 #include "adaptation/icap/ModXact.h"
14 #include "adaptation/icap/ServiceRep.h"
15 #include "adaptation/Initiator.h"
16 #include "auth/UserRequest.h"
17 #include "base/TextException.h"
19 #include "ChunkedCodingParser.h"
21 #include "comm/Connection.h"
22 #include "err_detail_type.h"
23 #include "HttpHeaderTools.h"
25 #include "HttpReply.h"
26 #include "HttpRequest.h"
27 #include "SquidTime.h"
30 // flow and terminology:
31 // HTTP| --> receive --> encode --> write --> |network
32 // end | <-- send <-- parse <-- read <-- |end
34 // TODO: replace gotEncapsulated() with something faster; we call it often
36 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXact
);
37 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXactLauncher
);
39 static const size_t TheBackupLimit
= BodyPipe::MaxCapacity
;
41 Adaptation::Icap::ModXact::State::State()
43 memset(this, 0, sizeof(*this));
46 Adaptation::Icap::ModXact::ModXact(HttpMsg
*virginHeader
,
47 HttpRequest
*virginCause
, Adaptation::Icap::ServiceRep::Pointer
&aService
):
48 AsyncJob("Adaptation::Icap::ModXact"),
49 Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", aService
),
52 canStartBypass(false), // too early
53 protectGroupBypass(true),
54 replyHttpHeaderSize(-1),
55 replyHttpBodySize(-1),
60 virgin
.setHeader(virginHeader
); // sets virgin.body_pipe if needed
61 virgin
.setCause(virginCause
); // may be NULL
63 // adapted header and body are initialized when we parse them
65 // writing and reading ends are handled by Adaptation::Icap::Xaction
68 // nothing to do because we are using temporary buffers
70 // parsing; TODO: do not set until we parse, see ICAPOptXact
71 icapReply
= new HttpReply
;
72 icapReply
->protoPrefix
= "ICAP/"; // TODO: make an IcapReply class?
74 debugs(93,7, HERE
<< "initialized." << status());
77 // initiator wants us to start
78 void Adaptation::Icap::ModXact::start()
80 Adaptation::Icap::Xaction::start();
82 // reserve an adaptation history slot (attempts are known at this time)
83 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
85 adaptHistoryId
= ah
->recordXactStart(service().cfg().key
, icap_tr_start
, attempts
> 1);
87 estimateVirginBody(); // before virgin disappears!
89 canStartBypass
= service().cfg().bypass
;
91 // it is an ICAP violation to send request to a service w/o known OPTIONS
92 // and the service may is too busy for us: honor Max-Connections and such
93 if (service().up() && service().availableForNew())
99 void Adaptation::Icap::ModXact::waitForService()
102 Must(!state
.serviceWaiting
);
104 if (!service().up()) {
105 AsyncCall::Pointer call
= JobCallback(93,5,
106 ConnWaiterDialer
, this, Adaptation::Icap::ModXact::noteServiceReady
);
108 service().callWhenReady(call
);
109 comment
= "to be up";
111 //The service is unavailable because of max-connection or other reason
113 if (service().cfg().onOverload
!= srvWait
) {
114 // The service is overloaded, but waiting to be available prohibited by
115 // user configuration (onOverload is set to "block" or "bypass")
116 if (service().cfg().onOverload
== srvBlock
)
117 disableBypass("not available", true);
118 else //if (service().cfg().onOverload == srvBypass)
119 canStartBypass
= true;
122 disableRepeats("ICAP service is not available");
124 debugs(93, 7, HERE
<< "will not wait for the service to be available" <<
127 throw TexcHere("ICAP service is not available");
130 AsyncCall::Pointer call
= JobCallback(93,5,
131 ConnWaiterDialer
, this, Adaptation::Icap::ModXact::noteServiceAvailable
);
132 service().callWhenAvailable(call
, state
.waitedForService
);
133 comment
= "to be available";
136 debugs(93, 7, HERE
<< "will wait for the service " << comment
<< status());
137 state
.serviceWaiting
= true; // after callWhenReady() which may throw
138 state
.waitedForService
= true;
141 void Adaptation::Icap::ModXact::noteServiceReady()
143 Must(state
.serviceWaiting
);
144 state
.serviceWaiting
= false;
146 if (!service().up()) {
148 disableRepeats("ICAP service is unusable");
149 throw TexcHere("ICAP service is unusable");
152 if (service().availableForOld())
158 void Adaptation::Icap::ModXact::noteServiceAvailable()
160 Must(state
.serviceWaiting
);
161 state
.serviceWaiting
= false;
163 if (service().up() && service().availableForOld())
169 void Adaptation::Icap::ModXact::startWriting()
171 state
.writing
= State::writingConnect
;
173 decideOnPreview(); // must be decided before we decideOnRetries
179 // connection with the ICAP service established
180 void Adaptation::Icap::ModXact::handleCommConnected()
182 Must(state
.writing
== State::writingConnect
);
184 startReading(); // wait for early errors from the ICAP server
189 makeRequestHeaders(requestBuf
);
190 debugs(93, 9, HERE
<< "will write" << status() << ":\n" <<
191 (requestBuf
.terminate(), requestBuf
.content()));
194 state
.writing
= State::writingHeaders
;
195 icap_tio_start
= current_time
;
196 scheduleWrite(requestBuf
);
199 void Adaptation::Icap::ModXact::handleCommWrote(size_t sz
)
201 debugs(93, 5, HERE
<< "Wrote " << sz
<< " bytes");
203 if (state
.writing
== State::writingHeaders
)
204 handleCommWroteHeaders();
206 handleCommWroteBody();
209 void Adaptation::Icap::ModXact::handleCommWroteHeaders()
211 Must(state
.writing
== State::writingHeaders
);
213 // determine next step
214 if (preview
.enabled()) {
216 decideWritingAfterPreview("zero-size");
218 state
.writing
= State::writingPreview
;
219 } else if (virginBody
.expected()) {
220 state
.writing
= State::writingPrime
;
229 void Adaptation::Icap::ModXact::writeMore()
231 debugs(93, 5, HERE
<< "checking whether to write more" << status());
233 if (writer
!= NULL
) // already writing something
236 switch (state
.writing
) {
238 case State::writingInit
: // waiting for service OPTIONS
239 Must(state
.serviceWaiting
);
241 case State::writingConnect
: // waiting for the connection to establish
243 case State::writingHeaders
: // waiting for the headers to be written
245 case State::writingPaused
: // waiting for the ICAP server response
247 case State::writingReallyDone
: // nothing more to write
250 case State::writingAlmostDone
: // was waiting for the last write
254 case State::writingPreview
:
258 case State::writingPrime
:
263 throw TexcHere("Adaptation::Icap::ModXact in bad writing state");
267 void Adaptation::Icap::ModXact::writePreviewBody()
269 debugs(93, 8, HERE
<< "will write Preview body from " <<
270 virgin
.body_pipe
<< status());
271 Must(state
.writing
== State::writingPreview
);
272 Must(virgin
.body_pipe
!= NULL
);
274 const size_t sizeMax
= (size_t)virgin
.body_pipe
->buf().contentSize();
275 const size_t size
= min(preview
.debt(), sizeMax
);
276 writeSomeBody("preview body", size
);
278 // change state once preview is written
281 decideWritingAfterPreview("body");
284 /// determine state.writing after we wrote the entire preview
285 void Adaptation::Icap::ModXact::decideWritingAfterPreview(const char *kind
)
287 if (preview
.ieof()) // nothing more to write
289 else if (state
.parsing
== State::psIcapHeader
) // did not get a reply yet
290 state
.writing
= State::writingPaused
; // wait for the ICAP server reply
292 stopWriting(true); // ICAP server reply implies no post-preview writing
294 debugs(93, 6, HERE
<< "decided on writing after " << kind
<< " preview" <<
298 void Adaptation::Icap::ModXact::writePrimeBody()
300 Must(state
.writing
== State::writingPrime
);
301 Must(virginBodyWriting
.active());
303 const size_t size
= (size_t)virgin
.body_pipe
->buf().contentSize();
304 writeSomeBody("prime virgin body", size
);
306 if (virginBodyEndReached(virginBodyWriting
)) {
307 debugs(93, 5, HERE
<< "wrote entire body");
312 void Adaptation::Icap::ModXact::writeSomeBody(const char *label
, size_t size
)
314 Must(!writer
&& state
.writing
< state
.writingAlmostDone
);
315 Must(virgin
.body_pipe
!= NULL
);
316 debugs(93, 8, HERE
<< "will write up to " << size
<< " bytes of " <<
319 MemBuf writeBuf
; // TODO: suggest a min size based on size and lastChunk
321 writeBuf
.init(); // note: we assume that last-chunk will fit
323 const size_t writableSize
= virginContentSize(virginBodyWriting
);
324 const size_t chunkSize
= min(writableSize
, size
);
327 debugs(93, 7, HERE
<< "will write " << chunkSize
<<
328 "-byte chunk of " << label
);
330 openChunk(writeBuf
, chunkSize
, false);
331 writeBuf
.append(virginContentData(virginBodyWriting
), chunkSize
);
332 closeChunk(writeBuf
);
334 virginBodyWriting
.progress(chunkSize
);
337 debugs(93, 7, HERE
<< "has no writable " << label
<< " content");
340 const bool wroteEof
= virginBodyEndReached(virginBodyWriting
);
341 bool lastChunk
= wroteEof
;
342 if (state
.writing
== State::writingPreview
) {
343 preview
.wrote(chunkSize
, wroteEof
); // even if wrote nothing
344 lastChunk
= lastChunk
|| preview
.done();
348 debugs(93, 8, HERE
<< "will write last-chunk of " << label
);
349 addLastRequestChunk(writeBuf
);
352 debugs(93, 7, HERE
<< "will write " << writeBuf
.contentSize()
353 << " raw bytes of " << label
);
355 if (writeBuf
.hasContent()) {
356 scheduleWrite(writeBuf
); // comm will free the chunk
362 void Adaptation::Icap::ModXact::addLastRequestChunk(MemBuf
&buf
)
364 const bool ieof
= state
.writing
== State::writingPreview
&& preview
.ieof();
365 openChunk(buf
, 0, ieof
);
369 void Adaptation::Icap::ModXact::openChunk(MemBuf
&buf
, size_t chunkSize
, bool ieof
)
371 buf
.Printf((ieof
? "%x; ieof\r\n" : "%x\r\n"), (int) chunkSize
);
374 void Adaptation::Icap::ModXact::closeChunk(MemBuf
&buf
)
376 buf
.append(ICAP::crlf
, 2); // chunk-terminating CRLF
379 const HttpRequest
&Adaptation::Icap::ModXact::virginRequest() const
381 const HttpRequest
*request
= virgin
.cause
?
382 virgin
.cause
: dynamic_cast<const HttpRequest
*>(virgin
.header
);
387 // did the activity reached the end of the virgin body?
388 bool Adaptation::Icap::ModXact::virginBodyEndReached(const Adaptation::Icap::VirginBodyAct
&act
) const
391 !act
.active() || // did all (assuming it was originally planned)
392 !virgin
.body_pipe
->expectMoreAfter(act
.offset()); // wont have more
395 // the size of buffered virgin body data available for the specified activity
396 // if this size is zero, we may be done or may be waiting for more data
397 size_t Adaptation::Icap::ModXact::virginContentSize(const Adaptation::Icap::VirginBodyAct
&act
) const
400 // asbolute start of unprocessed data
401 const uint64_t dataStart
= act
.offset();
402 // absolute end of buffered data
403 const uint64_t dataEnd
= virginConsumed
+ virgin
.body_pipe
->buf().contentSize();
404 Must(virginConsumed
<= dataStart
&& dataStart
<= dataEnd
);
405 return static_cast<size_t>(dataEnd
- dataStart
);
408 // pointer to buffered virgin body data available for the specified activity
409 const char *Adaptation::Icap::ModXact::virginContentData(const Adaptation::Icap::VirginBodyAct
&act
) const
412 const uint64_t dataStart
= act
.offset();
413 Must(virginConsumed
<= dataStart
);
414 return virgin
.body_pipe
->buf().content() + static_cast<size_t>(dataStart
-virginConsumed
);
417 void Adaptation::Icap::ModXact::virginConsume()
419 debugs(93, 9, HERE
<< "consumption guards: " << !virgin
.body_pipe
<< isRetriable
<<
420 isRepeatable
<< canStartBypass
<< protectGroupBypass
);
422 if (!virgin
.body_pipe
)
423 return; // nothing to consume
426 return; // do not consume if we may have to retry later
428 BodyPipe
&bp
= *virgin
.body_pipe
;
429 const bool wantToPostpone
= isRepeatable
|| canStartBypass
|| protectGroupBypass
;
431 // Why > 2? HttpState does not use the last bytes in the buffer
432 // because delayAwareRead() is arguably broken. See
433 // HttpStateData::maybeReadVirginBody for more details.
434 if (wantToPostpone
&& bp
.buf().spaceSize() > 2) {
435 // Postponing may increase memory footprint and slow the HTTP side
436 // down. Not postponing may increase the number of ICAP errors
437 // if the ICAP service fails. We may also use "potential" space to
438 // postpone more aggressively. Should the trade-off be configurable?
439 debugs(93, 8, HERE
<< "postponing consumption from " << bp
.status());
443 const size_t have
= static_cast<size_t>(bp
.buf().contentSize());
444 const uint64_t end
= virginConsumed
+ have
;
445 uint64_t offset
= end
;
447 debugs(93, 9, HERE
<< "max virgin consumption offset=" << offset
<<
448 " acts " << virginBodyWriting
.active() << virginBodySending
.active() <<
449 " consumed=" << virginConsumed
<<
450 " from " << virgin
.body_pipe
->status());
452 if (virginBodyWriting
.active())
453 offset
= min(virginBodyWriting
.offset(), offset
);
455 if (virginBodySending
.active())
456 offset
= min(virginBodySending
.offset(), offset
);
458 Must(virginConsumed
<= offset
&& offset
<= end
);
460 if (const size_t size
= static_cast<size_t>(offset
- virginConsumed
)) {
461 debugs(93, 8, HERE
<< "consuming " << size
<< " out of " << have
<<
462 " virgin body bytes");
464 virginConsumed
+= size
;
465 Must(!isRetriable
); // or we should not be consuming
466 disableRepeats("consumed content");
467 disableBypass("consumed content", true);
471 void Adaptation::Icap::ModXact::handleCommWroteBody()
476 // Called when we do not expect to call comm_write anymore.
477 // We may have a pending write though.
478 // If stopping nicely, we will just wait for that pending write, if any.
479 void Adaptation::Icap::ModXact::stopWriting(bool nicely
)
481 if (state
.writing
== State::writingReallyDone
)
484 if (writer
!= NULL
) {
486 debugs(93, 7, HERE
<< "will wait for the last write" << status());
487 state
.writing
= State::writingAlmostDone
; // may already be set
491 debugs(93, 3, HERE
<< "will NOT wait for the last write" << status());
493 // Comm does not have an interface to clear the writer callback nicely,
494 // but without clearing the writer we cannot recycle the connection.
495 // We prevent connection reuse and hope that we can handle a callback
496 // call at any time, usually in the middle of the destruction sequence!
497 // Somebody should add comm_remove_write_handler() to comm API.
498 reuseConnection
= false;
499 ignoreLastWrite
= true;
502 debugs(93, 7, HERE
<< "will no longer write" << status());
503 if (virginBodyWriting
.active()) {
504 virginBodyWriting
.disable();
507 state
.writing
= State::writingReallyDone
;
511 void Adaptation::Icap::ModXact::stopBackup()
513 if (!virginBodySending
.active())
516 debugs(93, 7, HERE
<< "will no longer backup" << status());
517 virginBodySending
.disable();
521 bool Adaptation::Icap::ModXact::doneAll() const
523 return Adaptation::Icap::Xaction::doneAll() && !state
.serviceWaiting
&&
525 doneReading() && state
.doneWriting();
528 void Adaptation::Icap::ModXact::startReading()
530 Must(haveConnection());
532 Must(!adapted
.header
);
533 Must(!adapted
.body_pipe
);
535 // we use the same buffer for headers and body and then consume headers
539 void Adaptation::Icap::ModXact::readMore()
541 if (reader
!= NULL
|| doneReading()) {
542 debugs(93,3,HERE
<< "returning from readMore because reader or doneReading()");
546 // do not fill readBuf if we have no space to store the result
547 if (adapted
.body_pipe
!= NULL
&&
548 !adapted
.body_pipe
->buf().hasPotentialSpace()) {
549 debugs(93,3,HERE
<< "not reading because ICAP reply pipe is full");
553 if (readBuf
.hasSpace())
556 debugs(93,3,HERE
<< "nothing to do because !readBuf.hasSpace()");
559 // comm module read a portion of the ICAP response for us
560 void Adaptation::Icap::ModXact::handleCommRead(size_t)
562 Must(!state
.doneParsing());
563 icap_tio_finish
= current_time
;
568 void Adaptation::Icap::ModXact::echoMore()
570 Must(state
.sending
== State::sendingVirgin
);
571 Must(adapted
.body_pipe
!= NULL
);
572 Must(virginBodySending
.active());
574 const size_t sizeMax
= virginContentSize(virginBodySending
);
575 debugs(93,5, HERE
<< "will echo up to " << sizeMax
<< " bytes from " <<
576 virgin
.body_pipe
->status());
577 debugs(93,5, HERE
<< "will echo up to " << sizeMax
<< " bytes to " <<
578 adapted
.body_pipe
->status());
581 const size_t size
= adapted
.body_pipe
->putMoreData(virginContentData(virginBodySending
), sizeMax
);
582 debugs(93,5, HERE
<< "echoed " << size
<< " out of " << sizeMax
<<
584 virginBodySending
.progress(size
);
585 disableRepeats("echoed content");
586 disableBypass("echoed content", true);
590 if (virginBodyEndReached(virginBodySending
)) {
591 debugs(93, 5, HERE
<< "echoed all" << status());
594 debugs(93, 5, HERE
<< "has " <<
595 virgin
.body_pipe
->buf().contentSize() << " bytes " <<
596 "and expects more to echo" << status());
597 // TODO: timeout if virgin or adapted pipes are broken
601 bool Adaptation::Icap::ModXact::doneSending() const
603 return state
.sending
== State::sendingDone
;
606 // stop (or do not start) sending adapted message body
607 void Adaptation::Icap::ModXact::stopSending(bool nicely
)
609 debugs(93, 7, HERE
<< "Enter stop sending ");
612 debugs(93, 7, HERE
<< "Proceed with stop sending ");
614 if (state
.sending
!= State::sendingUndecided
) {
615 debugs(93, 7, HERE
<< "will no longer send" << status());
616 if (adapted
.body_pipe
!= NULL
) {
617 virginBodySending
.disable();
618 // we may leave debts if we were echoing and the virgin
619 // body_pipe got exhausted before we echoed all planned bytes
620 const bool leftDebts
= adapted
.body_pipe
->needsMoreData();
621 stopProducingFor(adapted
.body_pipe
, nicely
&& !leftDebts
);
624 debugs(93, 7, HERE
<< "will not start sending" << status());
625 Must(!adapted
.body_pipe
);
628 state
.sending
= State::sendingDone
;
632 // should be called after certain state.writing or state.sending changes
633 void Adaptation::Icap::ModXact::checkConsuming()
635 // quit if we already stopped or are still using the pipe
636 if (!virgin
.body_pipe
|| !state
.doneConsumingVirgin())
639 debugs(93, 7, HERE
<< "will stop consuming" << status());
640 stopConsumingFrom(virgin
.body_pipe
);
643 void Adaptation::Icap::ModXact::parseMore()
645 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " bytes to parse" <<
647 debugs(93, 5, HERE
<< "\n" << readBuf
.content());
649 if (state
.parsingHeaders())
652 if (state
.parsing
== State::psBody
)
656 void Adaptation::Icap::ModXact::callException(const std::exception
&e
)
658 if (!canStartBypass
|| isRetriable
) {
660 if (const TextException
*te
= dynamic_cast<const TextException
*>(&e
))
661 detailError(ERR_DETAIL_EXCEPTION_START
+ te
->id());
663 detailError(ERR_DETAIL_EXCEPTION_OTHER
);
665 Adaptation::Icap::Xaction::callException(e
);
670 debugs(93, 3, HERE
<< "bypassing " << inCall
<< " exception: " <<
671 e
.what() << ' ' << status());
673 } catch (const TextException
&bypassTe
) {
674 detailError(ERR_DETAIL_EXCEPTION_START
+ bypassTe
.id());
675 Adaptation::Icap::Xaction::callException(bypassTe
);
676 } catch (const std::exception
&bypassE
) {
677 detailError(ERR_DETAIL_EXCEPTION_OTHER
);
678 Adaptation::Icap::Xaction::callException(bypassE
);
682 void Adaptation::Icap::ModXact::bypassFailure()
684 disableBypass("already started to bypass", false);
686 Must(!isRetriable
); // or we should not be bypassing
687 // TODO: should the same be enforced for isRepeatable? Check icap_repeat??
693 // end all activities associated with the ICAP server
697 stopWriting(true); // or should we force it?
698 if (haveConnection()) {
699 reuseConnection
= false; // be conservative
700 cancelRead(); // may not work; and we cannot stop connecting either
702 debugs(93, 7, HERE
<< "Warning: bypass failed to stop I/O" << status());
705 service().noteFailure(); // we are bypassing, but this is still a failure
708 void Adaptation::Icap::ModXact::disableBypass(const char *reason
, bool includingGroupBypass
)
710 if (canStartBypass
) {
711 debugs(93,7, HERE
<< "will never start bypass because " << reason
);
712 canStartBypass
= false;
714 if (protectGroupBypass
&& includingGroupBypass
) {
715 debugs(93,7, HERE
<< "not protecting group bypass because " << reason
);
716 protectGroupBypass
= false;
720 // note that allocation for echoing is done in handle204NoContent()
721 void Adaptation::Icap::ModXact::maybeAllocateHttpMsg()
723 if (adapted
.header
) // already allocated
726 if (gotEncapsulated("res-hdr")) {
727 adapted
.setHeader(new HttpReply
);
728 setOutcome(service().cfg().method
== ICAP::methodReqmod
?
729 xoSatisfied
: xoModified
);
730 } else if (gotEncapsulated("req-hdr")) {
731 adapted
.setHeader(new HttpRequest
);
732 setOutcome(xoModified
);
734 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
737 void Adaptation::Icap::ModXact::parseHeaders()
739 Must(state
.parsingHeaders());
741 if (state
.parsing
== State::psIcapHeader
) {
742 debugs(93, 5, HERE
<< "parse ICAP headers");
746 if (state
.parsing
== State::psHttpHeader
) {
747 debugs(93, 5, HERE
<< "parse HTTP headers");
751 if (state
.parsingHeaders()) { // need more data
759 // called after parsing all headers or when bypassing an exception
760 void Adaptation::Icap::ModXact::startSending()
762 disableRepeats("sent headers");
763 disableBypass("sent headers", true);
764 sendAnswer(Answer::Forward(adapted
.header
));
766 if (state
.sending
== State::sendingVirgin
)
770 void Adaptation::Icap::ModXact::parseIcapHead()
772 Must(state
.sending
== State::sendingUndecided
);
774 if (!parseHead(icapReply
.getRaw()))
777 if (httpHeaderHasConnDir(&icapReply
->header
, "close")) {
778 debugs(93, 5, HERE
<< "found connection close");
779 reuseConnection
= false;
782 switch (icapReply
->sline
.status()) {
784 case Http::scContinue
:
789 case Http::scCreated
: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
791 if (!validate200Ok()) {
792 throw TexcHere("Invalid ICAP Response");
799 case Http::scNoContent
:
800 handle204NoContent();
803 case Http::scPartialContent
:
804 handle206PartialContent();
808 debugs(93, 5, "ICAP status " << icapReply
->sline
.status());
809 handleUnknownScode();
813 const HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
815 request
= &virginRequest();
817 // update the cross-transactional database if needed (all status codes!)
818 if (const char *xxName
= Adaptation::Config::masterx_shared_name
) {
819 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
820 if (ah
!= NULL
) { // TODO: reorder checks to avoid creating history
821 const String val
= icapReply
->header
.getByName(xxName
);
822 if (val
.size() > 0) // XXX: HttpHeader lacks empty value detection
823 ah
->updateXxRecord(xxName
, val
);
827 // update the adaptation plan if needed (all status codes!)
828 if (service().cfg().routing
) {
830 if (icapReply
->header
.getList(HDR_X_NEXT_SERVICES
, &services
)) {
831 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
833 ah
->updateNextServices(services
);
835 } // TODO: else warn (occasionally!) if we got HDR_X_NEXT_SERVICES
837 // We need to store received ICAP headers for <icapLastHeader logformat option.
838 // If we already have stored headers from previous ICAP transaction related to this
839 // request, old headers will be replaced with the new one.
841 Adaptation::History::Pointer ah
= request
->adaptLogHistory();
843 ah
->recordMeta(&icapReply
->header
);
845 // handle100Continue() manages state.writing on its own.
846 // Non-100 status means the server needs no postPreview data from us.
847 if (state
.writing
== State::writingPaused
)
851 bool Adaptation::Icap::ModXact::validate200Ok()
853 if (ICAP::methodRespmod
== service().cfg().method
) {
854 if (!gotEncapsulated("res-hdr"))
860 if (ICAP::methodReqmod
== service().cfg().method
) {
861 if (!gotEncapsulated("res-hdr") && !gotEncapsulated("req-hdr"))
870 void Adaptation::Icap::ModXact::handle100Continue()
872 Must(state
.writing
== State::writingPaused
);
873 // server must not respond before the end of preview: we may send ieof
874 Must(preview
.enabled() && preview
.done() && !preview
.ieof());
876 // 100 "Continue" cancels our Preview commitment,
877 // but not commitment to handle 204 or 206 outside Preview
878 if (!state
.allowedPostview204
&& !state
.allowedPostview206
)
881 state
.parsing
= State::psIcapHeader
; // eventually
884 state
.writing
= State::writingPrime
;
889 void Adaptation::Icap::ModXact::handle200Ok()
891 state
.parsing
= State::psHttpHeader
;
892 state
.sending
= State::sendingAdapted
;
897 void Adaptation::Icap::ModXact::handle204NoContent()
903 void Adaptation::Icap::ModXact::handle206PartialContent()
905 if (state
.writing
== State::writingPaused
) {
906 Must(preview
.enabled());
907 Must(state
.allowedPreview206
);
908 debugs(93, 7, HERE
<< "206 inside preview");
910 Must(state
.writing
> State::writingPaused
);
911 Must(state
.allowedPostview206
);
912 debugs(93, 7, HERE
<< "206 outside preview");
914 state
.parsing
= State::psHttpHeader
;
915 state
.sending
= State::sendingAdapted
;
916 state
.readyForUob
= true;
920 // Called when we receive a 204 No Content response and
921 // when we are trying to bypass a service failure.
922 // We actually start sending (echoig or not) in startSending.
923 void Adaptation::Icap::ModXact::prepEchoing()
925 disableRepeats("preparing to echo content");
926 disableBypass("preparing to echo content", true);
929 // We want to clone the HTTP message, but we do not want
930 // to copy some non-HTTP state parts that HttpMsg kids carry in them.
931 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
932 // Instead, we simply write the HTTP message and "clone" it by parsing.
933 // TODO: use HttpMsg::clone()!
935 HttpMsg
*oldHead
= virgin
.header
;
936 debugs(93, 7, HERE
<< "cloning virgin message " << oldHead
);
940 // write the virgin message into a memory buffer
942 packHead(httpBuf
, oldHead
);
944 // allocate the adapted message and copy metainfo
945 Must(!adapted
.header
);
947 HttpMsg::Pointer newHead
;
948 if (dynamic_cast<const HttpRequest
*>(oldHead
)) {
949 newHead
= new HttpRequest
;
950 } else if (dynamic_cast<const HttpReply
*>(oldHead
)) {
951 newHead
= new HttpReply
;
953 Must(newHead
!= NULL
);
955 newHead
->inheritProperties(oldHead
);
957 adapted
.setHeader(newHead
.getRaw());
960 // parse the buffer back
961 Http::StatusCode error
= Http::scNone
;
963 Must(adapted
.header
->parse(&httpBuf
, true, &error
));
965 if (HttpRequest
*r
= dynamic_cast<HttpRequest
*>(adapted
.header
))
966 urlCanonical(r
); // parse does not set HttpRequest::canonical
968 Must(adapted
.header
->hdr_sz
== httpBuf
.contentSize()); // no leftovers
972 debugs(93, 7, HERE
<< "cloned virgin message " << oldHead
<< " to " <<
975 // setup adapted body pipe if needed
976 if (oldHead
->body_pipe
!= NULL
) {
977 debugs(93, 7, HERE
<< "will echo virgin body from " <<
979 if (!virginBodySending
.active())
980 virginBodySending
.plan(); // will throw if not possible
981 state
.sending
= State::sendingVirgin
;
984 // TODO: optimize: is it possible to just use the oldHead pipe and
985 // remove ICAP from the loop? This echoing is probably a common case!
986 makeAdaptedBodyPipe("echoed virgin response");
987 if (oldHead
->body_pipe
->bodySizeKnown())
988 adapted
.body_pipe
->setBodySize(oldHead
->body_pipe
->bodySize());
989 debugs(93, 7, HERE
<< "will echo virgin body to " <<
992 debugs(93, 7, HERE
<< "no virgin body to echo");
997 /// Called when we received use-original-body chunk extension in 206 response.
998 /// We actually start sending (echoing or not) in startSending().
999 void Adaptation::Icap::ModXact::prepPartialBodyEchoing(uint64_t pos
)
1001 Must(virginBodySending
.active());
1002 Must(virgin
.header
->body_pipe
!= NULL
);
1004 setOutcome(xoPartEcho
);
1006 debugs(93, 7, HERE
<< "will echo virgin body suffix from " <<
1007 virgin
.header
->body_pipe
<< " offset " << pos
);
1009 // check that use-original-body=N does not point beyond buffered data
1010 const uint64_t virginDataEnd
= virginConsumed
+
1011 virgin
.body_pipe
->buf().contentSize();
1012 Must(pos
<= virginDataEnd
);
1013 virginBodySending
.progress(static_cast<size_t>(pos
));
1015 state
.sending
= State::sendingVirgin
;
1018 if (virgin
.header
->body_pipe
->bodySizeKnown())
1019 adapted
.body_pipe
->expectProductionEndAfter(virgin
.header
->body_pipe
->bodySize() - pos
);
1021 debugs(93, 7, HERE
<< "will echo virgin body suffix to " <<
1024 // Start echoing data
1028 void Adaptation::Icap::ModXact::handleUnknownScode()
1032 // TODO: mark connection as "bad"
1034 // Terminate the transaction; we do not know how to handle this response.
1035 throw TexcHere("Unsupported ICAP status code");
1038 void Adaptation::Icap::ModXact::parseHttpHead()
1040 if (gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr")) {
1041 replyHttpHeaderSize
= 0;
1042 maybeAllocateHttpMsg();
1044 if (!parseHead(adapted
.header
))
1045 return; // need more header data
1048 replyHttpHeaderSize
= adapted
.header
->hdr_sz
;
1050 if (dynamic_cast<HttpRequest
*>(adapted
.header
)) {
1051 const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(virgin
.header
);
1053 // TODO: the adapted request did not really originate from the
1054 // client; give proxy admin an option to prevent copying of
1055 // sensitive client information here. See the following thread:
1056 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
1059 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
1061 adapted
.header
->inheritProperties(virgin
.header
);
1064 decideOnParsingBody();
1067 // parses both HTTP and ICAP headers
1068 bool Adaptation::Icap::ModXact::parseHead(HttpMsg
*head
)
1071 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " head bytes to parse" <<
1072 "; state: " << state
.parsing
);
1074 Http::StatusCode error
= Http::scNone
;
1075 const bool parsed
= head
->parse(&readBuf
, commEof
, &error
);
1076 Must(parsed
|| !error
); // success or need more data
1078 if (!parsed
) { // need more data
1079 debugs(93, 5, HERE
<< "parse failed, need more data, return false");
1084 if (HttpRequest
*r
= dynamic_cast<HttpRequest
*>(head
))
1085 urlCanonical(r
); // parse does not set HttpRequest::canonical
1087 debugs(93, 5, HERE
<< "parse success, consume " << head
->hdr_sz
<< " bytes, return true");
1088 readBuf
.consume(head
->hdr_sz
);
1092 void Adaptation::Icap::ModXact::decideOnParsingBody()
1094 if (gotEncapsulated("res-body") || gotEncapsulated("req-body")) {
1095 debugs(93, 5, HERE
<< "expecting a body");
1096 state
.parsing
= State::psBody
;
1097 replyHttpBodySize
= 0;
1098 bodyParser
= new ChunkedCodingParser
;
1099 makeAdaptedBodyPipe("adapted response from the ICAP server");
1100 Must(state
.sending
== State::sendingAdapted
);
1102 debugs(93, 5, HERE
<< "not expecting a body");
1108 void Adaptation::Icap::ModXact::parseBody()
1110 Must(state
.parsing
== State::psBody
);
1113 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " body bytes to parse");
1115 // the parser will throw on errors
1116 BodyPipeCheckout
bpc(*adapted
.body_pipe
);
1117 const bool parsed
= bodyParser
->parse(&readBuf
, &bpc
.buf
);
1120 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " body bytes after " <<
1121 "parse; parsed all: " << parsed
);
1122 replyHttpBodySize
+= adapted
.body_pipe
->buf().contentSize();
1124 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
1125 // TODO: do we really need this if we disable when sending headers?
1126 if (adapted
.body_pipe
->buf().contentSize() > 0) { // parsed something sometime
1127 disableRepeats("sent adapted content");
1128 disableBypass("sent adapted content", true);
1132 if (state
.readyForUob
&& bodyParser
->useOriginBody
>= 0) {
1133 prepPartialBodyEchoing(
1134 static_cast<uint64_t>(bodyParser
->useOriginBody
));
1140 stopSending(true); // the parser succeeds only if all parsed data fits
1144 debugs(93,3,HERE
<< this << " needsMoreData = " << bodyParser
->needsMoreData());
1146 if (bodyParser
->needsMoreData()) {
1147 debugs(93,3,HERE
<< this);
1148 Must(mayReadMore());
1152 if (bodyParser
->needsMoreSpace()) {
1153 Must(!doneSending()); // can hope for more space
1154 Must(adapted
.body_pipe
->buf().contentSize() > 0); // paranoid
1155 // TODO: there should be a timeout in case the sink is broken
1156 // or cannot consume partial content (while we need more space)
1160 void Adaptation::Icap::ModXact::stopParsing()
1162 if (state
.parsing
== State::psDone
)
1165 debugs(93, 7, HERE
<< "will no longer parse" << status());
1171 state
.parsing
= State::psDone
;
1174 // HTTP side added virgin body data
1175 void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer
)
1179 if (state
.sending
== State::sendingVirgin
)
1183 // HTTP side sent us all virgin info
1184 void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer
)
1186 Must(virgin
.body_pipe
->productionEnded());
1188 // push writer and sender in case we were waiting for the last-chunk
1191 if (state
.sending
== State::sendingVirgin
)
1195 // body producer aborted, but the initiator may still want to know
1196 // the answer, even though the HTTP message has been truncated
1197 void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer
)
1199 Must(virgin
.body_pipe
->productionEnded());
1201 // push writer and sender in case we were waiting for the last-chunk
1204 if (state
.sending
== State::sendingVirgin
)
1208 // adapted body consumer wants more adapted data and
1209 // possibly freed some buffer space
1210 void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
1212 if (state
.sending
== State::sendingVirgin
)
1214 else if (state
.sending
== State::sendingAdapted
)
1217 Must(state
.sending
== State::sendingUndecided
);
1220 // adapted body consumer aborted
1221 void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer
)
1223 detailError(ERR_DETAIL_ICAP_XACT_BODY_CONSUMER_ABORT
);
1224 mustStop("adapted body consumer aborted");
1227 Adaptation::Icap::ModXact::~ModXact()
1233 void Adaptation::Icap::ModXact::swanSong()
1235 debugs(93, 5, HERE
<< "swan sings" << status());
1240 if (theInitiator
.set()) // we have not sent the answer to the initiator
1241 detailError(ERR_DETAIL_ICAP_XACT_OTHER
);
1243 // update adaptation history if start was called and we reserved a slot
1244 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
1245 if (ah
!= NULL
&& adaptHistoryId
>= 0)
1246 ah
->recordXactFinish(adaptHistoryId
);
1248 Adaptation::Icap::Xaction::swanSong();
1251 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
1253 void Adaptation::Icap::ModXact::finalizeLogInfo()
1255 HttpRequest
* request_
= NULL
;
1256 HttpReply
* reply_
= NULL
;
1257 if (!(request_
= dynamic_cast<HttpRequest
*>(adapted
.header
))) {
1258 request_
= (virgin
.cause
? virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
));
1259 reply_
= dynamic_cast<HttpReply
*>(adapted
.header
);
1262 Adaptation::Icap::History::Pointer h
= request_
->icapHistory();
1263 Must(h
!= NULL
); // ICAPXaction::maybeLog calls only if there is a log
1264 al
.icp
.opcode
= ICP_INVALID
;
1265 al
.url
= h
->log_uri
.termedBuf();
1266 const Adaptation::Icap::ServiceRep
&s
= service();
1267 al
.icap
.reqMethod
= s
.cfg().method
;
1269 al
.cache
.caddr
= request_
->client_addr
;
1271 al
.request
= request_
;
1272 HTTPMSGLOCK(al
.request
);
1275 HTTPMSGLOCK(al
.reply
);
1279 if (h
->rfc931
.size())
1280 al
.cache
.rfc931
= h
->rfc931
.termedBuf();
1283 if (h
->ssluser
.size())
1284 al
.cache
.ssluser
= h
->ssluser
.termedBuf();
1286 al
.cache
.code
= h
->logType
;
1287 al
.cache
.requestSize
= h
->req_sz
;
1289 // leave al.icap.bodyBytesRead negative if no body
1290 if (replyHttpHeaderSize
>= 0 || replyHttpBodySize
>= 0) {
1291 const int64_t zero
= 0; // to make max() argument types the same
1292 al
.icap
.bodyBytesRead
=
1293 max(zero
, replyHttpHeaderSize
) + max(zero
, replyHttpBodySize
);
1297 al
.http
.code
= reply_
->sline
.status();
1298 al
.http
.content_type
= reply_
->content_type
.termedBuf();
1299 if (replyHttpBodySize
>= 0) {
1300 al
.cache
.replySize
= replyHttpBodySize
+ reply_
->hdr_sz
;
1301 al
.cache
.highOffset
= replyHttpBodySize
;
1303 //don't set al.cache.objectSize because it hasn't exist yet
1309 packerToMemInit(&p
, &mb
);
1311 reply_
->header
.packInto(&p
);
1312 al
.headers
.reply
= xstrdup(mb
.buf
);
1317 prepareLogWithRequestDetails(request_
, alep
);
1318 Xaction::finalizeLogInfo();
1321 void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf
&buf
)
1323 char ntoabuf
[MAX_IPSTRLEN
];
1325 * XXX These should use HttpHdr interfaces instead of Printfs
1327 const Adaptation::ServiceConfig
&s
= service().cfg();
1328 buf
.Printf("%s " SQUIDSTRINGPH
" ICAP/1.0\r\n", s
.methodStr(), SQUIDSTRINGPRINT(s
.uri
));
1329 buf
.Printf("Host: " SQUIDSTRINGPH
":%d\r\n", SQUIDSTRINGPRINT(s
.host
), s
.port
);
1330 buf
.Printf("Date: %s\r\n", mkrfc1123(squid_curtime
));
1332 if (!TheConfig
.reuse_connections
)
1333 buf
.Printf("Connection: close\r\n");
1335 const HttpRequest
*request
= &virginRequest();
1337 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1339 if (virgin
.header
->header
.has(HDR_PROXY_AUTHENTICATE
)) {
1340 String vh
=virgin
.header
->header
.getByName("Proxy-Authenticate");
1341 buf
.Printf("Proxy-Authenticate: " SQUIDSTRINGPH
"\r\n",SQUIDSTRINGPRINT(vh
));
1344 if (virgin
.header
->header
.has(HDR_PROXY_AUTHORIZATION
)) {
1345 String vh
=virgin
.header
->header
.getByName("Proxy-Authorization");
1346 buf
.Printf("Proxy-Authorization: " SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(vh
));
1347 } else if (request
->extacl_user
.defined() && request
->extacl_user
.size() && request
->extacl_passwd
.defined() && request
->extacl_passwd
.size()) {
1349 snprintf(loginbuf
, sizeof(loginbuf
), SQUIDSTRINGPH
":" SQUIDSTRINGPH
,
1350 SQUIDSTRINGPRINT(request
->extacl_user
),
1351 SQUIDSTRINGPRINT(request
->extacl_passwd
));
1352 buf
.Printf("Proxy-Authorization: Basic %s\r\n", old_base64_encode(loginbuf
));
1355 // share the cross-transactional database records if needed
1356 if (Adaptation::Config::masterx_shared_name
) {
1357 Adaptation::History::Pointer ah
= request
->adaptHistory(false);
1360 if (ah
->getXxRecord(name
, value
)) {
1361 buf
.Printf(SQUIDSTRINGPH
": " SQUIDSTRINGPH
"\r\n",
1362 SQUIDSTRINGPRINT(name
), SQUIDSTRINGPRINT(value
));
1367 buf
.Printf("Encapsulated: ");
1373 // build HTTP request header, if any
1374 ICAP::Method m
= s
.method
;
1376 // to simplify, we could assume that request is always available
1380 urlPath
= request
->urlpath
;
1381 if (ICAP::methodRespmod
== m
)
1382 encapsulateHead(buf
, "req-hdr", httpBuf
, request
);
1383 else if (ICAP::methodReqmod
== m
)
1384 encapsulateHead(buf
, "req-hdr", httpBuf
, virgin
.header
);
1387 if (ICAP::methodRespmod
== m
)
1388 if (const HttpMsg
*prime
= virgin
.header
)
1389 encapsulateHead(buf
, "res-hdr", httpBuf
, prime
);
1391 if (!virginBody
.expected())
1392 buf
.Printf("null-body=%d", (int) httpBuf
.contentSize());
1393 else if (ICAP::methodReqmod
== m
)
1394 buf
.Printf("req-body=%d", (int) httpBuf
.contentSize());
1396 buf
.Printf("res-body=%d", (int) httpBuf
.contentSize());
1398 buf
.append(ICAP::crlf
, 2); // terminate Encapsulated line
1400 if (preview
.enabled()) {
1401 buf
.Printf("Preview: %d\r\n", (int)preview
.ad());
1402 if (!virginBody
.expected()) // there is no body to preview
1403 finishNullOrEmptyBodyPreview(httpBuf
);
1406 makeAllowHeader(buf
);
1408 if (TheConfig
.send_client_ip
&& request
) {
1409 Ip::Address client_addr
;
1410 #if FOLLOW_X_FORWARDED_FOR
1411 if (TheConfig
.use_indirect_client
) {
1412 client_addr
= request
->indirect_client_addr
;
1415 client_addr
= request
->client_addr
;
1416 if (!client_addr
.isAnyAddr() && !client_addr
.isNoAddr())
1417 buf
.Printf("X-Client-IP: %s\r\n", client_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
1420 if (TheConfig
.send_username
&& request
)
1421 makeUsernameHeader(request
, buf
);
1423 // Adaptation::Config::metaHeaders
1424 typedef Notes::iterator ACAMLI
;
1425 for (ACAMLI i
= Adaptation::Config::metaHeaders
.begin(); i
!= Adaptation::Config::metaHeaders
.end(); ++i
) {
1426 HttpRequest
*r
= virgin
.cause
?
1427 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
1430 HttpReply
*reply
= dynamic_cast<HttpReply
*>(virgin
.header
);
1432 if (const char *value
= (*i
)->match(r
, reply
)) {
1433 buf
.Printf("%s: %s\r\n", (*i
)->key
.termedBuf(), value
);
1434 Adaptation::History::Pointer ah
= request
->adaptHistory(false);
1436 if (ah
->metaHeaders
== NULL
)
1437 ah
->metaHeaders
= new NotePairs
;
1438 if (!ah
->metaHeaders
->hasPair((*i
)->key
.termedBuf(), value
))
1439 ah
->metaHeaders
->add((*i
)->key
.termedBuf(), value
);
1444 // fprintf(stderr, "%s\n", buf.content());
1446 buf
.append(ICAP::crlf
, 2); // terminate ICAP header
1448 // fill icapRequest for logging
1449 Must(icapRequest
->parseCharBuf(buf
.content(), buf
.contentSize()));
1451 // start ICAP request body with encapsulated HTTP headers
1452 buf
.append(httpBuf
.content(), httpBuf
.contentSize());
1457 // decides which Allow values to write and updates the request buffer
1458 void Adaptation::Icap::ModXact::makeAllowHeader(MemBuf
&buf
)
1460 const bool allow204in
= preview
.enabled(); // TODO: add shouldAllow204in()
1461 const bool allow204out
= state
.allowedPostview204
= shouldAllow204();
1462 const bool allow206in
= state
.allowedPreview206
= shouldAllow206in();
1463 const bool allow206out
= state
.allowedPostview206
= shouldAllow206out();
1465 debugs(93,9, HERE
<< "Allows: " << allow204in
<< allow204out
<<
1466 allow206in
<< allow206out
);
1468 const bool allow204
= allow204in
|| allow204out
;
1469 const bool allow206
= allow206in
|| allow206out
;
1471 if (!allow204
&& !allow206
)
1472 return; // nothing to do
1474 if (virginBody
.expected()) // if there is a virgin body, plan to send it
1475 virginBodySending
.plan();
1477 // writing Preview:... means we will honor 204 inside preview
1478 // writing Allow/204 means we will honor 204 outside preview
1479 // writing Allow:206 means we will honor 206 inside preview
1480 // writing Allow:204,206 means we will honor 206 outside preview
1481 const char *allowHeader
= NULL
;
1482 if (allow204out
&& allow206
)
1483 allowHeader
= "Allow: 204, 206\r\n";
1484 else if (allow204out
)
1485 allowHeader
= "Allow: 204\r\n";
1487 allowHeader
= "Allow: 206\r\n";
1489 if (allowHeader
) { // may be nil if only allow204in is true
1490 buf
.append(allowHeader
, strlen(allowHeader
));
1491 debugs(93,5, HERE
<< "Will write " << allowHeader
);
1495 void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest
*request
, MemBuf
&buf
)
1498 if (request
->auth_user_request
!= NULL
) {
1499 char const *name
= request
->auth_user_request
->username();
1501 const char *value
= TheConfig
.client_username_encode
? old_base64_encode(name
) : name
;
1502 buf
.Printf("%s: %s\r\n", TheConfig
.client_username_header
, value
);
1504 } else if (request
->extacl_user
.defined() && request
->extacl_user
.size()) {
1505 const char *value
= TheConfig
.client_username_encode
? old_base64_encode(request
->extacl_user
.termedBuf()) : request
->extacl_user
.termedBuf();
1506 buf
.Printf("%s: %s\r\n", TheConfig
.client_username_header
, value
);
1511 void Adaptation::Icap::ModXact::encapsulateHead(MemBuf
&icapBuf
, const char *section
, MemBuf
&httpBuf
, const HttpMsg
*head
)
1513 // update ICAP header
1514 icapBuf
.Printf("%s=%d, ", section
, (int) httpBuf
.contentSize());
1517 HttpMsg::Pointer headClone
;
1519 if (const HttpRequest
* old_request
= dynamic_cast<const HttpRequest
*>(head
)) {
1520 HttpRequest::Pointer
new_request(new HttpRequest
);
1521 Must(old_request
->canonical
);
1522 urlParse(old_request
->method
, old_request
->canonical
, new_request
.getRaw());
1523 new_request
->http_ver
= old_request
->http_ver
;
1524 headClone
= new_request
.getRaw();
1525 } else if (const HttpReply
*old_reply
= dynamic_cast<const HttpReply
*>(head
)) {
1526 HttpReply::Pointer
new_reply(new HttpReply
);
1527 new_reply
->sline
= old_reply
->sline
;
1528 headClone
= new_reply
.getRaw();
1530 Must(headClone
!= NULL
);
1531 headClone
->inheritProperties(head
);
1533 HttpHeaderPos pos
= HttpHeaderInitPos
;
1534 HttpHeaderEntry
* p_head_entry
= NULL
;
1535 while (NULL
!= (p_head_entry
= head
->header
.getEntry(&pos
)) )
1536 headClone
->header
.addEntry(p_head_entry
->clone());
1540 // remove all hop-by-hop headers from the clone
1541 headClone
->header
.delById(HDR_PROXY_AUTHENTICATE
);
1542 headClone
->header
.removeHopByHopEntries();
1544 // pack polished HTTP header
1545 packHead(httpBuf
, headClone
.getRaw());
1547 // headClone unlocks and, hence, deletes the message we packed
1550 void Adaptation::Icap::ModXact::packHead(MemBuf
&httpBuf
, const HttpMsg
*head
)
1553 packerToMemInit(&p
, &httpBuf
);
1554 head
->packInto(&p
, true);
1558 // decides whether to offer a preview and calculates its size
1559 void Adaptation::Icap::ModXact::decideOnPreview()
1561 if (!TheConfig
.preview_enable
) {
1562 debugs(93, 5, HERE
<< "preview disabled by squid.conf");
1566 const String urlPath
= virginRequest().urlpath
;
1568 if (!service().wantsPreview(urlPath
, wantedSize
)) {
1569 debugs(93, 5, HERE
<< "should not offer preview for " << urlPath
);
1573 // we decided to do preview, now compute its size
1575 // cannot preview more than we can backup
1576 size_t ad
= min(wantedSize
, TheBackupLimit
);
1578 if (!virginBody
.expected())
1580 else if (virginBody
.knownSize())
1581 ad
= min(static_cast<uint64_t>(ad
), virginBody
.size()); // not more than we have
1583 debugs(93, 5, HERE
<< "should offer " << ad
<< "-byte preview " <<
1584 "(service wanted " << wantedSize
<< ")");
1587 Must(preview
.enabled());
1590 // decides whether to allow 204 responses
1591 bool Adaptation::Icap::ModXact::shouldAllow204()
1593 if (!service().allows204())
1596 return canBackupEverything();
1599 // decides whether to allow 206 responses in some mode
1600 bool Adaptation::Icap::ModXact::shouldAllow206any()
1602 return TheConfig
.allow206_enable
&& service().allows206() &&
1603 virginBody
.expected(); // no need for 206 without a body
1606 // decides whether to allow 206 responses in preview mode
1607 bool Adaptation::Icap::ModXact::shouldAllow206in()
1609 return shouldAllow206any() && preview
.enabled();
1612 // decides whether to allow 206 responses outside of preview
1613 bool Adaptation::Icap::ModXact::shouldAllow206out()
1615 return shouldAllow206any() && canBackupEverything();
1618 // used by shouldAllow204 and decideOnRetries
1619 bool Adaptation::Icap::ModXact::canBackupEverything() const
1621 if (!virginBody
.expected())
1622 return true; // no body means no problems with backup
1624 // if there is a body, check whether we can backup it all
1626 if (!virginBody
.knownSize())
1629 // or should we have a different backup limit?
1630 // note that '<' allows for 0-termination of the "full" backup buffer
1631 return virginBody
.size() < TheBackupLimit
;
1634 // Decide whether this transaction can be retried if pconn fails
1635 // Must be called after decideOnPreview and before openConnection()
1636 void Adaptation::Icap::ModXact::decideOnRetries()
1639 return; // no, already decided
1641 if (preview
.enabled())
1642 return; // yes, because preview provides enough guarantees
1644 if (canBackupEverything())
1645 return; // yes, because we can back everything up
1647 disableRetries(); // no, because we cannot back everything up
1650 // Normally, the body-writing code handles preview body. It can deal with
1651 // bodies of unexpected size, including those that turn out to be empty.
1652 // However, that code assumes that the body was expected and body control
1653 // structures were initialized. This is not the case when there is no body
1654 // or the body is known to be empty, because the virgin message will lack a
1655 // body_pipe. So we handle preview of null-body and zero-size bodies here.
1656 void Adaptation::Icap::ModXact::finishNullOrEmptyBodyPreview(MemBuf
&buf
)
1658 Must(!virginBodyWriting
.active()); // one reason we handle it here
1659 Must(!virgin
.body_pipe
); // another reason we handle it here
1660 Must(!preview
.ad());
1662 // do not add last-chunk because our Encapsulated header says null-body
1663 // addLastRequestChunk(buf);
1664 preview
.wrote(0, true);
1666 Must(preview
.done());
1667 Must(preview
.ieof());
1670 void Adaptation::Icap::ModXact::fillPendingStatus(MemBuf
&buf
) const
1672 Adaptation::Icap::Xaction::fillPendingStatus(buf
);
1674 if (state
.serviceWaiting
)
1677 if (virgin
.body_pipe
!= NULL
)
1680 if (haveConnection() && !doneReading())
1683 if (!state
.doneWriting() && state
.writing
!= State::writingInit
)
1684 buf
.Printf("w(%d)", state
.writing
);
1686 if (preview
.enabled()) {
1687 if (!preview
.done())
1688 buf
.Printf("P(%d)", (int) preview
.debt());
1691 if (virginBodySending
.active())
1694 if (!state
.doneParsing() && state
.parsing
!= State::psIcapHeader
)
1695 buf
.Printf("p(%d)", state
.parsing
);
1697 if (!doneSending() && state
.sending
!= State::sendingUndecided
)
1698 buf
.Printf("S(%d)", state
.sending
);
1700 if (state
.readyForUob
)
1706 if (protectGroupBypass
)
1710 void Adaptation::Icap::ModXact::fillDoneStatus(MemBuf
&buf
) const
1712 Adaptation::Icap::Xaction::fillDoneStatus(buf
);
1714 if (!virgin
.body_pipe
)
1717 if (state
.doneWriting())
1720 if (preview
.enabled()) {
1722 buf
.Printf("P%s", preview
.ieof() ? "(ieof)" : "");
1728 if (state
.doneParsing())
1735 bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section
) const
1737 return icapReply
->header
.getByNameListMember("Encapsulated",
1738 section
, ',').size() > 0;
1741 // calculate whether there is a virgin HTTP body and
1742 // whether its expected size is known
1743 // TODO: rename because we do not just estimate
1744 void Adaptation::Icap::ModXact::estimateVirginBody()
1746 // note: lack of size info may disable previews and 204s
1748 HttpMsg
*msg
= virgin
.header
;
1751 HttpRequestMethod method
;
1754 method
= virgin
.cause
->method
;
1755 else if (HttpRequest
*req
= dynamic_cast<HttpRequest
*>(msg
))
1756 method
= req
->method
;
1758 method
= Http::METHOD_NONE
;
1761 // expectingBody returns true for zero-sized bodies, but we will not
1762 // get a pipe for that body, so we treat the message as bodyless
1763 if (method
!= Http::METHOD_NONE
&& msg
->expectingBody(method
, size
) && size
) {
1764 debugs(93, 6, HERE
<< "expects virgin body from " <<
1765 virgin
.body_pipe
<< "; size: " << size
);
1767 virginBody
.expect(size
);
1768 virginBodyWriting
.plan();
1770 // sign up as a body consumer
1771 Must(msg
->body_pipe
!= NULL
);
1772 Must(msg
->body_pipe
== virgin
.body_pipe
);
1773 Must(virgin
.body_pipe
->setConsumerIfNotLate(this));
1775 // make sure TheBackupLimit is in-sync with the buffer size
1776 Must(TheBackupLimit
<= static_cast<size_t>(msg
->body_pipe
->buf().max_capacity
));
1778 debugs(93, 6, HERE
<< "does not expect virgin body");
1779 Must(msg
->body_pipe
== NULL
);
1784 void Adaptation::Icap::ModXact::makeAdaptedBodyPipe(const char *what
)
1786 Must(!adapted
.body_pipe
);
1787 Must(!adapted
.header
->body_pipe
);
1788 adapted
.header
->body_pipe
= new BodyPipe(this);
1789 adapted
.body_pipe
= adapted
.header
->body_pipe
;
1790 debugs(93, 7, HERE
<< "will supply " << what
<< " via " <<
1791 adapted
.body_pipe
<< " pipe");
1794 // TODO: Move SizedEstimate and Preview elsewhere
1796 Adaptation::Icap::SizedEstimate::SizedEstimate()
1797 : theData(dtUnexpected
)
1800 void Adaptation::Icap::SizedEstimate::expect(int64_t aSize
)
1802 theData
= (aSize
>= 0) ? aSize
: (int64_t)dtUnknown
;
1805 bool Adaptation::Icap::SizedEstimate::expected() const
1807 return theData
!= dtUnexpected
;
1810 bool Adaptation::Icap::SizedEstimate::knownSize() const
1813 return theData
!= dtUnknown
;
1816 uint64_t Adaptation::Icap::SizedEstimate::size() const
1819 return static_cast<uint64_t>(theData
);
1822 Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided
)
1825 void Adaptation::Icap::VirginBodyAct::plan()
1828 Must(!theStart
); // not started
1829 theState
= stActive
;
1832 void Adaptation::Icap::VirginBodyAct::disable()
1834 theState
= stDisabled
;
1837 void Adaptation::Icap::VirginBodyAct::progress(size_t size
)
1840 #if SIZEOF_SIZE_T > 4
1841 /* always true for smaller size_t's */
1842 Must(static_cast<int64_t>(size
) >= 0);
1844 theStart
+= static_cast<int64_t>(size
);
1847 uint64_t Adaptation::Icap::VirginBodyAct::offset() const
1850 return static_cast<uint64_t>(theStart
);
1853 Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled
)
1856 void Adaptation::Icap::Preview::enable(size_t anAd
)
1858 // TODO: check for anAd not exceeding preview size limit
1861 theState
= stWriting
;
1864 bool Adaptation::Icap::Preview::enabled() const
1866 return theState
!= stDisabled
;
1869 size_t Adaptation::Icap::Preview::ad() const
1875 bool Adaptation::Icap::Preview::done() const
1878 return theState
>= stIeof
;
1881 bool Adaptation::Icap::Preview::ieof() const
1884 return theState
== stIeof
;
1887 size_t Adaptation::Icap::Preview::debt() const
1890 return done() ? 0 : (theAd
- theWritten
);
1893 void Adaptation::Icap::Preview::wrote(size_t size
, bool wroteEof
)
1899 Must(theWritten
<= theAd
);
1902 theState
= stIeof
; // written size is irrelevant
1903 else if (theWritten
>= theAd
)
1907 bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf
&mb
) const
1909 if (virgin
.header
== NULL
)
1912 virgin
.header
->firstLineBuf(mb
);
1917 void Adaptation::Icap::ModXact::detailError(int errDetail
)
1919 HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
1920 // if no adapted request, update virgin (and inherit its properties later)
1921 // TODO: make this and HttpRequest::detailError constant, like adaptHistory
1923 request
= const_cast<HttpRequest
*>(&virginRequest());
1926 request
->detailError(ERR_ICAP_FAILURE
, errDetail
);
1929 void Adaptation::Icap::ModXact::clearError()
1931 HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
1932 // if no adapted request, update virgin (and inherit its properties later)
1934 request
= const_cast<HttpRequest
*>(&virginRequest());
1937 request
->clearError();
1940 /* Adaptation::Icap::ModXactLauncher */
1942 Adaptation::Icap::ModXactLauncher::ModXactLauncher(HttpMsg
*virginHeader
, HttpRequest
*virginCause
, Adaptation::ServicePointer aService
):
1943 AsyncJob("Adaptation::Icap::ModXactLauncher"),
1944 Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", aService
)
1946 virgin
.setHeader(virginHeader
);
1947 virgin
.setCause(virginCause
);
1948 updateHistory(true);
1951 Adaptation::Icap::Xaction
*Adaptation::Icap::ModXactLauncher::createXaction()
1953 Adaptation::Icap::ServiceRep::Pointer s
=
1954 dynamic_cast<Adaptation::Icap::ServiceRep
*>(theService
.getRaw());
1956 return new Adaptation::Icap::ModXact(virgin
.header
, virgin
.cause
, s
);
1959 void Adaptation::Icap::ModXactLauncher::swanSong()
1961 debugs(93, 5, HERE
<< "swan sings");
1962 updateHistory(false);
1963 Adaptation::Icap::Launcher::swanSong();
1966 void Adaptation::Icap::ModXactLauncher::updateHistory(bool doStart
)
1968 HttpRequest
*r
= virgin
.cause
?
1969 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
1971 // r should never be NULL but we play safe; TODO: add Should()
1973 Adaptation::Icap::History::Pointer h
= r
->icapHistory();
1976 h
->start("ICAPModXactLauncher");
1978 h
->stop("ICAPModXactLauncher");