2 * DEBUG: section 93 ICAP (RFC 3507) Client
6 #include "AccessLogEntry.h"
7 #include "adaptation/History.h"
8 #include "adaptation/icap/Client.h"
9 #include "adaptation/icap/Config.h"
10 #include "adaptation/icap/History.h"
11 #include "adaptation/icap/Launcher.h"
12 #include "adaptation/icap/ModXact.h"
13 #include "adaptation/icap/ServiceRep.h"
14 #include "adaptation/Initiator.h"
15 #include "auth/UserRequest.h"
16 #include "base/TextException.h"
17 #include "ChunkedCodingParser.h"
19 #include "comm/Connection.h"
21 #include "HttpRequest.h"
22 #include "HttpReply.h"
23 #include "SquidTime.h"
25 // flow and terminology:
26 // HTTP| --> receive --> encode --> write --> |network
27 // end | <-- send <-- parse <-- read <-- |end
29 // TODO: replace gotEncapsulated() with something faster; we call it often
31 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXact
);
32 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXactLauncher
);
34 static const size_t TheBackupLimit
= BodyPipe::MaxCapacity
;
36 Adaptation::Icap::ModXact::State::State()
38 memset(this, 0, sizeof(*this));
41 Adaptation::Icap::ModXact::ModXact(Adaptation::Initiator
*anInitiator
, HttpMsg
*virginHeader
,
42 HttpRequest
*virginCause
, Adaptation::Icap::ServiceRep::Pointer
&aService
):
43 AsyncJob("Adaptation::Icap::ModXact"),
44 Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", anInitiator
, aService
),
47 canStartBypass(false), // too early
48 protectGroupBypass(true),
54 virgin
.setHeader(virginHeader
); // sets virgin.body_pipe if needed
55 virgin
.setCause(virginCause
); // may be NULL
57 // adapted header and body are initialized when we parse them
59 // writing and reading ends are handled by Adaptation::Icap::Xaction
62 // nothing to do because we are using temporary buffers
64 // parsing; TODO: do not set until we parse, see ICAPOptXact
65 icapReply
= HTTPMSGLOCK(new HttpReply
);
66 icapReply
->protoPrefix
= "ICAP/"; // TODO: make an IcapReply class?
68 debugs(93,7, HERE
<< "initialized." << status());
71 // initiator wants us to start
72 void Adaptation::Icap::ModXact::start()
74 Adaptation::Icap::Xaction::start();
76 // reserve an adaptation history slot (attempts are known at this time)
77 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
79 adaptHistoryId
= ah
->recordXactStart(service().cfg().key
, icap_tr_start
, attempts
> 1);
81 estimateVirginBody(); // before virgin disappears!
83 canStartBypass
= service().cfg().bypass
;
85 // it is an ICAP violation to send request to a service w/o known OPTIONS
93 void Adaptation::Icap::ModXact::waitForService()
95 Must(!state
.serviceWaiting
);
96 debugs(93, 7, HERE
<< "will wait for the ICAP service" << status());
97 state
.serviceWaiting
= true;
98 AsyncCall::Pointer call
= asyncCall(93,5, "Adaptation::Icap::ModXact::noteServiceReady",
99 MemFun(this, &Adaptation::Icap::ModXact::noteServiceReady
));
100 service().callWhenReady(call
);
103 void Adaptation::Icap::ModXact::noteServiceReady()
105 Must(state
.serviceWaiting
);
106 state
.serviceWaiting
= false;
108 if (service().up()) {
112 disableRepeats("ICAP service is unusable");
113 throw TexcHere("ICAP service is unusable");
117 void Adaptation::Icap::ModXact::startWriting()
119 state
.writing
= State::writingConnect
;
121 decideOnPreview(); // must be decided before we decideOnRetries
127 // connection with the ICAP service established
128 void Adaptation::Icap::ModXact::handleCommConnected()
130 Must(state
.writing
== State::writingConnect
);
132 startReading(); // wait for early errors from the ICAP server
137 makeRequestHeaders(requestBuf
);
138 debugs(93, 9, HERE
<< "will write" << status() << ":\n" <<
139 (requestBuf
.terminate(), requestBuf
.content()));
142 state
.writing
= State::writingHeaders
;
143 icap_tio_start
= current_time
;
144 scheduleWrite(requestBuf
);
147 void Adaptation::Icap::ModXact::handleCommWrote(size_t sz
)
149 debugs(93, 5, HERE
<< "Wrote " << sz
<< " bytes");
151 if (state
.writing
== State::writingHeaders
)
152 handleCommWroteHeaders();
154 handleCommWroteBody();
157 void Adaptation::Icap::ModXact::handleCommWroteHeaders()
159 Must(state
.writing
== State::writingHeaders
);
161 // determine next step
162 if (preview
.enabled())
163 state
.writing
= preview
.done() ? State::writingPaused
: State::writingPreview
;
164 else if (virginBody
.expected())
165 state
.writing
= State::writingPrime
;
174 void Adaptation::Icap::ModXact::writeMore()
176 debugs(93, 5, HERE
<< "checking whether to write more" << status());
178 if (writer
!= NULL
) // already writing something
181 switch (state
.writing
) {
183 case State::writingInit
: // waiting for service OPTIONS
184 Must(state
.serviceWaiting
);
186 case State::writingConnect
: // waiting for the connection to establish
188 case State::writingHeaders
: // waiting for the headers to be written
190 case State::writingPaused
: // waiting for the ICAP server response
192 case State::writingReallyDone
: // nothing more to write
195 case State::writingAlmostDone
: // was waiting for the last write
199 case State::writingPreview
:
203 case State::writingPrime
:
208 throw TexcHere("Adaptation::Icap::ModXact in bad writing state");
212 void Adaptation::Icap::ModXact::writePreviewBody()
214 debugs(93, 8, HERE
<< "will write Preview body from " <<
215 virgin
.body_pipe
<< status());
216 Must(state
.writing
== State::writingPreview
);
217 Must(virgin
.body_pipe
!= NULL
);
219 const size_t sizeMax
= (size_t)virgin
.body_pipe
->buf().contentSize();
220 const size_t size
= min(preview
.debt(), sizeMax
);
221 writeSomeBody("preview body", size
);
223 // change state once preview is written
225 if (preview
.done()) {
226 debugs(93, 7, HERE
<< "wrote entire Preview body" << status());
231 state
.writing
= State::writingPaused
;
235 void Adaptation::Icap::ModXact::writePrimeBody()
237 Must(state
.writing
== State::writingPrime
);
238 Must(virginBodyWriting
.active());
240 const size_t size
= (size_t)virgin
.body_pipe
->buf().contentSize();
241 writeSomeBody("prime virgin body", size
);
243 if (virginBodyEndReached(virginBodyWriting
)) {
244 debugs(93, 5, HERE
<< "wrote entire body");
249 void Adaptation::Icap::ModXact::writeSomeBody(const char *label
, size_t size
)
251 Must(!writer
&& state
.writing
< state
.writingAlmostDone
);
252 Must(virgin
.body_pipe
!= NULL
);
253 debugs(93, 8, HERE
<< "will write up to " << size
<< " bytes of " <<
256 MemBuf writeBuf
; // TODO: suggest a min size based on size and lastChunk
258 writeBuf
.init(); // note: we assume that last-chunk will fit
260 const size_t writableSize
= virginContentSize(virginBodyWriting
);
261 const size_t chunkSize
= min(writableSize
, size
);
264 debugs(93, 7, HERE
<< "will write " << chunkSize
<<
265 "-byte chunk of " << label
);
267 openChunk(writeBuf
, chunkSize
, false);
268 writeBuf
.append(virginContentData(virginBodyWriting
), chunkSize
);
269 closeChunk(writeBuf
);
271 virginBodyWriting
.progress(chunkSize
);
274 debugs(93, 7, HERE
<< "has no writable " << label
<< " content");
277 const bool wroteEof
= virginBodyEndReached(virginBodyWriting
);
278 bool lastChunk
= wroteEof
;
279 if (state
.writing
== State::writingPreview
) {
280 preview
.wrote(chunkSize
, wroteEof
); // even if wrote nothing
281 lastChunk
= lastChunk
|| preview
.done();
285 debugs(93, 8, HERE
<< "will write last-chunk of " << label
);
286 addLastRequestChunk(writeBuf
);
289 debugs(93, 7, HERE
<< "will write " << writeBuf
.contentSize()
290 << " raw bytes of " << label
);
292 if (writeBuf
.hasContent()) {
293 scheduleWrite(writeBuf
); // comm will free the chunk
299 void Adaptation::Icap::ModXact::addLastRequestChunk(MemBuf
&buf
)
301 const bool ieof
= state
.writing
== State::writingPreview
&& preview
.ieof();
302 openChunk(buf
, 0, ieof
);
306 void Adaptation::Icap::ModXact::openChunk(MemBuf
&buf
, size_t chunkSize
, bool ieof
)
308 buf
.Printf((ieof
? "%x; ieof\r\n" : "%x\r\n"), (int) chunkSize
);
311 void Adaptation::Icap::ModXact::closeChunk(MemBuf
&buf
)
313 buf
.append(ICAP::crlf
, 2); // chunk-terminating CRLF
316 const HttpRequest
&Adaptation::Icap::ModXact::virginRequest() const
318 const HttpRequest
*request
= virgin
.cause
?
319 virgin
.cause
: dynamic_cast<const HttpRequest
*>(virgin
.header
);
324 // did the activity reached the end of the virgin body?
325 bool Adaptation::Icap::ModXact::virginBodyEndReached(const Adaptation::Icap::VirginBodyAct
&act
) const
328 !act
.active() || // did all (assuming it was originally planned)
329 !virgin
.body_pipe
->expectMoreAfter(act
.offset()); // wont have more
332 // the size of buffered virgin body data available for the specified activity
333 // if this size is zero, we may be done or may be waiting for more data
334 size_t Adaptation::Icap::ModXact::virginContentSize(const Adaptation::Icap::VirginBodyAct
&act
) const
337 // asbolute start of unprocessed data
338 const uint64_t dataStart
= act
.offset();
339 // absolute end of buffered data
340 const uint64_t dataEnd
= virginConsumed
+ virgin
.body_pipe
->buf().contentSize();
341 Must(virginConsumed
<= dataStart
&& dataStart
<= dataEnd
);
342 return static_cast<size_t>(dataEnd
- dataStart
);
345 // pointer to buffered virgin body data available for the specified activity
346 const char *Adaptation::Icap::ModXact::virginContentData(const Adaptation::Icap::VirginBodyAct
&act
) const
349 const uint64_t dataStart
= act
.offset();
350 Must(virginConsumed
<= dataStart
);
351 return virgin
.body_pipe
->buf().content() + static_cast<size_t>(dataStart
-virginConsumed
);
354 void Adaptation::Icap::ModXact::virginConsume()
356 debugs(93, 9, HERE
<< "consumption guards: " << !virgin
.body_pipe
<< isRetriable
<<
357 isRepeatable
<< canStartBypass
<< protectGroupBypass
);
359 if (!virgin
.body_pipe
)
360 return; // nothing to consume
363 return; // do not consume if we may have to retry later
365 BodyPipe
&bp
= *virgin
.body_pipe
;
366 const bool wantToPostpone
= isRepeatable
|| canStartBypass
|| protectGroupBypass
;
368 // Why > 2? HttpState does not use the last bytes in the buffer
369 // because delayAwareRead() is arguably broken. See
370 // HttpStateData::maybeReadVirginBody for more details.
371 if (wantToPostpone
&& bp
.buf().spaceSize() > 2) {
372 // Postponing may increase memory footprint and slow the HTTP side
373 // down. Not postponing may increase the number of ICAP errors
374 // if the ICAP service fails. We may also use "potential" space to
375 // postpone more aggressively. Should the trade-off be configurable?
376 debugs(93, 8, HERE
<< "postponing consumption from " << bp
.status());
380 const size_t have
= static_cast<size_t>(bp
.buf().contentSize());
381 const uint64_t end
= virginConsumed
+ have
;
382 uint64_t offset
= end
;
384 debugs(93, 9, HERE
<< "max virgin consumption offset=" << offset
<<
385 " acts " << virginBodyWriting
.active() << virginBodySending
.active() <<
386 " consumed=" << virginConsumed
<<
387 " from " << virgin
.body_pipe
->status());
389 if (virginBodyWriting
.active())
390 offset
= min(virginBodyWriting
.offset(), offset
);
392 if (virginBodySending
.active())
393 offset
= min(virginBodySending
.offset(), offset
);
395 Must(virginConsumed
<= offset
&& offset
<= end
);
397 if (const size_t size
= static_cast<size_t>(offset
- virginConsumed
)) {
398 debugs(93, 8, HERE
<< "consuming " << size
<< " out of " << have
<<
399 " virgin body bytes");
401 virginConsumed
+= size
;
402 Must(!isRetriable
); // or we should not be consuming
403 disableRepeats("consumed content");
404 disableBypass("consumed content", true);
408 void Adaptation::Icap::ModXact::handleCommWroteBody()
413 // Called when we do not expect to call comm_write anymore.
414 // We may have a pending write though.
415 // If stopping nicely, we will just wait for that pending write, if any.
416 void Adaptation::Icap::ModXact::stopWriting(bool nicely
)
418 if (state
.writing
== State::writingReallyDone
)
421 if (writer
!= NULL
) {
423 debugs(93, 7, HERE
<< "will wait for the last write" << status());
424 state
.writing
= State::writingAlmostDone
; // may already be set
428 debugs(93, 3, HERE
<< "will NOT wait for the last write" << status());
430 // Comm does not have an interface to clear the writer callback nicely,
431 // but without clearing the writer we cannot recycle the connection.
432 // We prevent connection reuse and hope that we can handle a callback
433 // call at any time, usually in the middle of the destruction sequence!
434 // Somebody should add comm_remove_write_handler() to comm API.
435 reuseConnection
= false;
436 ignoreLastWrite
= true;
439 debugs(93, 7, HERE
<< "will no longer write" << status());
440 if (virginBodyWriting
.active()) {
441 virginBodyWriting
.disable();
444 state
.writing
= State::writingReallyDone
;
448 void Adaptation::Icap::ModXact::stopBackup()
450 if (!virginBodySending
.active())
453 debugs(93, 7, HERE
<< "will no longer backup" << status());
454 virginBodySending
.disable();
458 bool Adaptation::Icap::ModXact::doneAll() const
460 return Adaptation::Icap::Xaction::doneAll() && !state
.serviceWaiting
&&
462 doneReading() && state
.doneWriting();
465 void Adaptation::Icap::ModXact::startReading()
467 Must(connection
!= NULL
&& connection
->isOpen());
469 Must(!adapted
.header
);
470 Must(!adapted
.body_pipe
);
472 // we use the same buffer for headers and body and then consume headers
476 void Adaptation::Icap::ModXact::readMore()
478 if (reader
!= NULL
|| doneReading()) {
479 debugs(93,3,HERE
<< "returning from readMore because reader or doneReading()");
483 // do not fill readBuf if we have no space to store the result
484 if (adapted
.body_pipe
!= NULL
&&
485 !adapted
.body_pipe
->buf().hasPotentialSpace()) {
486 debugs(93,3,HERE
<< "not reading because ICAP reply pipe is full");
490 if (readBuf
.hasSpace())
493 debugs(93,3,HERE
<< "nothing to do because !readBuf.hasSpace()");
496 // comm module read a portion of the ICAP response for us
497 void Adaptation::Icap::ModXact::handleCommRead(size_t)
499 Must(!state
.doneParsing());
500 icap_tio_finish
= current_time
;
505 void Adaptation::Icap::ModXact::echoMore()
507 Must(state
.sending
== State::sendingVirgin
);
508 Must(adapted
.body_pipe
!= NULL
);
509 Must(virginBodySending
.active());
511 const size_t sizeMax
= virginContentSize(virginBodySending
);
512 debugs(93,5, HERE
<< "will echo up to " << sizeMax
<< " bytes from " <<
513 virgin
.body_pipe
->status());
514 debugs(93,5, HERE
<< "will echo up to " << sizeMax
<< " bytes to " <<
515 adapted
.body_pipe
->status());
518 const size_t size
= adapted
.body_pipe
->putMoreData(virginContentData(virginBodySending
), sizeMax
);
519 debugs(93,5, HERE
<< "echoed " << size
<< " out of " << sizeMax
<<
521 virginBodySending
.progress(size
);
522 disableRepeats("echoed content");
523 disableBypass("echoed content", true);
527 if (virginBodyEndReached(virginBodySending
)) {
528 debugs(93, 5, HERE
<< "echoed all" << status());
531 debugs(93, 5, HERE
<< "has " <<
532 virgin
.body_pipe
->buf().contentSize() << " bytes " <<
533 "and expects more to echo" << status());
534 // TODO: timeout if virgin or adapted pipes are broken
538 bool Adaptation::Icap::ModXact::doneSending() const
540 return state
.sending
== State::sendingDone
;
543 // stop (or do not start) sending adapted message body
544 void Adaptation::Icap::ModXact::stopSending(bool nicely
)
546 debugs(93, 7, HERE
<< "Enter stop sending ");
549 debugs(93, 7, HERE
<< "Proceed with stop sending ");
551 if (state
.sending
!= State::sendingUndecided
) {
552 debugs(93, 7, HERE
<< "will no longer send" << status());
553 if (adapted
.body_pipe
!= NULL
) {
554 virginBodySending
.disable();
555 // we may leave debts if we were echoing and the virgin
556 // body_pipe got exhausted before we echoed all planned bytes
557 const bool leftDebts
= adapted
.body_pipe
->needsMoreData();
558 stopProducingFor(adapted
.body_pipe
, nicely
&& !leftDebts
);
561 debugs(93, 7, HERE
<< "will not start sending" << status());
562 Must(!adapted
.body_pipe
);
565 state
.sending
= State::sendingDone
;
569 // should be called after certain state.writing or state.sending changes
570 void Adaptation::Icap::ModXact::checkConsuming()
572 // quit if we already stopped or are still using the pipe
573 if (!virgin
.body_pipe
|| !state
.doneConsumingVirgin())
576 debugs(93, 7, HERE
<< "will stop consuming" << status());
577 stopConsumingFrom(virgin
.body_pipe
);
580 void Adaptation::Icap::ModXact::parseMore()
582 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " bytes to parse" <<
584 debugs(93, 5, HERE
<< "\n" << readBuf
.content());
586 if (state
.parsingHeaders())
589 if (state
.parsing
== State::psBody
)
593 void Adaptation::Icap::ModXact::callException(const std::exception
&e
)
595 if (!canStartBypass
|| isRetriable
) {
596 Adaptation::Icap::Xaction::callException(e
);
601 debugs(93, 3, HERE
<< "bypassing " << inCall
<< " exception: " <<
602 e
.what() << ' ' << status());
604 } catch (const std::exception
&bypassE
) {
605 Adaptation::Icap::Xaction::callException(bypassE
);
609 void Adaptation::Icap::ModXact::bypassFailure()
611 disableBypass("already started to bypass", false);
613 Must(!isRetriable
); // or we should not be bypassing
614 // TODO: should the same be enforced for isRepeatable? Check icap_repeat??
620 // end all activities associated with the ICAP server
624 stopWriting(true); // or should we force it?
625 if (connection
!= NULL
&& connection
->isOpen()) {
626 reuseConnection
= false; // be conservative
627 cancelRead(); // may not work; and we cannot stop connecting either
629 debugs(93, 7, HERE
<< "Warning: bypass failed to stop I/O" << status());
633 void Adaptation::Icap::ModXact::disableBypass(const char *reason
, bool includingGroupBypass
)
635 if (canStartBypass
) {
636 debugs(93,7, HERE
<< "will never start bypass because " << reason
);
637 canStartBypass
= false;
639 if (protectGroupBypass
&& includingGroupBypass
) {
640 debugs(93,7, HERE
<< "not protecting group bypass because " << reason
);
641 protectGroupBypass
= false;
647 // note that allocation for echoing is done in handle204NoContent()
648 void Adaptation::Icap::ModXact::maybeAllocateHttpMsg()
650 if (adapted
.header
) // already allocated
653 if (gotEncapsulated("res-hdr")) {
654 adapted
.setHeader(new HttpReply
);
655 setOutcome(service().cfg().method
== ICAP::methodReqmod
?
656 xoSatisfied
: xoModified
);
657 } else if (gotEncapsulated("req-hdr")) {
658 adapted
.setHeader(new HttpRequest
);
659 setOutcome(xoModified
);
661 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
664 void Adaptation::Icap::ModXact::parseHeaders()
666 Must(state
.parsingHeaders());
668 if (state
.parsing
== State::psIcapHeader
) {
669 debugs(93, 5, HERE
<< "parse ICAP headers");
673 if (state
.parsing
== State::psHttpHeader
) {
674 debugs(93, 5, HERE
<< "parse HTTP headers");
678 if (state
.parsingHeaders()) { // need more data
686 // called after parsing all headers or when bypassing an exception
687 void Adaptation::Icap::ModXact::startSending()
689 disableRepeats("sent headers");
690 disableBypass("sent headers", true);
691 sendAnswer(adapted
.header
);
693 if (state
.sending
== State::sendingVirgin
)
697 void Adaptation::Icap::ModXact::parseIcapHead()
699 Must(state
.sending
== State::sendingUndecided
);
701 if (!parseHead(icapReply
))
704 if (httpHeaderHasConnDir(&icapReply
->header
, "close")) {
705 debugs(93, 5, HERE
<< "found connection close");
706 reuseConnection
= false;
709 switch (icapReply
->sline
.status
) {
716 case 201: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
718 if (!validate200Ok()) {
719 throw TexcHere("Invalid ICAP Response");
727 handle204NoContent();
731 debugs(93, 5, HERE
<< "ICAP status " << icapReply
->sline
.status
);
732 handleUnknownScode();
736 const HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
738 request
= &virginRequest();
740 // update the cross-transactional database if needed (all status codes!)
741 if (const char *xxName
= Adaptation::Config::masterx_shared_name
) {
742 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
744 const String val
= icapReply
->header
.getByName(xxName
);
745 if (val
.size() > 0) // XXX: HttpHeader lacks empty value detection
746 ah
->updateXxRecord(xxName
, val
);
750 // update the adaptation plan if needed (all status codes!)
751 if (service().cfg().routing
) {
753 if (icapReply
->header
.getList(HDR_X_NEXT_SERVICES
, &services
)) {
754 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
756 ah
->updateNextServices(services
);
758 } // TODO: else warn (occasionally!) if we got HDR_X_NEXT_SERVICES
760 // We need to store received ICAP headers for <icapLastHeader logformat option.
761 // If we already have stored headers from previous ICAP transaction related to this
762 // request, old headers will be replaced with the new one.
764 Adaptation::Icap::History::Pointer h
= request
->icapHistory();
766 h
->mergeIcapHeaders(&icapReply
->header
);
767 h
->setIcapLastHeader(&icapReply
->header
);
770 // handle100Continue() manages state.writing on its own.
771 // Non-100 status means the server needs no postPreview data from us.
772 if (state
.writing
== State::writingPaused
)
776 bool Adaptation::Icap::ModXact::validate200Ok()
778 if (ICAP::methodRespmod
== service().cfg().method
) {
779 if (!gotEncapsulated("res-hdr"))
785 if (ICAP::methodReqmod
== service().cfg().method
) {
786 if (!gotEncapsulated("res-hdr") && !gotEncapsulated("req-hdr"))
795 void Adaptation::Icap::ModXact::handle100Continue()
797 Must(state
.writing
== State::writingPaused
);
798 // server must not respond before the end of preview: we may send ieof
799 Must(preview
.enabled() && preview
.done() && !preview
.ieof());
801 // 100 "Continue" cancels our preview commitment, not 204s outside preview
802 if (!state
.allowedPostview204
)
805 state
.parsing
= State::psIcapHeader
; // eventually
808 state
.writing
= State::writingPrime
;
813 void Adaptation::Icap::ModXact::handle200Ok()
815 state
.parsing
= State::psHttpHeader
;
816 state
.sending
= State::sendingAdapted
;
821 void Adaptation::Icap::ModXact::handle204NoContent()
827 // Called when we receive a 204 No Content response and
828 // when we are trying to bypass a service failure.
829 // We actually start sending (echoig or not) in startSending.
830 void Adaptation::Icap::ModXact::prepEchoing()
832 disableRepeats("preparing to echo content");
833 disableBypass("preparing to echo content", true);
836 // We want to clone the HTTP message, but we do not want
837 // to copy some non-HTTP state parts that HttpMsg kids carry in them.
838 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
839 // Instead, we simply write the HTTP message and "clone" it by parsing.
840 // TODO: use HttpMsg::clone()!
842 HttpMsg
*oldHead
= virgin
.header
;
843 debugs(93, 7, HERE
<< "cloning virgin message " << oldHead
);
847 // write the virgin message into a memory buffer
849 packHead(httpBuf
, oldHead
);
851 // allocate the adapted message and copy metainfo
852 Must(!adapted
.header
);
853 HttpMsg
*newHead
= NULL
;
854 if (const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(oldHead
)) {
855 HttpRequest
*newR
= new HttpRequest
;
856 newR
->canonical
= oldR
->canonical
?
857 xstrdup(oldR
->canonical
) : NULL
; // parse() does not set it
859 } else if (dynamic_cast<const HttpReply
*>(oldHead
)) {
860 HttpReply
*newRep
= new HttpReply
;
864 newHead
->inheritProperties(oldHead
);
866 adapted
.setHeader(newHead
);
868 // parse the buffer back
869 http_status error
= HTTP_STATUS_NONE
;
871 Must(newHead
->parse(&httpBuf
, true, &error
));
873 Must(newHead
->hdr_sz
== httpBuf
.contentSize()); // no leftovers
877 debugs(93, 7, HERE
<< "cloned virgin message " << oldHead
<< " to " <<
880 // setup adapted body pipe if needed
881 if (oldHead
->body_pipe
!= NULL
) {
882 debugs(93, 7, HERE
<< "will echo virgin body from " <<
884 if (!virginBodySending
.active())
885 virginBodySending
.plan(); // will throw if not possible
886 state
.sending
= State::sendingVirgin
;
889 // TODO: optimize: is it possible to just use the oldHead pipe and
890 // remove ICAP from the loop? This echoing is probably a common case!
891 makeAdaptedBodyPipe("echoed virgin response");
892 if (oldHead
->body_pipe
->bodySizeKnown())
893 adapted
.body_pipe
->setBodySize(oldHead
->body_pipe
->bodySize());
894 debugs(93, 7, HERE
<< "will echo virgin body to " <<
897 debugs(93, 7, HERE
<< "no virgin body to echo");
902 void Adaptation::Icap::ModXact::handleUnknownScode()
906 // TODO: mark connection as "bad"
908 // Terminate the transaction; we do not know how to handle this response.
909 throw TexcHere("Unsupported ICAP status code");
912 void Adaptation::Icap::ModXact::parseHttpHead()
914 if (gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr")) {
915 maybeAllocateHttpMsg();
917 if (!parseHead(adapted
.header
))
918 return; // need more header data
920 if (dynamic_cast<HttpRequest
*>(adapted
.header
)) {
921 const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(virgin
.header
);
923 // TODO: the adapted request did not really originate from the
924 // client; give proxy admin an option to prevent copying of
925 // sensitive client information here. See the following thread:
926 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
929 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
931 adapted
.header
->inheritProperties(virgin
.header
);
934 decideOnParsingBody();
937 // parses both HTTP and ICAP headers
938 bool Adaptation::Icap::ModXact::parseHead(HttpMsg
*head
)
941 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " head bytes to parse" <<
942 "; state: " << state
.parsing
);
944 http_status error
= HTTP_STATUS_NONE
;
945 const bool parsed
= head
->parse(&readBuf
, commEof
, &error
);
946 Must(parsed
|| !error
); // success or need more data
948 if (!parsed
) { // need more data
949 debugs(93, 5, HERE
<< "parse failed, need more data, return false");
954 if (HttpRequest
*r
= dynamic_cast<HttpRequest
*>(head
))
955 urlCanonical(r
); // parse does not set HttpRequest::canonical
957 debugs(93, 5, HERE
<< "parse success, consume " << head
->hdr_sz
<< " bytes, return true");
958 readBuf
.consume(head
->hdr_sz
);
962 void Adaptation::Icap::ModXact::decideOnParsingBody()
964 if (gotEncapsulated("res-body") || gotEncapsulated("req-body")) {
965 debugs(93, 5, HERE
<< "expecting a body");
966 state
.parsing
= State::psBody
;
967 bodyParser
= new ChunkedCodingParser
;
968 makeAdaptedBodyPipe("adapted response from the ICAP server");
969 Must(state
.sending
== State::sendingAdapted
);
971 debugs(93, 5, HERE
<< "not expecting a body");
977 void Adaptation::Icap::ModXact::parseBody()
979 Must(state
.parsing
== State::psBody
);
982 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " body bytes to parse");
984 // the parser will throw on errors
985 BodyPipeCheckout
bpc(*adapted
.body_pipe
);
986 const bool parsed
= bodyParser
->parse(&readBuf
, &bpc
.buf
);
989 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " body bytes after " <<
990 "parse; parsed all: " << parsed
);
991 replyBodySize
+= adapted
.body_pipe
->buf().contentSize();
993 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
994 // TODO: do we really need this if we disable when sending headers?
995 if (adapted
.body_pipe
->buf().contentSize() > 0) { // parsed something sometime
996 disableRepeats("sent adapted content");
997 disableBypass("sent adapted content", true);
1002 stopSending(true); // the parser succeeds only if all parsed data fits
1006 debugs(93,3,HERE
<< this << " needsMoreData = " << bodyParser
->needsMoreData());
1008 if (bodyParser
->needsMoreData()) {
1009 debugs(93,3,HERE
<< this);
1010 Must(mayReadMore());
1014 if (bodyParser
->needsMoreSpace()) {
1015 Must(!doneSending()); // can hope for more space
1016 Must(adapted
.body_pipe
->buf().contentSize() > 0); // paranoid
1017 // TODO: there should be a timeout in case the sink is broken
1018 // or cannot consume partial content (while we need more space)
1022 void Adaptation::Icap::ModXact::stopParsing()
1024 if (state
.parsing
== State::psDone
)
1027 debugs(93, 7, HERE
<< "will no longer parse" << status());
1033 state
.parsing
= State::psDone
;
1036 // HTTP side added virgin body data
1037 void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer
)
1041 if (state
.sending
== State::sendingVirgin
)
1045 // HTTP side sent us all virgin info
1046 void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer
)
1048 Must(virgin
.body_pipe
->productionEnded());
1050 // push writer and sender in case we were waiting for the last-chunk
1053 if (state
.sending
== State::sendingVirgin
)
1057 // body producer aborted, but the initiator may still want to know
1058 // the answer, even though the HTTP message has been truncated
1059 void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer
)
1061 Must(virgin
.body_pipe
->productionEnded());
1063 // push writer and sender in case we were waiting for the last-chunk
1066 if (state
.sending
== State::sendingVirgin
)
1070 // adapted body consumer wants more adapted data and
1071 // possibly freed some buffer space
1072 void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
1074 if (state
.sending
== State::sendingVirgin
)
1076 else if (state
.sending
== State::sendingAdapted
)
1079 Must(state
.sending
== State::sendingUndecided
);
1082 // adapted body consumer aborted
1083 void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer
)
1085 mustStop("adapted body consumer aborted");
1089 void Adaptation::Icap::ModXact::swanSong()
1091 debugs(93, 5, HERE
<< "swan sings" << status());
1096 // update adaptation history if start was called and we reserved a slot
1097 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
1098 if (ah
!= NULL
&& adaptHistoryId
>= 0)
1099 ah
->recordXactFinish(adaptHistoryId
);
1101 Adaptation::Icap::Xaction::swanSong();
1104 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry
*);
1106 void Adaptation::Icap::ModXact::finalizeLogInfo()
1108 HttpRequest
* request_
= NULL
;
1109 HttpReply
* reply_
= NULL
;
1110 if (!(request_
= dynamic_cast<HttpRequest
*>(adapted
.header
))) {
1111 request_
= (virgin
.cause
? virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
));
1112 reply_
= dynamic_cast<HttpReply
*>(adapted
.header
);
1115 Adaptation::Icap::History::Pointer h
= request_
->icapHistory();
1116 Must(h
!= NULL
); // ICAPXaction::maybeLog calls only if there is a log
1117 al
.icp
.opcode
= ICP_INVALID
;
1118 al
.url
= h
->log_uri
.termedBuf();
1119 const Adaptation::Icap::ServiceRep
&s
= service();
1120 al
.icap
.reqMethod
= s
.cfg().method
;
1122 al
.cache
.caddr
= request_
->client_addr
;
1124 al
.request
= HTTPMSGLOCK(request_
);
1126 al
.reply
= HTTPMSGLOCK(reply_
);
1130 if (h
->rfc931
.size())
1131 al
.cache
.rfc931
= h
->rfc931
.termedBuf();
1134 if (h
->ssluser
.size())
1135 al
.cache
.ssluser
= h
->ssluser
.termedBuf();
1137 al
.cache
.code
= h
->logType
;
1138 al
.cache
.requestSize
= h
->req_sz
;
1140 al
.http
.code
= reply_
->sline
.status
;
1141 al
.http
.content_type
= reply_
->content_type
.termedBuf();
1142 al
.cache
.replySize
= replyBodySize
+ reply_
->hdr_sz
;
1143 al
.cache
.highOffset
= replyBodySize
;
1144 //don't set al.cache.objectSize because it hasn't exist yet
1150 packerToMemInit(&p
, &mb
);
1152 reply_
->header
.packInto(&p
);
1153 al
.headers
.reply
= xstrdup(mb
.buf
);
1158 prepareLogWithRequestDetails(request_
, &al
);
1159 Xaction::finalizeLogInfo();
1163 void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf
&buf
)
1165 char ntoabuf
[MAX_IPSTRLEN
];
1167 * XXX These should use HttpHdr interfaces instead of Printfs
1169 const Adaptation::ServiceConfig
&s
= service().cfg();
1170 buf
.Printf("%s " SQUIDSTRINGPH
" ICAP/1.0\r\n", s
.methodStr(), SQUIDSTRINGPRINT(s
.uri
));
1171 buf
.Printf("Host: " SQUIDSTRINGPH
":%d\r\n", SQUIDSTRINGPRINT(s
.host
), s
.port
);
1172 buf
.Printf("Date: %s\r\n", mkrfc1123(squid_curtime
));
1174 if (!TheConfig
.reuse_connections
)
1175 buf
.Printf("Connection: close\r\n");
1177 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1179 if (virgin
.header
->header
.has(HDR_PROXY_AUTHENTICATE
)) {
1180 String vh
=virgin
.header
->header
.getByName("Proxy-Authenticate");
1181 buf
.Printf("Proxy-Authenticate: " SQUIDSTRINGPH
"\r\n",SQUIDSTRINGPRINT(vh
));
1184 if (virgin
.header
->header
.has(HDR_PROXY_AUTHORIZATION
)) {
1185 String vh
=virgin
.header
->header
.getByName("Proxy-Authorization");
1186 buf
.Printf("Proxy-Authorization: " SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(vh
));
1189 const HttpRequest
*request
= &virginRequest();
1191 // share the cross-transactional database records if needed
1192 if (Adaptation::Config::masterx_shared_name
) {
1193 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
1196 if (ah
->getXxRecord(name
, value
)) {
1197 buf
.Printf(SQUIDSTRINGPH
": " SQUIDSTRINGPH
"\r\n",
1198 SQUIDSTRINGPRINT(name
), SQUIDSTRINGPRINT(value
));
1204 buf
.Printf("Encapsulated: ");
1210 // build HTTP request header, if any
1211 ICAP::Method m
= s
.method
;
1213 // to simplify, we could assume that request is always available
1217 urlPath
= request
->urlpath
;
1218 if (ICAP::methodRespmod
== m
)
1219 encapsulateHead(buf
, "req-hdr", httpBuf
, request
);
1220 else if (ICAP::methodReqmod
== m
)
1221 encapsulateHead(buf
, "req-hdr", httpBuf
, virgin
.header
);
1224 if (ICAP::methodRespmod
== m
)
1225 if (const HttpMsg
*prime
= virgin
.header
)
1226 encapsulateHead(buf
, "res-hdr", httpBuf
, prime
);
1228 if (!virginBody
.expected())
1229 buf
.Printf("null-body=%d", (int) httpBuf
.contentSize());
1230 else if (ICAP::methodReqmod
== m
)
1231 buf
.Printf("req-body=%d", (int) httpBuf
.contentSize());
1233 buf
.Printf("res-body=%d", (int) httpBuf
.contentSize());
1235 buf
.append(ICAP::crlf
, 2); // terminate Encapsulated line
1237 if (preview
.enabled()) {
1238 buf
.Printf("Preview: %d\r\n", (int)preview
.ad());
1239 if (virginBody
.expected()) // there is a body to preview
1240 virginBodySending
.plan();
1242 finishNullOrEmptyBodyPreview(httpBuf
);
1245 if (shouldAllow204()) {
1246 debugs(93,5, HERE
<< "will allow 204s outside of preview");
1247 state
.allowedPostview204
= true;
1248 buf
.Printf("Allow: 204\r\n");
1249 if (virginBody
.expected()) // there is a body to echo
1250 virginBodySending
.plan();
1253 if (TheConfig
.send_client_ip
&& request
) {
1254 Ip::Address client_addr
;
1255 #if FOLLOW_X_FORWARDED_FOR
1256 if (TheConfig
.icap_uses_indirect_client
) {
1257 client_addr
= request
->indirect_client_addr
;
1260 client_addr
= request
->client_addr
;
1261 if (!client_addr
.IsAnyAddr() && !client_addr
.IsNoAddr())
1262 buf
.Printf("X-Client-IP: %s\r\n", client_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
1265 if (TheConfig
.send_client_username
&& request
)
1266 makeUsernameHeader(request
, buf
);
1268 // fprintf(stderr, "%s\n", buf.content());
1270 buf
.append(ICAP::crlf
, 2); // terminate ICAP header
1272 // fill icapRequest for logging
1273 Must(icapRequest
->parseCharBuf(buf
.content(), buf
.contentSize()));
1275 // start ICAP request body with encapsulated HTTP headers
1276 buf
.append(httpBuf
.content(), httpBuf
.contentSize());
1281 void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest
*request
, MemBuf
&buf
)
1283 if (request
->auth_user_request
!= NULL
) {
1284 char const *name
= request
->auth_user_request
->username();
1286 const char *value
= TheConfig
.client_username_encode
? base64_encode(name
) : name
;
1287 buf
.Printf("%s: %s\r\n", TheConfig
.client_username_header
, value
);
1292 void Adaptation::Icap::ModXact::encapsulateHead(MemBuf
&icapBuf
, const char *section
, MemBuf
&httpBuf
, const HttpMsg
*head
)
1294 // update ICAP header
1295 icapBuf
.Printf("%s=%d, ", section
, (int) httpBuf
.contentSize());
1298 HttpMsg
*headClone
= NULL
;
1300 if (const HttpRequest
* old_request
= dynamic_cast<const HttpRequest
*>(head
)) {
1301 HttpRequest
* new_request
= new HttpRequest
;
1302 assert(old_request
->canonical
);
1303 urlParse(old_request
->method
, old_request
->canonical
, new_request
);
1304 new_request
->http_ver
= old_request
->http_ver
;
1305 headClone
= new_request
;
1306 } else if (const HttpReply
*old_reply
= dynamic_cast<const HttpReply
*>(head
)) {
1307 HttpReply
* new_reply
= new HttpReply
;
1308 new_reply
->sline
= old_reply
->sline
;
1309 headClone
= new_reply
;
1313 headClone
->inheritProperties(head
);
1315 HttpHeaderPos pos
= HttpHeaderInitPos
;
1316 HttpHeaderEntry
* p_head_entry
= NULL
;
1317 while (NULL
!= (p_head_entry
= head
->header
.getEntry(&pos
)) )
1318 headClone
->header
.addEntry(p_head_entry
->clone());
1322 // remove all hop-by-hop headers from the clone
1323 headClone
->header
.delById(HDR_PROXY_AUTHENTICATE
);
1324 headClone
->header
.removeHopByHopEntries();
1326 // pack polished HTTP header
1327 packHead(httpBuf
, headClone
);
1332 void Adaptation::Icap::ModXact::packHead(MemBuf
&httpBuf
, const HttpMsg
*head
)
1335 packerToMemInit(&p
, &httpBuf
);
1336 head
->packInto(&p
, true);
1340 // decides whether to offer a preview and calculates its size
1341 void Adaptation::Icap::ModXact::decideOnPreview()
1343 if (!TheConfig
.preview_enable
) {
1344 debugs(93, 5, HERE
<< "preview disabled by squid.conf");
1348 const String urlPath
= virginRequest().urlpath
;
1350 if (!service().wantsPreview(urlPath
, wantedSize
)) {
1351 debugs(93, 5, HERE
<< "should not offer preview for " << urlPath
);
1355 // we decided to do preview, now compute its size
1357 Must(wantedSize
>= 0);
1359 // cannot preview more than we can backup
1360 size_t ad
= min(wantedSize
, TheBackupLimit
);
1362 if (!virginBody
.expected())
1364 else if (virginBody
.knownSize())
1365 ad
= min(static_cast<uint64_t>(ad
), virginBody
.size()); // not more than we have
1367 debugs(93, 5, HERE
<< "should offer " << ad
<< "-byte preview " <<
1368 "(service wanted " << wantedSize
<< ")");
1371 Must(preview
.enabled());
1374 // decides whether to allow 204 responses
1375 bool Adaptation::Icap::ModXact::shouldAllow204()
1377 if (!service().allows204())
1380 return canBackupEverything();
1383 // used by shouldAllow204 and decideOnRetries
1384 bool Adaptation::Icap::ModXact::canBackupEverything() const
1386 if (!virginBody
.expected())
1387 return true; // no body means no problems with backup
1389 // if there is a body, check whether we can backup it all
1391 if (!virginBody
.knownSize())
1394 // or should we have a different backup limit?
1395 // note that '<' allows for 0-termination of the "full" backup buffer
1396 return virginBody
.size() < TheBackupLimit
;
1399 // Decide whether this transaction can be retried if pconn fails
1400 // Must be called after decideOnPreview and before openConnection()
1401 void Adaptation::Icap::ModXact::decideOnRetries()
1404 return; // no, already decided
1406 if (preview
.enabled())
1407 return; // yes, because preview provides enough guarantees
1409 if (canBackupEverything())
1410 return; // yes, because we can back everything up
1412 disableRetries(); // no, because we cannot back everything up
1415 // Normally, the body-writing code handles preview body. It can deal with
1416 // bodies of unexpected size, including those that turn out to be empty.
1417 // However, that code assumes that the body was expected and body control
1418 // structures were initialized. This is not the case when there is no body
1419 // or the body is known to be empty, because the virgin message will lack a
1420 // body_pipe. So we handle preview of null-body and zero-size bodies here.
1421 void Adaptation::Icap::ModXact::finishNullOrEmptyBodyPreview(MemBuf
&buf
)
1423 Must(!virginBodyWriting
.active()); // one reason we handle it here
1424 Must(!virgin
.body_pipe
); // another reason we handle it here
1425 Must(!preview
.ad());
1427 // do not add last-chunk because our Encapsulated header says null-body
1428 // addLastRequestChunk(buf);
1429 preview
.wrote(0, true);
1431 Must(preview
.done());
1432 Must(preview
.ieof());
1435 void Adaptation::Icap::ModXact::fillPendingStatus(MemBuf
&buf
) const
1437 Adaptation::Icap::Xaction::fillPendingStatus(buf
);
1439 if (state
.serviceWaiting
)
1442 if (virgin
.body_pipe
!= NULL
)
1445 if (connection
!= NULL
&& connection
->isOpen() && !doneReading())
1448 if (!state
.doneWriting() && state
.writing
!= State::writingInit
)
1449 buf
.Printf("w(%d)", state
.writing
);
1451 if (preview
.enabled()) {
1452 if (!preview
.done())
1453 buf
.Printf("P(%d)", (int) preview
.debt());
1456 if (virginBodySending
.active())
1459 if (!state
.doneParsing() && state
.parsing
!= State::psIcapHeader
)
1460 buf
.Printf("p(%d)", state
.parsing
);
1462 if (!doneSending() && state
.sending
!= State::sendingUndecided
)
1463 buf
.Printf("S(%d)", state
.sending
);
1468 if (protectGroupBypass
)
1472 void Adaptation::Icap::ModXact::fillDoneStatus(MemBuf
&buf
) const
1474 Adaptation::Icap::Xaction::fillDoneStatus(buf
);
1476 if (!virgin
.body_pipe
)
1479 if (state
.doneWriting())
1482 if (preview
.enabled()) {
1484 buf
.Printf("P%s", preview
.ieof() ? "(ieof)" : "");
1490 if (state
.doneParsing())
1497 bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section
) const
1499 return icapReply
->header
.getByNameListMember("Encapsulated",
1500 section
, ',').size() > 0;
1503 // calculate whether there is a virgin HTTP body and
1504 // whether its expected size is known
1505 // TODO: rename because we do not just estimate
1506 void Adaptation::Icap::ModXact::estimateVirginBody()
1508 // note: lack of size info may disable previews and 204s
1510 HttpMsg
*msg
= virgin
.header
;
1513 HttpRequestMethod method
;
1516 method
= virgin
.cause
->method
;
1517 else if (HttpRequest
*req
= dynamic_cast<HttpRequest
*>(msg
))
1518 method
= req
->method
;
1520 method
= METHOD_NONE
;
1523 // expectingBody returns true for zero-sized bodies, but we will not
1524 // get a pipe for that body, so we treat the message as bodyless
1525 if (method
!= METHOD_NONE
&& msg
->expectingBody(method
, size
) && size
) {
1526 debugs(93, 6, HERE
<< "expects virgin body from " <<
1527 virgin
.body_pipe
<< "; size: " << size
);
1529 virginBody
.expect(size
);
1530 virginBodyWriting
.plan();
1532 // sign up as a body consumer
1533 Must(msg
->body_pipe
!= NULL
);
1534 Must(msg
->body_pipe
== virgin
.body_pipe
);
1535 Must(virgin
.body_pipe
->setConsumerIfNotLate(this));
1537 // make sure TheBackupLimit is in-sync with the buffer size
1538 Must(TheBackupLimit
<= static_cast<size_t>(msg
->body_pipe
->buf().max_capacity
));
1540 debugs(93, 6, HERE
<< "does not expect virgin body");
1541 Must(msg
->body_pipe
== NULL
);
1546 void Adaptation::Icap::ModXact::makeAdaptedBodyPipe(const char *what
)
1548 Must(!adapted
.body_pipe
);
1549 Must(!adapted
.header
->body_pipe
);
1550 adapted
.header
->body_pipe
= new BodyPipe(this);
1551 adapted
.body_pipe
= adapted
.header
->body_pipe
;
1552 debugs(93, 7, HERE
<< "will supply " << what
<< " via " <<
1553 adapted
.body_pipe
<< " pipe");
1557 // TODO: Move SizedEstimate and Preview elsewhere
1559 Adaptation::Icap::SizedEstimate::SizedEstimate()
1560 : theData(dtUnexpected
)
1563 void Adaptation::Icap::SizedEstimate::expect(int64_t aSize
)
1565 theData
= (aSize
>= 0) ? aSize
: (int64_t)dtUnknown
;
1568 bool Adaptation::Icap::SizedEstimate::expected() const
1570 return theData
!= dtUnexpected
;
1573 bool Adaptation::Icap::SizedEstimate::knownSize() const
1576 return theData
!= dtUnknown
;
1579 uint64_t Adaptation::Icap::SizedEstimate::size() const
1582 return static_cast<uint64_t>(theData
);
1587 Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided
)
1590 void Adaptation::Icap::VirginBodyAct::plan()
1593 Must(!theStart
); // not started
1594 theState
= stActive
;
1597 void Adaptation::Icap::VirginBodyAct::disable()
1599 theState
= stDisabled
;
1602 void Adaptation::Icap::VirginBodyAct::progress(size_t size
)
1606 theStart
+= static_cast<int64_t>(size
);
1609 uint64_t Adaptation::Icap::VirginBodyAct::offset() const
1612 return static_cast<uint64_t>(theStart
);
1616 Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled
)
1619 void Adaptation::Icap::Preview::enable(size_t anAd
)
1621 // TODO: check for anAd not exceeding preview size limit
1625 theState
= stWriting
;
1628 bool Adaptation::Icap::Preview::enabled() const
1630 return theState
!= stDisabled
;
1633 size_t Adaptation::Icap::Preview::ad() const
1639 bool Adaptation::Icap::Preview::done() const
1642 return theState
>= stIeof
;
1645 bool Adaptation::Icap::Preview::ieof() const
1648 return theState
== stIeof
;
1651 size_t Adaptation::Icap::Preview::debt() const
1654 return done() ? 0 : (theAd
- theWritten
);
1657 void Adaptation::Icap::Preview::wrote(size_t size
, bool wroteEof
)
1663 Must(theWritten
<= theAd
);
1666 theState
= stIeof
; // written size is irrelevant
1667 else if (theWritten
>= theAd
)
1671 bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf
&mb
) const
1673 if (virgin
.header
== NULL
)
1676 virgin
.header
->firstLineBuf(mb
);
1682 /* Adaptation::Icap::ModXactLauncher */
1684 Adaptation::Icap::ModXactLauncher::ModXactLauncher(Adaptation::Initiator
*anInitiator
, HttpMsg
*virginHeader
, HttpRequest
*virginCause
, Adaptation::ServicePointer aService
):
1685 AsyncJob("Adaptation::Icap::ModXactLauncher"),
1686 Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", anInitiator
, aService
)
1688 virgin
.setHeader(virginHeader
);
1689 virgin
.setCause(virginCause
);
1690 updateHistory(true);
1693 Adaptation::Icap::Xaction
*Adaptation::Icap::ModXactLauncher::createXaction()
1695 Adaptation::Icap::ServiceRep::Pointer s
=
1696 dynamic_cast<Adaptation::Icap::ServiceRep
*>(theService
.getRaw());
1698 return new Adaptation::Icap::ModXact(this, virgin
.header
, virgin
.cause
, s
);
1701 void Adaptation::Icap::ModXactLauncher::swanSong()
1703 debugs(93, 5, HERE
<< "swan sings");
1704 updateHistory(false);
1705 Adaptation::Icap::Launcher::swanSong();
1708 void Adaptation::Icap::ModXactLauncher::updateHistory(bool doStart
)
1710 HttpRequest
*r
= virgin
.cause
?
1711 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
1713 // r should never be NULL but we play safe; TODO: add Should()
1715 Adaptation::Icap::History::Pointer h
= r
->icapHistory();
1718 h
->start("ICAPModXactLauncher");
1720 h
->stop("ICAPModXactLauncher");