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(Adaptation::Initiator
*anInitiator
, HttpMsg
*virginHeader
,
41 HttpRequest
*virginCause
, Adaptation::Icap::ServiceRep::Pointer
&aService
):
42 AsyncJob("Adaptation::Icap::ModXact"),
43 Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", anInitiator
, 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
= 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
>= 0);
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
>= 0) {
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 handle206PartialContent();
735 debugs(93, 5, HERE
<< "ICAP status " << icapReply
->sline
.status
);
736 handleUnknownScode();
740 const HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
742 request
= &virginRequest();
744 // update the cross-transactional database if needed (all status codes!)
745 if (const char *xxName
= Adaptation::Config::masterx_shared_name
) {
746 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
748 const String val
= icapReply
->header
.getByName(xxName
);
749 if (val
.size() > 0) // XXX: HttpHeader lacks empty value detection
750 ah
->updateXxRecord(xxName
, val
);
754 // update the adaptation plan if needed (all status codes!)
755 if (service().cfg().routing
) {
757 if (icapReply
->header
.getList(HDR_X_NEXT_SERVICES
, &services
)) {
758 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
760 ah
->updateNextServices(services
);
762 } // TODO: else warn (occasionally!) if we got HDR_X_NEXT_SERVICES
764 // We need to store received ICAP headers for <icapLastHeader logformat option.
765 // If we already have stored headers from previous ICAP transaction related to this
766 // request, old headers will be replaced with the new one.
768 Adaptation::Icap::History::Pointer h
= request
->icapHistory();
770 h
->mergeIcapHeaders(&icapReply
->header
);
771 h
->setIcapLastHeader(&icapReply
->header
);
774 // handle100Continue() manages state.writing on its own.
775 // Non-100 status means the server needs no postPreview data from us.
776 if (state
.writing
== State::writingPaused
)
780 bool Adaptation::Icap::ModXact::validate200Ok()
782 if (ICAP::methodRespmod
== service().cfg().method
) {
783 if (!gotEncapsulated("res-hdr"))
789 if (ICAP::methodReqmod
== service().cfg().method
) {
790 if (!gotEncapsulated("res-hdr") && !gotEncapsulated("req-hdr"))
799 void Adaptation::Icap::ModXact::handle100Continue()
801 Must(state
.writing
== State::writingPaused
);
802 // server must not respond before the end of preview: we may send ieof
803 Must(preview
.enabled() && preview
.done() && !preview
.ieof());
805 // 100 "Continue" cancels our Preview commitment,
806 // but not commitment to handle 204 or 206 outside Preview
807 if (!state
.allowedPostview204
&& !state
.allowedPostview206
)
810 state
.parsing
= State::psIcapHeader
; // eventually
813 state
.writing
= State::writingPrime
;
818 void Adaptation::Icap::ModXact::handle200Ok()
820 state
.parsing
= State::psHttpHeader
;
821 state
.sending
= State::sendingAdapted
;
826 void Adaptation::Icap::ModXact::handle204NoContent()
832 void Adaptation::Icap::ModXact::handle206PartialContent()
834 if (state
.writing
== State::writingPaused
) {
835 Must(preview
.enabled());
836 Must(state
.allowedPreview206
);
837 debugs(93, 7, HERE
<< "206 inside preview");
839 Must(state
.writing
> State::writingPaused
);
840 Must(state
.allowedPostview206
);
841 debugs(93, 7, HERE
<< "206 outside preview");
843 state
.parsing
= State::psHttpHeader
;
844 state
.sending
= State::sendingAdapted
;
845 state
.readyForUob
= true;
849 // Called when we receive a 204 No Content response and
850 // when we are trying to bypass a service failure.
851 // We actually start sending (echoig or not) in startSending.
852 void Adaptation::Icap::ModXact::prepEchoing()
854 disableRepeats("preparing to echo content");
855 disableBypass("preparing to echo content", true);
858 // We want to clone the HTTP message, but we do not want
859 // to copy some non-HTTP state parts that HttpMsg kids carry in them.
860 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
861 // Instead, we simply write the HTTP message and "clone" it by parsing.
862 // TODO: use HttpMsg::clone()!
864 HttpMsg
*oldHead
= virgin
.header
;
865 debugs(93, 7, HERE
<< "cloning virgin message " << oldHead
);
869 // write the virgin message into a memory buffer
871 packHead(httpBuf
, oldHead
);
873 // allocate the adapted message and copy metainfo
874 Must(!adapted
.header
);
875 HttpMsg
*newHead
= NULL
;
876 if (const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(oldHead
)) {
877 HttpRequest
*newR
= new HttpRequest
;
878 newR
->canonical
= oldR
->canonical
?
879 xstrdup(oldR
->canonical
) : NULL
; // parse() does not set it
881 } else if (dynamic_cast<const HttpReply
*>(oldHead
)) {
882 HttpReply
*newRep
= new HttpReply
;
886 newHead
->inheritProperties(oldHead
);
888 adapted
.setHeader(newHead
);
890 // parse the buffer back
891 http_status error
= HTTP_STATUS_NONE
;
893 Must(newHead
->parse(&httpBuf
, true, &error
));
895 Must(newHead
->hdr_sz
== httpBuf
.contentSize()); // no leftovers
899 debugs(93, 7, HERE
<< "cloned virgin message " << oldHead
<< " to " <<
902 // setup adapted body pipe if needed
903 if (oldHead
->body_pipe
!= NULL
) {
904 debugs(93, 7, HERE
<< "will echo virgin body from " <<
906 if (!virginBodySending
.active())
907 virginBodySending
.plan(); // will throw if not possible
908 state
.sending
= State::sendingVirgin
;
911 // TODO: optimize: is it possible to just use the oldHead pipe and
912 // remove ICAP from the loop? This echoing is probably a common case!
913 makeAdaptedBodyPipe("echoed virgin response");
914 if (oldHead
->body_pipe
->bodySizeKnown())
915 adapted
.body_pipe
->setBodySize(oldHead
->body_pipe
->bodySize());
916 debugs(93, 7, HERE
<< "will echo virgin body to " <<
919 debugs(93, 7, HERE
<< "no virgin body to echo");
924 /// Called when we received use-original-body chunk extension in 206 response.
925 /// We actually start sending (echoing or not) in startSending().
926 void Adaptation::Icap::ModXact::prepPartialBodyEchoing(uint64_t pos
)
928 Must(virginBodySending
.active());
929 Must(virgin
.header
->body_pipe
!= NULL
);
931 setOutcome(xoPartEcho
);
933 debugs(93, 7, HERE
<< "will echo virgin body suffix from " <<
934 virgin
.header
->body_pipe
<< " offset " << pos
);
936 // check that use-original-body=N does not point beyond buffered data
937 const uint64_t virginDataEnd
= virginConsumed
+
938 virgin
.body_pipe
->buf().contentSize();
939 Must(pos
<= virginDataEnd
);
940 virginBodySending
.progress(static_cast<size_t>(pos
));
942 state
.sending
= State::sendingVirgin
;
945 if (virgin
.header
->body_pipe
->bodySizeKnown())
946 adapted
.body_pipe
->expectProductionEndAfter(virgin
.header
->body_pipe
->bodySize() - pos
);
948 debugs(93, 7, HERE
<< "will echo virgin body suffix to " <<
951 // Start echoing data
955 void Adaptation::Icap::ModXact::handleUnknownScode()
959 // TODO: mark connection as "bad"
961 // Terminate the transaction; we do not know how to handle this response.
962 throw TexcHere("Unsupported ICAP status code");
965 void Adaptation::Icap::ModXact::parseHttpHead()
967 if (gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr")) {
968 replyHttpHeaderSize
= 0;
969 maybeAllocateHttpMsg();
971 if (!parseHead(adapted
.header
))
972 return; // need more header data
975 replyHttpHeaderSize
= adapted
.header
->hdr_sz
;
977 if (dynamic_cast<HttpRequest
*>(adapted
.header
)) {
978 const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(virgin
.header
);
980 // TODO: the adapted request did not really originate from the
981 // client; give proxy admin an option to prevent copying of
982 // sensitive client information here. See the following thread:
983 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
986 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
988 adapted
.header
->inheritProperties(virgin
.header
);
991 decideOnParsingBody();
994 // parses both HTTP and ICAP headers
995 bool Adaptation::Icap::ModXact::parseHead(HttpMsg
*head
)
998 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " head bytes to parse" <<
999 "; state: " << state
.parsing
);
1001 http_status error
= HTTP_STATUS_NONE
;
1002 const bool parsed
= head
->parse(&readBuf
, commEof
, &error
);
1003 Must(parsed
|| !error
); // success or need more data
1005 if (!parsed
) { // need more data
1006 debugs(93, 5, HERE
<< "parse failed, need more data, return false");
1011 if (HttpRequest
*r
= dynamic_cast<HttpRequest
*>(head
))
1012 urlCanonical(r
); // parse does not set HttpRequest::canonical
1014 debugs(93, 5, HERE
<< "parse success, consume " << head
->hdr_sz
<< " bytes, return true");
1015 readBuf
.consume(head
->hdr_sz
);
1019 void Adaptation::Icap::ModXact::decideOnParsingBody()
1021 if (gotEncapsulated("res-body") || gotEncapsulated("req-body")) {
1022 debugs(93, 5, HERE
<< "expecting a body");
1023 state
.parsing
= State::psBody
;
1024 replyHttpBodySize
= 0;
1025 bodyParser
= new ChunkedCodingParser
;
1026 makeAdaptedBodyPipe("adapted response from the ICAP server");
1027 Must(state
.sending
== State::sendingAdapted
);
1029 debugs(93, 5, HERE
<< "not expecting a body");
1035 void Adaptation::Icap::ModXact::parseBody()
1037 Must(state
.parsing
== State::psBody
);
1040 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " body bytes to parse");
1042 // the parser will throw on errors
1043 BodyPipeCheckout
bpc(*adapted
.body_pipe
);
1044 const bool parsed
= bodyParser
->parse(&readBuf
, &bpc
.buf
);
1047 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " body bytes after " <<
1048 "parse; parsed all: " << parsed
);
1049 replyHttpBodySize
+= adapted
.body_pipe
->buf().contentSize();
1051 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
1052 // TODO: do we really need this if we disable when sending headers?
1053 if (adapted
.body_pipe
->buf().contentSize() > 0) { // parsed something sometime
1054 disableRepeats("sent adapted content");
1055 disableBypass("sent adapted content", true);
1059 if (state
.readyForUob
&& bodyParser
->useOriginBody
>= 0) {
1060 prepPartialBodyEchoing(
1061 static_cast<uint64_t>(bodyParser
->useOriginBody
));
1067 stopSending(true); // the parser succeeds only if all parsed data fits
1071 debugs(93,3,HERE
<< this << " needsMoreData = " << bodyParser
->needsMoreData());
1073 if (bodyParser
->needsMoreData()) {
1074 debugs(93,3,HERE
<< this);
1075 Must(mayReadMore());
1079 if (bodyParser
->needsMoreSpace()) {
1080 Must(!doneSending()); // can hope for more space
1081 Must(adapted
.body_pipe
->buf().contentSize() > 0); // paranoid
1082 // TODO: there should be a timeout in case the sink is broken
1083 // or cannot consume partial content (while we need more space)
1087 void Adaptation::Icap::ModXact::stopParsing()
1089 if (state
.parsing
== State::psDone
)
1092 debugs(93, 7, HERE
<< "will no longer parse" << status());
1098 state
.parsing
= State::psDone
;
1101 // HTTP side added virgin body data
1102 void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer
)
1106 if (state
.sending
== State::sendingVirgin
)
1110 // HTTP side sent us all virgin info
1111 void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer
)
1113 Must(virgin
.body_pipe
->productionEnded());
1115 // push writer and sender in case we were waiting for the last-chunk
1118 if (state
.sending
== State::sendingVirgin
)
1122 // body producer aborted, but the initiator may still want to know
1123 // the answer, even though the HTTP message has been truncated
1124 void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer
)
1126 Must(virgin
.body_pipe
->productionEnded());
1128 // push writer and sender in case we were waiting for the last-chunk
1131 if (state
.sending
== State::sendingVirgin
)
1135 // adapted body consumer wants more adapted data and
1136 // possibly freed some buffer space
1137 void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
1139 if (state
.sending
== State::sendingVirgin
)
1141 else if (state
.sending
== State::sendingAdapted
)
1144 Must(state
.sending
== State::sendingUndecided
);
1147 // adapted body consumer aborted
1148 void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer
)
1150 mustStop("adapted body consumer aborted");
1154 void Adaptation::Icap::ModXact::swanSong()
1156 debugs(93, 5, HERE
<< "swan sings" << status());
1161 // update adaptation history if start was called and we reserved a slot
1162 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
1163 if (ah
!= NULL
&& adaptHistoryId
>= 0)
1164 ah
->recordXactFinish(adaptHistoryId
);
1166 Adaptation::Icap::Xaction::swanSong();
1169 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry
*);
1171 void Adaptation::Icap::ModXact::finalizeLogInfo()
1173 HttpRequest
* request_
= NULL
;
1174 HttpReply
* reply_
= NULL
;
1175 if (!(request_
= dynamic_cast<HttpRequest
*>(adapted
.header
))) {
1176 request_
= (virgin
.cause
? virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
));
1177 reply_
= dynamic_cast<HttpReply
*>(adapted
.header
);
1180 Adaptation::Icap::History::Pointer h
= request_
->icapHistory();
1181 Must(h
!= NULL
); // ICAPXaction::maybeLog calls only if there is a log
1182 al
.icp
.opcode
= ICP_INVALID
;
1183 al
.url
= h
->log_uri
.termedBuf();
1184 const Adaptation::Icap::ServiceRep
&s
= service();
1185 al
.icap
.reqMethod
= s
.cfg().method
;
1187 al
.cache
.caddr
= request_
->client_addr
;
1189 al
.request
= HTTPMSGLOCK(request_
);
1191 al
.reply
= HTTPMSGLOCK(reply_
);
1195 if (h
->rfc931
.size())
1196 al
.cache
.rfc931
= h
->rfc931
.termedBuf();
1199 if (h
->ssluser
.size())
1200 al
.cache
.ssluser
= h
->ssluser
.termedBuf();
1202 al
.cache
.code
= h
->logType
;
1203 al
.cache
.requestSize
= h
->req_sz
;
1205 // leave al.icap.bodyBytesRead negative if no body
1206 if (replyHttpHeaderSize
>= 0 || replyHttpBodySize
>= 0) {
1207 const int64_t zero
= 0; // to make max() argument types the same
1208 al
.icap
.bodyBytesRead
=
1209 max(zero
, replyHttpHeaderSize
) + max(zero
, replyHttpBodySize
);
1213 al
.http
.code
= reply_
->sline
.status
;
1214 al
.http
.content_type
= reply_
->content_type
.termedBuf();
1215 if (replyHttpBodySize
>= 0) {
1216 al
.cache
.replySize
= replyHttpBodySize
+ reply_
->hdr_sz
;
1217 al
.cache
.highOffset
= replyHttpBodySize
;
1219 //don't set al.cache.objectSize because it hasn't exist yet
1225 packerToMemInit(&p
, &mb
);
1227 reply_
->header
.packInto(&p
);
1228 al
.headers
.reply
= xstrdup(mb
.buf
);
1233 prepareLogWithRequestDetails(request_
, &al
);
1234 Xaction::finalizeLogInfo();
1238 void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf
&buf
)
1240 char ntoabuf
[MAX_IPSTRLEN
];
1242 * XXX These should use HttpHdr interfaces instead of Printfs
1244 const Adaptation::ServiceConfig
&s
= service().cfg();
1245 buf
.Printf("%s " SQUIDSTRINGPH
" ICAP/1.0\r\n", s
.methodStr(), SQUIDSTRINGPRINT(s
.uri
));
1246 buf
.Printf("Host: " SQUIDSTRINGPH
":%d\r\n", SQUIDSTRINGPRINT(s
.host
), s
.port
);
1247 buf
.Printf("Date: %s\r\n", mkrfc1123(squid_curtime
));
1249 if (!TheConfig
.reuse_connections
)
1250 buf
.Printf("Connection: close\r\n");
1252 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1254 if (virgin
.header
->header
.has(HDR_PROXY_AUTHENTICATE
)) {
1255 String vh
=virgin
.header
->header
.getByName("Proxy-Authenticate");
1256 buf
.Printf("Proxy-Authenticate: " SQUIDSTRINGPH
"\r\n",SQUIDSTRINGPRINT(vh
));
1259 if (virgin
.header
->header
.has(HDR_PROXY_AUTHORIZATION
)) {
1260 String vh
=virgin
.header
->header
.getByName("Proxy-Authorization");
1261 buf
.Printf("Proxy-Authorization: " SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(vh
));
1264 const HttpRequest
*request
= &virginRequest();
1266 // share the cross-transactional database records if needed
1267 if (Adaptation::Config::masterx_shared_name
) {
1268 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
1271 if (ah
->getXxRecord(name
, value
)) {
1272 buf
.Printf(SQUIDSTRINGPH
": " SQUIDSTRINGPH
"\r\n",
1273 SQUIDSTRINGPRINT(name
), SQUIDSTRINGPRINT(value
));
1279 buf
.Printf("Encapsulated: ");
1285 // build HTTP request header, if any
1286 ICAP::Method m
= s
.method
;
1288 // to simplify, we could assume that request is always available
1292 urlPath
= request
->urlpath
;
1293 if (ICAP::methodRespmod
== m
)
1294 encapsulateHead(buf
, "req-hdr", httpBuf
, request
);
1295 else if (ICAP::methodReqmod
== m
)
1296 encapsulateHead(buf
, "req-hdr", httpBuf
, virgin
.header
);
1299 if (ICAP::methodRespmod
== m
)
1300 if (const HttpMsg
*prime
= virgin
.header
)
1301 encapsulateHead(buf
, "res-hdr", httpBuf
, prime
);
1303 if (!virginBody
.expected())
1304 buf
.Printf("null-body=%d", (int) httpBuf
.contentSize());
1305 else if (ICAP::methodReqmod
== m
)
1306 buf
.Printf("req-body=%d", (int) httpBuf
.contentSize());
1308 buf
.Printf("res-body=%d", (int) httpBuf
.contentSize());
1310 buf
.append(ICAP::crlf
, 2); // terminate Encapsulated line
1312 if (preview
.enabled()) {
1313 buf
.Printf("Preview: %d\r\n", (int)preview
.ad());
1314 if (!virginBody
.expected()) // there is no body to preview
1315 finishNullOrEmptyBodyPreview(httpBuf
);
1318 makeAllowHeader(buf
);
1320 if (TheConfig
.send_client_ip
&& request
) {
1321 Ip::Address client_addr
;
1322 #if FOLLOW_X_FORWARDED_FOR
1323 if (TheConfig
.icap_uses_indirect_client
) {
1324 client_addr
= request
->indirect_client_addr
;
1327 client_addr
= request
->client_addr
;
1328 if (!client_addr
.IsAnyAddr() && !client_addr
.IsNoAddr())
1329 buf
.Printf("X-Client-IP: %s\r\n", client_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
1332 if (TheConfig
.send_client_username
&& request
)
1333 makeUsernameHeader(request
, buf
);
1335 // fprintf(stderr, "%s\n", buf.content());
1337 buf
.append(ICAP::crlf
, 2); // terminate ICAP header
1339 // fill icapRequest for logging
1340 Must(icapRequest
->parseCharBuf(buf
.content(), buf
.contentSize()));
1342 // start ICAP request body with encapsulated HTTP headers
1343 buf
.append(httpBuf
.content(), httpBuf
.contentSize());
1348 // decides which Allow values to write and updates the request buffer
1349 void Adaptation::Icap::ModXact::makeAllowHeader(MemBuf
&buf
)
1351 const bool allow204in
= preview
.enabled(); // TODO: add shouldAllow204in()
1352 const bool allow204out
= state
.allowedPostview204
= shouldAllow204();
1353 const bool allow206in
= state
.allowedPreview206
= shouldAllow206in();
1354 const bool allow206out
= state
.allowedPostview206
= shouldAllow206out();
1356 debugs(93,9, HERE
<< "Allows: " << allow204in
<< allow204out
<<
1357 allow206in
<< allow206out
);
1359 const bool allow204
= allow204in
|| allow204out
;
1360 const bool allow206
= allow206in
|| allow206out
;
1362 if (!allow204
&& !allow206
)
1363 return; // nothing to do
1365 if (virginBody
.expected()) // if there is a virgin body, plan to send it
1366 virginBodySending
.plan();
1368 // writing Preview:... means we will honor 204 inside preview
1369 // writing Allow/204 means we will honor 204 outside preview
1370 // writing Allow:206 means we will honor 206 inside preview
1371 // writing Allow:204,206 means we will honor 206 outside preview
1372 const char *allowHeader
= NULL
;
1373 if (allow204out
&& allow206
)
1374 allowHeader
= "Allow: 204, 206\r\n";
1375 else if (allow204out
)
1376 allowHeader
= "Allow: 204\r\n";
1378 allowHeader
= "Allow: 206\r\n";
1380 if (allowHeader
) { // may be nil if only allow204in is true
1381 buf
.append(allowHeader
, strlen(allowHeader
));
1382 debugs(93,5, HERE
<< "Will write " << allowHeader
);
1386 void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest
*request
, MemBuf
&buf
)
1388 if (request
->auth_user_request
!= NULL
) {
1389 char const *name
= request
->auth_user_request
->username();
1391 const char *value
= TheConfig
.client_username_encode
? base64_encode(name
) : name
;
1392 buf
.Printf("%s: %s\r\n", TheConfig
.client_username_header
, value
);
1397 void Adaptation::Icap::ModXact::encapsulateHead(MemBuf
&icapBuf
, const char *section
, MemBuf
&httpBuf
, const HttpMsg
*head
)
1399 // update ICAP header
1400 icapBuf
.Printf("%s=%d, ", section
, (int) httpBuf
.contentSize());
1403 HttpMsg
*headClone
= NULL
;
1405 if (const HttpRequest
* old_request
= dynamic_cast<const HttpRequest
*>(head
)) {
1406 HttpRequest
* new_request
= new HttpRequest
;
1407 assert(old_request
->canonical
);
1408 urlParse(old_request
->method
, old_request
->canonical
, new_request
);
1409 new_request
->http_ver
= old_request
->http_ver
;
1410 headClone
= new_request
;
1411 } else if (const HttpReply
*old_reply
= dynamic_cast<const HttpReply
*>(head
)) {
1412 HttpReply
* new_reply
= new HttpReply
;
1413 new_reply
->sline
= old_reply
->sline
;
1414 headClone
= new_reply
;
1418 headClone
->inheritProperties(head
);
1420 HttpHeaderPos pos
= HttpHeaderInitPos
;
1421 HttpHeaderEntry
* p_head_entry
= NULL
;
1422 while (NULL
!= (p_head_entry
= head
->header
.getEntry(&pos
)) )
1423 headClone
->header
.addEntry(p_head_entry
->clone());
1427 // remove all hop-by-hop headers from the clone
1428 headClone
->header
.delById(HDR_PROXY_AUTHENTICATE
);
1429 headClone
->header
.removeHopByHopEntries();
1431 // pack polished HTTP header
1432 packHead(httpBuf
, headClone
);
1437 void Adaptation::Icap::ModXact::packHead(MemBuf
&httpBuf
, const HttpMsg
*head
)
1440 packerToMemInit(&p
, &httpBuf
);
1441 head
->packInto(&p
, true);
1445 // decides whether to offer a preview and calculates its size
1446 void Adaptation::Icap::ModXact::decideOnPreview()
1448 if (!TheConfig
.preview_enable
) {
1449 debugs(93, 5, HERE
<< "preview disabled by squid.conf");
1453 const String urlPath
= virginRequest().urlpath
;
1455 if (!service().wantsPreview(urlPath
, wantedSize
)) {
1456 debugs(93, 5, HERE
<< "should not offer preview for " << urlPath
);
1460 // we decided to do preview, now compute its size
1462 Must(wantedSize
>= 0);
1464 // cannot preview more than we can backup
1465 size_t ad
= min(wantedSize
, TheBackupLimit
);
1467 if (!virginBody
.expected())
1469 else if (virginBody
.knownSize())
1470 ad
= min(static_cast<uint64_t>(ad
), virginBody
.size()); // not more than we have
1472 debugs(93, 5, HERE
<< "should offer " << ad
<< "-byte preview " <<
1473 "(service wanted " << wantedSize
<< ")");
1476 Must(preview
.enabled());
1479 // decides whether to allow 204 responses
1480 bool Adaptation::Icap::ModXact::shouldAllow204()
1482 if (!service().allows204())
1485 return canBackupEverything();
1488 // decides whether to allow 206 responses in some mode
1489 bool Adaptation::Icap::ModXact::shouldAllow206any()
1491 return TheConfig
.allow206_enable
&& service().allows206() &&
1492 virginBody
.expected(); // no need for 206 without a body
1495 // decides whether to allow 206 responses in preview mode
1496 bool Adaptation::Icap::ModXact::shouldAllow206in()
1498 return shouldAllow206any() && preview
.enabled();
1501 // decides whether to allow 206 responses outside of preview
1502 bool Adaptation::Icap::ModXact::shouldAllow206out()
1504 return shouldAllow206any() && canBackupEverything();
1507 // used by shouldAllow204 and decideOnRetries
1508 bool Adaptation::Icap::ModXact::canBackupEverything() const
1510 if (!virginBody
.expected())
1511 return true; // no body means no problems with backup
1513 // if there is a body, check whether we can backup it all
1515 if (!virginBody
.knownSize())
1518 // or should we have a different backup limit?
1519 // note that '<' allows for 0-termination of the "full" backup buffer
1520 return virginBody
.size() < TheBackupLimit
;
1523 // Decide whether this transaction can be retried if pconn fails
1524 // Must be called after decideOnPreview and before openConnection()
1525 void Adaptation::Icap::ModXact::decideOnRetries()
1528 return; // no, already decided
1530 if (preview
.enabled())
1531 return; // yes, because preview provides enough guarantees
1533 if (canBackupEverything())
1534 return; // yes, because we can back everything up
1536 disableRetries(); // no, because we cannot back everything up
1539 // Normally, the body-writing code handles preview body. It can deal with
1540 // bodies of unexpected size, including those that turn out to be empty.
1541 // However, that code assumes that the body was expected and body control
1542 // structures were initialized. This is not the case when there is no body
1543 // or the body is known to be empty, because the virgin message will lack a
1544 // body_pipe. So we handle preview of null-body and zero-size bodies here.
1545 void Adaptation::Icap::ModXact::finishNullOrEmptyBodyPreview(MemBuf
&buf
)
1547 Must(!virginBodyWriting
.active()); // one reason we handle it here
1548 Must(!virgin
.body_pipe
); // another reason we handle it here
1549 Must(!preview
.ad());
1551 // do not add last-chunk because our Encapsulated header says null-body
1552 // addLastRequestChunk(buf);
1553 preview
.wrote(0, true);
1555 Must(preview
.done());
1556 Must(preview
.ieof());
1559 void Adaptation::Icap::ModXact::fillPendingStatus(MemBuf
&buf
) const
1561 Adaptation::Icap::Xaction::fillPendingStatus(buf
);
1563 if (state
.serviceWaiting
)
1566 if (virgin
.body_pipe
!= NULL
)
1569 if (connection
> 0 && !doneReading())
1572 if (!state
.doneWriting() && state
.writing
!= State::writingInit
)
1573 buf
.Printf("w(%d)", state
.writing
);
1575 if (preview
.enabled()) {
1576 if (!preview
.done())
1577 buf
.Printf("P(%d)", (int) preview
.debt());
1580 if (virginBodySending
.active())
1583 if (!state
.doneParsing() && state
.parsing
!= State::psIcapHeader
)
1584 buf
.Printf("p(%d)", state
.parsing
);
1586 if (!doneSending() && state
.sending
!= State::sendingUndecided
)
1587 buf
.Printf("S(%d)", state
.sending
);
1589 if (state
.readyForUob
)
1595 if (protectGroupBypass
)
1599 void Adaptation::Icap::ModXact::fillDoneStatus(MemBuf
&buf
) const
1601 Adaptation::Icap::Xaction::fillDoneStatus(buf
);
1603 if (!virgin
.body_pipe
)
1606 if (state
.doneWriting())
1609 if (preview
.enabled()) {
1611 buf
.Printf("P%s", preview
.ieof() ? "(ieof)" : "");
1617 if (state
.doneParsing())
1624 bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section
) const
1626 return icapReply
->header
.getByNameListMember("Encapsulated",
1627 section
, ',').size() > 0;
1630 // calculate whether there is a virgin HTTP body and
1631 // whether its expected size is known
1632 // TODO: rename because we do not just estimate
1633 void Adaptation::Icap::ModXact::estimateVirginBody()
1635 // note: lack of size info may disable previews and 204s
1637 HttpMsg
*msg
= virgin
.header
;
1640 HttpRequestMethod method
;
1643 method
= virgin
.cause
->method
;
1644 else if (HttpRequest
*req
= dynamic_cast<HttpRequest
*>(msg
))
1645 method
= req
->method
;
1647 method
= METHOD_NONE
;
1650 // expectingBody returns true for zero-sized bodies, but we will not
1651 // get a pipe for that body, so we treat the message as bodyless
1652 if (method
!= METHOD_NONE
&& msg
->expectingBody(method
, size
) && size
) {
1653 debugs(93, 6, HERE
<< "expects virgin body from " <<
1654 virgin
.body_pipe
<< "; size: " << size
);
1656 virginBody
.expect(size
);
1657 virginBodyWriting
.plan();
1659 // sign up as a body consumer
1660 Must(msg
->body_pipe
!= NULL
);
1661 Must(msg
->body_pipe
== virgin
.body_pipe
);
1662 Must(virgin
.body_pipe
->setConsumerIfNotLate(this));
1664 // make sure TheBackupLimit is in-sync with the buffer size
1665 Must(TheBackupLimit
<= static_cast<size_t>(msg
->body_pipe
->buf().max_capacity
));
1667 debugs(93, 6, HERE
<< "does not expect virgin body");
1668 Must(msg
->body_pipe
== NULL
);
1673 void Adaptation::Icap::ModXact::makeAdaptedBodyPipe(const char *what
)
1675 Must(!adapted
.body_pipe
);
1676 Must(!adapted
.header
->body_pipe
);
1677 adapted
.header
->body_pipe
= new BodyPipe(this);
1678 adapted
.body_pipe
= adapted
.header
->body_pipe
;
1679 debugs(93, 7, HERE
<< "will supply " << what
<< " via " <<
1680 adapted
.body_pipe
<< " pipe");
1684 // TODO: Move SizedEstimate and Preview elsewhere
1686 Adaptation::Icap::SizedEstimate::SizedEstimate()
1687 : theData(dtUnexpected
)
1690 void Adaptation::Icap::SizedEstimate::expect(int64_t aSize
)
1692 theData
= (aSize
>= 0) ? aSize
: (int64_t)dtUnknown
;
1695 bool Adaptation::Icap::SizedEstimate::expected() const
1697 return theData
!= dtUnexpected
;
1700 bool Adaptation::Icap::SizedEstimate::knownSize() const
1703 return theData
!= dtUnknown
;
1706 uint64_t Adaptation::Icap::SizedEstimate::size() const
1709 return static_cast<uint64_t>(theData
);
1714 Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided
)
1717 void Adaptation::Icap::VirginBodyAct::plan()
1720 Must(!theStart
); // not started
1721 theState
= stActive
;
1724 void Adaptation::Icap::VirginBodyAct::disable()
1726 theState
= stDisabled
;
1729 void Adaptation::Icap::VirginBodyAct::progress(size_t size
)
1733 theStart
+= static_cast<int64_t>(size
);
1736 uint64_t Adaptation::Icap::VirginBodyAct::offset() const
1739 return static_cast<uint64_t>(theStart
);
1743 Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled
)
1746 void Adaptation::Icap::Preview::enable(size_t anAd
)
1748 // TODO: check for anAd not exceeding preview size limit
1752 theState
= stWriting
;
1755 bool Adaptation::Icap::Preview::enabled() const
1757 return theState
!= stDisabled
;
1760 size_t Adaptation::Icap::Preview::ad() const
1766 bool Adaptation::Icap::Preview::done() const
1769 return theState
>= stIeof
;
1772 bool Adaptation::Icap::Preview::ieof() const
1775 return theState
== stIeof
;
1778 size_t Adaptation::Icap::Preview::debt() const
1781 return done() ? 0 : (theAd
- theWritten
);
1784 void Adaptation::Icap::Preview::wrote(size_t size
, bool wroteEof
)
1790 Must(theWritten
<= theAd
);
1793 theState
= stIeof
; // written size is irrelevant
1794 else if (theWritten
>= theAd
)
1798 bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf
&mb
) const
1800 if (virgin
.header
== NULL
)
1803 virgin
.header
->firstLineBuf(mb
);
1809 /* Adaptation::Icap::ModXactLauncher */
1811 Adaptation::Icap::ModXactLauncher::ModXactLauncher(Adaptation::Initiator
*anInitiator
, HttpMsg
*virginHeader
, HttpRequest
*virginCause
, Adaptation::ServicePointer aService
):
1812 AsyncJob("Adaptation::Icap::ModXactLauncher"),
1813 Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", anInitiator
, aService
)
1815 virgin
.setHeader(virginHeader
);
1816 virgin
.setCause(virginCause
);
1817 updateHistory(true);
1820 Adaptation::Icap::Xaction
*Adaptation::Icap::ModXactLauncher::createXaction()
1822 Adaptation::Icap::ServiceRep::Pointer s
=
1823 dynamic_cast<Adaptation::Icap::ServiceRep
*>(theService
.getRaw());
1825 return new Adaptation::Icap::ModXact(this, virgin
.header
, virgin
.cause
, s
);
1828 void Adaptation::Icap::ModXactLauncher::swanSong()
1830 debugs(93, 5, HERE
<< "swan sings");
1831 updateHistory(false);
1832 Adaptation::Icap::Launcher::swanSong();
1835 void Adaptation::Icap::ModXactLauncher::updateHistory(bool doStart
)
1837 HttpRequest
*r
= virgin
.cause
?
1838 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
1840 // r should never be NULL but we play safe; TODO: add Should()
1842 Adaptation::Icap::History::Pointer h
= r
->icapHistory();
1845 h
->start("ICAPModXactLauncher");
1847 h
->stop("ICAPModXactLauncher");