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"
20 #include "HttpRequest.h"
21 #include "HttpReply.h"
22 #include "SquidTime.h"
24 // flow and terminology:
25 // HTTP| --> receive --> encode --> write --> |network
26 // end | <-- send <-- parse <-- read <-- |end
28 // TODO: replace gotEncapsulated() with something faster; we call it often
30 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXact
);
31 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXactLauncher
);
33 static const size_t TheBackupLimit
= BodyPipe::MaxCapacity
;
35 Adaptation::Icap::ModXact::State::State()
37 memset(this, 0, sizeof(*this));
40 Adaptation::Icap::ModXact::ModXact(HttpMsg
*virginHeader
,
41 HttpRequest
*virginCause
, Adaptation::Icap::ServiceRep::Pointer
&aService
):
42 AsyncJob("Adaptation::Icap::ModXact"),
43 Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", aService
),
46 canStartBypass(false), // too early
47 protectGroupBypass(true),
48 replyHttpHeaderSize(-1),
49 replyHttpBodySize(-1),
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
= 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 typedef NullaryMemFunT
<ModXact
> Dialer
;
98 AsyncCall::Pointer call
= JobCallback(93,5,
99 Dialer
, this, Adaptation::Icap::ModXact::noteServiceReady
);
100 service().callWhenReady(call
);
101 state
.serviceWaiting
= true; // after callWhenReady() which may throw
104 void Adaptation::Icap::ModXact::noteServiceReady()
106 Must(state
.serviceWaiting
);
107 state
.serviceWaiting
= false;
109 if (service().up()) {
113 disableRepeats("ICAP service is unusable");
114 throw TexcHere("ICAP service is unusable");
118 void Adaptation::Icap::ModXact::startWriting()
120 state
.writing
= State::writingConnect
;
122 decideOnPreview(); // must be decided before we decideOnRetries
128 // connection with the ICAP service established
129 void Adaptation::Icap::ModXact::handleCommConnected()
131 Must(state
.writing
== State::writingConnect
);
133 startReading(); // wait for early errors from the ICAP server
138 makeRequestHeaders(requestBuf
);
139 debugs(93, 9, HERE
<< "will write" << status() << ":\n" <<
140 (requestBuf
.terminate(), requestBuf
.content()));
143 state
.writing
= State::writingHeaders
;
144 icap_tio_start
= current_time
;
145 scheduleWrite(requestBuf
);
148 void Adaptation::Icap::ModXact::handleCommWrote(size_t sz
)
150 debugs(93, 5, HERE
<< "Wrote " << sz
<< " bytes");
152 if (state
.writing
== State::writingHeaders
)
153 handleCommWroteHeaders();
155 handleCommWroteBody();
158 void Adaptation::Icap::ModXact::handleCommWroteHeaders()
160 Must(state
.writing
== State::writingHeaders
);
162 // determine next step
163 if (preview
.enabled()) {
165 decideWritingAfterPreview("zero-size");
167 state
.writing
= State::writingPreview
;
168 } else if (virginBody
.expected()) {
169 state
.writing
= State::writingPrime
;
178 void Adaptation::Icap::ModXact::writeMore()
180 debugs(93, 5, HERE
<< "checking whether to write more" << status());
182 if (writer
!= NULL
) // already writing something
185 switch (state
.writing
) {
187 case State::writingInit
: // waiting for service OPTIONS
188 Must(state
.serviceWaiting
);
190 case State::writingConnect
: // waiting for the connection to establish
192 case State::writingHeaders
: // waiting for the headers to be written
194 case State::writingPaused
: // waiting for the ICAP server response
196 case State::writingReallyDone
: // nothing more to write
199 case State::writingAlmostDone
: // was waiting for the last write
203 case State::writingPreview
:
207 case State::writingPrime
:
212 throw TexcHere("Adaptation::Icap::ModXact in bad writing state");
216 void Adaptation::Icap::ModXact::writePreviewBody()
218 debugs(93, 8, HERE
<< "will write Preview body from " <<
219 virgin
.body_pipe
<< status());
220 Must(state
.writing
== State::writingPreview
);
221 Must(virgin
.body_pipe
!= NULL
);
223 const size_t sizeMax
= (size_t)virgin
.body_pipe
->buf().contentSize();
224 const size_t size
= min(preview
.debt(), sizeMax
);
225 writeSomeBody("preview body", size
);
227 // change state once preview is written
230 decideWritingAfterPreview("body");
233 /// determine state.writing after we wrote the entire preview
234 void Adaptation::Icap::ModXact::decideWritingAfterPreview(const char *kind
)
236 if (preview
.ieof()) // nothing more to write
238 else if (state
.parsing
== State::psIcapHeader
) // did not get a reply yet
239 state
.writing
= State::writingPaused
; // wait for the ICAP server reply
241 stopWriting(true); // ICAP server reply implies no post-preview writing
243 debugs(93, 6, HERE
<< "decided on writing after " << kind
<< " preview" <<
247 void Adaptation::Icap::ModXact::writePrimeBody()
249 Must(state
.writing
== State::writingPrime
);
250 Must(virginBodyWriting
.active());
252 const size_t size
= (size_t)virgin
.body_pipe
->buf().contentSize();
253 writeSomeBody("prime virgin body", size
);
255 if (virginBodyEndReached(virginBodyWriting
)) {
256 debugs(93, 5, HERE
<< "wrote entire body");
261 void Adaptation::Icap::ModXact::writeSomeBody(const char *label
, size_t size
)
263 Must(!writer
&& state
.writing
< state
.writingAlmostDone
);
264 Must(virgin
.body_pipe
!= NULL
);
265 debugs(93, 8, HERE
<< "will write up to " << size
<< " bytes of " <<
268 MemBuf writeBuf
; // TODO: suggest a min size based on size and lastChunk
270 writeBuf
.init(); // note: we assume that last-chunk will fit
272 const size_t writableSize
= virginContentSize(virginBodyWriting
);
273 const size_t chunkSize
= min(writableSize
, size
);
276 debugs(93, 7, HERE
<< "will write " << chunkSize
<<
277 "-byte chunk of " << label
);
279 openChunk(writeBuf
, chunkSize
, false);
280 writeBuf
.append(virginContentData(virginBodyWriting
), chunkSize
);
281 closeChunk(writeBuf
);
283 virginBodyWriting
.progress(chunkSize
);
286 debugs(93, 7, HERE
<< "has no writable " << label
<< " content");
289 const bool wroteEof
= virginBodyEndReached(virginBodyWriting
);
290 bool lastChunk
= wroteEof
;
291 if (state
.writing
== State::writingPreview
) {
292 preview
.wrote(chunkSize
, wroteEof
); // even if wrote nothing
293 lastChunk
= lastChunk
|| preview
.done();
297 debugs(93, 8, HERE
<< "will write last-chunk of " << label
);
298 addLastRequestChunk(writeBuf
);
301 debugs(93, 7, HERE
<< "will write " << writeBuf
.contentSize()
302 << " raw bytes of " << label
);
304 if (writeBuf
.hasContent()) {
305 scheduleWrite(writeBuf
); // comm will free the chunk
311 void Adaptation::Icap::ModXact::addLastRequestChunk(MemBuf
&buf
)
313 const bool ieof
= state
.writing
== State::writingPreview
&& preview
.ieof();
314 openChunk(buf
, 0, ieof
);
318 void Adaptation::Icap::ModXact::openChunk(MemBuf
&buf
, size_t chunkSize
, bool ieof
)
320 buf
.Printf((ieof
? "%x; ieof\r\n" : "%x\r\n"), (int) chunkSize
);
323 void Adaptation::Icap::ModXact::closeChunk(MemBuf
&buf
)
325 buf
.append(ICAP::crlf
, 2); // chunk-terminating CRLF
328 const HttpRequest
&Adaptation::Icap::ModXact::virginRequest() const
330 const HttpRequest
*request
= virgin
.cause
?
331 virgin
.cause
: dynamic_cast<const HttpRequest
*>(virgin
.header
);
336 // did the activity reached the end of the virgin body?
337 bool Adaptation::Icap::ModXact::virginBodyEndReached(const Adaptation::Icap::VirginBodyAct
&act
) const
340 !act
.active() || // did all (assuming it was originally planned)
341 !virgin
.body_pipe
->expectMoreAfter(act
.offset()); // wont have more
344 // the size of buffered virgin body data available for the specified activity
345 // if this size is zero, we may be done or may be waiting for more data
346 size_t Adaptation::Icap::ModXact::virginContentSize(const Adaptation::Icap::VirginBodyAct
&act
) const
349 // asbolute start of unprocessed data
350 const uint64_t dataStart
= act
.offset();
351 // absolute end of buffered data
352 const uint64_t dataEnd
= virginConsumed
+ virgin
.body_pipe
->buf().contentSize();
353 Must(virginConsumed
<= dataStart
&& dataStart
<= dataEnd
);
354 return static_cast<size_t>(dataEnd
- dataStart
);
357 // pointer to buffered virgin body data available for the specified activity
358 const char *Adaptation::Icap::ModXact::virginContentData(const Adaptation::Icap::VirginBodyAct
&act
) const
361 const uint64_t dataStart
= act
.offset();
362 Must(virginConsumed
<= dataStart
);
363 return virgin
.body_pipe
->buf().content() + static_cast<size_t>(dataStart
-virginConsumed
);
366 void Adaptation::Icap::ModXact::virginConsume()
368 debugs(93, 9, HERE
<< "consumption guards: " << !virgin
.body_pipe
<< isRetriable
<<
369 isRepeatable
<< canStartBypass
<< protectGroupBypass
);
371 if (!virgin
.body_pipe
)
372 return; // nothing to consume
375 return; // do not consume if we may have to retry later
377 BodyPipe
&bp
= *virgin
.body_pipe
;
378 const bool wantToPostpone
= isRepeatable
|| canStartBypass
|| protectGroupBypass
;
380 // Why > 2? HttpState does not use the last bytes in the buffer
381 // because delayAwareRead() is arguably broken. See
382 // HttpStateData::maybeReadVirginBody for more details.
383 if (wantToPostpone
&& bp
.buf().spaceSize() > 2) {
384 // Postponing may increase memory footprint and slow the HTTP side
385 // down. Not postponing may increase the number of ICAP errors
386 // if the ICAP service fails. We may also use "potential" space to
387 // postpone more aggressively. Should the trade-off be configurable?
388 debugs(93, 8, HERE
<< "postponing consumption from " << bp
.status());
392 const size_t have
= static_cast<size_t>(bp
.buf().contentSize());
393 const uint64_t end
= virginConsumed
+ have
;
394 uint64_t offset
= end
;
396 debugs(93, 9, HERE
<< "max virgin consumption offset=" << offset
<<
397 " acts " << virginBodyWriting
.active() << virginBodySending
.active() <<
398 " consumed=" << virginConsumed
<<
399 " from " << virgin
.body_pipe
->status());
401 if (virginBodyWriting
.active())
402 offset
= min(virginBodyWriting
.offset(), offset
);
404 if (virginBodySending
.active())
405 offset
= min(virginBodySending
.offset(), offset
);
407 Must(virginConsumed
<= offset
&& offset
<= end
);
409 if (const size_t size
= static_cast<size_t>(offset
- virginConsumed
)) {
410 debugs(93, 8, HERE
<< "consuming " << size
<< " out of " << have
<<
411 " virgin body bytes");
413 virginConsumed
+= size
;
414 Must(!isRetriable
); // or we should not be consuming
415 disableRepeats("consumed content");
416 disableBypass("consumed content", true);
420 void Adaptation::Icap::ModXact::handleCommWroteBody()
425 // Called when we do not expect to call comm_write anymore.
426 // We may have a pending write though.
427 // If stopping nicely, we will just wait for that pending write, if any.
428 void Adaptation::Icap::ModXact::stopWriting(bool nicely
)
430 if (state
.writing
== State::writingReallyDone
)
433 if (writer
!= NULL
) {
435 debugs(93, 7, HERE
<< "will wait for the last write" << status());
436 state
.writing
= State::writingAlmostDone
; // may already be set
440 debugs(93, 3, HERE
<< "will NOT wait for the last write" << status());
442 // Comm does not have an interface to clear the writer callback nicely,
443 // but without clearing the writer we cannot recycle the connection.
444 // We prevent connection reuse and hope that we can handle a callback
445 // call at any time, usually in the middle of the destruction sequence!
446 // Somebody should add comm_remove_write_handler() to comm API.
447 reuseConnection
= false;
448 ignoreLastWrite
= true;
451 debugs(93, 7, HERE
<< "will no longer write" << status());
452 if (virginBodyWriting
.active()) {
453 virginBodyWriting
.disable();
456 state
.writing
= State::writingReallyDone
;
460 void Adaptation::Icap::ModXact::stopBackup()
462 if (!virginBodySending
.active())
465 debugs(93, 7, HERE
<< "will no longer backup" << status());
466 virginBodySending
.disable();
470 bool Adaptation::Icap::ModXact::doneAll() const
472 return Adaptation::Icap::Xaction::doneAll() && !state
.serviceWaiting
&&
474 doneReading() && state
.doneWriting();
477 void Adaptation::Icap::ModXact::startReading()
479 Must(connection
>= 0);
481 Must(!adapted
.header
);
482 Must(!adapted
.body_pipe
);
484 // we use the same buffer for headers and body and then consume headers
488 void Adaptation::Icap::ModXact::readMore()
490 if (reader
!= NULL
|| doneReading()) {
491 debugs(93,3,HERE
<< "returning from readMore because reader or doneReading()");
495 // do not fill readBuf if we have no space to store the result
496 if (adapted
.body_pipe
!= NULL
&&
497 !adapted
.body_pipe
->buf().hasPotentialSpace()) {
498 debugs(93,3,HERE
<< "not reading because ICAP reply pipe is full");
502 if (readBuf
.hasSpace())
505 debugs(93,3,HERE
<< "nothing to do because !readBuf.hasSpace()");
508 // comm module read a portion of the ICAP response for us
509 void Adaptation::Icap::ModXact::handleCommRead(size_t)
511 Must(!state
.doneParsing());
512 icap_tio_finish
= current_time
;
517 void Adaptation::Icap::ModXact::echoMore()
519 Must(state
.sending
== State::sendingVirgin
);
520 Must(adapted
.body_pipe
!= NULL
);
521 Must(virginBodySending
.active());
523 const size_t sizeMax
= virginContentSize(virginBodySending
);
524 debugs(93,5, HERE
<< "will echo up to " << sizeMax
<< " bytes from " <<
525 virgin
.body_pipe
->status());
526 debugs(93,5, HERE
<< "will echo up to " << sizeMax
<< " bytes to " <<
527 adapted
.body_pipe
->status());
530 const size_t size
= adapted
.body_pipe
->putMoreData(virginContentData(virginBodySending
), sizeMax
);
531 debugs(93,5, HERE
<< "echoed " << size
<< " out of " << sizeMax
<<
533 virginBodySending
.progress(size
);
534 disableRepeats("echoed content");
535 disableBypass("echoed content", true);
539 if (virginBodyEndReached(virginBodySending
)) {
540 debugs(93, 5, HERE
<< "echoed all" << status());
543 debugs(93, 5, HERE
<< "has " <<
544 virgin
.body_pipe
->buf().contentSize() << " bytes " <<
545 "and expects more to echo" << status());
546 // TODO: timeout if virgin or adapted pipes are broken
550 bool Adaptation::Icap::ModXact::doneSending() const
552 return state
.sending
== State::sendingDone
;
555 // stop (or do not start) sending adapted message body
556 void Adaptation::Icap::ModXact::stopSending(bool nicely
)
558 debugs(93, 7, HERE
<< "Enter stop sending ");
561 debugs(93, 7, HERE
<< "Proceed with stop sending ");
563 if (state
.sending
!= State::sendingUndecided
) {
564 debugs(93, 7, HERE
<< "will no longer send" << status());
565 if (adapted
.body_pipe
!= NULL
) {
566 virginBodySending
.disable();
567 // we may leave debts if we were echoing and the virgin
568 // body_pipe got exhausted before we echoed all planned bytes
569 const bool leftDebts
= adapted
.body_pipe
->needsMoreData();
570 stopProducingFor(adapted
.body_pipe
, nicely
&& !leftDebts
);
573 debugs(93, 7, HERE
<< "will not start sending" << status());
574 Must(!adapted
.body_pipe
);
577 state
.sending
= State::sendingDone
;
581 // should be called after certain state.writing or state.sending changes
582 void Adaptation::Icap::ModXact::checkConsuming()
584 // quit if we already stopped or are still using the pipe
585 if (!virgin
.body_pipe
|| !state
.doneConsumingVirgin())
588 debugs(93, 7, HERE
<< "will stop consuming" << status());
589 stopConsumingFrom(virgin
.body_pipe
);
592 void Adaptation::Icap::ModXact::parseMore()
594 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " bytes to parse" <<
596 debugs(93, 5, HERE
<< "\n" << readBuf
.content());
598 if (state
.parsingHeaders())
601 if (state
.parsing
== State::psBody
)
605 void Adaptation::Icap::ModXact::callException(const std::exception
&e
)
607 if (!canStartBypass
|| isRetriable
) {
608 Adaptation::Icap::Xaction::callException(e
);
613 debugs(93, 3, HERE
<< "bypassing " << inCall
<< " exception: " <<
614 e
.what() << ' ' << status());
616 } catch (const std::exception
&bypassE
) {
617 Adaptation::Icap::Xaction::callException(bypassE
);
621 void Adaptation::Icap::ModXact::bypassFailure()
623 disableBypass("already started to bypass", false);
625 Must(!isRetriable
); // or we should not be bypassing
626 // TODO: should the same be enforced for isRepeatable? Check icap_repeat??
632 // end all activities associated with the ICAP server
636 stopWriting(true); // or should we force it?
637 if (connection
>= 0) {
638 reuseConnection
= false; // be conservative
639 cancelRead(); // may not work; and we cannot stop connecting either
641 debugs(93, 7, HERE
<< "Warning: bypass failed to stop I/O" << status());
645 void Adaptation::Icap::ModXact::disableBypass(const char *reason
, bool includingGroupBypass
)
647 if (canStartBypass
) {
648 debugs(93,7, HERE
<< "will never start bypass because " << reason
);
649 canStartBypass
= false;
651 if (protectGroupBypass
&& includingGroupBypass
) {
652 debugs(93,7, HERE
<< "not protecting group bypass because " << reason
);
653 protectGroupBypass
= false;
659 // note that allocation for echoing is done in handle204NoContent()
660 void Adaptation::Icap::ModXact::maybeAllocateHttpMsg()
662 if (adapted
.header
) // already allocated
665 if (gotEncapsulated("res-hdr")) {
666 adapted
.setHeader(new HttpReply
);
667 setOutcome(service().cfg().method
== ICAP::methodReqmod
?
668 xoSatisfied
: xoModified
);
669 } else if (gotEncapsulated("req-hdr")) {
670 adapted
.setHeader(new HttpRequest
);
671 setOutcome(xoModified
);
673 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
676 void Adaptation::Icap::ModXact::parseHeaders()
678 Must(state
.parsingHeaders());
680 if (state
.parsing
== State::psIcapHeader
) {
681 debugs(93, 5, HERE
<< "parse ICAP headers");
685 if (state
.parsing
== State::psHttpHeader
) {
686 debugs(93, 5, HERE
<< "parse HTTP headers");
690 if (state
.parsingHeaders()) { // need more data
698 // called after parsing all headers or when bypassing an exception
699 void Adaptation::Icap::ModXact::startSending()
701 disableRepeats("sent headers");
702 disableBypass("sent headers", true);
703 sendAnswer(adapted
.header
);
705 if (state
.sending
== State::sendingVirgin
)
709 void Adaptation::Icap::ModXact::parseIcapHead()
711 Must(state
.sending
== State::sendingUndecided
);
713 if (!parseHead(icapReply
))
716 if (httpHeaderHasConnDir(&icapReply
->header
, "close")) {
717 debugs(93, 5, HERE
<< "found connection close");
718 reuseConnection
= false;
721 switch (icapReply
->sline
.status
) {
728 case 201: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
730 if (!validate200Ok()) {
731 throw TexcHere("Invalid ICAP Response");
739 handle204NoContent();
743 handle206PartialContent();
747 debugs(93, 5, HERE
<< "ICAP status " << icapReply
->sline
.status
);
748 handleUnknownScode();
752 const HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
754 request
= &virginRequest();
756 // update the cross-transactional database if needed (all status codes!)
757 if (const char *xxName
= Adaptation::Config::masterx_shared_name
) {
758 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
760 const String val
= icapReply
->header
.getByName(xxName
);
761 if (val
.size() > 0) // XXX: HttpHeader lacks empty value detection
762 ah
->updateXxRecord(xxName
, val
);
766 // update the adaptation plan if needed (all status codes!)
767 if (service().cfg().routing
) {
769 if (icapReply
->header
.getList(HDR_X_NEXT_SERVICES
, &services
)) {
770 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
772 ah
->updateNextServices(services
);
774 } // TODO: else warn (occasionally!) if we got HDR_X_NEXT_SERVICES
776 // We need to store received ICAP headers for <icapLastHeader logformat option.
777 // If we already have stored headers from previous ICAP transaction related to this
778 // request, old headers will be replaced with the new one.
780 Adaptation::Icap::History::Pointer h
= request
->icapHistory();
782 h
->mergeIcapHeaders(&icapReply
->header
);
783 h
->setIcapLastHeader(&icapReply
->header
);
786 // handle100Continue() manages state.writing on its own.
787 // Non-100 status means the server needs no postPreview data from us.
788 if (state
.writing
== State::writingPaused
)
792 bool Adaptation::Icap::ModXact::validate200Ok()
794 if (ICAP::methodRespmod
== service().cfg().method
) {
795 if (!gotEncapsulated("res-hdr"))
801 if (ICAP::methodReqmod
== service().cfg().method
) {
802 if (!gotEncapsulated("res-hdr") && !gotEncapsulated("req-hdr"))
811 void Adaptation::Icap::ModXact::handle100Continue()
813 Must(state
.writing
== State::writingPaused
);
814 // server must not respond before the end of preview: we may send ieof
815 Must(preview
.enabled() && preview
.done() && !preview
.ieof());
817 // 100 "Continue" cancels our Preview commitment,
818 // but not commitment to handle 204 or 206 outside Preview
819 if (!state
.allowedPostview204
&& !state
.allowedPostview206
)
822 state
.parsing
= State::psIcapHeader
; // eventually
825 state
.writing
= State::writingPrime
;
830 void Adaptation::Icap::ModXact::handle200Ok()
832 state
.parsing
= State::psHttpHeader
;
833 state
.sending
= State::sendingAdapted
;
838 void Adaptation::Icap::ModXact::handle204NoContent()
844 void Adaptation::Icap::ModXact::handle206PartialContent()
846 if (state
.writing
== State::writingPaused
) {
847 Must(preview
.enabled());
848 Must(state
.allowedPreview206
);
849 debugs(93, 7, HERE
<< "206 inside preview");
851 Must(state
.writing
> State::writingPaused
);
852 Must(state
.allowedPostview206
);
853 debugs(93, 7, HERE
<< "206 outside preview");
855 state
.parsing
= State::psHttpHeader
;
856 state
.sending
= State::sendingAdapted
;
857 state
.readyForUob
= true;
861 // Called when we receive a 204 No Content response and
862 // when we are trying to bypass a service failure.
863 // We actually start sending (echoig or not) in startSending.
864 void Adaptation::Icap::ModXact::prepEchoing()
866 disableRepeats("preparing to echo content");
867 disableBypass("preparing to echo content", true);
870 // We want to clone the HTTP message, but we do not want
871 // to copy some non-HTTP state parts that HttpMsg kids carry in them.
872 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
873 // Instead, we simply write the HTTP message and "clone" it by parsing.
874 // TODO: use HttpMsg::clone()!
876 HttpMsg
*oldHead
= virgin
.header
;
877 debugs(93, 7, HERE
<< "cloning virgin message " << oldHead
);
881 // write the virgin message into a memory buffer
883 packHead(httpBuf
, oldHead
);
885 // allocate the adapted message and copy metainfo
886 Must(!adapted
.header
);
888 HttpMsg::Pointer newHead
;
889 if (const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(oldHead
)) {
890 HttpRequest::Pointer
newR(new HttpRequest
);
891 newR
->canonical
= oldR
->canonical
?
892 xstrdup(oldR
->canonical
) : NULL
; // parse() does not set it
894 } else if (dynamic_cast<const HttpReply
*>(oldHead
)) {
895 newHead
= new HttpReply
;
897 Must(newHead
!= NULL
);
899 newHead
->inheritProperties(oldHead
);
901 adapted
.setHeader(newHead
);
904 // parse the buffer back
905 http_status error
= HTTP_STATUS_NONE
;
907 Must(adapted
.header
->parse(&httpBuf
, true, &error
));
909 Must(adapted
.header
->hdr_sz
== httpBuf
.contentSize()); // no leftovers
913 debugs(93, 7, HERE
<< "cloned virgin message " << oldHead
<< " to " <<
916 // setup adapted body pipe if needed
917 if (oldHead
->body_pipe
!= NULL
) {
918 debugs(93, 7, HERE
<< "will echo virgin body from " <<
920 if (!virginBodySending
.active())
921 virginBodySending
.plan(); // will throw if not possible
922 state
.sending
= State::sendingVirgin
;
925 // TODO: optimize: is it possible to just use the oldHead pipe and
926 // remove ICAP from the loop? This echoing is probably a common case!
927 makeAdaptedBodyPipe("echoed virgin response");
928 if (oldHead
->body_pipe
->bodySizeKnown())
929 adapted
.body_pipe
->setBodySize(oldHead
->body_pipe
->bodySize());
930 debugs(93, 7, HERE
<< "will echo virgin body to " <<
933 debugs(93, 7, HERE
<< "no virgin body to echo");
938 /// Called when we received use-original-body chunk extension in 206 response.
939 /// We actually start sending (echoing or not) in startSending().
940 void Adaptation::Icap::ModXact::prepPartialBodyEchoing(uint64_t pos
)
942 Must(virginBodySending
.active());
943 Must(virgin
.header
->body_pipe
!= NULL
);
945 setOutcome(xoPartEcho
);
947 debugs(93, 7, HERE
<< "will echo virgin body suffix from " <<
948 virgin
.header
->body_pipe
<< " offset " << pos
);
950 // check that use-original-body=N does not point beyond buffered data
951 const uint64_t virginDataEnd
= virginConsumed
+
952 virgin
.body_pipe
->buf().contentSize();
953 Must(pos
<= virginDataEnd
);
954 virginBodySending
.progress(static_cast<size_t>(pos
));
956 state
.sending
= State::sendingVirgin
;
959 if (virgin
.header
->body_pipe
->bodySizeKnown())
960 adapted
.body_pipe
->expectProductionEndAfter(virgin
.header
->body_pipe
->bodySize() - pos
);
962 debugs(93, 7, HERE
<< "will echo virgin body suffix to " <<
965 // Start echoing data
969 void Adaptation::Icap::ModXact::handleUnknownScode()
973 // TODO: mark connection as "bad"
975 // Terminate the transaction; we do not know how to handle this response.
976 throw TexcHere("Unsupported ICAP status code");
979 void Adaptation::Icap::ModXact::parseHttpHead()
981 if (gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr")) {
982 replyHttpHeaderSize
= 0;
983 maybeAllocateHttpMsg();
985 if (!parseHead(adapted
.header
))
986 return; // need more header data
989 replyHttpHeaderSize
= adapted
.header
->hdr_sz
;
991 if (dynamic_cast<HttpRequest
*>(adapted
.header
)) {
992 const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(virgin
.header
);
994 // TODO: the adapted request did not really originate from the
995 // client; give proxy admin an option to prevent copying of
996 // sensitive client information here. See the following thread:
997 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
1000 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
1002 adapted
.header
->inheritProperties(virgin
.header
);
1005 decideOnParsingBody();
1008 // parses both HTTP and ICAP headers
1009 bool Adaptation::Icap::ModXact::parseHead(HttpMsg
*head
)
1012 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " head bytes to parse" <<
1013 "; state: " << state
.parsing
);
1015 http_status error
= HTTP_STATUS_NONE
;
1016 const bool parsed
= head
->parse(&readBuf
, commEof
, &error
);
1017 Must(parsed
|| !error
); // success or need more data
1019 if (!parsed
) { // need more data
1020 debugs(93, 5, HERE
<< "parse failed, need more data, return false");
1025 if (HttpRequest
*r
= dynamic_cast<HttpRequest
*>(head
))
1026 urlCanonical(r
); // parse does not set HttpRequest::canonical
1028 debugs(93, 5, HERE
<< "parse success, consume " << head
->hdr_sz
<< " bytes, return true");
1029 readBuf
.consume(head
->hdr_sz
);
1033 void Adaptation::Icap::ModXact::decideOnParsingBody()
1035 if (gotEncapsulated("res-body") || gotEncapsulated("req-body")) {
1036 debugs(93, 5, HERE
<< "expecting a body");
1037 state
.parsing
= State::psBody
;
1038 replyHttpBodySize
= 0;
1039 bodyParser
= new ChunkedCodingParser
;
1040 makeAdaptedBodyPipe("adapted response from the ICAP server");
1041 Must(state
.sending
== State::sendingAdapted
);
1043 debugs(93, 5, HERE
<< "not expecting a body");
1049 void Adaptation::Icap::ModXact::parseBody()
1051 Must(state
.parsing
== State::psBody
);
1054 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " body bytes to parse");
1056 // the parser will throw on errors
1057 BodyPipeCheckout
bpc(*adapted
.body_pipe
);
1058 const bool parsed
= bodyParser
->parse(&readBuf
, &bpc
.buf
);
1061 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " body bytes after " <<
1062 "parse; parsed all: " << parsed
);
1063 replyHttpBodySize
+= adapted
.body_pipe
->buf().contentSize();
1065 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
1066 // TODO: do we really need this if we disable when sending headers?
1067 if (adapted
.body_pipe
->buf().contentSize() > 0) { // parsed something sometime
1068 disableRepeats("sent adapted content");
1069 disableBypass("sent adapted content", true);
1073 if (state
.readyForUob
&& bodyParser
->useOriginBody
>= 0) {
1074 prepPartialBodyEchoing(
1075 static_cast<uint64_t>(bodyParser
->useOriginBody
));
1081 stopSending(true); // the parser succeeds only if all parsed data fits
1085 debugs(93,3,HERE
<< this << " needsMoreData = " << bodyParser
->needsMoreData());
1087 if (bodyParser
->needsMoreData()) {
1088 debugs(93,3,HERE
<< this);
1089 Must(mayReadMore());
1093 if (bodyParser
->needsMoreSpace()) {
1094 Must(!doneSending()); // can hope for more space
1095 Must(adapted
.body_pipe
->buf().contentSize() > 0); // paranoid
1096 // TODO: there should be a timeout in case the sink is broken
1097 // or cannot consume partial content (while we need more space)
1101 void Adaptation::Icap::ModXact::stopParsing()
1103 if (state
.parsing
== State::psDone
)
1106 debugs(93, 7, HERE
<< "will no longer parse" << status());
1112 state
.parsing
= State::psDone
;
1115 // HTTP side added virgin body data
1116 void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer
)
1120 if (state
.sending
== State::sendingVirgin
)
1124 // HTTP side sent us all virgin info
1125 void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer
)
1127 Must(virgin
.body_pipe
->productionEnded());
1129 // push writer and sender in case we were waiting for the last-chunk
1132 if (state
.sending
== State::sendingVirgin
)
1136 // body producer aborted, but the initiator may still want to know
1137 // the answer, even though the HTTP message has been truncated
1138 void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer
)
1140 Must(virgin
.body_pipe
->productionEnded());
1142 // push writer and sender in case we were waiting for the last-chunk
1145 if (state
.sending
== State::sendingVirgin
)
1149 // adapted body consumer wants more adapted data and
1150 // possibly freed some buffer space
1151 void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
1153 if (state
.sending
== State::sendingVirgin
)
1155 else if (state
.sending
== State::sendingAdapted
)
1158 Must(state
.sending
== State::sendingUndecided
);
1161 // adapted body consumer aborted
1162 void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer
)
1164 mustStop("adapted body consumer aborted");
1167 Adaptation::Icap::ModXact::~ModXact()
1173 void Adaptation::Icap::ModXact::swanSong()
1175 debugs(93, 5, HERE
<< "swan sings" << status());
1180 // update adaptation history if start was called and we reserved a slot
1181 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
1182 if (ah
!= NULL
&& adaptHistoryId
>= 0)
1183 ah
->recordXactFinish(adaptHistoryId
);
1185 Adaptation::Icap::Xaction::swanSong();
1188 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry
*);
1190 void Adaptation::Icap::ModXact::finalizeLogInfo()
1192 HttpRequest
* request_
= NULL
;
1193 HttpReply
* reply_
= NULL
;
1194 if (!(request_
= dynamic_cast<HttpRequest
*>(adapted
.header
))) {
1195 request_
= (virgin
.cause
? virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
));
1196 reply_
= dynamic_cast<HttpReply
*>(adapted
.header
);
1199 Adaptation::Icap::History::Pointer h
= request_
->icapHistory();
1200 Must(h
!= NULL
); // ICAPXaction::maybeLog calls only if there is a log
1201 al
.icp
.opcode
= ICP_INVALID
;
1202 al
.url
= h
->log_uri
.termedBuf();
1203 const Adaptation::Icap::ServiceRep
&s
= service();
1204 al
.icap
.reqMethod
= s
.cfg().method
;
1206 al
.cache
.caddr
= request_
->client_addr
;
1208 al
.request
= HTTPMSGLOCK(request_
);
1210 al
.reply
= HTTPMSGLOCK(reply_
);
1214 if (h
->rfc931
.size())
1215 al
.cache
.rfc931
= h
->rfc931
.termedBuf();
1218 if (h
->ssluser
.size())
1219 al
.cache
.ssluser
= h
->ssluser
.termedBuf();
1221 al
.cache
.code
= h
->logType
;
1222 al
.cache
.requestSize
= h
->req_sz
;
1224 // leave al.icap.bodyBytesRead negative if no body
1225 if (replyHttpHeaderSize
>= 0 || replyHttpBodySize
>= 0) {
1226 const int64_t zero
= 0; // to make max() argument types the same
1227 al
.icap
.bodyBytesRead
=
1228 max(zero
, replyHttpHeaderSize
) + max(zero
, replyHttpBodySize
);
1232 al
.http
.code
= reply_
->sline
.status
;
1233 al
.http
.content_type
= reply_
->content_type
.termedBuf();
1234 if (replyHttpBodySize
>= 0) {
1235 al
.cache
.replySize
= replyHttpBodySize
+ reply_
->hdr_sz
;
1236 al
.cache
.highOffset
= replyHttpBodySize
;
1238 //don't set al.cache.objectSize because it hasn't exist yet
1244 packerToMemInit(&p
, &mb
);
1246 reply_
->header
.packInto(&p
);
1247 al
.headers
.reply
= xstrdup(mb
.buf
);
1252 prepareLogWithRequestDetails(request_
, &al
);
1253 Xaction::finalizeLogInfo();
1257 void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf
&buf
)
1259 char ntoabuf
[MAX_IPSTRLEN
];
1261 * XXX These should use HttpHdr interfaces instead of Printfs
1263 const Adaptation::ServiceConfig
&s
= service().cfg();
1264 buf
.Printf("%s " SQUIDSTRINGPH
" ICAP/1.0\r\n", s
.methodStr(), SQUIDSTRINGPRINT(s
.uri
));
1265 buf
.Printf("Host: " SQUIDSTRINGPH
":%d\r\n", SQUIDSTRINGPRINT(s
.host
), s
.port
);
1266 buf
.Printf("Date: %s\r\n", mkrfc1123(squid_curtime
));
1268 if (!TheConfig
.reuse_connections
)
1269 buf
.Printf("Connection: close\r\n");
1271 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1273 if (virgin
.header
->header
.has(HDR_PROXY_AUTHENTICATE
)) {
1274 String vh
=virgin
.header
->header
.getByName("Proxy-Authenticate");
1275 buf
.Printf("Proxy-Authenticate: " SQUIDSTRINGPH
"\r\n",SQUIDSTRINGPRINT(vh
));
1278 if (virgin
.header
->header
.has(HDR_PROXY_AUTHORIZATION
)) {
1279 String vh
=virgin
.header
->header
.getByName("Proxy-Authorization");
1280 buf
.Printf("Proxy-Authorization: " SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(vh
));
1283 const HttpRequest
*request
= &virginRequest();
1285 // share the cross-transactional database records if needed
1286 if (Adaptation::Config::masterx_shared_name
) {
1287 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
1290 if (ah
->getXxRecord(name
, value
)) {
1291 buf
.Printf(SQUIDSTRINGPH
": " SQUIDSTRINGPH
"\r\n",
1292 SQUIDSTRINGPRINT(name
), SQUIDSTRINGPRINT(value
));
1298 buf
.Printf("Encapsulated: ");
1304 // build HTTP request header, if any
1305 ICAP::Method m
= s
.method
;
1307 // to simplify, we could assume that request is always available
1311 urlPath
= request
->urlpath
;
1312 if (ICAP::methodRespmod
== m
)
1313 encapsulateHead(buf
, "req-hdr", httpBuf
, request
);
1314 else if (ICAP::methodReqmod
== m
)
1315 encapsulateHead(buf
, "req-hdr", httpBuf
, virgin
.header
);
1318 if (ICAP::methodRespmod
== m
)
1319 if (const HttpMsg
*prime
= virgin
.header
)
1320 encapsulateHead(buf
, "res-hdr", httpBuf
, prime
);
1322 if (!virginBody
.expected())
1323 buf
.Printf("null-body=%d", (int) httpBuf
.contentSize());
1324 else if (ICAP::methodReqmod
== m
)
1325 buf
.Printf("req-body=%d", (int) httpBuf
.contentSize());
1327 buf
.Printf("res-body=%d", (int) httpBuf
.contentSize());
1329 buf
.append(ICAP::crlf
, 2); // terminate Encapsulated line
1331 if (preview
.enabled()) {
1332 buf
.Printf("Preview: %d\r\n", (int)preview
.ad());
1333 if (!virginBody
.expected()) // there is no body to preview
1334 finishNullOrEmptyBodyPreview(httpBuf
);
1337 makeAllowHeader(buf
);
1339 if (TheConfig
.send_client_ip
&& request
) {
1340 Ip::Address client_addr
;
1341 #if FOLLOW_X_FORWARDED_FOR
1342 if (TheConfig
.icap_uses_indirect_client
) {
1343 client_addr
= request
->indirect_client_addr
;
1346 client_addr
= request
->client_addr
;
1347 if (!client_addr
.IsAnyAddr() && !client_addr
.IsNoAddr())
1348 buf
.Printf("X-Client-IP: %s\r\n", client_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
1351 if (TheConfig
.send_client_username
&& request
)
1352 makeUsernameHeader(request
, buf
);
1354 // fprintf(stderr, "%s\n", buf.content());
1356 buf
.append(ICAP::crlf
, 2); // terminate ICAP header
1358 // fill icapRequest for logging
1359 Must(icapRequest
->parseCharBuf(buf
.content(), buf
.contentSize()));
1361 // start ICAP request body with encapsulated HTTP headers
1362 buf
.append(httpBuf
.content(), httpBuf
.contentSize());
1367 // decides which Allow values to write and updates the request buffer
1368 void Adaptation::Icap::ModXact::makeAllowHeader(MemBuf
&buf
)
1370 const bool allow204in
= preview
.enabled(); // TODO: add shouldAllow204in()
1371 const bool allow204out
= state
.allowedPostview204
= shouldAllow204();
1372 const bool allow206in
= state
.allowedPreview206
= shouldAllow206in();
1373 const bool allow206out
= state
.allowedPostview206
= shouldAllow206out();
1375 debugs(93,9, HERE
<< "Allows: " << allow204in
<< allow204out
<<
1376 allow206in
<< allow206out
);
1378 const bool allow204
= allow204in
|| allow204out
;
1379 const bool allow206
= allow206in
|| allow206out
;
1381 if (!allow204
&& !allow206
)
1382 return; // nothing to do
1384 if (virginBody
.expected()) // if there is a virgin body, plan to send it
1385 virginBodySending
.plan();
1387 // writing Preview:... means we will honor 204 inside preview
1388 // writing Allow/204 means we will honor 204 outside preview
1389 // writing Allow:206 means we will honor 206 inside preview
1390 // writing Allow:204,206 means we will honor 206 outside preview
1391 const char *allowHeader
= NULL
;
1392 if (allow204out
&& allow206
)
1393 allowHeader
= "Allow: 204, 206\r\n";
1394 else if (allow204out
)
1395 allowHeader
= "Allow: 204\r\n";
1397 allowHeader
= "Allow: 206\r\n";
1399 if (allowHeader
) { // may be nil if only allow204in is true
1400 buf
.append(allowHeader
, strlen(allowHeader
));
1401 debugs(93,5, HERE
<< "Will write " << allowHeader
);
1405 void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest
*request
, MemBuf
&buf
)
1407 if (request
->auth_user_request
!= NULL
) {
1408 char const *name
= request
->auth_user_request
->username();
1410 const char *value
= TheConfig
.client_username_encode
? base64_encode(name
) : name
;
1411 buf
.Printf("%s: %s\r\n", TheConfig
.client_username_header
, value
);
1416 void Adaptation::Icap::ModXact::encapsulateHead(MemBuf
&icapBuf
, const char *section
, MemBuf
&httpBuf
, const HttpMsg
*head
)
1418 // update ICAP header
1419 icapBuf
.Printf("%s=%d, ", section
, (int) httpBuf
.contentSize());
1422 HttpMsg::Pointer headClone
;
1424 if (const HttpRequest
* old_request
= dynamic_cast<const HttpRequest
*>(head
)) {
1425 HttpRequest::Pointer
new_request(new HttpRequest
);
1426 Must(old_request
->canonical
);
1427 urlParse(old_request
->method
, old_request
->canonical
, new_request
);
1428 new_request
->http_ver
= old_request
->http_ver
;
1429 headClone
= new_request
;
1430 } else if (const HttpReply
*old_reply
= dynamic_cast<const HttpReply
*>(head
)) {
1431 HttpReply::Pointer
new_reply(new HttpReply
);
1432 new_reply
->sline
= old_reply
->sline
;
1433 headClone
= new_reply
;
1435 Must(headClone
!= NULL
);
1436 headClone
->inheritProperties(head
);
1438 HttpHeaderPos pos
= HttpHeaderInitPos
;
1439 HttpHeaderEntry
* p_head_entry
= NULL
;
1440 while (NULL
!= (p_head_entry
= head
->header
.getEntry(&pos
)) )
1441 headClone
->header
.addEntry(p_head_entry
->clone());
1445 // remove all hop-by-hop headers from the clone
1446 headClone
->header
.delById(HDR_PROXY_AUTHENTICATE
);
1447 headClone
->header
.removeHopByHopEntries();
1449 // pack polished HTTP header
1450 packHead(httpBuf
, headClone
);
1452 // headClone unlocks and, hence, deletes the message we packed
1455 void Adaptation::Icap::ModXact::packHead(MemBuf
&httpBuf
, const HttpMsg
*head
)
1458 packerToMemInit(&p
, &httpBuf
);
1459 head
->packInto(&p
, true);
1463 // decides whether to offer a preview and calculates its size
1464 void Adaptation::Icap::ModXact::decideOnPreview()
1466 if (!TheConfig
.preview_enable
) {
1467 debugs(93, 5, HERE
<< "preview disabled by squid.conf");
1471 const String urlPath
= virginRequest().urlpath
;
1473 if (!service().wantsPreview(urlPath
, wantedSize
)) {
1474 debugs(93, 5, HERE
<< "should not offer preview for " << urlPath
);
1478 // we decided to do preview, now compute its size
1480 Must(wantedSize
>= 0);
1482 // cannot preview more than we can backup
1483 size_t ad
= min(wantedSize
, TheBackupLimit
);
1485 if (!virginBody
.expected())
1487 else if (virginBody
.knownSize())
1488 ad
= min(static_cast<uint64_t>(ad
), virginBody
.size()); // not more than we have
1490 debugs(93, 5, HERE
<< "should offer " << ad
<< "-byte preview " <<
1491 "(service wanted " << wantedSize
<< ")");
1494 Must(preview
.enabled());
1497 // decides whether to allow 204 responses
1498 bool Adaptation::Icap::ModXact::shouldAllow204()
1500 if (!service().allows204())
1503 return canBackupEverything();
1506 // decides whether to allow 206 responses in some mode
1507 bool Adaptation::Icap::ModXact::shouldAllow206any()
1509 return TheConfig
.allow206_enable
&& service().allows206() &&
1510 virginBody
.expected(); // no need for 206 without a body
1513 // decides whether to allow 206 responses in preview mode
1514 bool Adaptation::Icap::ModXact::shouldAllow206in()
1516 return shouldAllow206any() && preview
.enabled();
1519 // decides whether to allow 206 responses outside of preview
1520 bool Adaptation::Icap::ModXact::shouldAllow206out()
1522 return shouldAllow206any() && canBackupEverything();
1525 // used by shouldAllow204 and decideOnRetries
1526 bool Adaptation::Icap::ModXact::canBackupEverything() const
1528 if (!virginBody
.expected())
1529 return true; // no body means no problems with backup
1531 // if there is a body, check whether we can backup it all
1533 if (!virginBody
.knownSize())
1536 // or should we have a different backup limit?
1537 // note that '<' allows for 0-termination of the "full" backup buffer
1538 return virginBody
.size() < TheBackupLimit
;
1541 // Decide whether this transaction can be retried if pconn fails
1542 // Must be called after decideOnPreview and before openConnection()
1543 void Adaptation::Icap::ModXact::decideOnRetries()
1546 return; // no, already decided
1548 if (preview
.enabled())
1549 return; // yes, because preview provides enough guarantees
1551 if (canBackupEverything())
1552 return; // yes, because we can back everything up
1554 disableRetries(); // no, because we cannot back everything up
1557 // Normally, the body-writing code handles preview body. It can deal with
1558 // bodies of unexpected size, including those that turn out to be empty.
1559 // However, that code assumes that the body was expected and body control
1560 // structures were initialized. This is not the case when there is no body
1561 // or the body is known to be empty, because the virgin message will lack a
1562 // body_pipe. So we handle preview of null-body and zero-size bodies here.
1563 void Adaptation::Icap::ModXact::finishNullOrEmptyBodyPreview(MemBuf
&buf
)
1565 Must(!virginBodyWriting
.active()); // one reason we handle it here
1566 Must(!virgin
.body_pipe
); // another reason we handle it here
1567 Must(!preview
.ad());
1569 // do not add last-chunk because our Encapsulated header says null-body
1570 // addLastRequestChunk(buf);
1571 preview
.wrote(0, true);
1573 Must(preview
.done());
1574 Must(preview
.ieof());
1577 void Adaptation::Icap::ModXact::fillPendingStatus(MemBuf
&buf
) const
1579 Adaptation::Icap::Xaction::fillPendingStatus(buf
);
1581 if (state
.serviceWaiting
)
1584 if (virgin
.body_pipe
!= NULL
)
1587 if (connection
> 0 && !doneReading())
1590 if (!state
.doneWriting() && state
.writing
!= State::writingInit
)
1591 buf
.Printf("w(%d)", state
.writing
);
1593 if (preview
.enabled()) {
1594 if (!preview
.done())
1595 buf
.Printf("P(%d)", (int) preview
.debt());
1598 if (virginBodySending
.active())
1601 if (!state
.doneParsing() && state
.parsing
!= State::psIcapHeader
)
1602 buf
.Printf("p(%d)", state
.parsing
);
1604 if (!doneSending() && state
.sending
!= State::sendingUndecided
)
1605 buf
.Printf("S(%d)", state
.sending
);
1607 if (state
.readyForUob
)
1613 if (protectGroupBypass
)
1617 void Adaptation::Icap::ModXact::fillDoneStatus(MemBuf
&buf
) const
1619 Adaptation::Icap::Xaction::fillDoneStatus(buf
);
1621 if (!virgin
.body_pipe
)
1624 if (state
.doneWriting())
1627 if (preview
.enabled()) {
1629 buf
.Printf("P%s", preview
.ieof() ? "(ieof)" : "");
1635 if (state
.doneParsing())
1642 bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section
) const
1644 return icapReply
->header
.getByNameListMember("Encapsulated",
1645 section
, ',').size() > 0;
1648 // calculate whether there is a virgin HTTP body and
1649 // whether its expected size is known
1650 // TODO: rename because we do not just estimate
1651 void Adaptation::Icap::ModXact::estimateVirginBody()
1653 // note: lack of size info may disable previews and 204s
1655 HttpMsg
*msg
= virgin
.header
;
1658 HttpRequestMethod method
;
1661 method
= virgin
.cause
->method
;
1662 else if (HttpRequest
*req
= dynamic_cast<HttpRequest
*>(msg
))
1663 method
= req
->method
;
1665 method
= METHOD_NONE
;
1668 // expectingBody returns true for zero-sized bodies, but we will not
1669 // get a pipe for that body, so we treat the message as bodyless
1670 if (method
!= METHOD_NONE
&& msg
->expectingBody(method
, size
) && size
) {
1671 debugs(93, 6, HERE
<< "expects virgin body from " <<
1672 virgin
.body_pipe
<< "; size: " << size
);
1674 virginBody
.expect(size
);
1675 virginBodyWriting
.plan();
1677 // sign up as a body consumer
1678 Must(msg
->body_pipe
!= NULL
);
1679 Must(msg
->body_pipe
== virgin
.body_pipe
);
1680 Must(virgin
.body_pipe
->setConsumerIfNotLate(this));
1682 // make sure TheBackupLimit is in-sync with the buffer size
1683 Must(TheBackupLimit
<= static_cast<size_t>(msg
->body_pipe
->buf().max_capacity
));
1685 debugs(93, 6, HERE
<< "does not expect virgin body");
1686 Must(msg
->body_pipe
== NULL
);
1691 void Adaptation::Icap::ModXact::makeAdaptedBodyPipe(const char *what
)
1693 Must(!adapted
.body_pipe
);
1694 Must(!adapted
.header
->body_pipe
);
1695 adapted
.header
->body_pipe
= new BodyPipe(this);
1696 adapted
.body_pipe
= adapted
.header
->body_pipe
;
1697 debugs(93, 7, HERE
<< "will supply " << what
<< " via " <<
1698 adapted
.body_pipe
<< " pipe");
1702 // TODO: Move SizedEstimate and Preview elsewhere
1704 Adaptation::Icap::SizedEstimate::SizedEstimate()
1705 : theData(dtUnexpected
)
1708 void Adaptation::Icap::SizedEstimate::expect(int64_t aSize
)
1710 theData
= (aSize
>= 0) ? aSize
: (int64_t)dtUnknown
;
1713 bool Adaptation::Icap::SizedEstimate::expected() const
1715 return theData
!= dtUnexpected
;
1718 bool Adaptation::Icap::SizedEstimate::knownSize() const
1721 return theData
!= dtUnknown
;
1724 uint64_t Adaptation::Icap::SizedEstimate::size() const
1727 return static_cast<uint64_t>(theData
);
1732 Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided
)
1735 void Adaptation::Icap::VirginBodyAct::plan()
1738 Must(!theStart
); // not started
1739 theState
= stActive
;
1742 void Adaptation::Icap::VirginBodyAct::disable()
1744 theState
= stDisabled
;
1747 void Adaptation::Icap::VirginBodyAct::progress(size_t size
)
1751 theStart
+= static_cast<int64_t>(size
);
1754 uint64_t Adaptation::Icap::VirginBodyAct::offset() const
1757 return static_cast<uint64_t>(theStart
);
1761 Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled
)
1764 void Adaptation::Icap::Preview::enable(size_t anAd
)
1766 // TODO: check for anAd not exceeding preview size limit
1770 theState
= stWriting
;
1773 bool Adaptation::Icap::Preview::enabled() const
1775 return theState
!= stDisabled
;
1778 size_t Adaptation::Icap::Preview::ad() const
1784 bool Adaptation::Icap::Preview::done() const
1787 return theState
>= stIeof
;
1790 bool Adaptation::Icap::Preview::ieof() const
1793 return theState
== stIeof
;
1796 size_t Adaptation::Icap::Preview::debt() const
1799 return done() ? 0 : (theAd
- theWritten
);
1802 void Adaptation::Icap::Preview::wrote(size_t size
, bool wroteEof
)
1808 Must(theWritten
<= theAd
);
1811 theState
= stIeof
; // written size is irrelevant
1812 else if (theWritten
>= theAd
)
1816 bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf
&mb
) const
1818 if (virgin
.header
== NULL
)
1821 virgin
.header
->firstLineBuf(mb
);
1827 /* Adaptation::Icap::ModXactLauncher */
1829 Adaptation::Icap::ModXactLauncher::ModXactLauncher(HttpMsg
*virginHeader
, HttpRequest
*virginCause
, Adaptation::ServicePointer aService
):
1830 AsyncJob("Adaptation::Icap::ModXactLauncher"),
1831 Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", aService
)
1833 virgin
.setHeader(virginHeader
);
1834 virgin
.setCause(virginCause
);
1835 updateHistory(true);
1838 Adaptation::Icap::Xaction
*Adaptation::Icap::ModXactLauncher::createXaction()
1840 Adaptation::Icap::ServiceRep::Pointer s
=
1841 dynamic_cast<Adaptation::Icap::ServiceRep
*>(theService
.getRaw());
1843 return new Adaptation::Icap::ModXact(virgin
.header
, virgin
.cause
, s
);
1846 void Adaptation::Icap::ModXactLauncher::swanSong()
1848 debugs(93, 5, HERE
<< "swan sings");
1849 updateHistory(false);
1850 Adaptation::Icap::Launcher::swanSong();
1853 void Adaptation::Icap::ModXactLauncher::updateHistory(bool doStart
)
1855 HttpRequest
*r
= virgin
.cause
?
1856 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
1858 // r should never be NULL but we play safe; TODO: add Should()
1860 Adaptation::Icap::History::Pointer h
= r
->icapHistory();
1863 h
->start("ICAPModXactLauncher");
1865 h
->stop("ICAPModXactLauncher");