2 * DEBUG: section 93 ICAP (RFC 3507) Client
6 #include "AccessLogEntry.h"
7 #include "adaptation/Answer.h"
8 #include "adaptation/History.h"
9 #include "adaptation/icap/Client.h"
10 #include "adaptation/icap/Config.h"
11 #include "adaptation/icap/History.h"
12 #include "adaptation/icap/Launcher.h"
13 #include "adaptation/icap/ModXact.h"
14 #include "adaptation/icap/ServiceRep.h"
15 #include "adaptation/Initiator.h"
16 #include "auth/UserRequest.h"
17 #include "base/TextException.h"
19 #include "ChunkedCodingParser.h"
22 #include "HttpRequest.h"
23 #include "HttpReply.h"
24 #include "SquidTime.h"
25 #include "err_detail_type.h"
27 // flow and terminology:
28 // HTTP| --> receive --> encode --> write --> |network
29 // end | <-- send <-- parse <-- read <-- |end
31 // TODO: replace gotEncapsulated() with something faster; we call it often
33 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXact
);
34 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXactLauncher
);
36 static const size_t TheBackupLimit
= BodyPipe::MaxCapacity
;
38 Adaptation::Icap::ModXact::State::State()
40 memset(this, 0, sizeof(*this));
43 Adaptation::Icap::ModXact::ModXact(HttpMsg
*virginHeader
,
44 HttpRequest
*virginCause
, Adaptation::Icap::ServiceRep::Pointer
&aService
):
45 AsyncJob("Adaptation::Icap::ModXact"),
46 Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", aService
),
49 canStartBypass(false), // too early
50 protectGroupBypass(true),
51 replyHttpHeaderSize(-1),
52 replyHttpBodySize(-1),
57 virgin
.setHeader(virginHeader
); // sets virgin.body_pipe if needed
58 virgin
.setCause(virginCause
); // may be NULL
60 // adapted header and body are initialized when we parse them
62 // writing and reading ends are handled by Adaptation::Icap::Xaction
65 // nothing to do because we are using temporary buffers
67 // parsing; TODO: do not set until we parse, see ICAPOptXact
68 icapReply
= new HttpReply
;
69 icapReply
->protoPrefix
= "ICAP/"; // TODO: make an IcapReply class?
71 debugs(93,7, HERE
<< "initialized." << status());
74 // initiator wants us to start
75 void Adaptation::Icap::ModXact::start()
77 Adaptation::Icap::Xaction::start();
79 // reserve an adaptation history slot (attempts are known at this time)
80 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
82 adaptHistoryId
= ah
->recordXactStart(service().cfg().key
, icap_tr_start
, attempts
> 1);
84 estimateVirginBody(); // before virgin disappears!
86 canStartBypass
= service().cfg().bypass
;
88 // it is an ICAP violation to send request to a service w/o known OPTIONS
89 // and the service may is too busy for us: honor Max-Connections and such
90 if (service().up() && service().availableForNew())
96 void Adaptation::Icap::ModXact::waitForService()
99 Must(!state
.serviceWaiting
);
101 if (!service().up()) {
102 AsyncCall::Pointer call
= JobCallback(93,5,
103 ConnWaiterDialer
, this, Adaptation::Icap::ModXact::noteServiceReady
);
105 service().callWhenReady(call
);
106 comment
= "to be up";
108 //The service is unavailable because of max-connection or other reason
110 if (service().cfg().onOverload
!= srvWait
) {
111 // The service is overloaded, but waiting to be available prohibited by
112 // user configuration (onOverload is set to "block" or "bypass")
113 if (service().cfg().onOverload
== srvBlock
)
114 disableBypass("not available", true);
115 else //if (service().cfg().onOverload == srvBypass)
116 canStartBypass
= true;
119 disableRepeats("ICAP service is not available");
121 debugs(93, 7, HERE
<< "will not wait for the service to be available" <<
124 throw TexcHere("ICAP service is not available");
127 AsyncCall::Pointer call
= JobCallback(93,5,
128 ConnWaiterDialer
, this, Adaptation::Icap::ModXact::noteServiceAvailable
);
129 service().callWhenAvailable(call
, state
.waitedForService
);
130 comment
= "to be available";
133 debugs(93, 7, HERE
<< "will wait for the service " << comment
<< status());
134 state
.serviceWaiting
= true; // after callWhenReady() which may throw
135 state
.waitedForService
= true;
138 void Adaptation::Icap::ModXact::noteServiceReady()
140 Must(state
.serviceWaiting
);
141 state
.serviceWaiting
= false;
143 if (!service().up()) {
145 disableRepeats("ICAP service is unusable");
146 throw TexcHere("ICAP service is unusable");
149 if (service().availableForOld())
155 void Adaptation::Icap::ModXact::noteServiceAvailable()
157 Must(state
.serviceWaiting
);
158 state
.serviceWaiting
= false;
160 if (service().up() && service().availableForOld())
166 void Adaptation::Icap::ModXact::startWriting()
168 state
.writing
= State::writingConnect
;
170 decideOnPreview(); // must be decided before we decideOnRetries
176 // connection with the ICAP service established
177 void Adaptation::Icap::ModXact::handleCommConnected()
179 Must(state
.writing
== State::writingConnect
);
181 startReading(); // wait for early errors from the ICAP server
186 makeRequestHeaders(requestBuf
);
187 debugs(93, 9, HERE
<< "will write" << status() << ":\n" <<
188 (requestBuf
.terminate(), requestBuf
.content()));
191 state
.writing
= State::writingHeaders
;
192 icap_tio_start
= current_time
;
193 scheduleWrite(requestBuf
);
196 void Adaptation::Icap::ModXact::handleCommWrote(size_t sz
)
198 debugs(93, 5, HERE
<< "Wrote " << sz
<< " bytes");
200 if (state
.writing
== State::writingHeaders
)
201 handleCommWroteHeaders();
203 handleCommWroteBody();
206 void Adaptation::Icap::ModXact::handleCommWroteHeaders()
208 Must(state
.writing
== State::writingHeaders
);
210 // determine next step
211 if (preview
.enabled()) {
213 decideWritingAfterPreview("zero-size");
215 state
.writing
= State::writingPreview
;
216 } else if (virginBody
.expected()) {
217 state
.writing
= State::writingPrime
;
226 void Adaptation::Icap::ModXact::writeMore()
228 debugs(93, 5, HERE
<< "checking whether to write more" << status());
230 if (writer
!= NULL
) // already writing something
233 switch (state
.writing
) {
235 case State::writingInit
: // waiting for service OPTIONS
236 Must(state
.serviceWaiting
);
238 case State::writingConnect
: // waiting for the connection to establish
240 case State::writingHeaders
: // waiting for the headers to be written
242 case State::writingPaused
: // waiting for the ICAP server response
244 case State::writingReallyDone
: // nothing more to write
247 case State::writingAlmostDone
: // was waiting for the last write
251 case State::writingPreview
:
255 case State::writingPrime
:
260 throw TexcHere("Adaptation::Icap::ModXact in bad writing state");
264 void Adaptation::Icap::ModXact::writePreviewBody()
266 debugs(93, 8, HERE
<< "will write Preview body from " <<
267 virgin
.body_pipe
<< status());
268 Must(state
.writing
== State::writingPreview
);
269 Must(virgin
.body_pipe
!= NULL
);
271 const size_t sizeMax
= (size_t)virgin
.body_pipe
->buf().contentSize();
272 const size_t size
= min(preview
.debt(), sizeMax
);
273 writeSomeBody("preview body", size
);
275 // change state once preview is written
278 decideWritingAfterPreview("body");
281 /// determine state.writing after we wrote the entire preview
282 void Adaptation::Icap::ModXact::decideWritingAfterPreview(const char *kind
)
284 if (preview
.ieof()) // nothing more to write
286 else if (state
.parsing
== State::psIcapHeader
) // did not get a reply yet
287 state
.writing
= State::writingPaused
; // wait for the ICAP server reply
289 stopWriting(true); // ICAP server reply implies no post-preview writing
291 debugs(93, 6, HERE
<< "decided on writing after " << kind
<< " preview" <<
295 void Adaptation::Icap::ModXact::writePrimeBody()
297 Must(state
.writing
== State::writingPrime
);
298 Must(virginBodyWriting
.active());
300 const size_t size
= (size_t)virgin
.body_pipe
->buf().contentSize();
301 writeSomeBody("prime virgin body", size
);
303 if (virginBodyEndReached(virginBodyWriting
)) {
304 debugs(93, 5, HERE
<< "wrote entire body");
309 void Adaptation::Icap::ModXact::writeSomeBody(const char *label
, size_t size
)
311 Must(!writer
&& state
.writing
< state
.writingAlmostDone
);
312 Must(virgin
.body_pipe
!= NULL
);
313 debugs(93, 8, HERE
<< "will write up to " << size
<< " bytes of " <<
316 MemBuf writeBuf
; // TODO: suggest a min size based on size and lastChunk
318 writeBuf
.init(); // note: we assume that last-chunk will fit
320 const size_t writableSize
= virginContentSize(virginBodyWriting
);
321 const size_t chunkSize
= min(writableSize
, size
);
324 debugs(93, 7, HERE
<< "will write " << chunkSize
<<
325 "-byte chunk of " << label
);
327 openChunk(writeBuf
, chunkSize
, false);
328 writeBuf
.append(virginContentData(virginBodyWriting
), chunkSize
);
329 closeChunk(writeBuf
);
331 virginBodyWriting
.progress(chunkSize
);
334 debugs(93, 7, HERE
<< "has no writable " << label
<< " content");
337 const bool wroteEof
= virginBodyEndReached(virginBodyWriting
);
338 bool lastChunk
= wroteEof
;
339 if (state
.writing
== State::writingPreview
) {
340 preview
.wrote(chunkSize
, wroteEof
); // even if wrote nothing
341 lastChunk
= lastChunk
|| preview
.done();
345 debugs(93, 8, HERE
<< "will write last-chunk of " << label
);
346 addLastRequestChunk(writeBuf
);
349 debugs(93, 7, HERE
<< "will write " << writeBuf
.contentSize()
350 << " raw bytes of " << label
);
352 if (writeBuf
.hasContent()) {
353 scheduleWrite(writeBuf
); // comm will free the chunk
359 void Adaptation::Icap::ModXact::addLastRequestChunk(MemBuf
&buf
)
361 const bool ieof
= state
.writing
== State::writingPreview
&& preview
.ieof();
362 openChunk(buf
, 0, ieof
);
366 void Adaptation::Icap::ModXact::openChunk(MemBuf
&buf
, size_t chunkSize
, bool ieof
)
368 buf
.Printf((ieof
? "%x; ieof\r\n" : "%x\r\n"), (int) chunkSize
);
371 void Adaptation::Icap::ModXact::closeChunk(MemBuf
&buf
)
373 buf
.append(ICAP::crlf
, 2); // chunk-terminating CRLF
376 const HttpRequest
&Adaptation::Icap::ModXact::virginRequest() const
378 const HttpRequest
*request
= virgin
.cause
?
379 virgin
.cause
: dynamic_cast<const HttpRequest
*>(virgin
.header
);
384 // did the activity reached the end of the virgin body?
385 bool Adaptation::Icap::ModXact::virginBodyEndReached(const Adaptation::Icap::VirginBodyAct
&act
) const
388 !act
.active() || // did all (assuming it was originally planned)
389 !virgin
.body_pipe
->expectMoreAfter(act
.offset()); // wont have more
392 // the size of buffered virgin body data available for the specified activity
393 // if this size is zero, we may be done or may be waiting for more data
394 size_t Adaptation::Icap::ModXact::virginContentSize(const Adaptation::Icap::VirginBodyAct
&act
) const
397 // asbolute start of unprocessed data
398 const uint64_t dataStart
= act
.offset();
399 // absolute end of buffered data
400 const uint64_t dataEnd
= virginConsumed
+ virgin
.body_pipe
->buf().contentSize();
401 Must(virginConsumed
<= dataStart
&& dataStart
<= dataEnd
);
402 return static_cast<size_t>(dataEnd
- dataStart
);
405 // pointer to buffered virgin body data available for the specified activity
406 const char *Adaptation::Icap::ModXact::virginContentData(const Adaptation::Icap::VirginBodyAct
&act
) const
409 const uint64_t dataStart
= act
.offset();
410 Must(virginConsumed
<= dataStart
);
411 return virgin
.body_pipe
->buf().content() + static_cast<size_t>(dataStart
-virginConsumed
);
414 void Adaptation::Icap::ModXact::virginConsume()
416 debugs(93, 9, HERE
<< "consumption guards: " << !virgin
.body_pipe
<< isRetriable
<<
417 isRepeatable
<< canStartBypass
<< protectGroupBypass
);
419 if (!virgin
.body_pipe
)
420 return; // nothing to consume
423 return; // do not consume if we may have to retry later
425 BodyPipe
&bp
= *virgin
.body_pipe
;
426 const bool wantToPostpone
= isRepeatable
|| canStartBypass
|| protectGroupBypass
;
428 // Why > 2? HttpState does not use the last bytes in the buffer
429 // because delayAwareRead() is arguably broken. See
430 // HttpStateData::maybeReadVirginBody for more details.
431 if (wantToPostpone
&& bp
.buf().spaceSize() > 2) {
432 // Postponing may increase memory footprint and slow the HTTP side
433 // down. Not postponing may increase the number of ICAP errors
434 // if the ICAP service fails. We may also use "potential" space to
435 // postpone more aggressively. Should the trade-off be configurable?
436 debugs(93, 8, HERE
<< "postponing consumption from " << bp
.status());
440 const size_t have
= static_cast<size_t>(bp
.buf().contentSize());
441 const uint64_t end
= virginConsumed
+ have
;
442 uint64_t offset
= end
;
444 debugs(93, 9, HERE
<< "max virgin consumption offset=" << offset
<<
445 " acts " << virginBodyWriting
.active() << virginBodySending
.active() <<
446 " consumed=" << virginConsumed
<<
447 " from " << virgin
.body_pipe
->status());
449 if (virginBodyWriting
.active())
450 offset
= min(virginBodyWriting
.offset(), offset
);
452 if (virginBodySending
.active())
453 offset
= min(virginBodySending
.offset(), offset
);
455 Must(virginConsumed
<= offset
&& offset
<= end
);
457 if (const size_t size
= static_cast<size_t>(offset
- virginConsumed
)) {
458 debugs(93, 8, HERE
<< "consuming " << size
<< " out of " << have
<<
459 " virgin body bytes");
461 virginConsumed
+= size
;
462 Must(!isRetriable
); // or we should not be consuming
463 disableRepeats("consumed content");
464 disableBypass("consumed content", true);
468 void Adaptation::Icap::ModXact::handleCommWroteBody()
473 // Called when we do not expect to call comm_write anymore.
474 // We may have a pending write though.
475 // If stopping nicely, we will just wait for that pending write, if any.
476 void Adaptation::Icap::ModXact::stopWriting(bool nicely
)
478 if (state
.writing
== State::writingReallyDone
)
481 if (writer
!= NULL
) {
483 debugs(93, 7, HERE
<< "will wait for the last write" << status());
484 state
.writing
= State::writingAlmostDone
; // may already be set
488 debugs(93, 3, HERE
<< "will NOT wait for the last write" << status());
490 // Comm does not have an interface to clear the writer callback nicely,
491 // but without clearing the writer we cannot recycle the connection.
492 // We prevent connection reuse and hope that we can handle a callback
493 // call at any time, usually in the middle of the destruction sequence!
494 // Somebody should add comm_remove_write_handler() to comm API.
495 reuseConnection
= false;
496 ignoreLastWrite
= true;
499 debugs(93, 7, HERE
<< "will no longer write" << status());
500 if (virginBodyWriting
.active()) {
501 virginBodyWriting
.disable();
504 state
.writing
= State::writingReallyDone
;
508 void Adaptation::Icap::ModXact::stopBackup()
510 if (!virginBodySending
.active())
513 debugs(93, 7, HERE
<< "will no longer backup" << status());
514 virginBodySending
.disable();
518 bool Adaptation::Icap::ModXact::doneAll() const
520 return Adaptation::Icap::Xaction::doneAll() && !state
.serviceWaiting
&&
522 doneReading() && state
.doneWriting();
525 void Adaptation::Icap::ModXact::startReading()
527 Must(connection
>= 0);
529 Must(!adapted
.header
);
530 Must(!adapted
.body_pipe
);
532 // we use the same buffer for headers and body and then consume headers
536 void Adaptation::Icap::ModXact::readMore()
538 if (reader
!= NULL
|| doneReading()) {
539 debugs(93,3,HERE
<< "returning from readMore because reader or doneReading()");
543 // do not fill readBuf if we have no space to store the result
544 if (adapted
.body_pipe
!= NULL
&&
545 !adapted
.body_pipe
->buf().hasPotentialSpace()) {
546 debugs(93,3,HERE
<< "not reading because ICAP reply pipe is full");
550 if (readBuf
.hasSpace())
553 debugs(93,3,HERE
<< "nothing to do because !readBuf.hasSpace()");
556 // comm module read a portion of the ICAP response for us
557 void Adaptation::Icap::ModXact::handleCommRead(size_t)
559 Must(!state
.doneParsing());
560 icap_tio_finish
= current_time
;
565 void Adaptation::Icap::ModXact::echoMore()
567 Must(state
.sending
== State::sendingVirgin
);
568 Must(adapted
.body_pipe
!= NULL
);
569 Must(virginBodySending
.active());
571 const size_t sizeMax
= virginContentSize(virginBodySending
);
572 debugs(93,5, HERE
<< "will echo up to " << sizeMax
<< " bytes from " <<
573 virgin
.body_pipe
->status());
574 debugs(93,5, HERE
<< "will echo up to " << sizeMax
<< " bytes to " <<
575 adapted
.body_pipe
->status());
578 const size_t size
= adapted
.body_pipe
->putMoreData(virginContentData(virginBodySending
), sizeMax
);
579 debugs(93,5, HERE
<< "echoed " << size
<< " out of " << sizeMax
<<
581 virginBodySending
.progress(size
);
582 disableRepeats("echoed content");
583 disableBypass("echoed content", true);
587 if (virginBodyEndReached(virginBodySending
)) {
588 debugs(93, 5, HERE
<< "echoed all" << status());
591 debugs(93, 5, HERE
<< "has " <<
592 virgin
.body_pipe
->buf().contentSize() << " bytes " <<
593 "and expects more to echo" << status());
594 // TODO: timeout if virgin or adapted pipes are broken
598 bool Adaptation::Icap::ModXact::doneSending() const
600 return state
.sending
== State::sendingDone
;
603 // stop (or do not start) sending adapted message body
604 void Adaptation::Icap::ModXact::stopSending(bool nicely
)
606 debugs(93, 7, HERE
<< "Enter stop sending ");
609 debugs(93, 7, HERE
<< "Proceed with stop sending ");
611 if (state
.sending
!= State::sendingUndecided
) {
612 debugs(93, 7, HERE
<< "will no longer send" << status());
613 if (adapted
.body_pipe
!= NULL
) {
614 virginBodySending
.disable();
615 // we may leave debts if we were echoing and the virgin
616 // body_pipe got exhausted before we echoed all planned bytes
617 const bool leftDebts
= adapted
.body_pipe
->needsMoreData();
618 stopProducingFor(adapted
.body_pipe
, nicely
&& !leftDebts
);
621 debugs(93, 7, HERE
<< "will not start sending" << status());
622 Must(!adapted
.body_pipe
);
625 state
.sending
= State::sendingDone
;
629 // should be called after certain state.writing or state.sending changes
630 void Adaptation::Icap::ModXact::checkConsuming()
632 // quit if we already stopped or are still using the pipe
633 if (!virgin
.body_pipe
|| !state
.doneConsumingVirgin())
636 debugs(93, 7, HERE
<< "will stop consuming" << status());
637 stopConsumingFrom(virgin
.body_pipe
);
640 void Adaptation::Icap::ModXact::parseMore()
642 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " bytes to parse" <<
644 debugs(93, 5, HERE
<< "\n" << readBuf
.content());
646 if (state
.parsingHeaders())
649 if (state
.parsing
== State::psBody
)
653 void Adaptation::Icap::ModXact::callException(const std::exception
&e
)
655 if (!canStartBypass
|| isRetriable
) {
657 if (const TextException
*te
= dynamic_cast<const TextException
*>(&e
))
658 detailError(ERR_DETAIL_EXCEPTION_START
+ te
->id());
660 detailError(ERR_DETAIL_EXCEPTION_OTHER
);
662 Adaptation::Icap::Xaction::callException(e
);
667 debugs(93, 3, HERE
<< "bypassing " << inCall
<< " exception: " <<
668 e
.what() << ' ' << status());
670 } catch (const TextException
&bypassTe
) {
671 detailError(ERR_DETAIL_EXCEPTION_START
+ bypassTe
.id());
672 Adaptation::Icap::Xaction::callException(bypassTe
);
673 } catch (const std::exception
&bypassE
) {
674 detailError(ERR_DETAIL_EXCEPTION_OTHER
);
675 Adaptation::Icap::Xaction::callException(bypassE
);
679 void Adaptation::Icap::ModXact::bypassFailure()
681 disableBypass("already started to bypass", false);
683 Must(!isRetriable
); // or we should not be bypassing
684 // TODO: should the same be enforced for isRepeatable? Check icap_repeat??
690 // end all activities associated with the ICAP server
694 stopWriting(true); // or should we force it?
695 if (connection
>= 0) {
696 reuseConnection
= false; // be conservative
697 cancelRead(); // may not work; and we cannot stop connecting either
699 debugs(93, 7, HERE
<< "Warning: bypass failed to stop I/O" << status());
702 service().noteFailure(); // we are bypassing, but this is still a failure
705 void Adaptation::Icap::ModXact::disableBypass(const char *reason
, bool includingGroupBypass
)
707 if (canStartBypass
) {
708 debugs(93,7, HERE
<< "will never start bypass because " << reason
);
709 canStartBypass
= false;
711 if (protectGroupBypass
&& includingGroupBypass
) {
712 debugs(93,7, HERE
<< "not protecting group bypass because " << reason
);
713 protectGroupBypass
= false;
719 // note that allocation for echoing is done in handle204NoContent()
720 void Adaptation::Icap::ModXact::maybeAllocateHttpMsg()
722 if (adapted
.header
) // already allocated
725 if (gotEncapsulated("res-hdr")) {
726 adapted
.setHeader(new HttpReply
);
727 setOutcome(service().cfg().method
== ICAP::methodReqmod
?
728 xoSatisfied
: xoModified
);
729 } else if (gotEncapsulated("req-hdr")) {
730 adapted
.setHeader(new HttpRequest
);
731 setOutcome(xoModified
);
733 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
736 void Adaptation::Icap::ModXact::parseHeaders()
738 Must(state
.parsingHeaders());
740 if (state
.parsing
== State::psIcapHeader
) {
741 debugs(93, 5, HERE
<< "parse ICAP headers");
745 if (state
.parsing
== State::psHttpHeader
) {
746 debugs(93, 5, HERE
<< "parse HTTP headers");
750 if (state
.parsingHeaders()) { // need more data
758 // called after parsing all headers or when bypassing an exception
759 void Adaptation::Icap::ModXact::startSending()
761 disableRepeats("sent headers");
762 disableBypass("sent headers", true);
763 sendAnswer(Answer::Forward(adapted
.header
));
765 if (state
.sending
== State::sendingVirgin
)
769 void Adaptation::Icap::ModXact::parseIcapHead()
771 Must(state
.sending
== State::sendingUndecided
);
773 if (!parseHead(icapReply
))
776 if (httpHeaderHasConnDir(&icapReply
->header
, "close")) {
777 debugs(93, 5, HERE
<< "found connection close");
778 reuseConnection
= false;
781 switch (icapReply
->sline
.status
) {
788 case 201: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
790 if (!validate200Ok()) {
791 throw TexcHere("Invalid ICAP Response");
799 handle204NoContent();
803 handle206PartialContent();
807 debugs(93, 5, HERE
<< "ICAP status " << icapReply
->sline
.status
);
808 handleUnknownScode();
812 const HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
814 request
= &virginRequest();
816 // update the cross-transactional database if needed (all status codes!)
817 if (const char *xxName
= Adaptation::Config::masterx_shared_name
) {
818 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
819 if (ah
!= NULL
) { // TODO: reorder checks to avoid creating history
820 const String val
= icapReply
->header
.getByName(xxName
);
821 if (val
.size() > 0) // XXX: HttpHeader lacks empty value detection
822 ah
->updateXxRecord(xxName
, val
);
826 // update the adaptation plan if needed (all status codes!)
827 if (service().cfg().routing
) {
829 if (icapReply
->header
.getList(HDR_X_NEXT_SERVICES
, &services
)) {
830 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
832 ah
->updateNextServices(services
);
834 } // TODO: else warn (occasionally!) if we got HDR_X_NEXT_SERVICES
836 // We need to store received ICAP headers for <icapLastHeader logformat option.
837 // If we already have stored headers from previous ICAP transaction related to this
838 // request, old headers will be replaced with the new one.
840 Adaptation::History::Pointer ah
= request
->adaptLogHistory();
842 ah
->recordMeta(&icapReply
->header
);
844 // handle100Continue() manages state.writing on its own.
845 // Non-100 status means the server needs no postPreview data from us.
846 if (state
.writing
== State::writingPaused
)
850 bool Adaptation::Icap::ModXact::validate200Ok()
852 if (ICAP::methodRespmod
== service().cfg().method
) {
853 if (!gotEncapsulated("res-hdr"))
859 if (ICAP::methodReqmod
== service().cfg().method
) {
860 if (!gotEncapsulated("res-hdr") && !gotEncapsulated("req-hdr"))
869 void Adaptation::Icap::ModXact::handle100Continue()
871 Must(state
.writing
== State::writingPaused
);
872 // server must not respond before the end of preview: we may send ieof
873 Must(preview
.enabled() && preview
.done() && !preview
.ieof());
875 // 100 "Continue" cancels our Preview commitment,
876 // but not commitment to handle 204 or 206 outside Preview
877 if (!state
.allowedPostview204
&& !state
.allowedPostview206
)
880 state
.parsing
= State::psIcapHeader
; // eventually
883 state
.writing
= State::writingPrime
;
888 void Adaptation::Icap::ModXact::handle200Ok()
890 state
.parsing
= State::psHttpHeader
;
891 state
.sending
= State::sendingAdapted
;
896 void Adaptation::Icap::ModXact::handle204NoContent()
902 void Adaptation::Icap::ModXact::handle206PartialContent()
904 if (state
.writing
== State::writingPaused
) {
905 Must(preview
.enabled());
906 Must(state
.allowedPreview206
);
907 debugs(93, 7, HERE
<< "206 inside preview");
909 Must(state
.writing
> State::writingPaused
);
910 Must(state
.allowedPostview206
);
911 debugs(93, 7, HERE
<< "206 outside preview");
913 state
.parsing
= State::psHttpHeader
;
914 state
.sending
= State::sendingAdapted
;
915 state
.readyForUob
= true;
919 // Called when we receive a 204 No Content response and
920 // when we are trying to bypass a service failure.
921 // We actually start sending (echoig or not) in startSending.
922 void Adaptation::Icap::ModXact::prepEchoing()
924 disableRepeats("preparing to echo content");
925 disableBypass("preparing to echo content", true);
928 // We want to clone the HTTP message, but we do not want
929 // to copy some non-HTTP state parts that HttpMsg kids carry in them.
930 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
931 // Instead, we simply write the HTTP message and "clone" it by parsing.
932 // TODO: use HttpMsg::clone()!
934 HttpMsg
*oldHead
= virgin
.header
;
935 debugs(93, 7, HERE
<< "cloning virgin message " << oldHead
);
939 // write the virgin message into a memory buffer
941 packHead(httpBuf
, oldHead
);
943 // allocate the adapted message and copy metainfo
944 Must(!adapted
.header
);
946 HttpMsg::Pointer newHead
;
947 if (const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(oldHead
)) {
948 HttpRequest::Pointer
newR(new HttpRequest
);
949 newR
->canonical
= oldR
->canonical
?
950 xstrdup(oldR
->canonical
) : NULL
; // parse() does not set it
952 } else if (dynamic_cast<const HttpReply
*>(oldHead
)) {
953 newHead
= new HttpReply
;
955 Must(newHead
!= NULL
);
957 newHead
->inheritProperties(oldHead
);
959 adapted
.setHeader(newHead
);
962 // parse the buffer back
963 http_status error
= HTTP_STATUS_NONE
;
965 Must(adapted
.header
->parse(&httpBuf
, true, &error
));
967 Must(adapted
.header
->hdr_sz
== httpBuf
.contentSize()); // no leftovers
971 debugs(93, 7, HERE
<< "cloned virgin message " << oldHead
<< " to " <<
974 // setup adapted body pipe if needed
975 if (oldHead
->body_pipe
!= NULL
) {
976 debugs(93, 7, HERE
<< "will echo virgin body from " <<
978 if (!virginBodySending
.active())
979 virginBodySending
.plan(); // will throw if not possible
980 state
.sending
= State::sendingVirgin
;
983 // TODO: optimize: is it possible to just use the oldHead pipe and
984 // remove ICAP from the loop? This echoing is probably a common case!
985 makeAdaptedBodyPipe("echoed virgin response");
986 if (oldHead
->body_pipe
->bodySizeKnown())
987 adapted
.body_pipe
->setBodySize(oldHead
->body_pipe
->bodySize());
988 debugs(93, 7, HERE
<< "will echo virgin body to " <<
991 debugs(93, 7, HERE
<< "no virgin body to echo");
996 /// Called when we received use-original-body chunk extension in 206 response.
997 /// We actually start sending (echoing or not) in startSending().
998 void Adaptation::Icap::ModXact::prepPartialBodyEchoing(uint64_t pos
)
1000 Must(virginBodySending
.active());
1001 Must(virgin
.header
->body_pipe
!= NULL
);
1003 setOutcome(xoPartEcho
);
1005 debugs(93, 7, HERE
<< "will echo virgin body suffix from " <<
1006 virgin
.header
->body_pipe
<< " offset " << pos
);
1008 // check that use-original-body=N does not point beyond buffered data
1009 const uint64_t virginDataEnd
= virginConsumed
+
1010 virgin
.body_pipe
->buf().contentSize();
1011 Must(pos
<= virginDataEnd
);
1012 virginBodySending
.progress(static_cast<size_t>(pos
));
1014 state
.sending
= State::sendingVirgin
;
1017 if (virgin
.header
->body_pipe
->bodySizeKnown())
1018 adapted
.body_pipe
->expectProductionEndAfter(virgin
.header
->body_pipe
->bodySize() - pos
);
1020 debugs(93, 7, HERE
<< "will echo virgin body suffix to " <<
1023 // Start echoing data
1027 void Adaptation::Icap::ModXact::handleUnknownScode()
1031 // TODO: mark connection as "bad"
1033 // Terminate the transaction; we do not know how to handle this response.
1034 throw TexcHere("Unsupported ICAP status code");
1037 void Adaptation::Icap::ModXact::parseHttpHead()
1039 if (gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr")) {
1040 replyHttpHeaderSize
= 0;
1041 maybeAllocateHttpMsg();
1043 if (!parseHead(adapted
.header
))
1044 return; // need more header data
1047 replyHttpHeaderSize
= adapted
.header
->hdr_sz
;
1049 if (dynamic_cast<HttpRequest
*>(adapted
.header
)) {
1050 const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(virgin
.header
);
1052 // TODO: the adapted request did not really originate from the
1053 // client; give proxy admin an option to prevent copying of
1054 // sensitive client information here. See the following thread:
1055 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
1058 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
1060 adapted
.header
->inheritProperties(virgin
.header
);
1063 decideOnParsingBody();
1066 // parses both HTTP and ICAP headers
1067 bool Adaptation::Icap::ModXact::parseHead(HttpMsg
*head
)
1070 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " head bytes to parse" <<
1071 "; state: " << state
.parsing
);
1073 http_status error
= HTTP_STATUS_NONE
;
1074 const bool parsed
= head
->parse(&readBuf
, commEof
, &error
);
1075 Must(parsed
|| !error
); // success or need more data
1077 if (!parsed
) { // need more data
1078 debugs(93, 5, HERE
<< "parse failed, need more data, return false");
1083 if (HttpRequest
*r
= dynamic_cast<HttpRequest
*>(head
))
1084 urlCanonical(r
); // parse does not set HttpRequest::canonical
1086 debugs(93, 5, HERE
<< "parse success, consume " << head
->hdr_sz
<< " bytes, return true");
1087 readBuf
.consume(head
->hdr_sz
);
1091 void Adaptation::Icap::ModXact::decideOnParsingBody()
1093 if (gotEncapsulated("res-body") || gotEncapsulated("req-body")) {
1094 debugs(93, 5, HERE
<< "expecting a body");
1095 state
.parsing
= State::psBody
;
1096 replyHttpBodySize
= 0;
1097 bodyParser
= new ChunkedCodingParser
;
1098 makeAdaptedBodyPipe("adapted response from the ICAP server");
1099 Must(state
.sending
== State::sendingAdapted
);
1101 debugs(93, 5, HERE
<< "not expecting a body");
1107 void Adaptation::Icap::ModXact::parseBody()
1109 Must(state
.parsing
== State::psBody
);
1112 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " body bytes to parse");
1114 // the parser will throw on errors
1115 BodyPipeCheckout
bpc(*adapted
.body_pipe
);
1116 const bool parsed
= bodyParser
->parse(&readBuf
, &bpc
.buf
);
1119 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " body bytes after " <<
1120 "parse; parsed all: " << parsed
);
1121 replyHttpBodySize
+= adapted
.body_pipe
->buf().contentSize();
1123 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
1124 // TODO: do we really need this if we disable when sending headers?
1125 if (adapted
.body_pipe
->buf().contentSize() > 0) { // parsed something sometime
1126 disableRepeats("sent adapted content");
1127 disableBypass("sent adapted content", true);
1131 if (state
.readyForUob
&& bodyParser
->useOriginBody
>= 0) {
1132 prepPartialBodyEchoing(
1133 static_cast<uint64_t>(bodyParser
->useOriginBody
));
1139 stopSending(true); // the parser succeeds only if all parsed data fits
1143 debugs(93,3,HERE
<< this << " needsMoreData = " << bodyParser
->needsMoreData());
1145 if (bodyParser
->needsMoreData()) {
1146 debugs(93,3,HERE
<< this);
1147 Must(mayReadMore());
1151 if (bodyParser
->needsMoreSpace()) {
1152 Must(!doneSending()); // can hope for more space
1153 Must(adapted
.body_pipe
->buf().contentSize() > 0); // paranoid
1154 // TODO: there should be a timeout in case the sink is broken
1155 // or cannot consume partial content (while we need more space)
1159 void Adaptation::Icap::ModXact::stopParsing()
1161 if (state
.parsing
== State::psDone
)
1164 debugs(93, 7, HERE
<< "will no longer parse" << status());
1170 state
.parsing
= State::psDone
;
1173 // HTTP side added virgin body data
1174 void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer
)
1178 if (state
.sending
== State::sendingVirgin
)
1182 // HTTP side sent us all virgin info
1183 void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer
)
1185 Must(virgin
.body_pipe
->productionEnded());
1187 // push writer and sender in case we were waiting for the last-chunk
1190 if (state
.sending
== State::sendingVirgin
)
1194 // body producer aborted, but the initiator may still want to know
1195 // the answer, even though the HTTP message has been truncated
1196 void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer
)
1198 Must(virgin
.body_pipe
->productionEnded());
1200 // push writer and sender in case we were waiting for the last-chunk
1203 if (state
.sending
== State::sendingVirgin
)
1207 // adapted body consumer wants more adapted data and
1208 // possibly freed some buffer space
1209 void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
1211 if (state
.sending
== State::sendingVirgin
)
1213 else if (state
.sending
== State::sendingAdapted
)
1216 Must(state
.sending
== State::sendingUndecided
);
1219 // adapted body consumer aborted
1220 void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer
)
1222 detailError(ERR_DETAIL_ICAP_XACT_BODY_CONSUMER_ABORT
);
1223 mustStop("adapted body consumer aborted");
1226 Adaptation::Icap::ModXact::~ModXact()
1232 void Adaptation::Icap::ModXact::swanSong()
1234 debugs(93, 5, HERE
<< "swan sings" << status());
1239 if (theInitiator
.set()) // we have not sent the answer to the initiator
1240 detailError(ERR_DETAIL_ICAP_XACT_OTHER
);
1242 // update adaptation history if start was called and we reserved a slot
1243 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
1244 if (ah
!= NULL
&& adaptHistoryId
>= 0)
1245 ah
->recordXactFinish(adaptHistoryId
);
1247 Adaptation::Icap::Xaction::swanSong();
1250 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry
*);
1252 void Adaptation::Icap::ModXact::finalizeLogInfo()
1254 HttpRequest
* request_
= NULL
;
1255 HttpReply
* reply_
= NULL
;
1256 if (!(request_
= dynamic_cast<HttpRequest
*>(adapted
.header
))) {
1257 request_
= (virgin
.cause
? virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
));
1258 reply_
= dynamic_cast<HttpReply
*>(adapted
.header
);
1261 Adaptation::Icap::History::Pointer h
= request_
->icapHistory();
1262 Must(h
!= NULL
); // ICAPXaction::maybeLog calls only if there is a log
1263 al
.icp
.opcode
= ICP_INVALID
;
1264 al
.url
= h
->log_uri
.termedBuf();
1265 const Adaptation::Icap::ServiceRep
&s
= service();
1266 al
.icap
.reqMethod
= s
.cfg().method
;
1268 al
.cache
.caddr
= request_
->client_addr
;
1270 al
.request
= HTTPMSGLOCK(request_
);
1272 al
.reply
= HTTPMSGLOCK(reply_
);
1276 if (h
->rfc931
.size())
1277 al
.cache
.rfc931
= h
->rfc931
.termedBuf();
1280 if (h
->ssluser
.size())
1281 al
.cache
.ssluser
= h
->ssluser
.termedBuf();
1283 al
.cache
.code
= h
->logType
;
1284 al
.cache
.requestSize
= h
->req_sz
;
1286 // leave al.icap.bodyBytesRead negative if no body
1287 if (replyHttpHeaderSize
>= 0 || replyHttpBodySize
>= 0) {
1288 const int64_t zero
= 0; // to make max() argument types the same
1289 al
.icap
.bodyBytesRead
=
1290 max(zero
, replyHttpHeaderSize
) + max(zero
, replyHttpBodySize
);
1294 al
.http
.code
= reply_
->sline
.status
;
1295 al
.http
.content_type
= reply_
->content_type
.termedBuf();
1296 if (replyHttpBodySize
>= 0) {
1297 al
.cache
.replySize
= replyHttpBodySize
+ reply_
->hdr_sz
;
1298 al
.cache
.highOffset
= replyHttpBodySize
;
1300 //don't set al.cache.objectSize because it hasn't exist yet
1306 packerToMemInit(&p
, &mb
);
1308 reply_
->header
.packInto(&p
);
1309 al
.headers
.reply
= xstrdup(mb
.buf
);
1314 prepareLogWithRequestDetails(request_
, &al
);
1315 Xaction::finalizeLogInfo();
1319 void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf
&buf
)
1321 char ntoabuf
[MAX_IPSTRLEN
];
1323 * XXX These should use HttpHdr interfaces instead of Printfs
1325 const Adaptation::ServiceConfig
&s
= service().cfg();
1326 buf
.Printf("%s " SQUIDSTRINGPH
" ICAP/1.0\r\n", s
.methodStr(), SQUIDSTRINGPRINT(s
.uri
));
1327 buf
.Printf("Host: " SQUIDSTRINGPH
":%d\r\n", SQUIDSTRINGPRINT(s
.host
), s
.port
);
1328 buf
.Printf("Date: %s\r\n", mkrfc1123(squid_curtime
));
1330 if (!TheConfig
.reuse_connections
)
1331 buf
.Printf("Connection: close\r\n");
1333 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1335 if (virgin
.header
->header
.has(HDR_PROXY_AUTHENTICATE
)) {
1336 String vh
=virgin
.header
->header
.getByName("Proxy-Authenticate");
1337 buf
.Printf("Proxy-Authenticate: " SQUIDSTRINGPH
"\r\n",SQUIDSTRINGPRINT(vh
));
1340 if (virgin
.header
->header
.has(HDR_PROXY_AUTHORIZATION
)) {
1341 String vh
=virgin
.header
->header
.getByName("Proxy-Authorization");
1342 buf
.Printf("Proxy-Authorization: " SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(vh
));
1345 const HttpRequest
*request
= &virginRequest();
1347 // share the cross-transactional database records if needed
1348 if (Adaptation::Config::masterx_shared_name
) {
1349 Adaptation::History::Pointer ah
= request
->adaptHistory(false);
1352 if (ah
->getXxRecord(name
, value
)) {
1353 buf
.Printf(SQUIDSTRINGPH
": " SQUIDSTRINGPH
"\r\n",
1354 SQUIDSTRINGPRINT(name
), SQUIDSTRINGPRINT(value
));
1360 buf
.Printf("Encapsulated: ");
1366 // build HTTP request header, if any
1367 ICAP::Method m
= s
.method
;
1369 // to simplify, we could assume that request is always available
1373 urlPath
= request
->urlpath
;
1374 if (ICAP::methodRespmod
== m
)
1375 encapsulateHead(buf
, "req-hdr", httpBuf
, request
);
1376 else if (ICAP::methodReqmod
== m
)
1377 encapsulateHead(buf
, "req-hdr", httpBuf
, virgin
.header
);
1380 if (ICAP::methodRespmod
== m
)
1381 if (const HttpMsg
*prime
= virgin
.header
)
1382 encapsulateHead(buf
, "res-hdr", httpBuf
, prime
);
1384 if (!virginBody
.expected())
1385 buf
.Printf("null-body=%d", (int) httpBuf
.contentSize());
1386 else if (ICAP::methodReqmod
== m
)
1387 buf
.Printf("req-body=%d", (int) httpBuf
.contentSize());
1389 buf
.Printf("res-body=%d", (int) httpBuf
.contentSize());
1391 buf
.append(ICAP::crlf
, 2); // terminate Encapsulated line
1393 if (preview
.enabled()) {
1394 buf
.Printf("Preview: %d\r\n", (int)preview
.ad());
1395 if (!virginBody
.expected()) // there is no body to preview
1396 finishNullOrEmptyBodyPreview(httpBuf
);
1399 makeAllowHeader(buf
);
1401 if (TheConfig
.send_client_ip
&& request
) {
1402 Ip::Address client_addr
;
1403 #if FOLLOW_X_FORWARDED_FOR
1404 if (TheConfig
.use_indirect_client
) {
1405 client_addr
= request
->indirect_client_addr
;
1408 client_addr
= request
->client_addr
;
1409 if (!client_addr
.IsAnyAddr() && !client_addr
.IsNoAddr())
1410 buf
.Printf("X-Client-IP: %s\r\n", client_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
1413 if (TheConfig
.send_username
&& request
)
1414 makeUsernameHeader(request
, buf
);
1416 // fprintf(stderr, "%s\n", buf.content());
1418 buf
.append(ICAP::crlf
, 2); // terminate ICAP header
1420 // fill icapRequest for logging
1421 Must(icapRequest
->parseCharBuf(buf
.content(), buf
.contentSize()));
1423 // start ICAP request body with encapsulated HTTP headers
1424 buf
.append(httpBuf
.content(), httpBuf
.contentSize());
1429 // decides which Allow values to write and updates the request buffer
1430 void Adaptation::Icap::ModXact::makeAllowHeader(MemBuf
&buf
)
1432 const bool allow204in
= preview
.enabled(); // TODO: add shouldAllow204in()
1433 const bool allow204out
= state
.allowedPostview204
= shouldAllow204();
1434 const bool allow206in
= state
.allowedPreview206
= shouldAllow206in();
1435 const bool allow206out
= state
.allowedPostview206
= shouldAllow206out();
1437 debugs(93,9, HERE
<< "Allows: " << allow204in
<< allow204out
<<
1438 allow206in
<< allow206out
);
1440 const bool allow204
= allow204in
|| allow204out
;
1441 const bool allow206
= allow206in
|| allow206out
;
1443 if (!allow204
&& !allow206
)
1444 return; // nothing to do
1446 if (virginBody
.expected()) // if there is a virgin body, plan to send it
1447 virginBodySending
.plan();
1449 // writing Preview:... means we will honor 204 inside preview
1450 // writing Allow/204 means we will honor 204 outside preview
1451 // writing Allow:206 means we will honor 206 inside preview
1452 // writing Allow:204,206 means we will honor 206 outside preview
1453 const char *allowHeader
= NULL
;
1454 if (allow204out
&& allow206
)
1455 allowHeader
= "Allow: 204, 206\r\n";
1456 else if (allow204out
)
1457 allowHeader
= "Allow: 204\r\n";
1459 allowHeader
= "Allow: 206\r\n";
1461 if (allowHeader
) { // may be nil if only allow204in is true
1462 buf
.append(allowHeader
, strlen(allowHeader
));
1463 debugs(93,5, HERE
<< "Will write " << allowHeader
);
1467 void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest
*request
, MemBuf
&buf
)
1470 if (request
->auth_user_request
!= NULL
) {
1471 char const *name
= request
->auth_user_request
->username();
1473 const char *value
= TheConfig
.client_username_encode
? old_base64_encode(name
) : name
;
1474 buf
.Printf("%s: %s\r\n", TheConfig
.client_username_header
, value
);
1480 void Adaptation::Icap::ModXact::encapsulateHead(MemBuf
&icapBuf
, const char *section
, MemBuf
&httpBuf
, const HttpMsg
*head
)
1482 // update ICAP header
1483 icapBuf
.Printf("%s=%d, ", section
, (int) httpBuf
.contentSize());
1486 HttpMsg::Pointer headClone
;
1488 if (const HttpRequest
* old_request
= dynamic_cast<const HttpRequest
*>(head
)) {
1489 HttpRequest::Pointer
new_request(new HttpRequest
);
1490 Must(old_request
->canonical
);
1491 urlParse(old_request
->method
, old_request
->canonical
, new_request
);
1492 new_request
->http_ver
= old_request
->http_ver
;
1493 headClone
= new_request
;
1494 } else if (const HttpReply
*old_reply
= dynamic_cast<const HttpReply
*>(head
)) {
1495 HttpReply::Pointer
new_reply(new HttpReply
);
1496 new_reply
->sline
= old_reply
->sline
;
1497 headClone
= new_reply
;
1499 Must(headClone
!= NULL
);
1500 headClone
->inheritProperties(head
);
1502 HttpHeaderPos pos
= HttpHeaderInitPos
;
1503 HttpHeaderEntry
* p_head_entry
= NULL
;
1504 while (NULL
!= (p_head_entry
= head
->header
.getEntry(&pos
)) )
1505 headClone
->header
.addEntry(p_head_entry
->clone());
1509 // remove all hop-by-hop headers from the clone
1510 headClone
->header
.delById(HDR_PROXY_AUTHENTICATE
);
1511 headClone
->header
.removeHopByHopEntries();
1513 // pack polished HTTP header
1514 packHead(httpBuf
, headClone
);
1516 // headClone unlocks and, hence, deletes the message we packed
1519 void Adaptation::Icap::ModXact::packHead(MemBuf
&httpBuf
, const HttpMsg
*head
)
1522 packerToMemInit(&p
, &httpBuf
);
1523 head
->packInto(&p
, true);
1527 // decides whether to offer a preview and calculates its size
1528 void Adaptation::Icap::ModXact::decideOnPreview()
1530 if (!TheConfig
.preview_enable
) {
1531 debugs(93, 5, HERE
<< "preview disabled by squid.conf");
1535 const String urlPath
= virginRequest().urlpath
;
1537 if (!service().wantsPreview(urlPath
, wantedSize
)) {
1538 debugs(93, 5, HERE
<< "should not offer preview for " << urlPath
);
1542 // we decided to do preview, now compute its size
1544 // cannot preview more than we can backup
1545 size_t ad
= min(wantedSize
, TheBackupLimit
);
1547 if (!virginBody
.expected())
1549 else if (virginBody
.knownSize())
1550 ad
= min(static_cast<uint64_t>(ad
), virginBody
.size()); // not more than we have
1552 debugs(93, 5, HERE
<< "should offer " << ad
<< "-byte preview " <<
1553 "(service wanted " << wantedSize
<< ")");
1556 Must(preview
.enabled());
1559 // decides whether to allow 204 responses
1560 bool Adaptation::Icap::ModXact::shouldAllow204()
1562 if (!service().allows204())
1565 return canBackupEverything();
1568 // decides whether to allow 206 responses in some mode
1569 bool Adaptation::Icap::ModXact::shouldAllow206any()
1571 return TheConfig
.allow206_enable
&& service().allows206() &&
1572 virginBody
.expected(); // no need for 206 without a body
1575 // decides whether to allow 206 responses in preview mode
1576 bool Adaptation::Icap::ModXact::shouldAllow206in()
1578 return shouldAllow206any() && preview
.enabled();
1581 // decides whether to allow 206 responses outside of preview
1582 bool Adaptation::Icap::ModXact::shouldAllow206out()
1584 return shouldAllow206any() && canBackupEverything();
1587 // used by shouldAllow204 and decideOnRetries
1588 bool Adaptation::Icap::ModXact::canBackupEverything() const
1590 if (!virginBody
.expected())
1591 return true; // no body means no problems with backup
1593 // if there is a body, check whether we can backup it all
1595 if (!virginBody
.knownSize())
1598 // or should we have a different backup limit?
1599 // note that '<' allows for 0-termination of the "full" backup buffer
1600 return virginBody
.size() < TheBackupLimit
;
1603 // Decide whether this transaction can be retried if pconn fails
1604 // Must be called after decideOnPreview and before openConnection()
1605 void Adaptation::Icap::ModXact::decideOnRetries()
1608 return; // no, already decided
1610 if (preview
.enabled())
1611 return; // yes, because preview provides enough guarantees
1613 if (canBackupEverything())
1614 return; // yes, because we can back everything up
1616 disableRetries(); // no, because we cannot back everything up
1619 // Normally, the body-writing code handles preview body. It can deal with
1620 // bodies of unexpected size, including those that turn out to be empty.
1621 // However, that code assumes that the body was expected and body control
1622 // structures were initialized. This is not the case when there is no body
1623 // or the body is known to be empty, because the virgin message will lack a
1624 // body_pipe. So we handle preview of null-body and zero-size bodies here.
1625 void Adaptation::Icap::ModXact::finishNullOrEmptyBodyPreview(MemBuf
&buf
)
1627 Must(!virginBodyWriting
.active()); // one reason we handle it here
1628 Must(!virgin
.body_pipe
); // another reason we handle it here
1629 Must(!preview
.ad());
1631 // do not add last-chunk because our Encapsulated header says null-body
1632 // addLastRequestChunk(buf);
1633 preview
.wrote(0, true);
1635 Must(preview
.done());
1636 Must(preview
.ieof());
1639 void Adaptation::Icap::ModXact::fillPendingStatus(MemBuf
&buf
) const
1641 Adaptation::Icap::Xaction::fillPendingStatus(buf
);
1643 if (state
.serviceWaiting
)
1646 if (virgin
.body_pipe
!= NULL
)
1649 if (connection
> 0 && !doneReading())
1652 if (!state
.doneWriting() && state
.writing
!= State::writingInit
)
1653 buf
.Printf("w(%d)", state
.writing
);
1655 if (preview
.enabled()) {
1656 if (!preview
.done())
1657 buf
.Printf("P(%d)", (int) preview
.debt());
1660 if (virginBodySending
.active())
1663 if (!state
.doneParsing() && state
.parsing
!= State::psIcapHeader
)
1664 buf
.Printf("p(%d)", state
.parsing
);
1666 if (!doneSending() && state
.sending
!= State::sendingUndecided
)
1667 buf
.Printf("S(%d)", state
.sending
);
1669 if (state
.readyForUob
)
1675 if (protectGroupBypass
)
1679 void Adaptation::Icap::ModXact::fillDoneStatus(MemBuf
&buf
) const
1681 Adaptation::Icap::Xaction::fillDoneStatus(buf
);
1683 if (!virgin
.body_pipe
)
1686 if (state
.doneWriting())
1689 if (preview
.enabled()) {
1691 buf
.Printf("P%s", preview
.ieof() ? "(ieof)" : "");
1697 if (state
.doneParsing())
1704 bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section
) const
1706 return icapReply
->header
.getByNameListMember("Encapsulated",
1707 section
, ',').size() > 0;
1710 // calculate whether there is a virgin HTTP body and
1711 // whether its expected size is known
1712 // TODO: rename because we do not just estimate
1713 void Adaptation::Icap::ModXact::estimateVirginBody()
1715 // note: lack of size info may disable previews and 204s
1717 HttpMsg
*msg
= virgin
.header
;
1720 HttpRequestMethod method
;
1723 method
= virgin
.cause
->method
;
1724 else if (HttpRequest
*req
= dynamic_cast<HttpRequest
*>(msg
))
1725 method
= req
->method
;
1727 method
= METHOD_NONE
;
1730 // expectingBody returns true for zero-sized bodies, but we will not
1731 // get a pipe for that body, so we treat the message as bodyless
1732 if (method
!= METHOD_NONE
&& msg
->expectingBody(method
, size
) && size
) {
1733 debugs(93, 6, HERE
<< "expects virgin body from " <<
1734 virgin
.body_pipe
<< "; size: " << size
);
1736 virginBody
.expect(size
);
1737 virginBodyWriting
.plan();
1739 // sign up as a body consumer
1740 Must(msg
->body_pipe
!= NULL
);
1741 Must(msg
->body_pipe
== virgin
.body_pipe
);
1742 Must(virgin
.body_pipe
->setConsumerIfNotLate(this));
1744 // make sure TheBackupLimit is in-sync with the buffer size
1745 Must(TheBackupLimit
<= static_cast<size_t>(msg
->body_pipe
->buf().max_capacity
));
1747 debugs(93, 6, HERE
<< "does not expect virgin body");
1748 Must(msg
->body_pipe
== NULL
);
1753 void Adaptation::Icap::ModXact::makeAdaptedBodyPipe(const char *what
)
1755 Must(!adapted
.body_pipe
);
1756 Must(!adapted
.header
->body_pipe
);
1757 adapted
.header
->body_pipe
= new BodyPipe(this);
1758 adapted
.body_pipe
= adapted
.header
->body_pipe
;
1759 debugs(93, 7, HERE
<< "will supply " << what
<< " via " <<
1760 adapted
.body_pipe
<< " pipe");
1764 // TODO: Move SizedEstimate and Preview elsewhere
1766 Adaptation::Icap::SizedEstimate::SizedEstimate()
1767 : theData(dtUnexpected
)
1770 void Adaptation::Icap::SizedEstimate::expect(int64_t aSize
)
1772 theData
= (aSize
>= 0) ? aSize
: (int64_t)dtUnknown
;
1775 bool Adaptation::Icap::SizedEstimate::expected() const
1777 return theData
!= dtUnexpected
;
1780 bool Adaptation::Icap::SizedEstimate::knownSize() const
1783 return theData
!= dtUnknown
;
1786 uint64_t Adaptation::Icap::SizedEstimate::size() const
1789 return static_cast<uint64_t>(theData
);
1794 Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided
)
1797 void Adaptation::Icap::VirginBodyAct::plan()
1800 Must(!theStart
); // not started
1801 theState
= stActive
;
1804 void Adaptation::Icap::VirginBodyAct::disable()
1806 theState
= stDisabled
;
1809 void Adaptation::Icap::VirginBodyAct::progress(size_t size
)
1812 #if SIZEOF_SIZE_T > 4
1813 /* always true for smaller size_t's */
1814 Must(static_cast<int64_t>(size
) >= 0);
1816 theStart
+= static_cast<int64_t>(size
);
1819 uint64_t Adaptation::Icap::VirginBodyAct::offset() const
1822 return static_cast<uint64_t>(theStart
);
1826 Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled
)
1829 void Adaptation::Icap::Preview::enable(size_t anAd
)
1831 // TODO: check for anAd not exceeding preview size limit
1834 theState
= stWriting
;
1837 bool Adaptation::Icap::Preview::enabled() const
1839 return theState
!= stDisabled
;
1842 size_t Adaptation::Icap::Preview::ad() const
1848 bool Adaptation::Icap::Preview::done() const
1851 return theState
>= stIeof
;
1854 bool Adaptation::Icap::Preview::ieof() const
1857 return theState
== stIeof
;
1860 size_t Adaptation::Icap::Preview::debt() const
1863 return done() ? 0 : (theAd
- theWritten
);
1866 void Adaptation::Icap::Preview::wrote(size_t size
, bool wroteEof
)
1872 Must(theWritten
<= theAd
);
1875 theState
= stIeof
; // written size is irrelevant
1876 else if (theWritten
>= theAd
)
1880 bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf
&mb
) const
1882 if (virgin
.header
== NULL
)
1885 virgin
.header
->firstLineBuf(mb
);
1890 void Adaptation::Icap::ModXact::detailError(int errDetail
)
1892 HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
1893 // if no adapted request, update virgin (and inherit its properties later)
1894 // TODO: make this and HttpRequest::detailError constant, like adaptHistory
1896 request
= const_cast<HttpRequest
*>(&virginRequest());
1899 request
->detailError(ERR_ICAP_FAILURE
, errDetail
);
1902 /* Adaptation::Icap::ModXactLauncher */
1904 Adaptation::Icap::ModXactLauncher::ModXactLauncher(HttpMsg
*virginHeader
, HttpRequest
*virginCause
, Adaptation::ServicePointer aService
):
1905 AsyncJob("Adaptation::Icap::ModXactLauncher"),
1906 Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", aService
)
1908 virgin
.setHeader(virginHeader
);
1909 virgin
.setCause(virginCause
);
1910 updateHistory(true);
1913 Adaptation::Icap::Xaction
*Adaptation::Icap::ModXactLauncher::createXaction()
1915 Adaptation::Icap::ServiceRep::Pointer s
=
1916 dynamic_cast<Adaptation::Icap::ServiceRep
*>(theService
.getRaw());
1918 return new Adaptation::Icap::ModXact(virgin
.header
, virgin
.cause
, s
);
1921 void Adaptation::Icap::ModXactLauncher::swanSong()
1923 debugs(93, 5, HERE
<< "swan sings");
1924 updateHistory(false);
1925 Adaptation::Icap::Launcher::swanSong();
1928 void Adaptation::Icap::ModXactLauncher::updateHistory(bool doStart
)
1930 HttpRequest
*r
= virgin
.cause
?
1931 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
1933 // r should never be NULL but we play safe; TODO: add Should()
1935 Adaptation::Icap::History::Pointer h
= r
->icapHistory();
1938 h
->start("ICAPModXactLauncher");
1940 h
->stop("ICAPModXactLauncher");