]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/adaptation/icap/ModXact.cc
2 * DEBUG: section 93 ICAP (RFC 3507) Client
8 #include "HttpRequest.h"
10 #include "adaptation/Initiator.h"
11 #include "adaptation/icap/ServiceRep.h"
12 #include "adaptation/icap/Launcher.h"
13 #include "adaptation/icap/ModXact.h"
14 #include "adaptation/icap/Client.h"
15 #include "ChunkedCodingParser.h"
16 #include "TextException.h"
17 #include "auth/UserRequest.h"
18 #include "adaptation/icap/Config.h"
19 #include "SquidTime.h"
20 #include "AccessLogEntry.h"
21 #include "adaptation/icap/History.h"
22 #include "adaptation/History.h"
24 // flow and terminology:
25 // HTTP| --> receive --> encode --> write --> |network
26 // end | <-- send <-- parse <-- read <-- |end
28 // TODO: replace gotEncapsulated() with something faster; we call it often
30 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXact
);
31 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXactLauncher
);
33 static const size_t TheBackupLimit
= BodyPipe::MaxCapacity
;
35 extern Adaptation::Icap::Config
Adaptation::Icap::TheConfig
;
38 Adaptation::Icap::ModXact::State::State()
40 memset(this, 0, sizeof(*this));
43 Adaptation::Icap::ModXact::ModXact(Adaptation::Initiator
*anInitiator
, HttpMsg
*virginHeader
,
44 HttpRequest
*virginCause
, Adaptation::Icap::ServiceRep::Pointer
&aService
):
45 AsyncJob("Adaptation::Icap::ModXact"),
46 Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", anInitiator
, aService
),
49 canStartBypass(false), // too early
50 protectGroupBypass(true),
56 virgin
.setHeader(virginHeader
); // sets virgin.body_pipe if needed
57 virgin
.setCause(virginCause
); // may be NULL
59 // adapted header and body are initialized when we parse them
61 // writing and reading ends are handled by Adaptation::Icap::Xaction
64 // nothing to do because we are using temporary buffers
66 // parsing; TODO: do not set until we parse, see ICAPOptXact
67 icapReply
= HTTPMSGLOCK(new HttpReply
);
68 icapReply
->protoPrefix
= "ICAP/"; // TODO: make an IcapReply class?
70 debugs(93,7, HERE
<< "initialized." << status());
73 // initiator wants us to start
74 void Adaptation::Icap::ModXact::start()
76 Adaptation::Icap::Xaction::start();
78 // reserve an adaptation history slot (attempts are known at this time)
79 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
81 adaptHistoryId
= ah
->recordXactStart(service().cfg().key
, icap_tr_start
, attempts
> 1);
83 estimateVirginBody(); // before virgin disappears!
85 canStartBypass
= service().cfg().bypass
;
87 // it is an ICAP violation to send request to a service w/o known OPTIONS
95 void Adaptation::Icap::ModXact::waitForService()
97 Must(!state
.serviceWaiting
);
98 debugs(93, 7, HERE
<< "will wait for the ICAP service" << status());
99 state
.serviceWaiting
= true;
100 AsyncCall::Pointer call
= asyncCall(93,5, "Adaptation::Icap::ModXact::noteServiceReady",
101 MemFun(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 start
= act
.offset();
341 // absolute end of buffered data
342 const uint64_t end
= virginConsumed
+ virgin
.body_pipe
->buf().contentSize();
343 Must(virginConsumed
<= start
&& start
<= end
);
344 return static_cast<size_t>(end
- start
);
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 start
= act
.offset();
352 Must(virginConsumed
<= start
);
353 return virgin
.body_pipe
->buf().content() + static_cast<size_t>(start
-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(connection
>= 0);
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 (connection
>= 0) {
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 debugs(93, 5, HERE
<< "ICAP status " << icapReply
->sline
.status
);
734 handleUnknownScode();
738 const HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
740 request
= &virginRequest();
742 // update the cross-transactional database if needed (all status codes!)
743 if (const char *xxName
= Adaptation::Config::masterx_shared_name
) {
744 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
746 const String val
= icapReply
->header
.getByName(xxName
);
747 if (val
.size() > 0) // XXX: HttpHeader lacks empty value detection
748 ah
->updateXxRecord(xxName
, val
);
752 // update the adaptation plan if needed (all status codes!)
753 if (service().cfg().routing
) {
755 if (icapReply
->header
.getList(HDR_X_NEXT_SERVICES
, &services
)) {
756 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
758 ah
->updateNextServices(services
);
760 } // TODO: else warn (occasionally!) if we got HDR_X_NEXT_SERVICES
762 // We need to store received ICAP headers for <icapLastHeader logformat option.
763 // If we already have stored headers from previous ICAP transaction related to this
764 // request, old headers will be replaced with the new one.
766 Adaptation::Icap::History::Pointer h
= request
->icapHistory();
768 h
->mergeIcapHeaders(&icapReply
->header
);
769 h
->setIcapLastHeader(&icapReply
->header
);
772 // handle100Continue() manages state.writing on its own.
773 // Non-100 status means the server needs no postPreview data from us.
774 if (state
.writing
== State::writingPaused
)
778 bool Adaptation::Icap::ModXact::validate200Ok()
780 if (ICAP::methodRespmod
== service().cfg().method
) {
781 if (!gotEncapsulated("res-hdr"))
787 if (ICAP::methodReqmod
== service().cfg().method
) {
788 if (!gotEncapsulated("res-hdr") && !gotEncapsulated("req-hdr"))
797 void Adaptation::Icap::ModXact::handle100Continue()
799 Must(state
.writing
== State::writingPaused
);
800 // server must not respond before the end of preview: we may send ieof
801 Must(preview
.enabled() && preview
.done() && !preview
.ieof());
803 // 100 "Continue" cancels our preview commitment, not 204s outside preview
804 if (!state
.allowedPostview204
)
807 state
.parsing
= State::psIcapHeader
; // eventually
810 state
.writing
= State::writingPrime
;
815 void Adaptation::Icap::ModXact::handle200Ok()
817 state
.parsing
= State::psHttpHeader
;
818 state
.sending
= State::sendingAdapted
;
823 void Adaptation::Icap::ModXact::handle204NoContent()
829 // Called when we receive a 204 No Content response and
830 // when we are trying to bypass a service failure.
831 // We actually start sending (echoig or not) in startSending.
832 void Adaptation::Icap::ModXact::prepEchoing()
834 disableRepeats("preparing to echo content");
835 disableBypass("preparing to echo content", true);
838 // We want to clone the HTTP message, but we do not want
839 // to copy some non-HTTP state parts that HttpMsg kids carry in them.
840 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
841 // Instead, we simply write the HTTP message and "clone" it by parsing.
842 // TODO: use HttpMsg::clone()!
844 HttpMsg
*oldHead
= virgin
.header
;
845 debugs(93, 7, HERE
<< "cloning virgin message " << oldHead
);
849 // write the virgin message into a memory buffer
851 packHead(httpBuf
, oldHead
);
853 // allocate the adapted message and copy metainfo
854 Must(!adapted
.header
);
855 HttpMsg
*newHead
= NULL
;
856 if (const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(oldHead
)) {
857 HttpRequest
*newR
= new HttpRequest
;
858 newR
->canonical
= oldR
->canonical
?
859 xstrdup(oldR
->canonical
) : NULL
; // parse() does not set it
861 } else if (dynamic_cast<const HttpReply
*>(oldHead
)) {
862 HttpReply
*newRep
= new HttpReply
;
866 newHead
->inheritProperties(oldHead
);
868 adapted
.setHeader(newHead
);
870 // parse the buffer back
871 http_status error
= HTTP_STATUS_NONE
;
873 Must(newHead
->parse(&httpBuf
, true, &error
));
875 Must(newHead
->hdr_sz
== httpBuf
.contentSize()); // no leftovers
879 debugs(93, 7, HERE
<< "cloned virgin message " << oldHead
<< " to " <<
882 // setup adapted body pipe if needed
883 if (oldHead
->body_pipe
!= NULL
) {
884 debugs(93, 7, HERE
<< "will echo virgin body from " <<
886 if (!virginBodySending
.active())
887 virginBodySending
.plan(); // will throw if not possible
888 state
.sending
= State::sendingVirgin
;
891 // TODO: optimize: is it possible to just use the oldHead pipe and
892 // remove ICAP from the loop? This echoing is probably a common case!
893 makeAdaptedBodyPipe("echoed virgin response");
894 if (oldHead
->body_pipe
->bodySizeKnown())
895 adapted
.body_pipe
->setBodySize(oldHead
->body_pipe
->bodySize());
896 debugs(93, 7, HERE
<< "will echo virgin body to " <<
899 debugs(93, 7, HERE
<< "no virgin body to echo");
904 void Adaptation::Icap::ModXact::handleUnknownScode()
908 // TODO: mark connection as "bad"
910 // Terminate the transaction; we do not know how to handle this response.
911 throw TexcHere("Unsupported ICAP status code");
914 void Adaptation::Icap::ModXact::parseHttpHead()
916 if (gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr")) {
917 maybeAllocateHttpMsg();
919 if (!parseHead(adapted
.header
))
920 return; // need more header data
922 if (dynamic_cast<HttpRequest
*>(adapted
.header
)) {
923 const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(virgin
.header
);
925 // TODO: the adapted request did not really originate from the
926 // client; give proxy admin an option to prevent copying of
927 // sensitive client information here. See the following thread:
928 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
931 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
933 adapted
.header
->inheritProperties(virgin
.header
);
936 decideOnParsingBody();
939 // parses both HTTP and ICAP headers
940 bool Adaptation::Icap::ModXact::parseHead(HttpMsg
*head
)
943 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " head bytes to parse" <<
944 "; state: " << state
.parsing
);
946 http_status error
= HTTP_STATUS_NONE
;
947 const bool parsed
= head
->parse(&readBuf
, commEof
, &error
);
948 Must(parsed
|| !error
); // success or need more data
950 if (!parsed
) { // need more data
951 debugs(93, 5, HERE
<< "parse failed, need more data, return false");
956 if (HttpRequest
*r
= dynamic_cast<HttpRequest
*>(head
))
957 urlCanonical(r
); // parse does not set HttpRequest::canonical
959 debugs(93, 5, HERE
<< "parse success, consume " << head
->hdr_sz
<< " bytes, return true");
960 readBuf
.consume(head
->hdr_sz
);
964 void Adaptation::Icap::ModXact::decideOnParsingBody()
966 if (gotEncapsulated("res-body") || gotEncapsulated("req-body")) {
967 debugs(93, 5, HERE
<< "expecting a body");
968 state
.parsing
= State::psBody
;
969 bodyParser
= new ChunkedCodingParser
;
970 makeAdaptedBodyPipe("adapted response from the ICAP server");
971 Must(state
.sending
== State::sendingAdapted
);
973 debugs(93, 5, HERE
<< "not expecting a body");
979 void Adaptation::Icap::ModXact::parseBody()
981 Must(state
.parsing
== State::psBody
);
984 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " body bytes to parse");
986 // the parser will throw on errors
987 BodyPipeCheckout
bpc(*adapted
.body_pipe
);
988 const bool parsed
= bodyParser
->parse(&readBuf
, &bpc
.buf
);
991 debugs(93, 5, HERE
<< "have " << readBuf
.contentSize() << " body bytes after " <<
992 "parse; parsed all: " << parsed
);
993 replyBodySize
+= adapted
.body_pipe
->buf().contentSize();
995 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
996 // TODO: do we really need this if we disable when sending headers?
997 if (adapted
.body_pipe
->buf().contentSize() > 0) { // parsed something sometime
998 disableRepeats("sent adapted content");
999 disableBypass("sent adapted content", true);
1004 stopSending(true); // the parser succeeds only if all parsed data fits
1008 debugs(93,3,HERE
<< this << " needsMoreData = " << bodyParser
->needsMoreData());
1010 if (bodyParser
->needsMoreData()) {
1011 debugs(93,3,HERE
<< this);
1012 Must(mayReadMore());
1016 if (bodyParser
->needsMoreSpace()) {
1017 Must(!doneSending()); // can hope for more space
1018 Must(adapted
.body_pipe
->buf().contentSize() > 0); // paranoid
1019 // TODO: there should be a timeout in case the sink is broken
1020 // or cannot consume partial content (while we need more space)
1024 void Adaptation::Icap::ModXact::stopParsing()
1026 if (state
.parsing
== State::psDone
)
1029 debugs(93, 7, HERE
<< "will no longer parse" << status());
1035 state
.parsing
= State::psDone
;
1038 // HTTP side added virgin body data
1039 void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer
)
1043 if (state
.sending
== State::sendingVirgin
)
1047 // HTTP side sent us all virgin info
1048 void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer
)
1050 Must(virgin
.body_pipe
->productionEnded());
1052 // push writer and sender in case we were waiting for the last-chunk
1055 if (state
.sending
== State::sendingVirgin
)
1059 // body producer aborted, but the initiator may still want to know
1060 // the answer, even though the HTTP message has been truncated
1061 void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer
)
1063 Must(virgin
.body_pipe
->productionEnded());
1065 // push writer and sender in case we were waiting for the last-chunk
1068 if (state
.sending
== State::sendingVirgin
)
1072 // adapted body consumer wants more adapted data and
1073 // possibly freed some buffer space
1074 void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
1076 if (state
.sending
== State::sendingVirgin
)
1078 else if (state
.sending
== State::sendingAdapted
)
1081 Must(state
.sending
== State::sendingUndecided
);
1084 // adapted body consumer aborted
1085 void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer
)
1087 mustStop("adapted body consumer aborted");
1091 void Adaptation::Icap::ModXact::swanSong()
1093 debugs(93, 5, HERE
<< "swan sings" << status());
1098 // update adaptation history if start was called and we reserved a slot
1099 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
1100 if (ah
!= NULL
&& adaptHistoryId
>= 0)
1101 ah
->recordXactFinish(adaptHistoryId
);
1103 Adaptation::Icap::Xaction::swanSong();
1106 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry
*);
1108 void Adaptation::Icap::ModXact::finalizeLogInfo()
1110 HttpRequest
* request_
= NULL
;
1111 HttpReply
* reply_
= NULL
;
1112 if (!(request_
= dynamic_cast<HttpRequest
*>(adapted
.header
))) {
1113 request_
= (virgin
.cause
? virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
));
1114 reply_
= dynamic_cast<HttpReply
*>(adapted
.header
);
1117 Adaptation::Icap::History::Pointer h
= request_
->icapHistory();
1118 Must(h
!= NULL
); // ICAPXaction::maybeLog calls only if there is a log
1119 al
.icp
.opcode
= ICP_INVALID
;
1120 al
.url
= h
->log_uri
.termedBuf();
1121 const Adaptation::Icap::ServiceRep
&s
= service();
1122 al
.icap
.reqMethod
= s
.cfg().method
;
1124 al
.cache
.caddr
= request_
->client_addr
;
1126 al
.request
= HTTPMSGLOCK(request_
);
1128 al
.reply
= HTTPMSGLOCK(reply_
);
1132 if (h
->rfc931
.size())
1133 al
.cache
.rfc931
= h
->rfc931
.termedBuf();
1136 if (h
->ssluser
.size())
1137 al
.cache
.ssluser
= h
->ssluser
.termedBuf();
1139 al
.cache
.code
= h
->logType
;
1140 al
.cache
.requestSize
= h
->req_sz
;
1142 al
.http
.code
= reply_
->sline
.status
;
1143 al
.http
.content_type
= reply_
->content_type
.termedBuf();
1144 al
.cache
.replySize
= replyBodySize
+ reply_
->hdr_sz
;
1145 al
.cache
.highOffset
= replyBodySize
;
1146 //don't set al.cache.objectSize because it hasn't exist yet
1152 packerToMemInit(&p
, &mb
);
1154 reply_
->header
.packInto(&p
);
1155 al
.headers
.reply
= xstrdup(mb
.buf
);
1160 prepareLogWithRequestDetails(request_
, &al
);
1161 Xaction::finalizeLogInfo();
1165 void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf
&buf
)
1167 char ntoabuf
[MAX_IPSTRLEN
];
1169 * XXX These should use HttpHdr interfaces instead of Printfs
1171 const Adaptation::ServiceConfig
&s
= service().cfg();
1172 buf
.Printf("%s " SQUIDSTRINGPH
" ICAP/1.0\r\n", s
.methodStr(), SQUIDSTRINGPRINT(s
.uri
));
1173 buf
.Printf("Host: " SQUIDSTRINGPH
":%d\r\n", SQUIDSTRINGPRINT(s
.host
), s
.port
);
1174 buf
.Printf("Date: %s\r\n", mkrfc1123(squid_curtime
));
1176 if (!TheConfig
.reuse_connections
)
1177 buf
.Printf("Connection: close\r\n");
1179 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1181 if (virgin
.header
->header
.has(HDR_PROXY_AUTHENTICATE
)) {
1182 String vh
=virgin
.header
->header
.getByName("Proxy-Authenticate");
1183 buf
.Printf("Proxy-Authenticate: " SQUIDSTRINGPH
"\r\n",SQUIDSTRINGPRINT(vh
));
1186 if (virgin
.header
->header
.has(HDR_PROXY_AUTHORIZATION
)) {
1187 String vh
=virgin
.header
->header
.getByName("Proxy-Authorization");
1188 buf
.Printf("Proxy-Authorization: " SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(vh
));
1191 const HttpRequest
*request
= &virginRequest();
1193 // share the cross-transactional database records if needed
1194 if (Adaptation::Config::masterx_shared_name
) {
1195 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
1198 if (ah
->getXxRecord(name
, value
)) {
1199 buf
.Printf(SQUIDSTRINGPH
": " SQUIDSTRINGPH
"\r\n",
1200 SQUIDSTRINGPRINT(name
), SQUIDSTRINGPRINT(value
));
1206 buf
.Printf("Encapsulated: ");
1212 // build HTTP request header, if any
1213 ICAP::Method m
= s
.method
;
1215 // to simplify, we could assume that request is always available
1219 urlPath
= request
->urlpath
;
1220 if (ICAP::methodRespmod
== m
)
1221 encapsulateHead(buf
, "req-hdr", httpBuf
, request
);
1222 else if (ICAP::methodReqmod
== m
)
1223 encapsulateHead(buf
, "req-hdr", httpBuf
, virgin
.header
);
1226 if (ICAP::methodRespmod
== m
)
1227 if (const HttpMsg
*prime
= virgin
.header
)
1228 encapsulateHead(buf
, "res-hdr", httpBuf
, prime
);
1230 if (!virginBody
.expected())
1231 buf
.Printf("null-body=%d", (int) httpBuf
.contentSize());
1232 else if (ICAP::methodReqmod
== m
)
1233 buf
.Printf("req-body=%d", (int) httpBuf
.contentSize());
1235 buf
.Printf("res-body=%d", (int) httpBuf
.contentSize());
1237 buf
.append(ICAP::crlf
, 2); // terminate Encapsulated line
1239 if (preview
.enabled()) {
1240 buf
.Printf("Preview: %d\r\n", (int)preview
.ad());
1241 if (virginBody
.expected()) // there is a body to preview
1242 virginBodySending
.plan();
1244 finishNullOrEmptyBodyPreview(httpBuf
);
1247 if (shouldAllow204()) {
1248 debugs(93,5, HERE
<< "will allow 204s outside of preview");
1249 state
.allowedPostview204
= true;
1250 buf
.Printf("Allow: 204\r\n");
1251 if (virginBody
.expected()) // there is a body to echo
1252 virginBodySending
.plan();
1255 if (TheConfig
.send_client_ip
&& request
)
1256 if (!request
->client_addr
.IsAnyAddr() && !request
->client_addr
.IsNoAddr())
1257 buf
.Printf("X-Client-IP: %s\r\n", request
->client_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
1259 if (TheConfig
.send_client_username
&& request
)
1260 makeUsernameHeader(request
, buf
);
1262 // fprintf(stderr, "%s\n", buf.content());
1264 buf
.append(ICAP::crlf
, 2); // terminate ICAP header
1266 // fill icapRequest for logging
1267 Must(icapRequest
->parseCharBuf(buf
.content(), buf
.contentSize()));
1269 // start ICAP request body with encapsulated HTTP headers
1270 buf
.append(httpBuf
.content(), httpBuf
.contentSize());
1275 void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest
*request
, MemBuf
&buf
)
1277 if (const AuthUserRequest
*auth
= request
->auth_user_request
) {
1278 if (char const *name
= auth
->username()) {
1279 const char *value
= TheConfig
.client_username_encode
?
1280 base64_encode(name
) : name
;
1281 buf
.Printf("%s: %s\r\n", TheConfig
.client_username_header
,
1287 void Adaptation::Icap::ModXact::encapsulateHead(MemBuf
&icapBuf
, const char *section
, MemBuf
&httpBuf
, const HttpMsg
*head
)
1289 // update ICAP header
1290 icapBuf
.Printf("%s=%d, ", section
, (int) httpBuf
.contentSize());
1293 HttpMsg
*headClone
= NULL
;
1295 if (const HttpRequest
* old_request
= dynamic_cast<const HttpRequest
*>(head
)) {
1296 HttpRequest
* new_request
= new HttpRequest
;
1297 assert(old_request
->canonical
);
1298 urlParse(old_request
->method
, old_request
->canonical
, new_request
);
1299 new_request
->http_ver
= old_request
->http_ver
;
1300 headClone
= new_request
;
1301 } else if (const HttpReply
*old_reply
= dynamic_cast<const HttpReply
*>(head
)) {
1302 HttpReply
* new_reply
= new HttpReply
;
1303 new_reply
->sline
= old_reply
->sline
;
1304 headClone
= new_reply
;
1308 headClone
->inheritProperties(head
);
1310 HttpHeaderPos pos
= HttpHeaderInitPos
;
1311 HttpHeaderEntry
* p_head_entry
= NULL
;
1312 while (NULL
!= (p_head_entry
= head
->header
.getEntry(&pos
)) )
1313 headClone
->header
.addEntry(p_head_entry
->clone());
1317 // remove all hop-by-hop headers from the clone
1318 headClone
->header
.delById(HDR_PROXY_AUTHENTICATE
);
1319 headClone
->header
.removeHopByHopEntries();
1321 // pack polished HTTP header
1322 packHead(httpBuf
, headClone
);
1327 void Adaptation::Icap::ModXact::packHead(MemBuf
&httpBuf
, const HttpMsg
*head
)
1330 packerToMemInit(&p
, &httpBuf
);
1331 head
->packInto(&p
, true);
1335 // decides whether to offer a preview and calculates its size
1336 void Adaptation::Icap::ModXact::decideOnPreview()
1338 if (!TheConfig
.preview_enable
) {
1339 debugs(93, 5, HERE
<< "preview disabled by squid.conf");
1343 const String urlPath
= virginRequest().urlpath
;
1345 if (!service().wantsPreview(urlPath
, wantedSize
)) {
1346 debugs(93, 5, HERE
<< "should not offer preview for " << urlPath
);
1350 // we decided to do preview, now compute its size
1352 Must(wantedSize
>= 0);
1354 // cannot preview more than we can backup
1355 size_t ad
= min(wantedSize
, TheBackupLimit
);
1357 if (!virginBody
.expected())
1359 else if (virginBody
.knownSize())
1360 ad
= min(static_cast<uint64_t>(ad
), virginBody
.size()); // not more than we have
1362 debugs(93, 5, HERE
<< "should offer " << ad
<< "-byte preview " <<
1363 "(service wanted " << wantedSize
<< ")");
1366 Must(preview
.enabled());
1369 // decides whether to allow 204 responses
1370 bool Adaptation::Icap::ModXact::shouldAllow204()
1372 if (!service().allows204())
1375 return canBackupEverything();
1378 // used by shouldAllow204 and decideOnRetries
1379 bool Adaptation::Icap::ModXact::canBackupEverything() const
1381 if (!virginBody
.expected())
1382 return true; // no body means no problems with backup
1384 // if there is a body, check whether we can backup it all
1386 if (!virginBody
.knownSize())
1389 // or should we have a different backup limit?
1390 // note that '<' allows for 0-termination of the "full" backup buffer
1391 return virginBody
.size() < TheBackupLimit
;
1394 // Decide whether this transaction can be retried if pconn fails
1395 // Must be called after decideOnPreview and before openConnection()
1396 void Adaptation::Icap::ModXact::decideOnRetries()
1399 return; // no, already decided
1401 if (preview
.enabled())
1402 return; // yes, because preview provides enough guarantees
1404 if (canBackupEverything())
1405 return; // yes, because we can back everything up
1407 disableRetries(); // no, because we cannot back everything up
1410 // Normally, the body-writing code handles preview body. It can deal with
1411 // bodies of unexpected size, including those that turn out to be empty.
1412 // However, that code assumes that the body was expected and body control
1413 // structures were initialized. This is not the case when there is no body
1414 // or the body is known to be empty, because the virgin message will lack a
1415 // body_pipe. So we handle preview of null-body and zero-size bodies here.
1416 void Adaptation::Icap::ModXact::finishNullOrEmptyBodyPreview(MemBuf
&buf
)
1418 Must(!virginBodyWriting
.active()); // one reason we handle it here
1419 Must(!virgin
.body_pipe
); // another reason we handle it here
1420 Must(!preview
.ad());
1422 // do not add last-chunk because our Encapsulated header says null-body
1423 // addLastRequestChunk(buf);
1424 preview
.wrote(0, true);
1426 Must(preview
.done());
1427 Must(preview
.ieof());
1430 void Adaptation::Icap::ModXact::fillPendingStatus(MemBuf
&buf
) const
1432 Adaptation::Icap::Xaction::fillPendingStatus(buf
);
1434 if (state
.serviceWaiting
)
1437 if (virgin
.body_pipe
!= NULL
)
1440 if (connection
> 0 && !doneReading())
1443 if (!state
.doneWriting() && state
.writing
!= State::writingInit
)
1444 buf
.Printf("w(%d)", state
.writing
);
1446 if (preview
.enabled()) {
1447 if (!preview
.done())
1448 buf
.Printf("P(%d)", (int) preview
.debt());
1451 if (virginBodySending
.active())
1454 if (!state
.doneParsing() && state
.parsing
!= State::psIcapHeader
)
1455 buf
.Printf("p(%d)", state
.parsing
);
1457 if (!doneSending() && state
.sending
!= State::sendingUndecided
)
1458 buf
.Printf("S(%d)", state
.sending
);
1463 if (protectGroupBypass
)
1467 void Adaptation::Icap::ModXact::fillDoneStatus(MemBuf
&buf
) const
1469 Adaptation::Icap::Xaction::fillDoneStatus(buf
);
1471 if (!virgin
.body_pipe
)
1474 if (state
.doneWriting())
1477 if (preview
.enabled()) {
1479 buf
.Printf("P%s", preview
.ieof() ? "(ieof)" : "");
1485 if (state
.doneParsing())
1492 bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section
) const
1494 return icapReply
->header
.getByNameListMember("Encapsulated",
1495 section
, ',').size() > 0;
1498 // calculate whether there is a virgin HTTP body and
1499 // whether its expected size is known
1500 // TODO: rename because we do not just estimate
1501 void Adaptation::Icap::ModXact::estimateVirginBody()
1503 // note: lack of size info may disable previews and 204s
1505 HttpMsg
*msg
= virgin
.header
;
1508 HttpRequestMethod method
;
1511 method
= virgin
.cause
->method
;
1512 else if (HttpRequest
*req
= dynamic_cast<HttpRequest
*>(msg
))
1513 method
= req
->method
;
1515 method
= METHOD_NONE
;
1518 // expectingBody returns true for zero-sized bodies, but we will not
1519 // get a pipe for that body, so we treat the message as bodyless
1520 if (method
!= METHOD_NONE
&& msg
->expectingBody(method
, size
) && size
) {
1521 debugs(93, 6, HERE
<< "expects virgin body from " <<
1522 virgin
.body_pipe
<< "; size: " << size
);
1524 virginBody
.expect(size
);
1525 virginBodyWriting
.plan();
1527 // sign up as a body consumer
1528 Must(msg
->body_pipe
!= NULL
);
1529 Must(msg
->body_pipe
== virgin
.body_pipe
);
1530 Must(virgin
.body_pipe
->setConsumerIfNotLate(this));
1532 // make sure TheBackupLimit is in-sync with the buffer size
1533 Must(TheBackupLimit
<= static_cast<size_t>(msg
->body_pipe
->buf().max_capacity
));
1535 debugs(93, 6, HERE
<< "does not expect virgin body");
1536 Must(msg
->body_pipe
== NULL
);
1541 void Adaptation::Icap::ModXact::makeAdaptedBodyPipe(const char *what
)
1543 Must(!adapted
.body_pipe
);
1544 Must(!adapted
.header
->body_pipe
);
1545 adapted
.header
->body_pipe
= new BodyPipe(this);
1546 adapted
.body_pipe
= adapted
.header
->body_pipe
;
1547 debugs(93, 7, HERE
<< "will supply " << what
<< " via " <<
1548 adapted
.body_pipe
<< " pipe");
1552 // TODO: Move SizedEstimate and Preview elsewhere
1554 Adaptation::Icap::SizedEstimate::SizedEstimate()
1555 : theData(dtUnexpected
)
1558 void Adaptation::Icap::SizedEstimate::expect(int64_t aSize
)
1560 theData
= (aSize
>= 0) ? aSize
: (int64_t)dtUnknown
;
1563 bool Adaptation::Icap::SizedEstimate::expected() const
1565 return theData
!= dtUnexpected
;
1568 bool Adaptation::Icap::SizedEstimate::knownSize() const
1571 return theData
!= dtUnknown
;
1574 uint64_t Adaptation::Icap::SizedEstimate::size() const
1577 return static_cast<uint64_t>(theData
);
1582 Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided
)
1585 void Adaptation::Icap::VirginBodyAct::plan()
1588 Must(!theStart
); // not started
1589 theState
= stActive
;
1592 void Adaptation::Icap::VirginBodyAct::disable()
1594 theState
= stDisabled
;
1597 void Adaptation::Icap::VirginBodyAct::progress(size_t size
)
1601 theStart
+= static_cast<int64_t>(size
);
1604 uint64_t Adaptation::Icap::VirginBodyAct::offset() const
1607 return static_cast<uint64_t>(theStart
);
1611 Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled
)
1614 void Adaptation::Icap::Preview::enable(size_t anAd
)
1616 // TODO: check for anAd not exceeding preview size limit
1620 theState
= stWriting
;
1623 bool Adaptation::Icap::Preview::enabled() const
1625 return theState
!= stDisabled
;
1628 size_t Adaptation::Icap::Preview::ad() const
1634 bool Adaptation::Icap::Preview::done() const
1637 return theState
>= stIeof
;
1640 bool Adaptation::Icap::Preview::ieof() const
1643 return theState
== stIeof
;
1646 size_t Adaptation::Icap::Preview::debt() const
1649 return done() ? 0 : (theAd
- theWritten
);
1652 void Adaptation::Icap::Preview::wrote(size_t size
, bool wroteEof
)
1658 Must(theWritten
<= theAd
);
1661 theState
= stIeof
; // written size is irrelevant
1662 else if (theWritten
>= theAd
)
1666 bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf
&mb
) const
1668 if (virgin
.header
== NULL
)
1671 virgin
.header
->firstLineBuf(mb
);
1677 /* Adaptation::Icap::ModXactLauncher */
1679 Adaptation::Icap::ModXactLauncher::ModXactLauncher(Adaptation::Initiator
*anInitiator
, HttpMsg
*virginHeader
, HttpRequest
*virginCause
, Adaptation::ServicePointer aService
):
1680 AsyncJob("Adaptation::Icap::ModXactLauncher"),
1681 Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", anInitiator
, aService
)
1683 virgin
.setHeader(virginHeader
);
1684 virgin
.setCause(virginCause
);
1685 updateHistory(true);
1688 Adaptation::Icap::Xaction
*Adaptation::Icap::ModXactLauncher::createXaction()
1690 Adaptation::Icap::ServiceRep::Pointer s
=
1691 dynamic_cast<Adaptation::Icap::ServiceRep
*>(theService
.getRaw());
1693 return new Adaptation::Icap::ModXact(this, virgin
.header
, virgin
.cause
, s
);
1696 void Adaptation::Icap::ModXactLauncher::swanSong()
1698 debugs(93, 5, HERE
<< "swan sings");
1699 updateHistory(false);
1700 Adaptation::Icap::Launcher::swanSong();
1703 void Adaptation::Icap::ModXactLauncher::updateHistory(bool start
)
1705 HttpRequest
*r
= virgin
.cause
?
1706 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
1708 // r should never be NULL but we play safe; TODO: add Should()
1710 Adaptation::Icap::History::Pointer h
= r
->icapHistory();
1713 h
->start("ICAPModXactLauncher");
1715 h
->stop("ICAPModXactLauncher");