2 * DEBUG: section 93 ICAP (RFC 3507) Client
6 #include "AccessLogEntry.h"
7 #include "adaptation/History.h"
8 #include "adaptation/icap/Client.h"
9 #include "adaptation/icap/Config.h"
10 #include "adaptation/icap/History.h"
11 #include "adaptation/icap/Launcher.h"
12 #include "adaptation/icap/ModXact.h"
13 #include "adaptation/icap/ServiceRep.h"
14 #include "adaptation/Initiator.h"
15 #include "auth/UserRequest.h"
16 #include "base/TextException.h"
17 #include "ChunkedCodingParser.h"
19 #include "comm/Connection.h"
21 #include "HttpRequest.h"
22 #include "HttpReply.h"
23 #include "SquidTime.h"
25 // flow and terminology:
26 // HTTP| --> receive --> encode --> write --> |network
27 // end | <-- send <-- parse <-- read <-- |end
29 // TODO: replace gotEncapsulated() with something faster; we call it often
31 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXact
);
32 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXactLauncher
);
34 static const size_t TheBackupLimit
= BodyPipe::MaxCapacity
;
36 Adaptation::Icap::ModXact::State::State()
38 memset(this, 0, sizeof(*this));
41 Adaptation::Icap::ModXact::ModXact(HttpMsg
*virginHeader
,
42 HttpRequest
*virginCause
, Adaptation::Icap::ServiceRep::Pointer
&aService
):
43 AsyncJob("Adaptation::Icap::ModXact"),
44 Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", aService
),
47 canStartBypass(false), // too early
48 protectGroupBypass(true),
49 replyHttpHeaderSize(-1),
50 replyHttpBodySize(-1),
55 virgin
.setHeader(virginHeader
); // sets virgin.body_pipe if needed
56 virgin
.setCause(virginCause
); // may be NULL
58 // adapted header and body are initialized when we parse them
60 // writing and reading ends are handled by Adaptation::Icap::Xaction
63 // nothing to do because we are using temporary buffers
65 // parsing; TODO: do not set until we parse, see ICAPOptXact
66 icapReply
= HTTPMSGLOCK(new HttpReply
);
67 icapReply
->protoPrefix
= "ICAP/"; // TODO: make an IcapReply class?
69 debugs(93,7, HERE
<< "initialized." << status());
72 // initiator wants us to start
73 void Adaptation::Icap::ModXact::start()
75 Adaptation::Icap::Xaction::start();
77 // reserve an adaptation history slot (attempts are known at this time)
78 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
80 adaptHistoryId
= ah
->recordXactStart(service().cfg().key
, icap_tr_start
, attempts
> 1);
82 estimateVirginBody(); // before virgin disappears!
84 canStartBypass
= service().cfg().bypass
;
86 // it is an ICAP violation to send request to a service w/o known OPTIONS
94 void Adaptation::Icap::ModXact::waitForService()
96 Must(!state
.serviceWaiting
);
97 debugs(93, 7, HERE
<< "will wait for the ICAP service" << status());
98 state
.serviceWaiting
= true;
99 typedef NullaryMemFunT
<ModXact
> Dialer
;
100 AsyncCall::Pointer call
= JobCallback(93,5,
101 Dialer
, this, Adaptation::Icap::ModXact::noteServiceReady
);
102 service().callWhenReady(call
);
105 void Adaptation::Icap::ModXact::noteServiceReady()
107 Must(state
.serviceWaiting
);
108 state
.serviceWaiting
= false;
110 if (service().up()) {
114 disableRepeats("ICAP service is unusable");
115 throw TexcHere("ICAP service is unusable");
119 void Adaptation::Icap::ModXact::startWriting()
121 state
.writing
= State::writingConnect
;
123 decideOnPreview(); // must be decided before we decideOnRetries
129 // connection with the ICAP service established
130 void Adaptation::Icap::ModXact::handleCommConnected()
132 Must(state
.writing
== State::writingConnect
);
134 startReading(); // wait for early errors from the ICAP server
139 makeRequestHeaders(requestBuf
);
140 debugs(93, 9, HERE
<< "will write" << status() << ":\n" <<
141 (requestBuf
.terminate(), requestBuf
.content()));
144 state
.writing
= State::writingHeaders
;
145 icap_tio_start
= current_time
;
146 scheduleWrite(requestBuf
);
149 void Adaptation::Icap::ModXact::handleCommWrote(size_t sz
)
151 debugs(93, 5, HERE
<< "Wrote " << sz
<< " bytes");
153 if (state
.writing
== State::writingHeaders
)
154 handleCommWroteHeaders();
156 handleCommWroteBody();
159 void Adaptation::Icap::ModXact::handleCommWroteHeaders()
161 Must(state
.writing
== State::writingHeaders
);
163 // determine next step
164 if (preview
.enabled())
165 state
.writing
= preview
.done() ? State::writingPaused
: State::writingPreview
;
166 else if (virginBody
.expected())
167 state
.writing
= State::writingPrime
;
176 void Adaptation::Icap::ModXact::writeMore()
178 debugs(93, 5, HERE
<< "checking whether to write more" << status());
180 if (writer
!= NULL
) // already writing something
183 switch (state
.writing
) {
185 case State::writingInit
: // waiting for service OPTIONS
186 Must(state
.serviceWaiting
);
188 case State::writingConnect
: // waiting for the connection to establish
190 case State::writingHeaders
: // waiting for the headers to be written
192 case State::writingPaused
: // waiting for the ICAP server response
194 case State::writingReallyDone
: // nothing more to write
197 case State::writingAlmostDone
: // was waiting for the last write
201 case State::writingPreview
:
205 case State::writingPrime
:
210 throw TexcHere("Adaptation::Icap::ModXact in bad writing state");
214 void Adaptation::Icap::ModXact::writePreviewBody()
216 debugs(93, 8, HERE
<< "will write Preview body from " <<
217 virgin
.body_pipe
<< status());
218 Must(state
.writing
== State::writingPreview
);
219 Must(virgin
.body_pipe
!= NULL
);
221 const size_t sizeMax
= (size_t)virgin
.body_pipe
->buf().contentSize();
222 const size_t size
= min(preview
.debt(), sizeMax
);
223 writeSomeBody("preview body", size
);
225 // change state once preview is written
227 if (preview
.done()) {
228 debugs(93, 7, HERE
<< "wrote entire Preview body" << status());
233 state
.writing
= State::writingPaused
;
237 void Adaptation::Icap::ModXact::writePrimeBody()
239 Must(state
.writing
== State::writingPrime
);
240 Must(virginBodyWriting
.active());
242 const size_t size
= (size_t)virgin
.body_pipe
->buf().contentSize();
243 writeSomeBody("prime virgin body", size
);
245 if (virginBodyEndReached(virginBodyWriting
)) {
246 debugs(93, 5, HERE
<< "wrote entire body");
251 void Adaptation::Icap::ModXact::writeSomeBody(const char *label
, size_t size
)
253 Must(!writer
&& state
.writing
< state
.writingAlmostDone
);
254 Must(virgin
.body_pipe
!= NULL
);
255 debugs(93, 8, HERE
<< "will write up to " << size
<< " bytes of " <<
258 MemBuf writeBuf
; // TODO: suggest a min size based on size and lastChunk
260 writeBuf
.init(); // note: we assume that last-chunk will fit
262 const size_t writableSize
= virginContentSize(virginBodyWriting
);
263 const size_t chunkSize
= min(writableSize
, size
);
266 debugs(93, 7, HERE
<< "will write " << chunkSize
<<
267 "-byte chunk of " << label
);
269 openChunk(writeBuf
, chunkSize
, false);
270 writeBuf
.append(virginContentData(virginBodyWriting
), chunkSize
);
271 closeChunk(writeBuf
);
273 virginBodyWriting
.progress(chunkSize
);
276 debugs(93, 7, HERE
<< "has no writable " << label
<< " content");
279 const bool wroteEof
= virginBodyEndReached(virginBodyWriting
);
280 bool lastChunk
= wroteEof
;
281 if (state
.writing
== State::writingPreview
) {
282 preview
.wrote(chunkSize
, wroteEof
); // even if wrote nothing
283 lastChunk
= lastChunk
|| preview
.done();
287 debugs(93, 8, HERE
<< "will write last-chunk of " << label
);
288 addLastRequestChunk(writeBuf
);
291 debugs(93, 7, HERE
<< "will write " << writeBuf
.contentSize()
292 << " raw bytes of " << label
);
294 if (writeBuf
.hasContent()) {
295 scheduleWrite(writeBuf
); // comm will free the chunk
301 void Adaptation::Icap::ModXact::addLastRequestChunk(MemBuf
&buf
)
303 const bool ieof
= state
.writing
== State::writingPreview
&& preview
.ieof();
304 openChunk(buf
, 0, ieof
);
308 void Adaptation::Icap::ModXact::openChunk(MemBuf
&buf
, size_t chunkSize
, bool ieof
)
310 buf
.Printf((ieof
? "%x; ieof\r\n" : "%x\r\n"), (int) chunkSize
);
313 void Adaptation::Icap::ModXact::closeChunk(MemBuf
&buf
)
315 buf
.append(ICAP::crlf
, 2); // chunk-terminating CRLF
318 const HttpRequest
&Adaptation::Icap::ModXact::virginRequest() const
320 const HttpRequest
*request
= virgin
.cause
?
321 virgin
.cause
: dynamic_cast<const HttpRequest
*>(virgin
.header
);
326 // did the activity reached the end of the virgin body?
327 bool Adaptation::Icap::ModXact::virginBodyEndReached(const Adaptation::Icap::VirginBodyAct
&act
) const
330 !act
.active() || // did all (assuming it was originally planned)
331 !virgin
.body_pipe
->expectMoreAfter(act
.offset()); // wont have more
334 // the size of buffered virgin body data available for the specified activity
335 // if this size is zero, we may be done or may be waiting for more data
336 size_t Adaptation::Icap::ModXact::virginContentSize(const Adaptation::Icap::VirginBodyAct
&act
) const
339 // asbolute start of unprocessed data
340 const uint64_t dataStart
= act
.offset();
341 // absolute end of buffered data
342 const uint64_t dataEnd
= virginConsumed
+ virgin
.body_pipe
->buf().contentSize();
343 Must(virginConsumed
<= dataStart
&& dataStart
<= dataEnd
);
344 return static_cast<size_t>(dataEnd
- dataStart
);
347 // pointer to buffered virgin body data available for the specified activity
348 const char *Adaptation::Icap::ModXact::virginContentData(const Adaptation::Icap::VirginBodyAct
&act
) const
351 const uint64_t dataStart
= act
.offset();
352 Must(virginConsumed
<= dataStart
);
353 return virgin
.body_pipe
->buf().content() + static_cast<size_t>(dataStart
-virginConsumed
);
356 void Adaptation::Icap::ModXact::virginConsume()
358 debugs(93, 9, HERE
<< "consumption guards: " << !virgin
.body_pipe
<< isRetriable
<<
359 isRepeatable
<< canStartBypass
<< protectGroupBypass
);
361 if (!virgin
.body_pipe
)
362 return; // nothing to consume
365 return; // do not consume if we may have to retry later
367 BodyPipe
&bp
= *virgin
.body_pipe
;
368 const bool wantToPostpone
= isRepeatable
|| canStartBypass
|| protectGroupBypass
;
370 // Why > 2? HttpState does not use the last bytes in the buffer
371 // because delayAwareRead() is arguably broken. See
372 // HttpStateData::maybeReadVirginBody for more details.
373 if (wantToPostpone
&& bp
.buf().spaceSize() > 2) {
374 // Postponing may increase memory footprint and slow the HTTP side
375 // down. Not postponing may increase the number of ICAP errors
376 // if the ICAP service fails. We may also use "potential" space to
377 // postpone more aggressively. Should the trade-off be configurable?
378 debugs(93, 8, HERE
<< "postponing consumption from " << bp
.status());
382 const size_t have
= static_cast<size_t>(bp
.buf().contentSize());
383 const uint64_t end
= virginConsumed
+ have
;
384 uint64_t offset
= end
;
386 debugs(93, 9, HERE
<< "max virgin consumption offset=" << offset
<<
387 " acts " << virginBodyWriting
.active() << virginBodySending
.active() <<
388 " consumed=" << virginConsumed
<<
389 " from " << virgin
.body_pipe
->status());
391 if (virginBodyWriting
.active())
392 offset
= min(virginBodyWriting
.offset(), offset
);
394 if (virginBodySending
.active())
395 offset
= min(virginBodySending
.offset(), offset
);
397 Must(virginConsumed
<= offset
&& offset
<= end
);
399 if (const size_t size
= static_cast<size_t>(offset
- virginConsumed
)) {
400 debugs(93, 8, HERE
<< "consuming " << size
<< " out of " << have
<<
401 " virgin body bytes");
403 virginConsumed
+= size
;
404 Must(!isRetriable
); // or we should not be consuming
405 disableRepeats("consumed content");
406 disableBypass("consumed content", true);
410 void Adaptation::Icap::ModXact::handleCommWroteBody()
415 // Called when we do not expect to call comm_write anymore.
416 // We may have a pending write though.
417 // If stopping nicely, we will just wait for that pending write, if any.
418 void Adaptation::Icap::ModXact::stopWriting(bool nicely
)
420 if (state
.writing
== State::writingReallyDone
)
423 if (writer
!= NULL
) {
425 debugs(93, 7, HERE
<< "will wait for the last write" << status());
426 state
.writing
= State::writingAlmostDone
; // may already be set
430 debugs(93, 3, HERE
<< "will NOT wait for the last write" << status());
432 // Comm does not have an interface to clear the writer callback nicely,
433 // but without clearing the writer we cannot recycle the connection.
434 // We prevent connection reuse and hope that we can handle a callback
435 // call at any time, usually in the middle of the destruction sequence!
436 // Somebody should add comm_remove_write_handler() to comm API.
437 reuseConnection
= false;
438 ignoreLastWrite
= true;
441 debugs(93, 7, HERE
<< "will no longer write" << status());
442 if (virginBodyWriting
.active()) {
443 virginBodyWriting
.disable();
446 state
.writing
= State::writingReallyDone
;
450 void Adaptation::Icap::ModXact::stopBackup()
452 if (!virginBodySending
.active())
455 debugs(93, 7, HERE
<< "will no longer backup" << status());
456 virginBodySending
.disable();
460 bool Adaptation::Icap::ModXact::doneAll() const
462 return Adaptation::Icap::Xaction::doneAll() && !state
.serviceWaiting
&&
464 doneReading() && state
.doneWriting();
467 void Adaptation::Icap::ModXact::startReading()
469 Must(haveConnection());
471 Must(!adapted
.header
);
472 Must(!adapted
.body_pipe
);
474 // we use the same buffer for headers and body and then consume headers
478 void Adaptation::Icap::ModXact::readMore()
480 if (reader
!= NULL
|| doneReading()) {
481 debugs(93,3,HERE
<< "returning from readMore because reader or doneReading()");
485 // do not fill readBuf if we have no space to store the result
486 if (adapted
.body_pipe
!= NULL
&&
487 !adapted
.body_pipe
->buf().hasPotentialSpace()) {
488 debugs(93,3,HERE
<< "not reading because ICAP reply pipe is full");
492 if (readBuf
.hasSpace())
495 debugs(93,3,HERE
<< "nothing to do because !readBuf.hasSpace()");
498 // comm module read a portion of the ICAP response for us
499 void Adaptation::Icap::ModXact::handleCommRead(size_t)
501 Must(!state
.doneParsing());
502 icap_tio_finish
= current_time
;
507 void Adaptation::Icap::ModXact::echoMore()
509 Must(state
.sending
== State::sendingVirgin
);
510 Must(adapted
.body_pipe
!= NULL
);
511 Must(virginBodySending
.active());
513 const size_t sizeMax
= virginContentSize(virginBodySending
);
514 debugs(93,5, HERE
<< "will echo up to " << sizeMax
<< " bytes from " <<
515 virgin
.body_pipe
->status());
516 debugs(93,5, HERE
<< "will echo up to " << sizeMax
<< " bytes to " <<
517 adapted
.body_pipe
->status());
520 const size_t size
= adapted
.body_pipe
->putMoreData(virginContentData(virginBodySending
), sizeMax
);
521 debugs(93,5, HERE
<< "echoed " << size
<< " out of " << sizeMax
<<
523 virginBodySending
.progress(size
);
524 disableRepeats("echoed content");
525 disableBypass("echoed content", true);
529 if (virginBodyEndReached(virginBodySending
)) {
530 debugs(93, 5, HERE
<< "echoed all" << status());
533 debugs(93, 5, HERE
<< "has " <<
534 virgin
.body_pipe
->buf().contentSize() << " bytes " <<
535 "and expects more to echo" << status());
536 // TODO: timeout if virgin or adapted pipes are broken
540 bool Adaptation::Icap::ModXact::doneSending() const
542 return state
.sending
== State::sendingDone
;
545 // stop (or do not start) sending adapted message body
546 void Adaptation::Icap::ModXact::stopSending(bool nicely
)
548 debugs(93, 7, HERE
<< "Enter stop sending ");
551 debugs(93, 7, HERE
<< "Proceed with stop sending ");
553 if (state
.sending
!= State::sendingUndecided
) {
554 debugs(93, 7, HERE
<< "will no longer send" << status());
555 if (adapted
.body_pipe
!= NULL
) {
556 virginBodySending
.disable();
557 // we may leave debts if we were echoing and the virgin
558 // body_pipe got exhausted before we echoed all planned bytes
559 const bool leftDebts
= adapted
.body_pipe
->needsMoreData();
560 stopProducingFor(adapted
.body_pipe
, nicely
&& !leftDebts
);
563 debugs(93, 7, HERE
<< "will not start sending" << status());
564 Must(!adapted
.body_pipe
);
567 state
.sending
= State::sendingDone
;
571 // should be called after certain state.writing or state.sending changes
572 void Adaptation::Icap::ModXact::checkConsuming()
574 // quit if we already stopped or are still using the pipe
575 if (!virgin
.body_pipe
|| !state
.doneConsumingVirgin())
578 debugs(93, 7, HERE
<< "will stop consuming" << status());
579 stopConsumingFrom(virgin
.body_pipe
);
582 void Adaptation::Icap::ModXact::parseMore()
584 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " bytes to parse" <<
586 debugs(93, 5, HERE
<< "\n" << readBuf
.content());
588 if (state
.parsingHeaders())
591 if (state
.parsing
== State::psBody
)
595 void Adaptation::Icap::ModXact::callException(const std::exception
&e
)
597 if (!canStartBypass
|| isRetriable
) {
598 Adaptation::Icap::Xaction::callException(e
);
603 debugs(93, 3, HERE
<< "bypassing " << inCall
<< " exception: " <<
604 e
.what() << ' ' << status());
606 } catch (const std::exception
&bypassE
) {
607 Adaptation::Icap::Xaction::callException(bypassE
);
611 void Adaptation::Icap::ModXact::bypassFailure()
613 disableBypass("already started to bypass", false);
615 Must(!isRetriable
); // or we should not be bypassing
616 // TODO: should the same be enforced for isRepeatable? Check icap_repeat??
622 // end all activities associated with the ICAP server
626 stopWriting(true); // or should we force it?
627 if (haveConnection()) {
628 reuseConnection
= false; // be conservative
629 cancelRead(); // may not work; and we cannot stop connecting either
631 debugs(93, 7, HERE
<< "Warning: bypass failed to stop I/O" << status());
635 void Adaptation::Icap::ModXact::disableBypass(const char *reason
, bool includingGroupBypass
)
637 if (canStartBypass
) {
638 debugs(93,7, HERE
<< "will never start bypass because " << reason
);
639 canStartBypass
= false;
641 if (protectGroupBypass
&& includingGroupBypass
) {
642 debugs(93,7, HERE
<< "not protecting group bypass because " << reason
);
643 protectGroupBypass
= false;
649 // note that allocation for echoing is done in handle204NoContent()
650 void Adaptation::Icap::ModXact::maybeAllocateHttpMsg()
652 if (adapted
.header
) // already allocated
655 if (gotEncapsulated("res-hdr")) {
656 adapted
.setHeader(new HttpReply
);
657 setOutcome(service().cfg().method
== ICAP::methodReqmod
?
658 xoSatisfied
: xoModified
);
659 } else if (gotEncapsulated("req-hdr")) {
660 adapted
.setHeader(new HttpRequest
);
661 setOutcome(xoModified
);
663 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
666 void Adaptation::Icap::ModXact::parseHeaders()
668 Must(state
.parsingHeaders());
670 if (state
.parsing
== State::psIcapHeader
) {
671 debugs(93, 5, HERE
<< "parse ICAP headers");
675 if (state
.parsing
== State::psHttpHeader
) {
676 debugs(93, 5, HERE
<< "parse HTTP headers");
680 if (state
.parsingHeaders()) { // need more data
688 // called after parsing all headers or when bypassing an exception
689 void Adaptation::Icap::ModXact::startSending()
691 disableRepeats("sent headers");
692 disableBypass("sent headers", true);
693 sendAnswer(adapted
.header
);
695 if (state
.sending
== State::sendingVirgin
)
699 void Adaptation::Icap::ModXact::parseIcapHead()
701 Must(state
.sending
== State::sendingUndecided
);
703 if (!parseHead(icapReply
))
706 if (httpHeaderHasConnDir(&icapReply
->header
, "close")) {
707 debugs(93, 5, HERE
<< "found connection close");
708 reuseConnection
= false;
711 switch (icapReply
->sline
.status
) {
718 case 201: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
720 if (!validate200Ok()) {
721 throw TexcHere("Invalid ICAP Response");
729 handle204NoContent();
733 handle206PartialContent();
737 debugs(93, 5, HERE
<< "ICAP status " << icapReply
->sline
.status
);
738 handleUnknownScode();
742 const HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
744 request
= &virginRequest();
746 // update the cross-transactional database if needed (all status codes!)
747 if (const char *xxName
= Adaptation::Config::masterx_shared_name
) {
748 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
750 const String val
= icapReply
->header
.getByName(xxName
);
751 if (val
.size() > 0) // XXX: HttpHeader lacks empty value detection
752 ah
->updateXxRecord(xxName
, val
);
756 // update the adaptation plan if needed (all status codes!)
757 if (service().cfg().routing
) {
759 if (icapReply
->header
.getList(HDR_X_NEXT_SERVICES
, &services
)) {
760 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
762 ah
->updateNextServices(services
);
764 } // TODO: else warn (occasionally!) if we got HDR_X_NEXT_SERVICES
766 // We need to store received ICAP headers for <icapLastHeader logformat option.
767 // If we already have stored headers from previous ICAP transaction related to this
768 // request, old headers will be replaced with the new one.
770 Adaptation::Icap::History::Pointer h
= request
->icapHistory();
772 h
->mergeIcapHeaders(&icapReply
->header
);
773 h
->setIcapLastHeader(&icapReply
->header
);
776 // handle100Continue() manages state.writing on its own.
777 // Non-100 status means the server needs no postPreview data from us.
778 if (state
.writing
== State::writingPaused
)
782 bool Adaptation::Icap::ModXact::validate200Ok()
784 if (ICAP::methodRespmod
== service().cfg().method
) {
785 if (!gotEncapsulated("res-hdr"))
791 if (ICAP::methodReqmod
== service().cfg().method
) {
792 if (!gotEncapsulated("res-hdr") && !gotEncapsulated("req-hdr"))
801 void Adaptation::Icap::ModXact::handle100Continue()
803 Must(state
.writing
== State::writingPaused
);
804 // server must not respond before the end of preview: we may send ieof
805 Must(preview
.enabled() && preview
.done() && !preview
.ieof());
807 // 100 "Continue" cancels our Preview commitment,
808 // but not commitment to handle 204 or 206 outside Preview
809 if (!state
.allowedPostview204
&& !state
.allowedPostview206
)
812 state
.parsing
= State::psIcapHeader
; // eventually
815 state
.writing
= State::writingPrime
;
820 void Adaptation::Icap::ModXact::handle200Ok()
822 state
.parsing
= State::psHttpHeader
;
823 state
.sending
= State::sendingAdapted
;
828 void Adaptation::Icap::ModXact::handle204NoContent()
834 void Adaptation::Icap::ModXact::handle206PartialContent()
836 if (state
.writing
== State::writingPaused
) {
837 Must(preview
.enabled());
838 Must(state
.allowedPreview206
);
839 debugs(93, 7, HERE
<< "206 inside preview");
841 Must(state
.writing
> State::writingPaused
);
842 Must(state
.allowedPostview206
);
843 debugs(93, 7, HERE
<< "206 outside preview");
845 state
.parsing
= State::psHttpHeader
;
846 state
.sending
= State::sendingAdapted
;
847 state
.readyForUob
= true;
851 // Called when we receive a 204 No Content response and
852 // when we are trying to bypass a service failure.
853 // We actually start sending (echoig or not) in startSending.
854 void Adaptation::Icap::ModXact::prepEchoing()
856 disableRepeats("preparing to echo content");
857 disableBypass("preparing to echo content", true);
860 // We want to clone the HTTP message, but we do not want
861 // to copy some non-HTTP state parts that HttpMsg kids carry in them.
862 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
863 // Instead, we simply write the HTTP message and "clone" it by parsing.
864 // TODO: use HttpMsg::clone()!
866 HttpMsg
*oldHead
= virgin
.header
;
867 debugs(93, 7, HERE
<< "cloning virgin message " << oldHead
);
871 // write the virgin message into a memory buffer
873 packHead(httpBuf
, oldHead
);
875 // allocate the adapted message and copy metainfo
876 Must(!adapted
.header
);
877 HttpMsg
*newHead
= NULL
;
878 if (const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(oldHead
)) {
879 HttpRequest
*newR
= new HttpRequest
;
880 newR
->canonical
= oldR
->canonical
?
881 xstrdup(oldR
->canonical
) : NULL
; // parse() does not set it
883 } else if (dynamic_cast<const HttpReply
*>(oldHead
)) {
884 HttpReply
*newRep
= new HttpReply
;
888 newHead
->inheritProperties(oldHead
);
890 adapted
.setHeader(newHead
);
892 // parse the buffer back
893 http_status error
= HTTP_STATUS_NONE
;
895 Must(newHead
->parse(&httpBuf
, true, &error
));
897 Must(newHead
->hdr_sz
== httpBuf
.contentSize()); // no leftovers
901 debugs(93, 7, HERE
<< "cloned virgin message " << oldHead
<< " to " <<
904 // setup adapted body pipe if needed
905 if (oldHead
->body_pipe
!= NULL
) {
906 debugs(93, 7, HERE
<< "will echo virgin body from " <<
908 if (!virginBodySending
.active())
909 virginBodySending
.plan(); // will throw if not possible
910 state
.sending
= State::sendingVirgin
;
913 // TODO: optimize: is it possible to just use the oldHead pipe and
914 // remove ICAP from the loop? This echoing is probably a common case!
915 makeAdaptedBodyPipe("echoed virgin response");
916 if (oldHead
->body_pipe
->bodySizeKnown())
917 adapted
.body_pipe
->setBodySize(oldHead
->body_pipe
->bodySize());
918 debugs(93, 7, HERE
<< "will echo virgin body to " <<
921 debugs(93, 7, HERE
<< "no virgin body to echo");
926 /// Called when we received use-original-body chunk extension in 206 response.
927 /// We actually start sending (echoing or not) in startSending().
928 void Adaptation::Icap::ModXact::prepPartialBodyEchoing(uint64_t pos
)
930 Must(virginBodySending
.active());
931 Must(virgin
.header
->body_pipe
!= NULL
);
933 setOutcome(xoPartEcho
);
935 debugs(93, 7, HERE
<< "will echo virgin body suffix from " <<
936 virgin
.header
->body_pipe
<< " offset " << pos
);
938 // check that use-original-body=N does not point beyond buffered data
939 const uint64_t virginDataEnd
= virginConsumed
+
940 virgin
.body_pipe
->buf().contentSize();
941 Must(pos
<= virginDataEnd
);
942 virginBodySending
.progress(static_cast<size_t>(pos
));
944 state
.sending
= State::sendingVirgin
;
947 if (virgin
.header
->body_pipe
->bodySizeKnown())
948 adapted
.body_pipe
->expectProductionEndAfter(virgin
.header
->body_pipe
->bodySize() - pos
);
950 debugs(93, 7, HERE
<< "will echo virgin body suffix to " <<
953 // Start echoing data
957 void Adaptation::Icap::ModXact::handleUnknownScode()
961 // TODO: mark connection as "bad"
963 // Terminate the transaction; we do not know how to handle this response.
964 throw TexcHere("Unsupported ICAP status code");
967 void Adaptation::Icap::ModXact::parseHttpHead()
969 if (gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr")) {
970 replyHttpHeaderSize
= 0;
971 maybeAllocateHttpMsg();
973 if (!parseHead(adapted
.header
))
974 return; // need more header data
977 replyHttpHeaderSize
= adapted
.header
->hdr_sz
;
979 if (dynamic_cast<HttpRequest
*>(adapted
.header
)) {
980 const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(virgin
.header
);
982 // TODO: the adapted request did not really originate from the
983 // client; give proxy admin an option to prevent copying of
984 // sensitive client information here. See the following thread:
985 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
988 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
990 adapted
.header
->inheritProperties(virgin
.header
);
993 decideOnParsingBody();
996 // parses both HTTP and ICAP headers
997 bool Adaptation::Icap::ModXact::parseHead(HttpMsg
*head
)
1000 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " head bytes to parse" <<
1001 "; state: " << state
.parsing
);
1003 http_status error
= HTTP_STATUS_NONE
;
1004 const bool parsed
= head
->parse(&readBuf
, commEof
, &error
);
1005 Must(parsed
|| !error
); // success or need more data
1007 if (!parsed
) { // need more data
1008 debugs(93, 5, HERE
<< "parse failed, need more data, return false");
1013 if (HttpRequest
*r
= dynamic_cast<HttpRequest
*>(head
))
1014 urlCanonical(r
); // parse does not set HttpRequest::canonical
1016 debugs(93, 5, HERE
<< "parse success, consume " << head
->hdr_sz
<< " bytes, return true");
1017 readBuf
.consume(head
->hdr_sz
);
1021 void Adaptation::Icap::ModXact::decideOnParsingBody()
1023 if (gotEncapsulated("res-body") || gotEncapsulated("req-body")) {
1024 debugs(93, 5, HERE
<< "expecting a body");
1025 state
.parsing
= State::psBody
;
1026 replyHttpBodySize
= 0;
1027 bodyParser
= new ChunkedCodingParser
;
1028 makeAdaptedBodyPipe("adapted response from the ICAP server");
1029 Must(state
.sending
== State::sendingAdapted
);
1031 debugs(93, 5, HERE
<< "not expecting a body");
1037 void Adaptation::Icap::ModXact::parseBody()
1039 Must(state
.parsing
== State::psBody
);
1042 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " body bytes to parse");
1044 // the parser will throw on errors
1045 BodyPipeCheckout
bpc(*adapted
.body_pipe
);
1046 const bool parsed
= bodyParser
->parse(&readBuf
, &bpc
.buf
);
1049 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " body bytes after " <<
1050 "parse; parsed all: " << parsed
);
1051 replyHttpBodySize
+= adapted
.body_pipe
->buf().contentSize();
1053 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
1054 // TODO: do we really need this if we disable when sending headers?
1055 if (adapted
.body_pipe
->buf().contentSize() > 0) { // parsed something sometime
1056 disableRepeats("sent adapted content");
1057 disableBypass("sent adapted content", true);
1061 if (state
.readyForUob
&& bodyParser
->useOriginBody
>= 0) {
1062 prepPartialBodyEchoing(
1063 static_cast<uint64_t>(bodyParser
->useOriginBody
));
1069 stopSending(true); // the parser succeeds only if all parsed data fits
1073 debugs(93,3,HERE
<< this << " needsMoreData = " << bodyParser
->needsMoreData());
1075 if (bodyParser
->needsMoreData()) {
1076 debugs(93,3,HERE
<< this);
1077 Must(mayReadMore());
1081 if (bodyParser
->needsMoreSpace()) {
1082 Must(!doneSending()); // can hope for more space
1083 Must(adapted
.body_pipe
->buf().contentSize() > 0); // paranoid
1084 // TODO: there should be a timeout in case the sink is broken
1085 // or cannot consume partial content (while we need more space)
1089 void Adaptation::Icap::ModXact::stopParsing()
1091 if (state
.parsing
== State::psDone
)
1094 debugs(93, 7, HERE
<< "will no longer parse" << status());
1100 state
.parsing
= State::psDone
;
1103 // HTTP side added virgin body data
1104 void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer
)
1108 if (state
.sending
== State::sendingVirgin
)
1112 // HTTP side sent us all virgin info
1113 void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer
)
1115 Must(virgin
.body_pipe
->productionEnded());
1117 // push writer and sender in case we were waiting for the last-chunk
1120 if (state
.sending
== State::sendingVirgin
)
1124 // body producer aborted, but the initiator may still want to know
1125 // the answer, even though the HTTP message has been truncated
1126 void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer
)
1128 Must(virgin
.body_pipe
->productionEnded());
1130 // push writer and sender in case we were waiting for the last-chunk
1133 if (state
.sending
== State::sendingVirgin
)
1137 // adapted body consumer wants more adapted data and
1138 // possibly freed some buffer space
1139 void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
1141 if (state
.sending
== State::sendingVirgin
)
1143 else if (state
.sending
== State::sendingAdapted
)
1146 Must(state
.sending
== State::sendingUndecided
);
1149 // adapted body consumer aborted
1150 void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer
)
1152 mustStop("adapted body consumer aborted");
1156 void Adaptation::Icap::ModXact::swanSong()
1158 debugs(93, 5, HERE
<< "swan sings" << status());
1163 // update adaptation history if start was called and we reserved a slot
1164 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
1165 if (ah
!= NULL
&& adaptHistoryId
>= 0)
1166 ah
->recordXactFinish(adaptHistoryId
);
1168 Adaptation::Icap::Xaction::swanSong();
1171 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry
*);
1173 void Adaptation::Icap::ModXact::finalizeLogInfo()
1175 HttpRequest
* request_
= NULL
;
1176 HttpReply
* reply_
= NULL
;
1177 if (!(request_
= dynamic_cast<HttpRequest
*>(adapted
.header
))) {
1178 request_
= (virgin
.cause
? virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
));
1179 reply_
= dynamic_cast<HttpReply
*>(adapted
.header
);
1182 Adaptation::Icap::History::Pointer h
= request_
->icapHistory();
1183 Must(h
!= NULL
); // ICAPXaction::maybeLog calls only if there is a log
1184 al
.icp
.opcode
= ICP_INVALID
;
1185 al
.url
= h
->log_uri
.termedBuf();
1186 const Adaptation::Icap::ServiceRep
&s
= service();
1187 al
.icap
.reqMethod
= s
.cfg().method
;
1189 al
.cache
.caddr
= request_
->client_addr
;
1191 al
.request
= HTTPMSGLOCK(request_
);
1193 al
.reply
= HTTPMSGLOCK(reply_
);
1197 if (h
->rfc931
.size())
1198 al
.cache
.rfc931
= h
->rfc931
.termedBuf();
1201 if (h
->ssluser
.size())
1202 al
.cache
.ssluser
= h
->ssluser
.termedBuf();
1204 al
.cache
.code
= h
->logType
;
1205 al
.cache
.requestSize
= h
->req_sz
;
1207 // leave al.icap.bodyBytesRead negative if no body
1208 if (replyHttpHeaderSize
>= 0 || replyHttpBodySize
>= 0) {
1209 const int64_t zero
= 0; // to make max() argument types the same
1210 al
.icap
.bodyBytesRead
=
1211 max(zero
, replyHttpHeaderSize
) + max(zero
, replyHttpBodySize
);
1215 al
.http
.code
= reply_
->sline
.status
;
1216 al
.http
.content_type
= reply_
->content_type
.termedBuf();
1217 if (replyHttpBodySize
>= 0) {
1218 al
.cache
.replySize
= replyHttpBodySize
+ reply_
->hdr_sz
;
1219 al
.cache
.highOffset
= replyHttpBodySize
;
1221 //don't set al.cache.objectSize because it hasn't exist yet
1227 packerToMemInit(&p
, &mb
);
1229 reply_
->header
.packInto(&p
);
1230 al
.headers
.reply
= xstrdup(mb
.buf
);
1235 prepareLogWithRequestDetails(request_
, &al
);
1236 Xaction::finalizeLogInfo();
1240 void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf
&buf
)
1242 char ntoabuf
[MAX_IPSTRLEN
];
1244 * XXX These should use HttpHdr interfaces instead of Printfs
1246 const Adaptation::ServiceConfig
&s
= service().cfg();
1247 buf
.Printf("%s " SQUIDSTRINGPH
" ICAP/1.0\r\n", s
.methodStr(), SQUIDSTRINGPRINT(s
.uri
));
1248 buf
.Printf("Host: " SQUIDSTRINGPH
":%d\r\n", SQUIDSTRINGPRINT(s
.host
), s
.port
);
1249 buf
.Printf("Date: %s\r\n", mkrfc1123(squid_curtime
));
1251 if (!TheConfig
.reuse_connections
)
1252 buf
.Printf("Connection: close\r\n");
1254 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1256 if (virgin
.header
->header
.has(HDR_PROXY_AUTHENTICATE
)) {
1257 String vh
=virgin
.header
->header
.getByName("Proxy-Authenticate");
1258 buf
.Printf("Proxy-Authenticate: " SQUIDSTRINGPH
"\r\n",SQUIDSTRINGPRINT(vh
));
1261 if (virgin
.header
->header
.has(HDR_PROXY_AUTHORIZATION
)) {
1262 String vh
=virgin
.header
->header
.getByName("Proxy-Authorization");
1263 buf
.Printf("Proxy-Authorization: " SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(vh
));
1266 const HttpRequest
*request
= &virginRequest();
1268 // share the cross-transactional database records if needed
1269 if (Adaptation::Config::masterx_shared_name
) {
1270 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
1273 if (ah
->getXxRecord(name
, value
)) {
1274 buf
.Printf(SQUIDSTRINGPH
": " SQUIDSTRINGPH
"\r\n",
1275 SQUIDSTRINGPRINT(name
), SQUIDSTRINGPRINT(value
));
1281 buf
.Printf("Encapsulated: ");
1287 // build HTTP request header, if any
1288 ICAP::Method m
= s
.method
;
1290 // to simplify, we could assume that request is always available
1294 urlPath
= request
->urlpath
;
1295 if (ICAP::methodRespmod
== m
)
1296 encapsulateHead(buf
, "req-hdr", httpBuf
, request
);
1297 else if (ICAP::methodReqmod
== m
)
1298 encapsulateHead(buf
, "req-hdr", httpBuf
, virgin
.header
);
1301 if (ICAP::methodRespmod
== m
)
1302 if (const HttpMsg
*prime
= virgin
.header
)
1303 encapsulateHead(buf
, "res-hdr", httpBuf
, prime
);
1305 if (!virginBody
.expected())
1306 buf
.Printf("null-body=%d", (int) httpBuf
.contentSize());
1307 else if (ICAP::methodReqmod
== m
)
1308 buf
.Printf("req-body=%d", (int) httpBuf
.contentSize());
1310 buf
.Printf("res-body=%d", (int) httpBuf
.contentSize());
1312 buf
.append(ICAP::crlf
, 2); // terminate Encapsulated line
1314 if (preview
.enabled()) {
1315 buf
.Printf("Preview: %d\r\n", (int)preview
.ad());
1316 if (!virginBody
.expected()) // there is no body to preview
1317 finishNullOrEmptyBodyPreview(httpBuf
);
1320 makeAllowHeader(buf
);
1322 if (TheConfig
.send_client_ip
&& request
) {
1323 Ip::Address client_addr
;
1324 #if FOLLOW_X_FORWARDED_FOR
1325 if (TheConfig
.icap_uses_indirect_client
) {
1326 client_addr
= request
->indirect_client_addr
;
1329 client_addr
= request
->client_addr
;
1330 if (!client_addr
.IsAnyAddr() && !client_addr
.IsNoAddr())
1331 buf
.Printf("X-Client-IP: %s\r\n", client_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
1334 if (TheConfig
.send_client_username
&& request
)
1335 makeUsernameHeader(request
, buf
);
1337 // fprintf(stderr, "%s\n", buf.content());
1339 buf
.append(ICAP::crlf
, 2); // terminate ICAP header
1341 // fill icapRequest for logging
1342 Must(icapRequest
->parseCharBuf(buf
.content(), buf
.contentSize()));
1344 // start ICAP request body with encapsulated HTTP headers
1345 buf
.append(httpBuf
.content(), httpBuf
.contentSize());
1350 // decides which Allow values to write and updates the request buffer
1351 void Adaptation::Icap::ModXact::makeAllowHeader(MemBuf
&buf
)
1353 const bool allow204in
= preview
.enabled(); // TODO: add shouldAllow204in()
1354 const bool allow204out
= state
.allowedPostview204
= shouldAllow204();
1355 const bool allow206in
= state
.allowedPreview206
= shouldAllow206in();
1356 const bool allow206out
= state
.allowedPostview206
= shouldAllow206out();
1358 debugs(93,9, HERE
<< "Allows: " << allow204in
<< allow204out
<<
1359 allow206in
<< allow206out
);
1361 const bool allow204
= allow204in
|| allow204out
;
1362 const bool allow206
= allow206in
|| allow206out
;
1364 if (!allow204
&& !allow206
)
1365 return; // nothing to do
1367 if (virginBody
.expected()) // if there is a virgin body, plan to send it
1368 virginBodySending
.plan();
1370 // writing Preview:... means we will honor 204 inside preview
1371 // writing Allow/204 means we will honor 204 outside preview
1372 // writing Allow:206 means we will honor 206 inside preview
1373 // writing Allow:204,206 means we will honor 206 outside preview
1374 const char *allowHeader
= NULL
;
1375 if (allow204out
&& allow206
)
1376 allowHeader
= "Allow: 204, 206\r\n";
1377 else if (allow204out
)
1378 allowHeader
= "Allow: 204\r\n";
1380 allowHeader
= "Allow: 206\r\n";
1382 if (allowHeader
) { // may be nil if only allow204in is true
1383 buf
.append(allowHeader
, strlen(allowHeader
));
1384 debugs(93,5, HERE
<< "Will write " << allowHeader
);
1388 void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest
*request
, MemBuf
&buf
)
1390 if (request
->auth_user_request
!= NULL
) {
1391 char const *name
= request
->auth_user_request
->username();
1393 const char *value
= TheConfig
.client_username_encode
? base64_encode(name
) : name
;
1394 buf
.Printf("%s: %s\r\n", TheConfig
.client_username_header
, value
);
1399 void Adaptation::Icap::ModXact::encapsulateHead(MemBuf
&icapBuf
, const char *section
, MemBuf
&httpBuf
, const HttpMsg
*head
)
1401 // update ICAP header
1402 icapBuf
.Printf("%s=%d, ", section
, (int) httpBuf
.contentSize());
1405 HttpMsg
*headClone
= NULL
;
1407 if (const HttpRequest
* old_request
= dynamic_cast<const HttpRequest
*>(head
)) {
1408 HttpRequest
* new_request
= new HttpRequest
;
1409 assert(old_request
->canonical
);
1410 urlParse(old_request
->method
, old_request
->canonical
, new_request
);
1411 new_request
->http_ver
= old_request
->http_ver
;
1412 headClone
= new_request
;
1413 } else if (const HttpReply
*old_reply
= dynamic_cast<const HttpReply
*>(head
)) {
1414 HttpReply
* new_reply
= new HttpReply
;
1415 new_reply
->sline
= old_reply
->sline
;
1416 headClone
= new_reply
;
1420 headClone
->inheritProperties(head
);
1422 HttpHeaderPos pos
= HttpHeaderInitPos
;
1423 HttpHeaderEntry
* p_head_entry
= NULL
;
1424 while (NULL
!= (p_head_entry
= head
->header
.getEntry(&pos
)) )
1425 headClone
->header
.addEntry(p_head_entry
->clone());
1429 // remove all hop-by-hop headers from the clone
1430 headClone
->header
.delById(HDR_PROXY_AUTHENTICATE
);
1431 headClone
->header
.removeHopByHopEntries();
1433 // pack polished HTTP header
1434 packHead(httpBuf
, headClone
);
1439 void Adaptation::Icap::ModXact::packHead(MemBuf
&httpBuf
, const HttpMsg
*head
)
1442 packerToMemInit(&p
, &httpBuf
);
1443 head
->packInto(&p
, true);
1447 // decides whether to offer a preview and calculates its size
1448 void Adaptation::Icap::ModXact::decideOnPreview()
1450 if (!TheConfig
.preview_enable
) {
1451 debugs(93, 5, HERE
<< "preview disabled by squid.conf");
1455 const String urlPath
= virginRequest().urlpath
;
1457 if (!service().wantsPreview(urlPath
, wantedSize
)) {
1458 debugs(93, 5, HERE
<< "should not offer preview for " << urlPath
);
1462 // we decided to do preview, now compute its size
1464 Must(wantedSize
>= 0);
1466 // cannot preview more than we can backup
1467 size_t ad
= min(wantedSize
, TheBackupLimit
);
1469 if (!virginBody
.expected())
1471 else if (virginBody
.knownSize())
1472 ad
= min(static_cast<uint64_t>(ad
), virginBody
.size()); // not more than we have
1474 debugs(93, 5, HERE
<< "should offer " << ad
<< "-byte preview " <<
1475 "(service wanted " << wantedSize
<< ")");
1478 Must(preview
.enabled());
1481 // decides whether to allow 204 responses
1482 bool Adaptation::Icap::ModXact::shouldAllow204()
1484 if (!service().allows204())
1487 return canBackupEverything();
1490 // decides whether to allow 206 responses in some mode
1491 bool Adaptation::Icap::ModXact::shouldAllow206any()
1493 return TheConfig
.allow206_enable
&& service().allows206() &&
1494 virginBody
.expected(); // no need for 206 without a body
1497 // decides whether to allow 206 responses in preview mode
1498 bool Adaptation::Icap::ModXact::shouldAllow206in()
1500 return shouldAllow206any() && preview
.enabled();
1503 // decides whether to allow 206 responses outside of preview
1504 bool Adaptation::Icap::ModXact::shouldAllow206out()
1506 return shouldAllow206any() && canBackupEverything();
1509 // used by shouldAllow204 and decideOnRetries
1510 bool Adaptation::Icap::ModXact::canBackupEverything() const
1512 if (!virginBody
.expected())
1513 return true; // no body means no problems with backup
1515 // if there is a body, check whether we can backup it all
1517 if (!virginBody
.knownSize())
1520 // or should we have a different backup limit?
1521 // note that '<' allows for 0-termination of the "full" backup buffer
1522 return virginBody
.size() < TheBackupLimit
;
1525 // Decide whether this transaction can be retried if pconn fails
1526 // Must be called after decideOnPreview and before openConnection()
1527 void Adaptation::Icap::ModXact::decideOnRetries()
1530 return; // no, already decided
1532 if (preview
.enabled())
1533 return; // yes, because preview provides enough guarantees
1535 if (canBackupEverything())
1536 return; // yes, because we can back everything up
1538 disableRetries(); // no, because we cannot back everything up
1541 // Normally, the body-writing code handles preview body. It can deal with
1542 // bodies of unexpected size, including those that turn out to be empty.
1543 // However, that code assumes that the body was expected and body control
1544 // structures were initialized. This is not the case when there is no body
1545 // or the body is known to be empty, because the virgin message will lack a
1546 // body_pipe. So we handle preview of null-body and zero-size bodies here.
1547 void Adaptation::Icap::ModXact::finishNullOrEmptyBodyPreview(MemBuf
&buf
)
1549 Must(!virginBodyWriting
.active()); // one reason we handle it here
1550 Must(!virgin
.body_pipe
); // another reason we handle it here
1551 Must(!preview
.ad());
1553 // do not add last-chunk because our Encapsulated header says null-body
1554 // addLastRequestChunk(buf);
1555 preview
.wrote(0, true);
1557 Must(preview
.done());
1558 Must(preview
.ieof());
1561 void Adaptation::Icap::ModXact::fillPendingStatus(MemBuf
&buf
) const
1563 Adaptation::Icap::Xaction::fillPendingStatus(buf
);
1565 if (state
.serviceWaiting
)
1568 if (virgin
.body_pipe
!= NULL
)
1571 if (haveConnection() && !doneReading())
1574 if (!state
.doneWriting() && state
.writing
!= State::writingInit
)
1575 buf
.Printf("w(%d)", state
.writing
);
1577 if (preview
.enabled()) {
1578 if (!preview
.done())
1579 buf
.Printf("P(%d)", (int) preview
.debt());
1582 if (virginBodySending
.active())
1585 if (!state
.doneParsing() && state
.parsing
!= State::psIcapHeader
)
1586 buf
.Printf("p(%d)", state
.parsing
);
1588 if (!doneSending() && state
.sending
!= State::sendingUndecided
)
1589 buf
.Printf("S(%d)", state
.sending
);
1591 if (state
.readyForUob
)
1597 if (protectGroupBypass
)
1601 void Adaptation::Icap::ModXact::fillDoneStatus(MemBuf
&buf
) const
1603 Adaptation::Icap::Xaction::fillDoneStatus(buf
);
1605 if (!virgin
.body_pipe
)
1608 if (state
.doneWriting())
1611 if (preview
.enabled()) {
1613 buf
.Printf("P%s", preview
.ieof() ? "(ieof)" : "");
1619 if (state
.doneParsing())
1626 bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section
) const
1628 return icapReply
->header
.getByNameListMember("Encapsulated",
1629 section
, ',').size() > 0;
1632 // calculate whether there is a virgin HTTP body and
1633 // whether its expected size is known
1634 // TODO: rename because we do not just estimate
1635 void Adaptation::Icap::ModXact::estimateVirginBody()
1637 // note: lack of size info may disable previews and 204s
1639 HttpMsg
*msg
= virgin
.header
;
1642 HttpRequestMethod method
;
1645 method
= virgin
.cause
->method
;
1646 else if (HttpRequest
*req
= dynamic_cast<HttpRequest
*>(msg
))
1647 method
= req
->method
;
1649 method
= METHOD_NONE
;
1652 // expectingBody returns true for zero-sized bodies, but we will not
1653 // get a pipe for that body, so we treat the message as bodyless
1654 if (method
!= METHOD_NONE
&& msg
->expectingBody(method
, size
) && size
) {
1655 debugs(93, 6, HERE
<< "expects virgin body from " <<
1656 virgin
.body_pipe
<< "; size: " << size
);
1658 virginBody
.expect(size
);
1659 virginBodyWriting
.plan();
1661 // sign up as a body consumer
1662 Must(msg
->body_pipe
!= NULL
);
1663 Must(msg
->body_pipe
== virgin
.body_pipe
);
1664 Must(virgin
.body_pipe
->setConsumerIfNotLate(this));
1666 // make sure TheBackupLimit is in-sync with the buffer size
1667 Must(TheBackupLimit
<= static_cast<size_t>(msg
->body_pipe
->buf().max_capacity
));
1669 debugs(93, 6, HERE
<< "does not expect virgin body");
1670 Must(msg
->body_pipe
== NULL
);
1675 void Adaptation::Icap::ModXact::makeAdaptedBodyPipe(const char *what
)
1677 Must(!adapted
.body_pipe
);
1678 Must(!adapted
.header
->body_pipe
);
1679 adapted
.header
->body_pipe
= new BodyPipe(this);
1680 adapted
.body_pipe
= adapted
.header
->body_pipe
;
1681 debugs(93, 7, HERE
<< "will supply " << what
<< " via " <<
1682 adapted
.body_pipe
<< " pipe");
1686 // TODO: Move SizedEstimate and Preview elsewhere
1688 Adaptation::Icap::SizedEstimate::SizedEstimate()
1689 : theData(dtUnexpected
)
1692 void Adaptation::Icap::SizedEstimate::expect(int64_t aSize
)
1694 theData
= (aSize
>= 0) ? aSize
: (int64_t)dtUnknown
;
1697 bool Adaptation::Icap::SizedEstimate::expected() const
1699 return theData
!= dtUnexpected
;
1702 bool Adaptation::Icap::SizedEstimate::knownSize() const
1705 return theData
!= dtUnknown
;
1708 uint64_t Adaptation::Icap::SizedEstimate::size() const
1711 return static_cast<uint64_t>(theData
);
1716 Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided
)
1719 void Adaptation::Icap::VirginBodyAct::plan()
1722 Must(!theStart
); // not started
1723 theState
= stActive
;
1726 void Adaptation::Icap::VirginBodyAct::disable()
1728 theState
= stDisabled
;
1731 void Adaptation::Icap::VirginBodyAct::progress(size_t size
)
1735 theStart
+= static_cast<int64_t>(size
);
1738 uint64_t Adaptation::Icap::VirginBodyAct::offset() const
1741 return static_cast<uint64_t>(theStart
);
1745 Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled
)
1748 void Adaptation::Icap::Preview::enable(size_t anAd
)
1750 // TODO: check for anAd not exceeding preview size limit
1754 theState
= stWriting
;
1757 bool Adaptation::Icap::Preview::enabled() const
1759 return theState
!= stDisabled
;
1762 size_t Adaptation::Icap::Preview::ad() const
1768 bool Adaptation::Icap::Preview::done() const
1771 return theState
>= stIeof
;
1774 bool Adaptation::Icap::Preview::ieof() const
1777 return theState
== stIeof
;
1780 size_t Adaptation::Icap::Preview::debt() const
1783 return done() ? 0 : (theAd
- theWritten
);
1786 void Adaptation::Icap::Preview::wrote(size_t size
, bool wroteEof
)
1792 Must(theWritten
<= theAd
);
1795 theState
= stIeof
; // written size is irrelevant
1796 else if (theWritten
>= theAd
)
1800 bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf
&mb
) const
1802 if (virgin
.header
== NULL
)
1805 virgin
.header
->firstLineBuf(mb
);
1811 /* Adaptation::Icap::ModXactLauncher */
1813 Adaptation::Icap::ModXactLauncher::ModXactLauncher(HttpMsg
*virginHeader
, HttpRequest
*virginCause
, Adaptation::ServicePointer aService
):
1814 AsyncJob("Adaptation::Icap::ModXactLauncher"),
1815 Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", aService
)
1817 virgin
.setHeader(virginHeader
);
1818 virgin
.setCause(virginCause
);
1819 updateHistory(true);
1822 Adaptation::Icap::Xaction
*Adaptation::Icap::ModXactLauncher::createXaction()
1824 Adaptation::Icap::ServiceRep::Pointer s
=
1825 dynamic_cast<Adaptation::Icap::ServiceRep
*>(theService
.getRaw());
1827 return new Adaptation::Icap::ModXact(virgin
.header
, virgin
.cause
, s
);
1830 void Adaptation::Icap::ModXactLauncher::swanSong()
1832 debugs(93, 5, HERE
<< "swan sings");
1833 updateHistory(false);
1834 Adaptation::Icap::Launcher::swanSong();
1837 void Adaptation::Icap::ModXactLauncher::updateHistory(bool doStart
)
1839 HttpRequest
*r
= virgin
.cause
?
1840 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
1842 // r should never be NULL but we play safe; TODO: add Should()
1844 Adaptation::Icap::History::Pointer h
= r
->icapHistory();
1847 h
->start("ICAPModXactLauncher");
1849 h
->stop("ICAPModXactLauncher");