2 * Copyright (C) 1996-2017 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 93 ICAP (RFC 3507) Client */
12 #include "AccessLogEntry.h"
13 #include "adaptation/Answer.h"
14 #include "adaptation/History.h"
15 #include "adaptation/icap/Client.h"
16 #include "adaptation/icap/Config.h"
17 #include "adaptation/icap/History.h"
18 #include "adaptation/icap/Launcher.h"
19 #include "adaptation/icap/ModXact.h"
20 #include "adaptation/icap/ServiceRep.h"
21 #include "adaptation/Initiator.h"
22 #include "auth/UserRequest.h"
23 #include "base/TextException.h"
26 #include "comm/Connection.h"
27 #include "err_detail_type.h"
28 #include "http/one/TeChunkedParser.h"
29 #include "HttpHeaderTools.h"
31 #include "HttpReply.h"
32 #include "HttpRequest.h"
33 #include "SquidTime.h"
36 // flow and terminology:
37 // HTTP| --> receive --> encode --> write --> |network
38 // end | <-- send <-- parse <-- read <-- |end
40 // TODO: replace gotEncapsulated() with something faster; we call it often
42 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXact
);
43 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ModXactLauncher
);
45 static const size_t TheBackupLimit
= BodyPipe::MaxCapacity
;
47 Adaptation::Icap::ModXact::State::State()
49 memset(this, 0, sizeof(*this));
52 Adaptation::Icap::ModXact::ModXact(HttpMsg
*virginHeader
,
53 HttpRequest
*virginCause
, AccessLogEntry::Pointer
&alp
, Adaptation::Icap::ServiceRep::Pointer
&aService
):
54 AsyncJob("Adaptation::Icap::ModXact"),
55 Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", aService
),
58 canStartBypass(false), // too early
59 protectGroupBypass(true),
60 replyHttpHeaderSize(-1),
61 replyHttpBodySize(-1),
63 trailerParser(nullptr),
68 virgin
.setHeader(virginHeader
); // sets virgin.body_pipe if needed
69 virgin
.setCause(virginCause
); // may be NULL
71 // adapted header and body are initialized when we parse them
73 // writing and reading ends are handled by Adaptation::Icap::Xaction
76 // nothing to do because we are using temporary buffers
78 // parsing; TODO: do not set until we parse, see ICAPOptXact
79 icapReply
= new HttpReply
;
80 icapReply
->protoPrefix
= "ICAP/"; // TODO: make an IcapReply class?
82 debugs(93,7, HERE
<< "initialized." << status());
85 // initiator wants us to start
86 void Adaptation::Icap::ModXact::start()
88 Adaptation::Icap::Xaction::start();
90 // reserve an adaptation history slot (attempts are known at this time)
91 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
93 adaptHistoryId
= ah
->recordXactStart(service().cfg().key
, icap_tr_start
, attempts
> 1);
95 estimateVirginBody(); // before virgin disappears!
97 canStartBypass
= service().cfg().bypass
;
99 // it is an ICAP violation to send request to a service w/o known OPTIONS
100 // and the service may is too busy for us: honor Max-Connections and such
101 if (service().up() && service().availableForNew())
107 void Adaptation::Icap::ModXact::waitForService()
110 Must(!state
.serviceWaiting
);
112 if (!service().up()) {
113 AsyncCall::Pointer call
= JobCallback(93,5,
114 ConnWaiterDialer
, this, Adaptation::Icap::ModXact::noteServiceReady
);
116 service().callWhenReady(call
);
117 comment
= "to be up";
119 //The service is unavailable because of max-connection or other reason
121 if (service().cfg().onOverload
!= srvWait
) {
122 // The service is overloaded, but waiting to be available prohibited by
123 // user configuration (onOverload is set to "block" or "bypass")
124 if (service().cfg().onOverload
== srvBlock
)
125 disableBypass("not available", true);
126 else //if (service().cfg().onOverload == srvBypass)
127 canStartBypass
= true;
130 disableRepeats("ICAP service is not available");
132 debugs(93, 7, HERE
<< "will not wait for the service to be available" <<
135 throw TexcHere("ICAP service is not available");
138 AsyncCall::Pointer call
= JobCallback(93,5,
139 ConnWaiterDialer
, this, Adaptation::Icap::ModXact::noteServiceAvailable
);
140 service().callWhenAvailable(call
, state
.waitedForService
);
141 comment
= "to be available";
144 debugs(93, 7, HERE
<< "will wait for the service " << comment
<< status());
145 state
.serviceWaiting
= true; // after callWhenReady() which may throw
146 state
.waitedForService
= true;
149 void Adaptation::Icap::ModXact::noteServiceReady()
151 Must(state
.serviceWaiting
);
152 state
.serviceWaiting
= false;
154 if (!service().up()) {
156 disableRepeats("ICAP service is unusable");
157 throw TexcHere("ICAP service is unusable");
160 if (service().availableForOld())
166 void Adaptation::Icap::ModXact::noteServiceAvailable()
168 Must(state
.serviceWaiting
);
169 state
.serviceWaiting
= false;
171 if (service().up() && service().availableForOld())
177 void Adaptation::Icap::ModXact::startWriting()
179 state
.writing
= State::writingConnect
;
181 decideOnPreview(); // must be decided before we decideOnRetries
187 // connection with the ICAP service established
188 void Adaptation::Icap::ModXact::handleCommConnected()
190 Must(state
.writing
== State::writingConnect
);
192 startReading(); // wait for early errors from the ICAP server
197 makeRequestHeaders(requestBuf
);
198 debugs(93, 9, HERE
<< "will write" << status() << ":\n" <<
199 (requestBuf
.terminate(), requestBuf
.content()));
202 state
.writing
= State::writingHeaders
;
203 icap_tio_start
= current_time
;
204 scheduleWrite(requestBuf
);
207 void Adaptation::Icap::ModXact::handleCommWrote(size_t sz
)
209 debugs(93, 5, HERE
<< "Wrote " << sz
<< " bytes");
211 if (state
.writing
== State::writingHeaders
)
212 handleCommWroteHeaders();
214 handleCommWroteBody();
217 void Adaptation::Icap::ModXact::handleCommWroteHeaders()
219 Must(state
.writing
== State::writingHeaders
);
221 // determine next step
222 if (preview
.enabled()) {
224 decideWritingAfterPreview("zero-size");
226 state
.writing
= State::writingPreview
;
227 } else if (virginBody
.expected()) {
228 state
.writing
= State::writingPrime
;
237 void Adaptation::Icap::ModXact::writeMore()
239 debugs(93, 5, HERE
<< "checking whether to write more" << status());
241 if (writer
!= NULL
) // already writing something
244 switch (state
.writing
) {
246 case State::writingInit
: // waiting for service OPTIONS
247 Must(state
.serviceWaiting
);
249 case State::writingConnect
: // waiting for the connection to establish
251 case State::writingHeaders
: // waiting for the headers to be written
253 case State::writingPaused
: // waiting for the ICAP server response
255 case State::writingReallyDone
: // nothing more to write
258 case State::writingAlmostDone
: // was waiting for the last write
262 case State::writingPreview
:
266 case State::writingPrime
:
271 throw TexcHere("Adaptation::Icap::ModXact in bad writing state");
275 void Adaptation::Icap::ModXact::writePreviewBody()
277 debugs(93, 8, HERE
<< "will write Preview body from " <<
278 virgin
.body_pipe
<< status());
279 Must(state
.writing
== State::writingPreview
);
280 Must(virgin
.body_pipe
!= NULL
);
282 const size_t sizeMax
= (size_t)virgin
.body_pipe
->buf().contentSize();
283 const size_t size
= min(preview
.debt(), sizeMax
);
284 writeSomeBody("preview body", size
);
286 // change state once preview is written
289 decideWritingAfterPreview("body");
292 /// determine state.writing after we wrote the entire preview
293 void Adaptation::Icap::ModXact::decideWritingAfterPreview(const char *kind
)
295 if (preview
.ieof()) // nothing more to write
297 else if (state
.parsing
== State::psIcapHeader
) // did not get a reply yet
298 state
.writing
= State::writingPaused
; // wait for the ICAP server reply
300 stopWriting(true); // ICAP server reply implies no post-preview writing
302 debugs(93, 6, HERE
<< "decided on writing after " << kind
<< " preview" <<
306 void Adaptation::Icap::ModXact::writePrimeBody()
308 Must(state
.writing
== State::writingPrime
);
309 Must(virginBodyWriting
.active());
311 const size_t size
= (size_t)virgin
.body_pipe
->buf().contentSize();
312 writeSomeBody("prime virgin body", size
);
314 if (virginBodyEndReached(virginBodyWriting
)) {
315 debugs(93, 5, HERE
<< "wrote entire body");
320 void Adaptation::Icap::ModXact::writeSomeBody(const char *label
, size_t size
)
322 Must(!writer
&& state
.writing
< state
.writingAlmostDone
);
323 Must(virgin
.body_pipe
!= NULL
);
324 debugs(93, 8, HERE
<< "will write up to " << size
<< " bytes of " <<
327 MemBuf writeBuf
; // TODO: suggest a min size based on size and lastChunk
329 writeBuf
.init(); // note: we assume that last-chunk will fit
331 const size_t writableSize
= virginContentSize(virginBodyWriting
);
332 const size_t chunkSize
= min(writableSize
, size
);
335 debugs(93, 7, HERE
<< "will write " << chunkSize
<<
336 "-byte chunk of " << label
);
338 openChunk(writeBuf
, chunkSize
, false);
339 writeBuf
.append(virginContentData(virginBodyWriting
), chunkSize
);
340 closeChunk(writeBuf
);
342 virginBodyWriting
.progress(chunkSize
);
345 debugs(93, 7, HERE
<< "has no writable " << label
<< " content");
348 const bool wroteEof
= virginBodyEndReached(virginBodyWriting
);
349 bool lastChunk
= wroteEof
;
350 if (state
.writing
== State::writingPreview
) {
351 preview
.wrote(chunkSize
, wroteEof
); // even if wrote nothing
352 lastChunk
= lastChunk
|| preview
.done();
356 debugs(93, 8, HERE
<< "will write last-chunk of " << label
);
357 addLastRequestChunk(writeBuf
);
360 debugs(93, 7, HERE
<< "will write " << writeBuf
.contentSize()
361 << " raw bytes of " << label
);
363 if (writeBuf
.hasContent()) {
364 scheduleWrite(writeBuf
); // comm will free the chunk
370 void Adaptation::Icap::ModXact::addLastRequestChunk(MemBuf
&buf
)
372 const bool ieof
= state
.writing
== State::writingPreview
&& preview
.ieof();
373 openChunk(buf
, 0, ieof
);
377 void Adaptation::Icap::ModXact::openChunk(MemBuf
&buf
, size_t chunkSize
, bool ieof
)
379 buf
.appendf((ieof
? "%x; ieof\r\n" : "%x\r\n"), (int) chunkSize
);
382 void Adaptation::Icap::ModXact::closeChunk(MemBuf
&buf
)
384 buf
.append(ICAP::crlf
, 2); // chunk-terminating CRLF
387 const HttpRequest
&Adaptation::Icap::ModXact::virginRequest() const
389 const HttpRequest
*request
= virgin
.cause
?
390 virgin
.cause
: dynamic_cast<const HttpRequest
*>(virgin
.header
);
395 // did the activity reached the end of the virgin body?
396 bool Adaptation::Icap::ModXact::virginBodyEndReached(const Adaptation::Icap::VirginBodyAct
&act
) const
399 !act
.active() || // did all (assuming it was originally planned)
400 !virgin
.body_pipe
->expectMoreAfter(act
.offset()); // wont have more
403 // the size of buffered virgin body data available for the specified activity
404 // if this size is zero, we may be done or may be waiting for more data
405 size_t Adaptation::Icap::ModXact::virginContentSize(const Adaptation::Icap::VirginBodyAct
&act
) const
408 // asbolute start of unprocessed data
409 const uint64_t dataStart
= act
.offset();
410 // absolute end of buffered data
411 const uint64_t dataEnd
= virginConsumed
+ virgin
.body_pipe
->buf().contentSize();
412 Must(virginConsumed
<= dataStart
&& dataStart
<= dataEnd
);
413 return static_cast<size_t>(dataEnd
- dataStart
);
416 // pointer to buffered virgin body data available for the specified activity
417 const char *Adaptation::Icap::ModXact::virginContentData(const Adaptation::Icap::VirginBodyAct
&act
) const
420 const uint64_t dataStart
= act
.offset();
421 Must(virginConsumed
<= dataStart
);
422 return virgin
.body_pipe
->buf().content() + static_cast<size_t>(dataStart
-virginConsumed
);
425 void Adaptation::Icap::ModXact::virginConsume()
427 debugs(93, 9, HERE
<< "consumption guards: " << !virgin
.body_pipe
<< isRetriable
<<
428 isRepeatable
<< canStartBypass
<< protectGroupBypass
);
430 if (!virgin
.body_pipe
)
431 return; // nothing to consume
434 return; // do not consume if we may have to retry later
436 BodyPipe
&bp
= *virgin
.body_pipe
;
437 const bool wantToPostpone
= isRepeatable
|| canStartBypass
|| protectGroupBypass
;
439 // Why > 2? HttpState does not use the last bytes in the buffer
440 // because delayAwareRead() is arguably broken. See
441 // HttpStateData::maybeReadVirginBody for more details.
442 if (wantToPostpone
&& bp
.buf().spaceSize() > 2) {
443 // Postponing may increase memory footprint and slow the HTTP side
444 // down. Not postponing may increase the number of ICAP errors
445 // if the ICAP service fails. We may also use "potential" space to
446 // postpone more aggressively. Should the trade-off be configurable?
447 debugs(93, 8, HERE
<< "postponing consumption from " << bp
.status());
451 const size_t have
= static_cast<size_t>(bp
.buf().contentSize());
452 const uint64_t end
= virginConsumed
+ have
;
453 uint64_t offset
= end
;
455 debugs(93, 9, HERE
<< "max virgin consumption offset=" << offset
<<
456 " acts " << virginBodyWriting
.active() << virginBodySending
.active() <<
457 " consumed=" << virginConsumed
<<
458 " from " << virgin
.body_pipe
->status());
460 if (virginBodyWriting
.active())
461 offset
= min(virginBodyWriting
.offset(), offset
);
463 if (virginBodySending
.active())
464 offset
= min(virginBodySending
.offset(), offset
);
466 Must(virginConsumed
<= offset
&& offset
<= end
);
468 if (const size_t size
= static_cast<size_t>(offset
- virginConsumed
)) {
469 debugs(93, 8, HERE
<< "consuming " << size
<< " out of " << have
<<
470 " virgin body bytes");
472 virginConsumed
+= size
;
473 Must(!isRetriable
); // or we should not be consuming
474 disableRepeats("consumed content");
475 disableBypass("consumed content", true);
479 void Adaptation::Icap::ModXact::handleCommWroteBody()
484 // Called when we do not expect to call comm_write anymore.
485 // We may have a pending write though.
486 // If stopping nicely, we will just wait for that pending write, if any.
487 void Adaptation::Icap::ModXact::stopWriting(bool nicely
)
489 if (state
.writing
== State::writingReallyDone
)
492 if (writer
!= NULL
) {
494 debugs(93, 7, HERE
<< "will wait for the last write" << status());
495 state
.writing
= State::writingAlmostDone
; // may already be set
499 debugs(93, 3, HERE
<< "will NOT wait for the last write" << status());
501 // Comm does not have an interface to clear the writer callback nicely,
502 // but without clearing the writer we cannot recycle the connection.
503 // We prevent connection reuse and hope that we can handle a callback
504 // call at any time, usually in the middle of the destruction sequence!
505 // Somebody should add comm_remove_write_handler() to comm API.
506 reuseConnection
= false;
507 ignoreLastWrite
= true;
510 debugs(93, 7, HERE
<< "will no longer write" << status());
511 if (virginBodyWriting
.active()) {
512 virginBodyWriting
.disable();
515 state
.writing
= State::writingReallyDone
;
519 void Adaptation::Icap::ModXact::stopBackup()
521 if (!virginBodySending
.active())
524 debugs(93, 7, HERE
<< "will no longer backup" << status());
525 virginBodySending
.disable();
529 bool Adaptation::Icap::ModXact::doneAll() const
531 return Adaptation::Icap::Xaction::doneAll() && !state
.serviceWaiting
&&
533 doneReading() && state
.doneWriting();
536 void Adaptation::Icap::ModXact::startReading()
538 Must(haveConnection());
540 Must(!adapted
.header
);
541 Must(!adapted
.body_pipe
);
543 // we use the same buffer for headers and body and then consume headers
547 void Adaptation::Icap::ModXact::readMore()
549 if (reader
!= NULL
|| doneReading()) {
550 debugs(93,3,HERE
<< "returning from readMore because reader or doneReading()");
554 // do not fill readBuf if we have no space to store the result
555 if (adapted
.body_pipe
!= NULL
&&
556 !adapted
.body_pipe
->buf().hasPotentialSpace()) {
557 debugs(93,3,HERE
<< "not reading because ICAP reply pipe is full");
561 if (readBuf
.length() < SQUID_TCP_SO_RCVBUF
)
564 debugs(93,3,HERE
<< "cannot read with a full buffer");
567 // comm module read a portion of the ICAP response for us
568 void Adaptation::Icap::ModXact::handleCommRead(size_t)
570 Must(!state
.doneParsing());
571 icap_tio_finish
= current_time
;
576 void Adaptation::Icap::ModXact::echoMore()
578 Must(state
.sending
== State::sendingVirgin
);
579 Must(adapted
.body_pipe
!= NULL
);
580 Must(virginBodySending
.active());
582 const size_t sizeMax
= virginContentSize(virginBodySending
);
583 debugs(93,5, HERE
<< "will echo up to " << sizeMax
<< " bytes from " <<
584 virgin
.body_pipe
->status());
585 debugs(93,5, HERE
<< "will echo up to " << sizeMax
<< " bytes to " <<
586 adapted
.body_pipe
->status());
589 const size_t size
= adapted
.body_pipe
->putMoreData(virginContentData(virginBodySending
), sizeMax
);
590 debugs(93,5, HERE
<< "echoed " << size
<< " out of " << sizeMax
<<
592 virginBodySending
.progress(size
);
593 disableRepeats("echoed content");
594 disableBypass("echoed content", true);
598 if (virginBodyEndReached(virginBodySending
)) {
599 debugs(93, 5, HERE
<< "echoed all" << status());
602 debugs(93, 5, HERE
<< "has " <<
603 virgin
.body_pipe
->buf().contentSize() << " bytes " <<
604 "and expects more to echo" << status());
605 // TODO: timeout if virgin or adapted pipes are broken
609 bool Adaptation::Icap::ModXact::doneSending() const
611 return state
.sending
== State::sendingDone
;
614 // stop (or do not start) sending adapted message body
615 void Adaptation::Icap::ModXact::stopSending(bool nicely
)
617 debugs(93, 7, HERE
<< "Enter stop sending ");
620 debugs(93, 7, HERE
<< "Proceed with stop sending ");
622 if (state
.sending
!= State::sendingUndecided
) {
623 debugs(93, 7, HERE
<< "will no longer send" << status());
624 if (adapted
.body_pipe
!= NULL
) {
625 virginBodySending
.disable();
626 // we may leave debts if we were echoing and the virgin
627 // body_pipe got exhausted before we echoed all planned bytes
628 const bool leftDebts
= adapted
.body_pipe
->needsMoreData();
629 stopProducingFor(adapted
.body_pipe
, nicely
&& !leftDebts
);
632 debugs(93, 7, HERE
<< "will not start sending" << status());
633 Must(!adapted
.body_pipe
);
636 state
.sending
= State::sendingDone
;
640 // should be called after certain state.writing or state.sending changes
641 void Adaptation::Icap::ModXact::checkConsuming()
643 // quit if we already stopped or are still using the pipe
644 if (!virgin
.body_pipe
|| !state
.doneConsumingVirgin())
647 debugs(93, 7, HERE
<< "will stop consuming" << status());
648 stopConsumingFrom(virgin
.body_pipe
);
651 void Adaptation::Icap::ModXact::parseMore()
653 debugs(93, 5, "have " << readBuf
.length() << " bytes to parse" << status());
654 debugs(93, 5, "\n" << readBuf
);
656 if (state
.parsingHeaders())
659 if (state
.parsing
== State::psBody
)
662 if (state
.parsing
== State::psIcapTrailer
)
666 void Adaptation::Icap::ModXact::callException(const std::exception
&e
)
668 if (!canStartBypass
|| isRetriable
) {
670 if (const TextException
*te
= dynamic_cast<const TextException
*>(&e
))
671 detailError(ERR_DETAIL_EXCEPTION_START
+ te
->id());
673 detailError(ERR_DETAIL_EXCEPTION_OTHER
);
675 Adaptation::Icap::Xaction::callException(e
);
680 debugs(93, 3, HERE
<< "bypassing " << inCall
<< " exception: " <<
681 e
.what() << ' ' << status());
683 } catch (const TextException
&bypassTe
) {
684 detailError(ERR_DETAIL_EXCEPTION_START
+ bypassTe
.id());
685 Adaptation::Icap::Xaction::callException(bypassTe
);
686 } catch (const std::exception
&bypassE
) {
687 detailError(ERR_DETAIL_EXCEPTION_OTHER
);
688 Adaptation::Icap::Xaction::callException(bypassE
);
692 void Adaptation::Icap::ModXact::bypassFailure()
694 disableBypass("already started to bypass", false);
696 Must(!isRetriable
); // or we should not be bypassing
697 // TODO: should the same be enforced for isRepeatable? Check icap_repeat??
703 // end all activities associated with the ICAP server
707 stopWriting(true); // or should we force it?
708 if (haveConnection()) {
709 reuseConnection
= false; // be conservative
710 cancelRead(); // may not work; and we cannot stop connecting either
712 debugs(93, 7, HERE
<< "Warning: bypass failed to stop I/O" << status());
715 service().noteFailure(); // we are bypassing, but this is still a failure
718 void Adaptation::Icap::ModXact::disableBypass(const char *reason
, bool includingGroupBypass
)
720 if (canStartBypass
) {
721 debugs(93,7, HERE
<< "will never start bypass because " << reason
);
722 canStartBypass
= false;
724 if (protectGroupBypass
&& includingGroupBypass
) {
725 debugs(93,7, HERE
<< "not protecting group bypass because " << reason
);
726 protectGroupBypass
= false;
730 // note that allocation for echoing is done in handle204NoContent()
731 void Adaptation::Icap::ModXact::maybeAllocateHttpMsg()
733 if (adapted
.header
) // already allocated
736 if (gotEncapsulated("res-hdr")) {
737 adapted
.setHeader(new HttpReply
);
738 setOutcome(service().cfg().method
== ICAP::methodReqmod
?
739 xoSatisfied
: xoModified
);
740 } else if (gotEncapsulated("req-hdr")) {
741 adapted
.setHeader(new HttpRequest
);
742 setOutcome(xoModified
);
744 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
747 void Adaptation::Icap::ModXact::parseHeaders()
749 Must(state
.parsingHeaders());
751 if (state
.parsing
== State::psIcapHeader
) {
752 debugs(93, 5, HERE
<< "parse ICAP headers");
756 if (state
.parsing
== State::psHttpHeader
) {
757 debugs(93, 5, HERE
<< "parse HTTP headers");
761 if (state
.parsingHeaders()) { // need more data
769 // called after parsing all headers or when bypassing an exception
770 void Adaptation::Icap::ModXact::startSending()
772 disableRepeats("sent headers");
773 disableBypass("sent headers", true);
774 sendAnswer(Answer::Forward(adapted
.header
));
776 if (state
.sending
== State::sendingVirgin
)
779 // If we are not using the virgin HTTP object update the
780 // HttpMsg::sources flag.
781 // The state.sending may set to State::sendingVirgin in the case
782 // of 206 responses too, where we do not want to update HttpMsg::sources
783 // flag. However even for 206 responses the state.sending is
784 // not set yet to sendingVirgin. This is done in later step
785 // after the parseBody method called.
790 void Adaptation::Icap::ModXact::parseIcapHead()
792 Must(state
.sending
== State::sendingUndecided
);
794 if (!parseHead(icapReply
.getRaw()))
797 if (expectIcapTrailers()) {
798 Must(!trailerParser
);
799 trailerParser
= new TrailerParser
;
802 if (httpHeaderHasConnDir(&icapReply
->header
, "close")) {
803 debugs(93, 5, HERE
<< "found connection close");
804 reuseConnection
= false;
807 switch (icapReply
->sline
.status()) {
809 case Http::scContinue
:
814 case Http::scCreated
: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
816 if (!validate200Ok()) {
817 throw TexcHere("Invalid ICAP Response");
824 case Http::scNoContent
:
825 handle204NoContent();
828 case Http::scPartialContent
:
829 handle206PartialContent();
833 debugs(93, 5, "ICAP status " << icapReply
->sline
.status());
834 handleUnknownScode();
838 const HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
840 request
= &virginRequest();
842 // update the cross-transactional database if needed (all status codes!)
843 if (const char *xxName
= Adaptation::Config::masterx_shared_name
) {
844 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
845 if (ah
!= NULL
) { // TODO: reorder checks to avoid creating history
846 const String val
= icapReply
->header
.getByName(xxName
);
847 if (val
.size() > 0) // XXX: HttpHeader lacks empty value detection
848 ah
->updateXxRecord(xxName
, val
);
852 // update the adaptation plan if needed (all status codes!)
853 if (service().cfg().routing
) {
855 if (icapReply
->header
.getList(Http::HdrType::X_NEXT_SERVICES
, &services
)) {
856 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
858 ah
->updateNextServices(services
);
860 } // TODO: else warn (occasionally!) if we got Http::HdrType::X_NEXT_SERVICES
862 // We need to store received ICAP headers for <icapLastHeader logformat option.
863 // If we already have stored headers from previous ICAP transaction related to this
864 // request, old headers will be replaced with the new one.
866 Adaptation::History::Pointer ah
= request
->adaptLogHistory();
868 ah
->recordMeta(&icapReply
->header
);
870 // handle100Continue() manages state.writing on its own.
871 // Non-100 status means the server needs no postPreview data from us.
872 if (state
.writing
== State::writingPaused
)
876 /// Parses ICAP trailers and stops parsing, if all trailer data
877 /// have been received.
878 void Adaptation::Icap::ModXact::parseIcapTrailer() {
880 if (parsePart(trailerParser
, "trailer")) {
881 for (const auto &e
: trailerParser
->trailer
.entries
)
882 debugs(93, 5, "ICAP trailer: " << e
->name
<< ": " << e
->value
);
887 bool Adaptation::Icap::ModXact::validate200Ok()
889 if (service().cfg().method
== ICAP::methodRespmod
)
890 return gotEncapsulated("res-hdr");
892 return service().cfg().method
== ICAP::methodReqmod
&&
896 void Adaptation::Icap::ModXact::handle100Continue()
898 Must(state
.writing
== State::writingPaused
);
899 // server must not respond before the end of preview: we may send ieof
900 Must(preview
.enabled() && preview
.done() && !preview
.ieof());
902 // 100 "Continue" cancels our Preview commitment,
903 // but not commitment to handle 204 or 206 outside Preview
904 if (!state
.allowedPostview204
&& !state
.allowedPostview206
)
907 state
.parsing
= State::psIcapHeader
; // eventually
910 state
.writing
= State::writingPrime
;
915 void Adaptation::Icap::ModXact::handle200Ok()
917 state
.parsing
= State::psHttpHeader
;
918 state
.sending
= State::sendingAdapted
;
923 void Adaptation::Icap::ModXact::handle204NoContent()
929 void Adaptation::Icap::ModXact::handle206PartialContent()
931 if (state
.writing
== State::writingPaused
) {
932 Must(preview
.enabled());
933 Must(state
.allowedPreview206
);
934 debugs(93, 7, HERE
<< "206 inside preview");
936 Must(state
.writing
> State::writingPaused
);
937 Must(state
.allowedPostview206
);
938 debugs(93, 7, HERE
<< "206 outside preview");
940 state
.parsing
= State::psHttpHeader
;
941 state
.sending
= State::sendingAdapted
;
942 state
.readyForUob
= true;
946 // Called when we receive a 204 No Content response and
947 // when we are trying to bypass a service failure.
948 // We actually start sending (echoig or not) in startSending.
949 void Adaptation::Icap::ModXact::prepEchoing()
951 disableRepeats("preparing to echo content");
952 disableBypass("preparing to echo content", true);
955 // We want to clone the HTTP message, but we do not want
956 // to copy some non-HTTP state parts that HttpMsg kids carry in them.
957 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
958 // Instead, we simply write the HTTP message and "clone" it by parsing.
959 // TODO: use HttpMsg::clone()!
961 HttpMsg
*oldHead
= virgin
.header
;
962 debugs(93, 7, HERE
<< "cloning virgin message " << oldHead
);
966 // write the virgin message into a memory buffer
968 packHead(httpBuf
, oldHead
);
970 // allocate the adapted message and copy metainfo
971 Must(!adapted
.header
);
973 HttpMsg::Pointer newHead
;
974 if (dynamic_cast<const HttpRequest
*>(oldHead
)) {
975 newHead
= new HttpRequest
;
976 } else if (dynamic_cast<const HttpReply
*>(oldHead
)) {
977 newHead
= new HttpReply
;
979 Must(newHead
!= NULL
);
981 newHead
->inheritProperties(oldHead
);
983 adapted
.setHeader(newHead
.getRaw());
986 // parse the buffer back
987 Http::StatusCode error
= Http::scNone
;
989 httpBuf
.terminate(); // HttpMsg::parse requires nil-terminated buffer
990 Must(adapted
.header
->parse(httpBuf
.content(), httpBuf
.contentSize(), true, &error
));
991 Must(adapted
.header
->hdr_sz
== httpBuf
.contentSize()); // no leftovers
995 debugs(93, 7, HERE
<< "cloned virgin message " << oldHead
<< " to " <<
998 // setup adapted body pipe if needed
999 if (oldHead
->body_pipe
!= NULL
) {
1000 debugs(93, 7, HERE
<< "will echo virgin body from " <<
1001 oldHead
->body_pipe
);
1002 if (!virginBodySending
.active())
1003 virginBodySending
.plan(); // will throw if not possible
1004 state
.sending
= State::sendingVirgin
;
1007 // TODO: optimize: is it possible to just use the oldHead pipe and
1008 // remove ICAP from the loop? This echoing is probably a common case!
1009 makeAdaptedBodyPipe("echoed virgin response");
1010 if (oldHead
->body_pipe
->bodySizeKnown())
1011 adapted
.body_pipe
->setBodySize(oldHead
->body_pipe
->bodySize());
1012 debugs(93, 7, HERE
<< "will echo virgin body to " <<
1015 debugs(93, 7, HERE
<< "no virgin body to echo");
1020 /// Called when we received use-original-body chunk extension in 206 response.
1021 /// We actually start sending (echoing or not) in startSending().
1022 void Adaptation::Icap::ModXact::prepPartialBodyEchoing(uint64_t pos
)
1024 Must(virginBodySending
.active());
1025 Must(virgin
.header
->body_pipe
!= NULL
);
1027 setOutcome(xoPartEcho
);
1029 debugs(93, 7, HERE
<< "will echo virgin body suffix from " <<
1030 virgin
.header
->body_pipe
<< " offset " << pos
);
1032 // check that use-original-body=N does not point beyond buffered data
1033 const uint64_t virginDataEnd
= virginConsumed
+
1034 virgin
.body_pipe
->buf().contentSize();
1035 Must(pos
<= virginDataEnd
);
1036 virginBodySending
.progress(static_cast<size_t>(pos
));
1038 state
.sending
= State::sendingVirgin
;
1041 if (virgin
.header
->body_pipe
->bodySizeKnown())
1042 adapted
.body_pipe
->expectProductionEndAfter(virgin
.header
->body_pipe
->bodySize() - pos
);
1044 debugs(93, 7, HERE
<< "will echo virgin body suffix to " <<
1047 // Start echoing data
1051 void Adaptation::Icap::ModXact::handleUnknownScode()
1055 // TODO: mark connection as "bad"
1057 // Terminate the transaction; we do not know how to handle this response.
1058 throw TexcHere("Unsupported ICAP status code");
1061 void Adaptation::Icap::ModXact::parseHttpHead()
1063 if (expectHttpHeader()) {
1064 replyHttpHeaderSize
= 0;
1065 maybeAllocateHttpMsg();
1067 if (!parseHead(adapted
.header
))
1068 return; // need more header data
1071 replyHttpHeaderSize
= adapted
.header
->hdr_sz
;
1073 if (dynamic_cast<HttpRequest
*>(adapted
.header
)) {
1074 const HttpRequest
*oldR
= dynamic_cast<const HttpRequest
*>(virgin
.header
);
1076 // TODO: the adapted request did not really originate from the
1077 // client; give proxy admin an option to prevent copying of
1078 // sensitive client information here. See the following thread:
1079 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
1082 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
1084 adapted
.header
->inheritProperties(virgin
.header
);
1087 decideOnParsingBody();
1090 template<class Part
>
1091 bool Adaptation::Icap::ModXact::parsePart(Part
*part
, const char *description
)
1094 debugs(93, 5, "have " << readBuf
.length() << ' ' << description
<< " bytes to parse; state: " << state
.parsing
);
1095 Http::StatusCode error
= Http::scNone
;
1096 // XXX: performance regression. c_str() data copies
1097 // XXX: HttpMsg::parse requires a terminated string buffer
1098 const char *tmpBuf
= readBuf
.c_str();
1099 const bool parsed
= part
->parse(tmpBuf
, readBuf
.length(), commEof
, &error
);
1100 debugs(93, (!parsed
&& error
) ? 2 : 5, description
<< " parsing result: " << parsed
<< " detail: " << error
);
1101 Must(parsed
|| !error
);
1103 readBuf
.consume(part
->hdr_sz
);
1107 // parses both HTTP and ICAP headers
1108 bool Adaptation::Icap::ModXact::parseHead(HttpMsg
*head
)
1110 if (!parsePart(head
, "head")) {
1117 bool Adaptation::Icap::ModXact::expectHttpHeader() const
1119 return gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr");
1122 bool Adaptation::Icap::ModXact::expectHttpBody() const
1124 return gotEncapsulated("res-body") || gotEncapsulated("req-body");
1127 bool Adaptation::Icap::ModXact::expectIcapTrailers() const
1130 const bool promisesToSendTrailer
= icapReply
->header
.getByIdIfPresent(Http::HdrType::TRAILER
, trailers
);
1131 const bool supportsTrailers
= icapReply
->header
.hasListMember(Http::HdrType::ALLOW
, "trailers", ',');
1132 // ICAP Trailer specs require us to reject transactions having either Trailer
1133 // header or Allow:trailers
1134 Must((promisesToSendTrailer
== supportsTrailers
) || (!promisesToSendTrailer
&& supportsTrailers
));
1135 if (promisesToSendTrailer
&& !trailers
.size())
1136 debugs(93, DBG_IMPORTANT
, "ERROR: ICAP Trailer response header field must not be empty (salvaged)");
1137 return promisesToSendTrailer
;
1140 void Adaptation::Icap::ModXact::decideOnParsingBody()
1142 if (expectHttpBody()) {
1143 debugs(93, 5, HERE
<< "expecting a body");
1144 state
.parsing
= State::psBody
;
1145 replyHttpBodySize
= 0;
1146 bodyParser
= new Http1::TeChunkedParser
;
1147 makeAdaptedBodyPipe("adapted response from the ICAP server");
1148 Must(state
.sending
== State::sendingAdapted
);
1150 debugs(93, 5, HERE
<< "not expecting a body");
1152 state
.parsing
= State::psIcapTrailer
;
1159 void Adaptation::Icap::ModXact::parseBody()
1161 Must(state
.parsing
== State::psBody
);
1164 debugs(93, 5, "have " << readBuf
.length() << " body bytes to parse");
1166 // the parser will throw on errors
1167 BodyPipeCheckout
bpc(*adapted
.body_pipe
);
1168 bodyParser
->setPayloadBuffer(&bpc
.buf
);
1169 const bool parsed
= bodyParser
->parse(readBuf
);
1170 readBuf
= bodyParser
->remaining(); // sync buffers after parse
1173 debugs(93, 5, "have " << readBuf
.length() << " body bytes after parsed all: " << parsed
);
1174 replyHttpBodySize
+= adapted
.body_pipe
->buf().contentSize();
1176 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
1177 // TODO: do we really need this if we disable when sending headers?
1178 if (adapted
.body_pipe
->buf().contentSize() > 0) { // parsed something sometime
1179 disableRepeats("sent adapted content");
1180 disableBypass("sent adapted content", true);
1184 if (state
.readyForUob
&& bodyParser
->useOriginBody
>= 0)
1185 prepPartialBodyEchoing(static_cast<uint64_t>(bodyParser
->useOriginBody
));
1187 stopSending(true); // the parser succeeds only if all parsed data fits
1189 state
.parsing
= State::psIcapTrailer
;
1195 debugs(93,3,HERE
<< this << " needsMoreData = " << bodyParser
->needsMoreData());
1197 if (bodyParser
->needsMoreData()) {
1198 debugs(93,3,HERE
<< this);
1199 Must(mayReadMore());
1203 if (bodyParser
->needsMoreSpace()) {
1204 Must(!doneSending()); // can hope for more space
1205 Must(adapted
.body_pipe
->buf().contentSize() > 0); // paranoid
1206 // TODO: there should be a timeout in case the sink is broken
1207 // or cannot consume partial content (while we need more space)
1211 void Adaptation::Icap::ModXact::stopParsing(const bool checkUnparsedData
)
1213 if (state
.parsing
== State::psDone
)
1216 if (checkUnparsedData
)
1217 Must(readBuf
.isEmpty());
1219 debugs(93, 7, "will no longer parse" << status());
1222 bodyParser
= nullptr;
1224 delete trailerParser
;
1225 trailerParser
= nullptr;
1227 state
.parsing
= State::psDone
;
1230 // HTTP side added virgin body data
1231 void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer
)
1235 if (state
.sending
== State::sendingVirgin
)
1239 // HTTP side sent us all virgin info
1240 void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer
)
1242 Must(virgin
.body_pipe
->productionEnded());
1244 // push writer and sender in case we were waiting for the last-chunk
1247 if (state
.sending
== State::sendingVirgin
)
1251 // body producer aborted, but the initiator may still want to know
1252 // the answer, even though the HTTP message has been truncated
1253 void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer
)
1255 Must(virgin
.body_pipe
->productionEnded());
1257 // push writer and sender in case we were waiting for the last-chunk
1260 if (state
.sending
== State::sendingVirgin
)
1264 // adapted body consumer wants more adapted data and
1265 // possibly freed some buffer space
1266 void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
1268 if (state
.sending
== State::sendingVirgin
)
1270 else if (state
.sending
== State::sendingAdapted
)
1273 Must(state
.sending
== State::sendingUndecided
);
1276 // adapted body consumer aborted
1277 void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer
)
1279 detailError(ERR_DETAIL_ICAP_XACT_BODY_CONSUMER_ABORT
);
1280 mustStop("adapted body consumer aborted");
1283 Adaptation::Icap::ModXact::~ModXact()
1286 delete trailerParser
;
1290 void Adaptation::Icap::ModXact::swanSong()
1292 debugs(93, 5, HERE
<< "swan sings" << status());
1297 if (theInitiator
.set()) // we have not sent the answer to the initiator
1298 detailError(ERR_DETAIL_ICAP_XACT_OTHER
);
1300 // update adaptation history if start was called and we reserved a slot
1301 Adaptation::History::Pointer ah
= virginRequest().adaptLogHistory();
1302 if (ah
!= NULL
&& adaptHistoryId
>= 0)
1303 ah
->recordXactFinish(adaptHistoryId
);
1305 Adaptation::Icap::Xaction::swanSong();
1308 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
1310 void Adaptation::Icap::ModXact::finalizeLogInfo()
1312 HttpRequest
*adapted_request_
= nullptr;
1313 HttpReply
*adapted_reply_
= nullptr;
1314 HttpRequest
*virgin_request_
= const_cast<HttpRequest
*>(&virginRequest());
1315 if (!(adapted_request_
= dynamic_cast<HttpRequest
*>(adapted
.header
))) {
1316 // if the request was not adapted, use virgin request to simplify
1317 // the code further below
1318 adapted_request_
= virgin_request_
;
1319 adapted_reply_
= dynamic_cast<HttpReply
*>(adapted
.header
);
1322 Adaptation::Icap::History::Pointer h
= virgin_request_
->icapHistory();
1323 Must(h
!= NULL
); // ICAPXaction::maybeLog calls only if there is a log
1324 al
.icp
.opcode
= ICP_INVALID
;
1325 al
.url
= h
->log_uri
.termedBuf();
1326 const Adaptation::Icap::ServiceRep
&s
= service();
1327 al
.icap
.reqMethod
= s
.cfg().method
;
1329 al
.cache
.caddr
= virgin_request_
->client_addr
;
1331 al
.request
= virgin_request_
;
1332 HTTPMSGLOCK(al
.request
);
1333 al
.adapted_request
= adapted_request_
;
1334 HTTPMSGLOCK(al
.adapted_request
);
1336 if (adapted_reply_
) {
1337 al
.reply
= adapted_reply_
;
1338 HTTPMSGLOCK(al
.reply
);
1342 if (h
->rfc931
.size())
1343 al
.cache
.rfc931
= h
->rfc931
.termedBuf();
1346 if (h
->ssluser
.size())
1347 al
.cache
.ssluser
= h
->ssluser
.termedBuf();
1349 al
.cache
.code
= h
->logType
;
1351 const HttpMsg
*virgin_msg
= dynamic_cast<HttpReply
*>(virgin
.header
);
1353 virgin_msg
= virgin_request_
;
1354 assert(virgin_msg
!= virgin
.cause
);
1355 al
.http
.clientRequestSz
.header
= virgin_msg
->hdr_sz
;
1356 if (virgin_msg
->body_pipe
!= NULL
)
1357 al
.http
.clientRequestSz
.payloadData
= virgin_msg
->body_pipe
->producedSize();
1359 // leave al.icap.bodyBytesRead negative if no body
1360 if (replyHttpHeaderSize
>= 0 || replyHttpBodySize
>= 0) {
1361 const int64_t zero
= 0; // to make max() argument types the same
1362 const uint64_t headerSize
= max(zero
, replyHttpHeaderSize
);
1363 const uint64_t bodySize
= max(zero
, replyHttpBodySize
);
1364 al
.icap
.bodyBytesRead
= headerSize
+ bodySize
;
1365 al
.http
.clientReplySz
.header
= headerSize
;
1366 al
.http
.clientReplySz
.payloadData
= bodySize
;
1369 if (adapted_reply_
) {
1370 al
.http
.code
= adapted_reply_
->sline
.status();
1371 al
.http
.content_type
= adapted_reply_
->content_type
.termedBuf();
1372 if (replyHttpBodySize
>= 0)
1373 al
.cache
.highOffset
= replyHttpBodySize
;
1374 //don't set al.cache.objectSize because it hasn't exist yet
1378 adapted_reply_
->header
.packInto(&mb
);
1379 al
.headers
.reply
= xstrdup(mb
.buf
);
1382 prepareLogWithRequestDetails(adapted_request_
, alep
);
1383 Xaction::finalizeLogInfo();
1386 void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf
&buf
)
1388 char ntoabuf
[MAX_IPSTRLEN
];
1390 * XXX These should use HttpHdr interfaces instead of Printfs
1392 const Adaptation::ServiceConfig
&s
= service().cfg();
1393 buf
.appendf("%s " SQUIDSTRINGPH
" ICAP/1.0\r\n", s
.methodStr(), SQUIDSTRINGPRINT(s
.uri
));
1394 buf
.appendf("Host: " SQUIDSTRINGPH
":%d\r\n", SQUIDSTRINGPRINT(s
.host
), s
.port
);
1395 buf
.appendf("Date: %s\r\n", mkrfc1123(squid_curtime
));
1397 if (!TheConfig
.reuse_connections
)
1398 buf
.appendf("Connection: close\r\n");
1400 const HttpRequest
*request
= &virginRequest();
1402 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1404 if (virgin
.header
->header
.has(Http::HdrType::PROXY_AUTHENTICATE
)) {
1405 String vh
=virgin
.header
->header
.getById(Http::HdrType::PROXY_AUTHENTICATE
);
1406 buf
.appendf("Proxy-Authenticate: " SQUIDSTRINGPH
"\r\n",SQUIDSTRINGPRINT(vh
));
1409 if (virgin
.header
->header
.has(Http::HdrType::PROXY_AUTHORIZATION
)) {
1410 String vh
=virgin
.header
->header
.getById(Http::HdrType::PROXY_AUTHORIZATION
);
1411 buf
.appendf("Proxy-Authorization: " SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(vh
));
1412 } else if (request
->extacl_user
.size() > 0 && request
->extacl_passwd
.size() > 0) {
1413 struct base64_encode_ctx ctx
;
1414 base64_encode_init(&ctx
);
1415 uint8_t base64buf
[base64_encode_len(MAX_LOGIN_SZ
)];
1416 size_t resultLen
= base64_encode_update(&ctx
, base64buf
, request
->extacl_user
.size(), reinterpret_cast<const uint8_t*>(request
->extacl_user
.rawBuf()));
1417 resultLen
+= base64_encode_update(&ctx
, base64buf
+resultLen
, 1, reinterpret_cast<const uint8_t*>(":"));
1418 resultLen
+= base64_encode_update(&ctx
, base64buf
+resultLen
, request
->extacl_passwd
.size(), reinterpret_cast<const uint8_t*>(request
->extacl_passwd
.rawBuf()));
1419 resultLen
+= base64_encode_final(&ctx
, base64buf
+resultLen
);
1420 buf
.appendf("Proxy-Authorization: Basic %.*s\r\n", (int)resultLen
, base64buf
);
1423 // share the cross-transactional database records if needed
1424 if (Adaptation::Config::masterx_shared_name
) {
1425 Adaptation::History::Pointer ah
= request
->adaptHistory(false);
1428 if (ah
->getXxRecord(name
, value
)) {
1429 buf
.appendf(SQUIDSTRINGPH
": " SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(name
), SQUIDSTRINGPRINT(value
));
1434 buf
.append("Encapsulated: ", 14);
1440 // build HTTP request header, if any
1441 ICAP::Method m
= s
.method
;
1443 // to simplify, we could assume that request is always available
1446 if (ICAP::methodRespmod
== m
)
1447 encapsulateHead(buf
, "req-hdr", httpBuf
, request
);
1448 else if (ICAP::methodReqmod
== m
)
1449 encapsulateHead(buf
, "req-hdr", httpBuf
, virgin
.header
);
1452 if (ICAP::methodRespmod
== m
)
1453 if (const HttpMsg
*prime
= virgin
.header
)
1454 encapsulateHead(buf
, "res-hdr", httpBuf
, prime
);
1456 if (!virginBody
.expected())
1457 buf
.appendf("null-body=%d", (int) httpBuf
.contentSize());
1458 else if (ICAP::methodReqmod
== m
)
1459 buf
.appendf("req-body=%d", (int) httpBuf
.contentSize());
1461 buf
.appendf("res-body=%d", (int) httpBuf
.contentSize());
1463 buf
.append(ICAP::crlf
, 2); // terminate Encapsulated line
1465 if (preview
.enabled()) {
1466 buf
.appendf("Preview: %d\r\n", (int)preview
.ad());
1467 if (!virginBody
.expected()) // there is no body to preview
1468 finishNullOrEmptyBodyPreview(httpBuf
);
1471 makeAllowHeader(buf
);
1473 if (TheConfig
.send_client_ip
&& request
) {
1474 Ip::Address client_addr
;
1475 #if FOLLOW_X_FORWARDED_FOR
1476 if (TheConfig
.use_indirect_client
) {
1477 client_addr
= request
->indirect_client_addr
;
1480 client_addr
= request
->client_addr
;
1481 if (!client_addr
.isAnyAddr() && !client_addr
.isNoAddr())
1482 buf
.appendf("X-Client-IP: %s\r\n", client_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
1485 if (TheConfig
.send_username
&& request
)
1486 makeUsernameHeader(request
, buf
);
1488 // Adaptation::Config::metaHeaders
1489 for (auto h
: Adaptation::Config::metaHeaders
) {
1490 HttpRequest
*r
= virgin
.cause
?
1491 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
1494 HttpReply
*reply
= dynamic_cast<HttpReply
*>(virgin
.header
);
1497 if (h
->match(r
, reply
, alMaster
, matched
)) {
1498 buf
.append(h
->key().rawContent(), h
->key().length());
1499 buf
.append(": ", 2);
1500 buf
.append(matched
.rawContent(), matched
.length());
1501 buf
.append("\r\n", 2);
1502 Adaptation::History::Pointer ah
= request
->adaptHistory(false);
1504 if (ah
->metaHeaders
== NULL
)
1505 ah
->metaHeaders
= new NotePairs
;
1506 if (!ah
->metaHeaders
->hasPair(h
->key(), matched
))
1507 ah
->metaHeaders
->add(h
->key(), matched
);
1512 // fprintf(stderr, "%s\n", buf.content());
1514 buf
.append(ICAP::crlf
, 2); // terminate ICAP header
1516 // fill icapRequest for logging
1517 Must(icapRequest
->parseCharBuf(buf
.content(), buf
.contentSize()));
1519 // start ICAP request body with encapsulated HTTP headers
1520 buf
.append(httpBuf
.content(), httpBuf
.contentSize());
1525 // decides which Allow values to write and updates the request buffer
1526 void Adaptation::Icap::ModXact::makeAllowHeader(MemBuf
&buf
)
1528 const bool allow204in
= preview
.enabled(); // TODO: add shouldAllow204in()
1529 const bool allow204out
= state
.allowedPostview204
= shouldAllow204();
1530 const bool allow206in
= state
.allowedPreview206
= shouldAllow206in();
1531 const bool allow206out
= state
.allowedPostview206
= shouldAllow206out();
1532 const bool allowTrailers
= true; // TODO: make configurable
1534 debugs(93, 9, "Allows: " << allow204in
<< allow204out
<<
1535 allow206in
<< allow206out
<< allowTrailers
);
1537 const bool allow204
= allow204in
|| allow204out
;
1538 const bool allow206
= allow206in
|| allow206out
;
1540 if (!allow204
&& !allow206
&& !allowTrailers
)
1541 return; // nothing to do
1543 if (virginBody
.expected()) // if there is a virgin body, plan to send it
1544 virginBodySending
.plan();
1546 // writing Preview:... means we will honor 204 inside preview
1547 // writing Allow/204 means we will honor 204 outside preview
1548 // writing Allow:206 means we will honor 206 inside preview
1549 // writing Allow:204,206 means we will honor 206 outside preview
1550 if (allow204
|| allow206
|| allowTrailers
) {
1551 buf
.appendf("Allow: ");
1553 buf
.appendf("204, ");
1555 buf
.appendf("206, ");
1557 buf
.appendf("trailers");
1558 buf
.appendf("\r\n");
1562 void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest
*request
, MemBuf
&buf
)
1565 struct base64_encode_ctx ctx
;
1566 base64_encode_init(&ctx
);
1568 const char *value
= NULL
;
1569 if (request
->auth_user_request
!= NULL
) {
1570 value
= request
->auth_user_request
->username();
1571 } else if (request
->extacl_user
.size() > 0) {
1572 value
= request
->extacl_user
.termedBuf();
1576 if (TheConfig
.client_username_encode
) {
1577 uint8_t base64buf
[base64_encode_len(MAX_LOGIN_SZ
)];
1578 size_t resultLen
= base64_encode_update(&ctx
, base64buf
, strlen(value
), reinterpret_cast<const uint8_t*>(value
));
1579 resultLen
+= base64_encode_final(&ctx
, base64buf
+resultLen
);
1580 buf
.appendf("%s: %.*s\r\n", TheConfig
.client_username_header
, (int)resultLen
, base64buf
);
1582 buf
.appendf("%s: %s\r\n", TheConfig
.client_username_header
, value
);
1587 void Adaptation::Icap::ModXact::encapsulateHead(MemBuf
&icapBuf
, const char *section
, MemBuf
&httpBuf
, const HttpMsg
*head
)
1589 // update ICAP header
1590 icapBuf
.appendf("%s=%d, ", section
, (int) httpBuf
.contentSize());
1593 HttpMsg::Pointer headClone
;
1595 if (const HttpRequest
* old_request
= dynamic_cast<const HttpRequest
*>(head
)) {
1596 HttpRequest::Pointer
new_request(new HttpRequest
);
1597 // copy the requst-line details
1598 new_request
->method
= old_request
->method
;
1599 new_request
->url
= old_request
->url
;
1600 new_request
->http_ver
= old_request
->http_ver
;
1601 headClone
= new_request
.getRaw();
1602 } else if (const HttpReply
*old_reply
= dynamic_cast<const HttpReply
*>(head
)) {
1603 HttpReply::Pointer
new_reply(new HttpReply
);
1604 new_reply
->sline
= old_reply
->sline
;
1605 headClone
= new_reply
.getRaw();
1607 Must(headClone
!= NULL
);
1608 headClone
->inheritProperties(head
);
1610 HttpHeaderPos pos
= HttpHeaderInitPos
;
1611 HttpHeaderEntry
* p_head_entry
= NULL
;
1612 while (NULL
!= (p_head_entry
= head
->header
.getEntry(&pos
)) )
1613 headClone
->header
.addEntry(p_head_entry
->clone());
1617 // remove all hop-by-hop headers from the clone
1618 headClone
->header
.delById(Http::HdrType::PROXY_AUTHENTICATE
);
1619 headClone
->header
.removeHopByHopEntries();
1621 // pack polished HTTP header
1622 packHead(httpBuf
, headClone
.getRaw());
1624 // headClone unlocks and, hence, deletes the message we packed
1627 void Adaptation::Icap::ModXact::packHead(MemBuf
&httpBuf
, const HttpMsg
*head
)
1629 head
->packInto(&httpBuf
, true);
1632 // decides whether to offer a preview and calculates its size
1633 void Adaptation::Icap::ModXact::decideOnPreview()
1635 if (!TheConfig
.preview_enable
) {
1636 debugs(93, 5, HERE
<< "preview disabled by squid.conf");
1640 const SBuf
urlPath(virginRequest().url
.path());
1642 if (!service().wantsPreview(urlPath
, wantedSize
)) {
1643 debugs(93, 5, "should not offer preview for " << urlPath
);
1647 // we decided to do preview, now compute its size
1649 // cannot preview more than we can backup
1650 size_t ad
= min(wantedSize
, TheBackupLimit
);
1652 if (!virginBody
.expected())
1654 else if (virginBody
.knownSize())
1655 ad
= min(static_cast<uint64_t>(ad
), virginBody
.size()); // not more than we have
1657 debugs(93, 5, HERE
<< "should offer " << ad
<< "-byte preview " <<
1658 "(service wanted " << wantedSize
<< ")");
1661 Must(preview
.enabled());
1664 // decides whether to allow 204 responses
1665 bool Adaptation::Icap::ModXact::shouldAllow204()
1667 if (!service().allows204())
1670 return canBackupEverything();
1673 // decides whether to allow 206 responses in some mode
1674 bool Adaptation::Icap::ModXact::shouldAllow206any()
1676 return TheConfig
.allow206_enable
&& service().allows206() &&
1677 virginBody
.expected(); // no need for 206 without a body
1680 // decides whether to allow 206 responses in preview mode
1681 bool Adaptation::Icap::ModXact::shouldAllow206in()
1683 return shouldAllow206any() && preview
.enabled();
1686 // decides whether to allow 206 responses outside of preview
1687 bool Adaptation::Icap::ModXact::shouldAllow206out()
1689 return shouldAllow206any() && canBackupEverything();
1692 // used by shouldAllow204 and decideOnRetries
1693 bool Adaptation::Icap::ModXact::canBackupEverything() const
1695 if (!virginBody
.expected())
1696 return true; // no body means no problems with backup
1698 // if there is a body, check whether we can backup it all
1700 if (!virginBody
.knownSize())
1703 // or should we have a different backup limit?
1704 // note that '<' allows for 0-termination of the "full" backup buffer
1705 return virginBody
.size() < TheBackupLimit
;
1708 // Decide whether this transaction can be retried if pconn fails
1709 // Must be called after decideOnPreview and before openConnection()
1710 void Adaptation::Icap::ModXact::decideOnRetries()
1713 return; // no, already decided
1715 if (preview
.enabled())
1716 return; // yes, because preview provides enough guarantees
1718 if (canBackupEverything())
1719 return; // yes, because we can back everything up
1721 disableRetries(); // no, because we cannot back everything up
1724 // Normally, the body-writing code handles preview body. It can deal with
1725 // bodies of unexpected size, including those that turn out to be empty.
1726 // However, that code assumes that the body was expected and body control
1727 // structures were initialized. This is not the case when there is no body
1728 // or the body is known to be empty, because the virgin message will lack a
1729 // body_pipe. So we handle preview of null-body and zero-size bodies here.
1730 void Adaptation::Icap::ModXact::finishNullOrEmptyBodyPreview(MemBuf
&)
1732 Must(!virginBodyWriting
.active()); // one reason we handle it here
1733 Must(!virgin
.body_pipe
); // another reason we handle it here
1734 Must(!preview
.ad());
1736 // do not add last-chunk because our Encapsulated header says null-body
1737 // addLastRequestChunk(buf);
1738 preview
.wrote(0, true);
1740 Must(preview
.done());
1741 Must(preview
.ieof());
1744 void Adaptation::Icap::ModXact::fillPendingStatus(MemBuf
&buf
) const
1746 Adaptation::Icap::Xaction::fillPendingStatus(buf
);
1748 if (state
.serviceWaiting
)
1751 if (virgin
.body_pipe
!= NULL
)
1754 if (haveConnection() && !doneReading())
1757 if (!state
.doneWriting() && state
.writing
!= State::writingInit
)
1758 buf
.appendf("w(%d)", state
.writing
);
1760 if (preview
.enabled()) {
1761 if (!preview
.done())
1762 buf
.appendf("P(%d)", (int) preview
.debt());
1765 if (virginBodySending
.active())
1768 if (!state
.doneParsing() && state
.parsing
!= State::psIcapHeader
)
1769 buf
.appendf("p(%d)", state
.parsing
);
1771 if (!doneSending() && state
.sending
!= State::sendingUndecided
)
1772 buf
.appendf("S(%d)", state
.sending
);
1774 if (state
.readyForUob
)
1780 if (protectGroupBypass
)
1784 void Adaptation::Icap::ModXact::fillDoneStatus(MemBuf
&buf
) const
1786 Adaptation::Icap::Xaction::fillDoneStatus(buf
);
1788 if (!virgin
.body_pipe
)
1791 if (state
.doneWriting())
1794 if (preview
.enabled()) {
1796 buf
.appendf("P%s", preview
.ieof() ? "(ieof)" : "");
1802 if (state
.doneParsing())
1809 bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section
) const
1811 return icapReply
->header
.getByNameListMember("Encapsulated",
1812 section
, ',').size() > 0;
1815 // calculate whether there is a virgin HTTP body and
1816 // whether its expected size is known
1817 // TODO: rename because we do not just estimate
1818 void Adaptation::Icap::ModXact::estimateVirginBody()
1820 // note: lack of size info may disable previews and 204s
1822 HttpMsg
*msg
= virgin
.header
;
1825 HttpRequestMethod method
;
1828 method
= virgin
.cause
->method
;
1829 else if (HttpRequest
*req
= dynamic_cast<HttpRequest
*>(msg
))
1830 method
= req
->method
;
1832 method
= Http::METHOD_NONE
;
1835 // expectingBody returns true for zero-sized bodies, but we will not
1836 // get a pipe for that body, so we treat the message as bodyless
1837 if (method
!= Http::METHOD_NONE
&& msg
->expectingBody(method
, size
) && size
) {
1838 debugs(93, 6, HERE
<< "expects virgin body from " <<
1839 virgin
.body_pipe
<< "; size: " << size
);
1841 virginBody
.expect(size
);
1842 virginBodyWriting
.plan();
1844 // sign up as a body consumer
1845 Must(msg
->body_pipe
!= NULL
);
1846 Must(msg
->body_pipe
== virgin
.body_pipe
);
1847 Must(virgin
.body_pipe
->setConsumerIfNotLate(this));
1849 // make sure TheBackupLimit is in-sync with the buffer size
1850 Must(TheBackupLimit
<= static_cast<size_t>(msg
->body_pipe
->buf().max_capacity
));
1852 debugs(93, 6, HERE
<< "does not expect virgin body");
1853 Must(msg
->body_pipe
== NULL
);
1858 void Adaptation::Icap::ModXact::makeAdaptedBodyPipe(const char *what
)
1860 Must(!adapted
.body_pipe
);
1861 Must(!adapted
.header
->body_pipe
);
1862 adapted
.header
->body_pipe
= new BodyPipe(this);
1863 adapted
.body_pipe
= adapted
.header
->body_pipe
;
1864 debugs(93, 7, HERE
<< "will supply " << what
<< " via " <<
1865 adapted
.body_pipe
<< " pipe");
1868 // TODO: Move SizedEstimate and Preview elsewhere
1870 Adaptation::Icap::SizedEstimate::SizedEstimate()
1871 : theData(dtUnexpected
)
1874 void Adaptation::Icap::SizedEstimate::expect(int64_t aSize
)
1876 theData
= (aSize
>= 0) ? aSize
: (int64_t)dtUnknown
;
1879 bool Adaptation::Icap::SizedEstimate::expected() const
1881 return theData
!= dtUnexpected
;
1884 bool Adaptation::Icap::SizedEstimate::knownSize() const
1887 return theData
!= dtUnknown
;
1890 uint64_t Adaptation::Icap::SizedEstimate::size() const
1893 return static_cast<uint64_t>(theData
);
1896 Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided
)
1899 void Adaptation::Icap::VirginBodyAct::plan()
1902 Must(!theStart
); // not started
1903 theState
= stActive
;
1906 void Adaptation::Icap::VirginBodyAct::disable()
1908 theState
= stDisabled
;
1911 void Adaptation::Icap::VirginBodyAct::progress(size_t size
)
1914 #if SIZEOF_SIZE_T > 4
1915 /* always true for smaller size_t's */
1916 Must(static_cast<int64_t>(size
) >= 0);
1918 theStart
+= static_cast<int64_t>(size
);
1921 uint64_t Adaptation::Icap::VirginBodyAct::offset() const
1924 return static_cast<uint64_t>(theStart
);
1927 Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled
)
1930 void Adaptation::Icap::Preview::enable(size_t anAd
)
1932 // TODO: check for anAd not exceeding preview size limit
1935 theState
= stWriting
;
1938 bool Adaptation::Icap::Preview::enabled() const
1940 return theState
!= stDisabled
;
1943 size_t Adaptation::Icap::Preview::ad() const
1949 bool Adaptation::Icap::Preview::done() const
1952 return theState
>= stIeof
;
1955 bool Adaptation::Icap::Preview::ieof() const
1958 return theState
== stIeof
;
1961 size_t Adaptation::Icap::Preview::debt() const
1964 return done() ? 0 : (theAd
- theWritten
);
1967 void Adaptation::Icap::Preview::wrote(size_t size
, bool wroteEof
)
1973 Must(theWritten
<= theAd
);
1976 theState
= stIeof
; // written size is irrelevant
1977 else if (theWritten
>= theAd
)
1981 bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf
&mb
) const
1983 if (virgin
.header
== NULL
)
1986 virgin
.header
->firstLineBuf(mb
);
1991 void Adaptation::Icap::ModXact::detailError(int errDetail
)
1993 HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
1994 // if no adapted request, update virgin (and inherit its properties later)
1995 // TODO: make this and HttpRequest::detailError constant, like adaptHistory
1997 request
= const_cast<HttpRequest
*>(&virginRequest());
2000 request
->detailError(ERR_ICAP_FAILURE
, errDetail
);
2003 void Adaptation::Icap::ModXact::clearError()
2005 HttpRequest
*request
= dynamic_cast<HttpRequest
*>(adapted
.header
);
2006 // if no adapted request, update virgin (and inherit its properties later)
2008 request
= const_cast<HttpRequest
*>(&virginRequest());
2011 request
->clearError();
2014 void Adaptation::Icap::ModXact::updateSources()
2016 Must(adapted
.header
);
2017 adapted
.header
->sources
|= (service().cfg().connectionEncryption
? HttpMsg::srcIcaps
: HttpMsg::srcIcap
);
2020 /* Adaptation::Icap::ModXactLauncher */
2022 Adaptation::Icap::ModXactLauncher::ModXactLauncher(HttpMsg
*virginHeader
, HttpRequest
*virginCause
, AccessLogEntry::Pointer
&alp
, Adaptation::ServicePointer aService
):
2023 AsyncJob("Adaptation::Icap::ModXactLauncher"),
2024 Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", aService
),
2027 virgin
.setHeader(virginHeader
);
2028 virgin
.setCause(virginCause
);
2029 updateHistory(true);
2032 Adaptation::Icap::Xaction
*Adaptation::Icap::ModXactLauncher::createXaction()
2034 Adaptation::Icap::ServiceRep::Pointer s
=
2035 dynamic_cast<Adaptation::Icap::ServiceRep
*>(theService
.getRaw());
2037 return new Adaptation::Icap::ModXact(virgin
.header
, virgin
.cause
, al
, s
);
2040 void Adaptation::Icap::ModXactLauncher::swanSong()
2042 debugs(93, 5, HERE
<< "swan sings");
2043 updateHistory(false);
2044 Adaptation::Icap::Launcher::swanSong();
2047 void Adaptation::Icap::ModXactLauncher::updateHistory(bool doStart
)
2049 HttpRequest
*r
= virgin
.cause
?
2050 virgin
.cause
: dynamic_cast<HttpRequest
*>(virgin
.header
);
2052 // r should never be NULL but we play safe; TODO: add Should()
2054 Adaptation::Icap::History::Pointer h
= r
->icapHistory();
2057 h
->start("ICAPModXactLauncher");
2059 h
->stop("ICAPModXactLauncher");
2064 bool Adaptation::Icap::TrailerParser::parse(const char *buf
, int len
, int atEnd
, Http::StatusCode
*error
) {
2065 const int parsed
= trailer
.parse(buf
, len
, atEnd
, hdr_sz
);
2067 *error
= Http::scInvalidHeader
; // TODO: should we add a new Http::scInvalidTrailer?