]> git.ipfire.org Git - thirdparty/squid.git/blame - src/adaptation/icap/ModXact.cc
Moved AccessLogEntry.headers.adapt_last to AccessLogEntry.adapt.last_meta
[thirdparty/squid.git] / src / adaptation / icap / ModXact.cc
CommitLineData
774c051c 1/*
507d0a78 2 * DEBUG: section 93 ICAP (RFC 3507) Client
774c051c 3 */
4
5#include "squid.h"
3d93a84d
AJ
6#include "AccessLogEntry.h"
7#include "adaptation/History.h"
8#include "adaptation/icap/Client.h"
9#include "adaptation/icap/Config.h"
10#include "adaptation/icap/History.h"
11#include "adaptation/icap/Launcher.h"
12#include "adaptation/icap/ModXact.h"
13#include "adaptation/icap/ServiceRep.h"
14#include "adaptation/Initiator.h"
15#include "auth/UserRequest.h"
16#include "base/TextException.h"
25f98340 17#include "base64.h"
3d93a84d 18#include "ChunkedCodingParser.h"
774c051c 19#include "comm.h"
5f8252d2 20#include "HttpMsg.h"
774c051c 21#include "HttpRequest.h"
22#include "HttpReply.h"
985c86bc 23#include "SquidTime.h"
64b66b76 24#include "err_detail_type.h"
774c051c 25
26// flow and terminology:
27// HTTP| --> receive --> encode --> write --> |network
28// end | <-- send <-- parse <-- read <-- |end
29
774c051c 30// TODO: replace gotEncapsulated() with something faster; we call it often
31
26cc52cb
AR
32CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap, ModXact);
33CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap, ModXactLauncher);
774c051c 34
5f8252d2 35static const size_t TheBackupLimit = BodyPipe::MaxCapacity;
774c051c 36
26cc52cb 37Adaptation::Icap::ModXact::State::State()
774c051c 38{
09bfe95f 39 memset(this, 0, sizeof(*this));
774c051c 40}
41
4299f876 42Adaptation::Icap::ModXact::ModXact(HttpMsg *virginHeader,
4cb2536f 43 HttpRequest *virginCause, Adaptation::Icap::ServiceRep::Pointer &aService):
26cc52cb 44 AsyncJob("Adaptation::Icap::ModXact"),
4299f876 45 Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", aService),
9e008dda
AJ
46 virginConsumed(0),
47 bodyParser(NULL),
3ff65596 48 canStartBypass(false), // too early
a22e6cd3 49 protectGroupBypass(true),
bae917ac
CT
50 replyHttpHeaderSize(-1),
51 replyHttpBodySize(-1),
3ff65596 52 adaptHistoryId(-1)
774c051c 53{
5f8252d2 54 assert(virginHeader);
774c051c 55
5f8252d2 56 virgin.setHeader(virginHeader); // sets virgin.body_pipe if needed
57 virgin.setCause(virginCause); // may be NULL
774c051c 58
5f8252d2 59 // adapted header and body are initialized when we parse them
774c051c 60
26cc52cb 61 // writing and reading ends are handled by Adaptation::Icap::Xaction
774c051c 62
63 // encoding
64 // nothing to do because we are using temporary buffers
65
3ff65596 66 // parsing; TODO: do not set until we parse, see ICAPOptXact
c7d51c86 67 icapReply = new HttpReply;
774c051c 68 icapReply->protoPrefix = "ICAP/"; // TODO: make an IcapReply class?
69
192378eb 70 debugs(93,7, HERE << "initialized." << status());
774c051c 71}
72
5f8252d2 73// initiator wants us to start
26cc52cb 74void Adaptation::Icap::ModXact::start()
774c051c 75{
26cc52cb 76 Adaptation::Icap::Xaction::start();
774c051c 77
3ff65596 78 // reserve an adaptation history slot (attempts are known at this time)
a22e6cd3 79 Adaptation::History::Pointer ah = virginRequest().adaptLogHistory();
3ff65596
AR
80 if (ah != NULL)
81 adaptHistoryId = ah->recordXactStart(service().cfg().key, icap_tr_start, attempts > 1);
82
774c051c 83 estimateVirginBody(); // before virgin disappears!
84
0bef8dd7 85 canStartBypass = service().cfg().bypass;
478cfe99 86
774c051c 87 // it is an ICAP violation to send request to a service w/o known OPTIONS
88
89 if (service().up())
90 startWriting();
91 else
92 waitForService();
774c051c 93}
94
26cc52cb 95void Adaptation::Icap::ModXact::waitForService()
774c051c 96{
97 Must(!state.serviceWaiting);
192378eb 98 debugs(93, 7, HERE << "will wait for the ICAP service" << status());
4299f876
AR
99 typedef NullaryMemFunT<ModXact> Dialer;
100 AsyncCall::Pointer call = JobCallback(93,5,
4cb2536f 101 Dialer, this, Adaptation::Icap::ModXact::noteServiceReady);
bd7f2ede 102 service().callWhenReady(call);
c7d51c86 103 state.serviceWaiting = true; // after callWhenReady() which may throw
774c051c 104}
105
26cc52cb 106void Adaptation::Icap::ModXact::noteServiceReady()
774c051c 107{
774c051c 108 Must(state.serviceWaiting);
109 state.serviceWaiting = false;
c99de607 110
c824c43b 111 if (service().up()) {
112 startWriting();
113 } else {
114 disableRetries();
3ff65596 115 disableRepeats("ICAP service is unusable");
478cfe99 116 throw TexcHere("ICAP service is unusable");
c824c43b 117 }
774c051c 118}
119
26cc52cb 120void Adaptation::Icap::ModXact::startWriting()
774c051c 121{
774c051c 122 state.writing = State::writingConnect;
c824c43b 123
124 decideOnPreview(); // must be decided before we decideOnRetries
125 decideOnRetries();
126
774c051c 127 openConnection();
774c051c 128}
129
130// connection with the ICAP service established
26cc52cb 131void Adaptation::Icap::ModXact::handleCommConnected()
774c051c 132{
133 Must(state.writing == State::writingConnect);
134
135 startReading(); // wait for early errors from the ICAP server
136
137 MemBuf requestBuf;
138 requestBuf.init();
139
140 makeRequestHeaders(requestBuf);
192378eb 141 debugs(93, 9, HERE << "will write" << status() << ":\n" <<
774c051c 142 (requestBuf.terminate(), requestBuf.content()));
143
144 // write headers
145 state.writing = State::writingHeaders;
3ff65596 146 icap_tio_start = current_time;
774c051c 147 scheduleWrite(requestBuf);
148}
149
26cc52cb 150void Adaptation::Icap::ModXact::handleCommWrote(size_t sz)
774c051c 151{
b107a5a5 152 debugs(93, 5, HERE << "Wrote " << sz << " bytes");
153
774c051c 154 if (state.writing == State::writingHeaders)
155 handleCommWroteHeaders();
156 else
157 handleCommWroteBody();
158}
159
26cc52cb 160void Adaptation::Icap::ModXact::handleCommWroteHeaders()
774c051c 161{
162 Must(state.writing == State::writingHeaders);
163
5f8252d2 164 // determine next step
23e05fb1
AR
165 if (preview.enabled()) {
166 if (preview.done())
167 decideWritingAfterPreview("zero-size");
168 else
169 state.writing = State::writingPreview;
170 } else if (virginBody.expected()) {
e1381638 171 state.writing = State::writingPrime;
23e05fb1 172 } else {
e1381638
AJ
173 stopWriting(true);
174 return;
175 }
5f8252d2 176
177 writeMore();
774c051c 178}
179
26cc52cb 180void Adaptation::Icap::ModXact::writeMore()
774c051c 181{
5f8252d2 182 debugs(93, 5, HERE << "checking whether to write more" << status());
183
bd7f2ede 184 if (writer != NULL) // already writing something
774c051c 185 return;
186
187 switch (state.writing) {
188
189 case State::writingInit: // waiting for service OPTIONS
190 Must(state.serviceWaiting);
191
192 case State::writingConnect: // waiting for the connection to establish
193
194 case State::writingHeaders: // waiting for the headers to be written
195
196 case State::writingPaused: // waiting for the ICAP server response
197
c99de607 198 case State::writingReallyDone: // nothing more to write
199 return;
200
201 case State::writingAlmostDone: // was waiting for the last write
202 stopWriting(false);
774c051c 203 return;
204
205 case State::writingPreview:
5f8252d2 206 writePreviewBody();
774c051c 207 return;
208
209 case State::writingPrime:
210 writePrimeBody();
211 return;
212
213 default:
26cc52cb 214 throw TexcHere("Adaptation::Icap::ModXact in bad writing state");
774c051c 215 }
216}
217
26cc52cb 218void Adaptation::Icap::ModXact::writePreviewBody()
774c051c 219{
5f8252d2 220 debugs(93, 8, HERE << "will write Preview body from " <<
9e008dda 221 virgin.body_pipe << status());
774c051c 222 Must(state.writing == State::writingPreview);
5f8252d2 223 Must(virgin.body_pipe != NULL);
774c051c 224
5f8252d2 225 const size_t sizeMax = (size_t)virgin.body_pipe->buf().contentSize();
d85c3078 226 const size_t size = min(preview.debt(), sizeMax);
774c051c 227 writeSomeBody("preview body", size);
228
229 // change state once preview is written
230
23e05fb1
AR
231 if (preview.done())
232 decideWritingAfterPreview("body");
233}
774c051c 234
23e05fb1
AR
235/// determine state.writing after we wrote the entire preview
236void Adaptation::Icap::ModXact::decideWritingAfterPreview(const char *kind)
237{
238 if (preview.ieof()) // nothing more to write
239 stopWriting(true);
e81d21e0 240 else if (state.parsing == State::psIcapHeader) // did not get a reply yet
23e05fb1
AR
241 state.writing = State::writingPaused; // wait for the ICAP server reply
242 else
243 stopWriting(true); // ICAP server reply implies no post-preview writing
244
245 debugs(93, 6, HERE << "decided on writing after " << kind << " preview" <<
e81d21e0 246 status());
774c051c 247}
248
26cc52cb 249void Adaptation::Icap::ModXact::writePrimeBody()
774c051c 250{
251 Must(state.writing == State::writingPrime);
5f8252d2 252 Must(virginBodyWriting.active());
774c051c 253
5f8252d2 254 const size_t size = (size_t)virgin.body_pipe->buf().contentSize();
774c051c 255 writeSomeBody("prime virgin body", size);
256
5f8252d2 257 if (virginBodyEndReached(virginBodyWriting)) {
258 debugs(93, 5, HERE << "wrote entire body");
c99de607 259 stopWriting(true);
b107a5a5 260 }
774c051c 261}
262
26cc52cb 263void Adaptation::Icap::ModXact::writeSomeBody(const char *label, size_t size)
774c051c 264{
c99de607 265 Must(!writer && state.writing < state.writingAlmostDone);
5f8252d2 266 Must(virgin.body_pipe != NULL);
12f4b710 267 debugs(93, 8, HERE << "will write up to " << size << " bytes of " <<
774c051c 268 label);
269
270 MemBuf writeBuf; // TODO: suggest a min size based on size and lastChunk
271
272 writeBuf.init(); // note: we assume that last-chunk will fit
273
5f8252d2 274 const size_t writableSize = virginContentSize(virginBodyWriting);
d85c3078 275 const size_t chunkSize = min(writableSize, size);
774c051c 276
277 if (chunkSize) {
12f4b710 278 debugs(93, 7, HERE << "will write " << chunkSize <<
774c051c 279 "-byte chunk of " << label);
5f8252d2 280
281 openChunk(writeBuf, chunkSize, false);
282 writeBuf.append(virginContentData(virginBodyWriting), chunkSize);
283 closeChunk(writeBuf);
284
285 virginBodyWriting.progress(chunkSize);
286 virginConsume();
774c051c 287 } else {
192378eb 288 debugs(93, 7, HERE << "has no writable " << label << " content");
774c051c 289 }
290
5f8252d2 291 const bool wroteEof = virginBodyEndReached(virginBodyWriting);
292 bool lastChunk = wroteEof;
293 if (state.writing == State::writingPreview) {
294 preview.wrote(chunkSize, wroteEof); // even if wrote nothing
295 lastChunk = lastChunk || preview.done();
296 }
774c051c 297
5f8252d2 298 if (lastChunk) {
12f4b710 299 debugs(93, 8, HERE << "will write last-chunk of " << label);
774c051c 300 addLastRequestChunk(writeBuf);
301 }
302
12f4b710 303 debugs(93, 7, HERE << "will write " << writeBuf.contentSize()
774c051c 304 << " raw bytes of " << label);
305
306 if (writeBuf.hasContent()) {
307 scheduleWrite(writeBuf); // comm will free the chunk
308 } else {
309 writeBuf.clean();
310 }
311}
312
26cc52cb 313void Adaptation::Icap::ModXact::addLastRequestChunk(MemBuf &buf)
774c051c 314{
c99de607 315 const bool ieof = state.writing == State::writingPreview && preview.ieof();
316 openChunk(buf, 0, ieof);
317 closeChunk(buf);
774c051c 318}
319
26cc52cb 320void Adaptation::Icap::ModXact::openChunk(MemBuf &buf, size_t chunkSize, bool ieof)
774c051c 321{
c99de607 322 buf.Printf((ieof ? "%x; ieof\r\n" : "%x\r\n"), (int) chunkSize);
774c051c 323}
324
26cc52cb 325void Adaptation::Icap::ModXact::closeChunk(MemBuf &buf)
774c051c 326{
774c051c 327 buf.append(ICAP::crlf, 2); // chunk-terminating CRLF
328}
329
3ff65596
AR
330const HttpRequest &Adaptation::Icap::ModXact::virginRequest() const
331{
332 const HttpRequest *request = virgin.cause ?
e1381638 333 virgin.cause : dynamic_cast<const HttpRequest*>(virgin.header);
3ff65596
AR
334 Must(request);
335 return *request;
336}
337
5f8252d2 338// did the activity reached the end of the virgin body?
26cc52cb 339bool Adaptation::Icap::ModXact::virginBodyEndReached(const Adaptation::Icap::VirginBodyAct &act) const
5f8252d2 340{
9e008dda 341 return
5f8252d2 342 !act.active() || // did all (assuming it was originally planned)
343 !virgin.body_pipe->expectMoreAfter(act.offset()); // wont have more
344}
345
346// the size of buffered virgin body data available for the specified activity
347// if this size is zero, we may be done or may be waiting for more data
26cc52cb 348size_t Adaptation::Icap::ModXact::virginContentSize(const Adaptation::Icap::VirginBodyAct &act) const
774c051c 349{
5f8252d2 350 Must(act.active());
351 // asbolute start of unprocessed data
b0365bd9 352 const uint64_t dataStart = act.offset();
5f8252d2 353 // absolute end of buffered data
b0365bd9
FC
354 const uint64_t dataEnd = virginConsumed + virgin.body_pipe->buf().contentSize();
355 Must(virginConsumed <= dataStart && dataStart <= dataEnd);
356 return static_cast<size_t>(dataEnd - dataStart);
774c051c 357}
358
5f8252d2 359// pointer to buffered virgin body data available for the specified activity
26cc52cb 360const char *Adaptation::Icap::ModXact::virginContentData(const Adaptation::Icap::VirginBodyAct &act) const
774c051c 361{
5f8252d2 362 Must(act.active());
b0365bd9
FC
363 const uint64_t dataStart = act.offset();
364 Must(virginConsumed <= dataStart);
365 return virgin.body_pipe->buf().content() + static_cast<size_t>(dataStart-virginConsumed);
774c051c 366}
367
26cc52cb 368void Adaptation::Icap::ModXact::virginConsume()
774c051c 369{
3ff65596 370 debugs(93, 9, HERE << "consumption guards: " << !virgin.body_pipe << isRetriable <<
a22e6cd3 371 isRepeatable << canStartBypass << protectGroupBypass);
478cfe99 372
5f8252d2 373 if (!virgin.body_pipe)
c824c43b 374 return; // nothing to consume
375
376 if (isRetriable)
377 return; // do not consume if we may have to retry later
5f8252d2 378
379 BodyPipe &bp = *virgin.body_pipe;
a22e6cd3 380 const bool wantToPostpone = isRepeatable || canStartBypass || protectGroupBypass;
478cfe99 381
382 // Why > 2? HttpState does not use the last bytes in the buffer
9e008dda 383 // because delayAwareRead() is arguably broken. See
478cfe99 384 // HttpStateData::maybeReadVirginBody for more details.
3ff65596 385 if (wantToPostpone && bp.buf().spaceSize() > 2) {
478cfe99 386 // Postponing may increase memory footprint and slow the HTTP side
9e008dda 387 // down. Not postponing may increase the number of ICAP errors
478cfe99 388 // if the ICAP service fails. We may also use "potential" space to
389 // postpone more aggressively. Should the trade-off be configurable?
390 debugs(93, 8, HERE << "postponing consumption from " << bp.status());
391 return;
392 }
393
5f8252d2 394 const size_t have = static_cast<size_t>(bp.buf().contentSize());
47f6e231 395 const uint64_t end = virginConsumed + have;
396 uint64_t offset = end;
774c051c 397
478cfe99 398 debugs(93, 9, HERE << "max virgin consumption offset=" << offset <<
9e008dda
AJ
399 " acts " << virginBodyWriting.active() << virginBodySending.active() <<
400 " consumed=" << virginConsumed <<
401 " from " << virgin.body_pipe->status());
478cfe99 402
5f8252d2 403 if (virginBodyWriting.active())
d85c3078 404 offset = min(virginBodyWriting.offset(), offset);
774c051c 405
5f8252d2 406 if (virginBodySending.active())
d85c3078 407 offset = min(virginBodySending.offset(), offset);
774c051c 408
409 Must(virginConsumed <= offset && offset <= end);
410
47f6e231 411 if (const size_t size = static_cast<size_t>(offset - virginConsumed)) {
b107a5a5 412 debugs(93, 8, HERE << "consuming " << size << " out of " << have <<
774c051c 413 " virgin body bytes");
5f8252d2 414 bp.consume(size);
774c051c 415 virginConsumed += size;
c824c43b 416 Must(!isRetriable); // or we should not be consuming
3ff65596 417 disableRepeats("consumed content");
a22e6cd3 418 disableBypass("consumed content", true);
774c051c 419 }
420}
421
26cc52cb 422void Adaptation::Icap::ModXact::handleCommWroteBody()
774c051c 423{
424 writeMore();
425}
426
c99de607 427// Called when we do not expect to call comm_write anymore.
428// We may have a pending write though.
429// If stopping nicely, we will just wait for that pending write, if any.
26cc52cb 430void Adaptation::Icap::ModXact::stopWriting(bool nicely)
774c051c 431{
c99de607 432 if (state.writing == State::writingReallyDone)
774c051c 433 return;
434
bd7f2ede 435 if (writer != NULL) {
c99de607 436 if (nicely) {
5f8252d2 437 debugs(93, 7, HERE << "will wait for the last write" << status());
c99de607 438 state.writing = State::writingAlmostDone; // may already be set
5f8252d2 439 checkConsuming();
c99de607 440 return;
441 }
4932ad93 442 debugs(93, 3, HERE << "will NOT wait for the last write" << status());
774c051c 443
c99de607 444 // Comm does not have an interface to clear the writer callback nicely,
445 // but without clearing the writer we cannot recycle the connection.
446 // We prevent connection reuse and hope that we can handle a callback
5f8252d2 447 // call at any time, usually in the middle of the destruction sequence!
448 // Somebody should add comm_remove_write_handler() to comm API.
c99de607 449 reuseConnection = false;
478cfe99 450 ignoreLastWrite = true;
c99de607 451 }
452
5f8252d2 453 debugs(93, 7, HERE << "will no longer write" << status());
5f8252d2 454 if (virginBodyWriting.active()) {
455 virginBodyWriting.disable();
456 virginConsume();
457 }
478cfe99 458 state.writing = State::writingReallyDone;
459 checkConsuming();
774c051c 460}
461
26cc52cb 462void Adaptation::Icap::ModXact::stopBackup()
774c051c 463{
5f8252d2 464 if (!virginBodySending.active())
774c051c 465 return;
466
192378eb 467 debugs(93, 7, HERE << "will no longer backup" << status());
5f8252d2 468 virginBodySending.disable();
774c051c 469 virginConsume();
470}
471
26cc52cb 472bool Adaptation::Icap::ModXact::doneAll() const
774c051c 473{
26cc52cb 474 return Adaptation::Icap::Xaction::doneAll() && !state.serviceWaiting &&
5f8252d2 475 doneSending() &&
774c051c 476 doneReading() && state.doneWriting();
477}
478
26cc52cb 479void Adaptation::Icap::ModXact::startReading()
774c051c 480{
481 Must(connection >= 0);
482 Must(!reader);
5f8252d2 483 Must(!adapted.header);
484 Must(!adapted.body_pipe);
774c051c 485
486 // we use the same buffer for headers and body and then consume headers
487 readMore();
488}
489
26cc52cb 490void Adaptation::Icap::ModXact::readMore()
774c051c 491{
bd7f2ede 492 if (reader != NULL || doneReading()) {
c99de607 493 debugs(93,3,HERE << "returning from readMore because reader or doneReading()");
774c051c 494 return;
3b299123 495 }
774c051c 496
497 // do not fill readBuf if we have no space to store the result
5f8252d2 498 if (adapted.body_pipe != NULL &&
9e008dda 499 !adapted.body_pipe->buf().hasPotentialSpace()) {
5f8252d2 500 debugs(93,3,HERE << "not reading because ICAP reply pipe is full");
774c051c 501 return;
3b299123 502 }
774c051c 503
504 if (readBuf.hasSpace())
505 scheduleRead();
3b299123 506 else
c99de607 507 debugs(93,3,HERE << "nothing to do because !readBuf.hasSpace()");
774c051c 508}
509
510// comm module read a portion of the ICAP response for us
26cc52cb 511void Adaptation::Icap::ModXact::handleCommRead(size_t)
774c051c 512{
513 Must(!state.doneParsing());
3ff65596 514 icap_tio_finish = current_time;
774c051c 515 parseMore();
516 readMore();
517}
518
26cc52cb 519void Adaptation::Icap::ModXact::echoMore()
774c051c 520{
521 Must(state.sending == State::sendingVirgin);
5f8252d2 522 Must(adapted.body_pipe != NULL);
523 Must(virginBodySending.active());
524
525 const size_t sizeMax = virginContentSize(virginBodySending);
526 debugs(93,5, HERE << "will echo up to " << sizeMax << " bytes from " <<
9e008dda 527 virgin.body_pipe->status());
5f8252d2 528 debugs(93,5, HERE << "will echo up to " << sizeMax << " bytes to " <<
9e008dda 529 adapted.body_pipe->status());
5f8252d2 530
531 if (sizeMax > 0) {
532 const size_t size = adapted.body_pipe->putMoreData(virginContentData(virginBodySending), sizeMax);
533 debugs(93,5, HERE << "echoed " << size << " out of " << sizeMax <<
9e008dda 534 " bytes");
5f8252d2 535 virginBodySending.progress(size);
3ff65596 536 disableRepeats("echoed content");
a22e6cd3
AR
537 disableBypass("echoed content", true);
538 virginConsume();
774c051c 539 }
540
5f8252d2 541 if (virginBodyEndReached(virginBodySending)) {
192378eb 542 debugs(93, 5, HERE << "echoed all" << status());
774c051c 543 stopSending(true);
544 } else {
192378eb 545 debugs(93, 5, HERE << "has " <<
9e008dda
AJ
546 virgin.body_pipe->buf().contentSize() << " bytes " <<
547 "and expects more to echo" << status());
5f8252d2 548 // TODO: timeout if virgin or adapted pipes are broken
774c051c 549 }
550}
551
26cc52cb 552bool Adaptation::Icap::ModXact::doneSending() const
774c051c 553{
774c051c 554 return state.sending == State::sendingDone;
555}
556
478cfe99 557// stop (or do not start) sending adapted message body
26cc52cb 558void Adaptation::Icap::ModXact::stopSending(bool nicely)
774c051c 559{
3ff65596 560 debugs(93, 7, HERE << "Enter stop sending ");
774c051c 561 if (doneSending())
562 return;
3ff65596 563 debugs(93, 7, HERE << "Proceed with stop sending ");
774c051c 564
565 if (state.sending != State::sendingUndecided) {
192378eb 566 debugs(93, 7, HERE << "will no longer send" << status());
5f8252d2 567 if (adapted.body_pipe != NULL) {
568 virginBodySending.disable();
569 // we may leave debts if we were echoing and the virgin
570 // body_pipe got exhausted before we echoed all planned bytes
571 const bool leftDebts = adapted.body_pipe->needsMoreData();
572 stopProducingFor(adapted.body_pipe, nicely && !leftDebts);
573 }
774c051c 574 } else {
192378eb 575 debugs(93, 7, HERE << "will not start sending" << status());
5f8252d2 576 Must(!adapted.body_pipe);
774c051c 577 }
578
579 state.sending = State::sendingDone;
5f8252d2 580 checkConsuming();
774c051c 581}
582
5f8252d2 583// should be called after certain state.writing or state.sending changes
26cc52cb 584void Adaptation::Icap::ModXact::checkConsuming()
774c051c 585{
5f8252d2 586 // quit if we already stopped or are still using the pipe
587 if (!virgin.body_pipe || !state.doneConsumingVirgin())
774c051c 588 return;
589
5f8252d2 590 debugs(93, 7, HERE << "will stop consuming" << status());
591 stopConsumingFrom(virgin.body_pipe);
774c051c 592}
593
26cc52cb 594void Adaptation::Icap::ModXact::parseMore()
774c051c 595{
aa761e5f 596 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " bytes to parse" <<
774c051c 597 status());
d5cfacfb 598 debugs(93, 5, HERE << "\n" << readBuf.content());
774c051c 599
600 if (state.parsingHeaders())
601 parseHeaders();
602
603 if (state.parsing == State::psBody)
604 parseBody();
605}
606
26cc52cb 607void Adaptation::Icap::ModXact::callException(const std::exception &e)
478cfe99 608{
609 if (!canStartBypass || isRetriable) {
64b66b76
CT
610 if (!isRetriable) {
611 if (const TextException *te = dynamic_cast<const TextException *>(&e))
612 detailError(ERR_DETAIL_EXCEPTION_START + te->id());
613 else
614 detailError(ERR_DETAIL_EXCEPTION_OTHER);
615 }
26cc52cb 616 Adaptation::Icap::Xaction::callException(e);
478cfe99 617 return;
618 }
619
620 try {
192378eb 621 debugs(93, 3, HERE << "bypassing " << inCall << " exception: " <<
af6a12ee 622 e.what() << ' ' << status());
478cfe99 623 bypassFailure();
64b66b76
CT
624 } catch (const TextException &bypassTe) {
625 detailError(ERR_DETAIL_EXCEPTION_START + bypassTe.id());
626 Adaptation::Icap::Xaction::callException(bypassTe);
9e008dda 627 } catch (const std::exception &bypassE) {
64b66b76 628 detailError(ERR_DETAIL_EXCEPTION_OTHER);
26cc52cb 629 Adaptation::Icap::Xaction::callException(bypassE);
478cfe99 630 }
631}
632
26cc52cb 633void Adaptation::Icap::ModXact::bypassFailure()
478cfe99 634{
a22e6cd3 635 disableBypass("already started to bypass", false);
478cfe99 636
637 Must(!isRetriable); // or we should not be bypassing
3ff65596 638 // TODO: should the same be enforced for isRepeatable? Check icap_repeat??
478cfe99 639
640 prepEchoing();
641
642 startSending();
643
644 // end all activities associated with the ICAP server
645
646 stopParsing();
647
648 stopWriting(true); // or should we force it?
649 if (connection >= 0) {
650 reuseConnection = false; // be conservative
651 cancelRead(); // may not work; and we cannot stop connecting either
652 if (!doneWithIo())
192378eb 653 debugs(93, 7, HERE << "Warning: bypass failed to stop I/O" << status());
478cfe99 654 }
61cb3565
AR
655
656 service().noteFailure(); // we are bypassing, but this is still a failure
478cfe99 657}
658
a22e6cd3 659void Adaptation::Icap::ModXact::disableBypass(const char *reason, bool includingGroupBypass)
478cfe99 660{
661 if (canStartBypass) {
662 debugs(93,7, HERE << "will never start bypass because " << reason);
663 canStartBypass = false;
664 }
a22e6cd3
AR
665 if (protectGroupBypass && includingGroupBypass) {
666 debugs(93,7, HERE << "not protecting group bypass because " << reason);
667 protectGroupBypass = false;
668 }
478cfe99 669}
670
671
672
774c051c 673// note that allocation for echoing is done in handle204NoContent()
26cc52cb 674void Adaptation::Icap::ModXact::maybeAllocateHttpMsg()
774c051c 675{
5f8252d2 676 if (adapted.header) // already allocated
774c051c 677 return;
678
679 if (gotEncapsulated("res-hdr")) {
5f8252d2 680 adapted.setHeader(new HttpReply);
3ff65596 681 setOutcome(service().cfg().method == ICAP::methodReqmod ?
e1381638 682 xoSatisfied : xoModified);
774c051c 683 } else if (gotEncapsulated("req-hdr")) {
5f8252d2 684 adapted.setHeader(new HttpRequest);
3ff65596 685 setOutcome(xoModified);
774c051c 686 } else
687 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
688}
689
26cc52cb 690void Adaptation::Icap::ModXact::parseHeaders()
774c051c 691{
692 Must(state.parsingHeaders());
693
b107a5a5 694 if (state.parsing == State::psIcapHeader) {
695 debugs(93, 5, HERE << "parse ICAP headers");
774c051c 696 parseIcapHead();
b107a5a5 697 }
774c051c 698
b107a5a5 699 if (state.parsing == State::psHttpHeader) {
700 debugs(93, 5, HERE << "parse HTTP headers");
774c051c 701 parseHttpHead();
b107a5a5 702 }
774c051c 703
704 if (state.parsingHeaders()) { // need more data
705 Must(mayReadMore());
706 return;
707 }
708
478cfe99 709 startSending();
710}
711
712// called after parsing all headers or when bypassing an exception
26cc52cb 713void Adaptation::Icap::ModXact::startSending()
478cfe99 714{
3ff65596 715 disableRepeats("sent headers");
a22e6cd3 716 disableBypass("sent headers", true);
3af10ac0 717 sendAnswer(Answer::Forward(adapted.header));
774c051c 718
719 if (state.sending == State::sendingVirgin)
720 echoMore();
721}
722
26cc52cb 723void Adaptation::Icap::ModXact::parseIcapHead()
774c051c 724{
725 Must(state.sending == State::sendingUndecided);
726
727 if (!parseHead(icapReply))
728 return;
729
fc764d26 730 if (httpHeaderHasConnDir(&icapReply->header, "close")) {
731 debugs(93, 5, HERE << "found connection close");
732 reuseConnection = false;
733 }
734
774c051c 735 switch (icapReply->sline.status) {
736
737 case 100:
738 handle100Continue();
739 break;
740
741 case 200:
5bd21e1d 742 case 201: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
b559db5d 743
744 if (!validate200Ok()) {
745 throw TexcHere("Invalid ICAP Response");
746 } else {
747 handle200Ok();
748 }
749
774c051c 750 break;
751
752 case 204:
753 handle204NoContent();
754 break;
755
83c51da9
CT
756 case 206:
757 handle206PartialContent();
758 break;
759
774c051c 760 default:
b559db5d 761 debugs(93, 5, HERE << "ICAP status " << icapReply->sline.status);
774c051c 762 handleUnknownScode();
763 break;
764 }
765
3ff65596
AR
766 const HttpRequest *request = dynamic_cast<HttpRequest*>(adapted.header);
767 if (!request)
768 request = &virginRequest();
769
770 // update the cross-transactional database if needed (all status codes!)
771 if (const char *xxName = Adaptation::Config::masterx_shared_name) {
a22e6cd3 772 Adaptation::History::Pointer ah = request->adaptHistory(true);
5038f9d8 773 if (ah != NULL) { // TODO: reorder checks to avoid creating history
3ff65596
AR
774 const String val = icapReply->header.getByName(xxName);
775 if (val.size() > 0) // XXX: HttpHeader lacks empty value detection
776 ah->updateXxRecord(xxName, val);
777 }
778 }
779
a22e6cd3
AR
780 // update the adaptation plan if needed (all status codes!)
781 if (service().cfg().routing) {
782 String services;
783 if (icapReply->header.getList(HDR_X_NEXT_SERVICES, &services)) {
784 Adaptation::History::Pointer ah = request->adaptHistory(true);
785 if (ah != NULL)
786 ah->updateNextServices(services);
787 }
788 } // TODO: else warn (occasionally!) if we got HDR_X_NEXT_SERVICES
789
3ff65596
AR
790 // We need to store received ICAP headers for <icapLastHeader logformat option.
791 // If we already have stored headers from previous ICAP transaction related to this
792 // request, old headers will be replaced with the new one.
e1381638 793
5038f9d8
AR
794 Adaptation::History::Pointer ah = request->adaptLogHistory();
795 if (ah != NULL)
796 ah->recordMeta(&icapReply->header);
3ff65596 797
774c051c 798 // handle100Continue() manages state.writing on its own.
799 // Non-100 status means the server needs no postPreview data from us.
800 if (state.writing == State::writingPaused)
c99de607 801 stopWriting(true);
774c051c 802}
803
26cc52cb 804bool Adaptation::Icap::ModXact::validate200Ok()
b559db5d 805{
0bef8dd7 806 if (ICAP::methodRespmod == service().cfg().method) {
b559db5d 807 if (!gotEncapsulated("res-hdr"))
808 return false;
809
810 return true;
811 }
812
0bef8dd7 813 if (ICAP::methodReqmod == service().cfg().method) {
b559db5d 814 if (!gotEncapsulated("res-hdr") && !gotEncapsulated("req-hdr"))
815 return false;
816
817 return true;
818 }
819
820 return false;
821}
822
26cc52cb 823void Adaptation::Icap::ModXact::handle100Continue()
774c051c 824{
825 Must(state.writing == State::writingPaused);
5f8252d2 826 // server must not respond before the end of preview: we may send ieof
774c051c 827 Must(preview.enabled() && preview.done() && !preview.ieof());
774c051c 828
83c51da9
CT
829 // 100 "Continue" cancels our Preview commitment,
830 // but not commitment to handle 204 or 206 outside Preview
831 if (!state.allowedPostview204 && !state.allowedPostview206)
774c051c 832 stopBackup();
833
c99de607 834 state.parsing = State::psIcapHeader; // eventually
835 icapReply->reset();
774c051c 836
837 state.writing = State::writingPrime;
838
839 writeMore();
840}
841
26cc52cb 842void Adaptation::Icap::ModXact::handle200Ok()
774c051c 843{
844 state.parsing = State::psHttpHeader;
845 state.sending = State::sendingAdapted;
846 stopBackup();
5f8252d2 847 checkConsuming();
774c051c 848}
849
26cc52cb 850void Adaptation::Icap::ModXact::handle204NoContent()
774c051c 851{
852 stopParsing();
478cfe99 853 prepEchoing();
854}
855
83c51da9
CT
856void Adaptation::Icap::ModXact::handle206PartialContent()
857{
858 if (state.writing == State::writingPaused) {
859 Must(preview.enabled());
860 Must(state.allowedPreview206);
861 debugs(93, 7, HERE << "206 inside preview");
862 } else {
863 Must(state.writing > State::writingPaused);
864 Must(state.allowedPostview206);
865 debugs(93, 7, HERE << "206 outside preview");
866 }
867 state.parsing = State::psHttpHeader;
868 state.sending = State::sendingAdapted;
869 state.readyForUob = true;
870 checkConsuming();
871}
872
478cfe99 873// Called when we receive a 204 No Content response and
874// when we are trying to bypass a service failure.
875// We actually start sending (echoig or not) in startSending.
26cc52cb 876void Adaptation::Icap::ModXact::prepEchoing()
478cfe99 877{
3ff65596 878 disableRepeats("preparing to echo content");
a22e6cd3 879 disableBypass("preparing to echo content", true);
3ff65596 880 setOutcome(xoEcho);
774c051c 881
882 // We want to clone the HTTP message, but we do not want
5f8252d2 883 // to copy some non-HTTP state parts that HttpMsg kids carry in them.
774c051c 884 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
885 // Instead, we simply write the HTTP message and "clone" it by parsing.
a22e6cd3 886 // TODO: use HttpMsg::clone()!
774c051c 887
5f8252d2 888 HttpMsg *oldHead = virgin.header;
192378eb 889 debugs(93, 7, HERE << "cloning virgin message " << oldHead);
774c051c 890
891 MemBuf httpBuf;
892
893 // write the virgin message into a memory buffer
894 httpBuf.init();
895 packHead(httpBuf, oldHead);
896
c99de607 897 // allocate the adapted message and copy metainfo
5f8252d2 898 Must(!adapted.header);
c7d51c86 899 {
e6f9e263
A
900 HttpMsg::Pointer newHead;
901 if (const HttpRequest *oldR = dynamic_cast<const HttpRequest*>(oldHead)) {
902 HttpRequest::Pointer newR(new HttpRequest);
903 newR->canonical = oldR->canonical ?
904 xstrdup(oldR->canonical) : NULL; // parse() does not set it
905 newHead = newR;
906 } else if (dynamic_cast<const HttpReply*>(oldHead)) {
907 newHead = new HttpReply;
908 }
909 Must(newHead != NULL);
c7d51c86 910
e6f9e263 911 newHead->inheritProperties(oldHead);
774c051c 912
e6f9e263 913 adapted.setHeader(newHead);
c7d51c86 914 }
7514268e 915
774c051c 916 // parse the buffer back
917 http_status error = HTTP_STATUS_NONE;
918
c7d51c86 919 Must(adapted.header->parse(&httpBuf, true, &error));
774c051c 920
c7d51c86 921 Must(adapted.header->hdr_sz == httpBuf.contentSize()); // no leftovers
774c051c 922
923 httpBuf.clean();
924
192378eb 925 debugs(93, 7, HERE << "cloned virgin message " << oldHead << " to " <<
c7d51c86 926 adapted.header);
5f8252d2 927
928 // setup adapted body pipe if needed
929 if (oldHead->body_pipe != NULL) {
930 debugs(93, 7, HERE << "will echo virgin body from " <<
9e008dda 931 oldHead->body_pipe);
478cfe99 932 if (!virginBodySending.active())
933 virginBodySending.plan(); // will throw if not possible
5f8252d2 934 state.sending = State::sendingVirgin;
935 checkConsuming();
478cfe99 936
5f8252d2 937 // TODO: optimize: is it possible to just use the oldHead pipe and
938 // remove ICAP from the loop? This echoing is probably a common case!
939 makeAdaptedBodyPipe("echoed virgin response");
940 if (oldHead->body_pipe->bodySizeKnown())
941 adapted.body_pipe->setBodySize(oldHead->body_pipe->bodySize());
942 debugs(93, 7, HERE << "will echo virgin body to " <<
9e008dda 943 adapted.body_pipe);
5f8252d2 944 } else {
945 debugs(93, 7, HERE << "no virgin body to echo");
946 stopSending(true);
947 }
774c051c 948}
949
83c51da9
CT
950/// Called when we received use-original-body chunk extension in 206 response.
951/// We actually start sending (echoing or not) in startSending().
952void Adaptation::Icap::ModXact::prepPartialBodyEchoing(uint64_t pos)
953{
954 Must(virginBodySending.active());
955 Must(virgin.header->body_pipe != NULL);
956
957 setOutcome(xoPartEcho);
958
959 debugs(93, 7, HERE << "will echo virgin body suffix from " <<
960 virgin.header->body_pipe << " offset " << pos );
961
962 // check that use-original-body=N does not point beyond buffered data
963 const uint64_t virginDataEnd = virginConsumed +
7ddcfbab 964 virgin.body_pipe->buf().contentSize();
83c51da9
CT
965 Must(pos <= virginDataEnd);
966 virginBodySending.progress(static_cast<size_t>(pos));
967
968 state.sending = State::sendingVirgin;
969 checkConsuming();
970
971 if (virgin.header->body_pipe->bodySizeKnown())
972 adapted.body_pipe->expectProductionEndAfter(virgin.header->body_pipe->bodySize() - pos);
973
974 debugs(93, 7, HERE << "will echo virgin body suffix to " <<
975 adapted.body_pipe);
976
977 // Start echoing data
978 echoMore();
979}
980
26cc52cb 981void Adaptation::Icap::ModXact::handleUnknownScode()
774c051c 982{
983 stopParsing();
984 stopBackup();
985 // TODO: mark connection as "bad"
986
987 // Terminate the transaction; we do not know how to handle this response.
988 throw TexcHere("Unsupported ICAP status code");
989}
990
26cc52cb 991void Adaptation::Icap::ModXact::parseHttpHead()
774c051c 992{
993 if (gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr")) {
bae917ac 994 replyHttpHeaderSize = 0;
774c051c 995 maybeAllocateHttpMsg();
996
5f8252d2 997 if (!parseHead(adapted.header))
c99de607 998 return; // need more header data
5f8252d2 999
bae917ac
CT
1000 if (adapted.header)
1001 replyHttpHeaderSize = adapted.header->hdr_sz;
1002
d67acb4e 1003 if (dynamic_cast<HttpRequest*>(adapted.header)) {
5f8252d2 1004 const HttpRequest *oldR = dynamic_cast<const HttpRequest*>(virgin.header);
1005 Must(oldR);
9e008dda
AJ
1006 // TODO: the adapted request did not really originate from the
1007 // client; give proxy admin an option to prevent copying of
5f8252d2 1008 // sensitive client information here. See the following thread:
1009 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
5f8252d2 1010 }
d67acb4e 1011
9e008dda
AJ
1012 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
1013 if (adapted.header)
1014 adapted.header->inheritProperties(virgin.header);
774c051c 1015 }
1016
5f8252d2 1017 decideOnParsingBody();
774c051c 1018}
1019
c99de607 1020// parses both HTTP and ICAP headers
26cc52cb 1021bool Adaptation::Icap::ModXact::parseHead(HttpMsg *head)
774c051c 1022{
c99de607 1023 Must(head);
def17b6a 1024 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " head bytes to parse" <<
774c051c 1025 "; state: " << state.parsing);
1026
1027 http_status error = HTTP_STATUS_NONE;
1028 const bool parsed = head->parse(&readBuf, commEof, &error);
1029 Must(parsed || !error); // success or need more data
1030
c99de607 1031 if (!parsed) { // need more data
b107a5a5 1032 debugs(93, 5, HERE << "parse failed, need more data, return false");
774c051c 1033 head->reset();
1034 return false;
1035 }
1036
a22e6cd3
AR
1037 if (HttpRequest *r = dynamic_cast<HttpRequest*>(head))
1038 urlCanonical(r); // parse does not set HttpRequest::canonical
1039
b107a5a5 1040 debugs(93, 5, HERE << "parse success, consume " << head->hdr_sz << " bytes, return true");
774c051c 1041 readBuf.consume(head->hdr_sz);
1042 return true;
1043}
1044
26cc52cb 1045void Adaptation::Icap::ModXact::decideOnParsingBody()
9e008dda 1046{
200ac359 1047 if (gotEncapsulated("res-body") || gotEncapsulated("req-body")) {
5f8252d2 1048 debugs(93, 5, HERE << "expecting a body");
1049 state.parsing = State::psBody;
bae917ac 1050 replyHttpBodySize = 0;
5f8252d2 1051 bodyParser = new ChunkedCodingParser;
1052 makeAdaptedBodyPipe("adapted response from the ICAP server");
1053 Must(state.sending == State::sendingAdapted);
774c051c 1054 } else {
b559db5d 1055 debugs(93, 5, HERE << "not expecting a body");
5f8252d2 1056 stopParsing();
1057 stopSending(true);
774c051c 1058 }
774c051c 1059}
1060
26cc52cb 1061void Adaptation::Icap::ModXact::parseBody()
774c051c 1062{
5f8252d2 1063 Must(state.parsing == State::psBody);
1064 Must(bodyParser);
774c051c 1065
5f8252d2 1066 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " body bytes to parse");
774c051c 1067
5f8252d2 1068 // the parser will throw on errors
1069 BodyPipeCheckout bpc(*adapted.body_pipe);
1070 const bool parsed = bodyParser->parse(&readBuf, &bpc.buf);
1071 bpc.checkIn();
774c051c 1072
aa761e5f 1073 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " body bytes after " <<
774c051c 1074 "parse; parsed all: " << parsed);
bae917ac 1075 replyHttpBodySize += adapted.body_pipe->buf().contentSize();
774c051c 1076
478cfe99 1077 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
3ff65596
AR
1078 // TODO: do we really need this if we disable when sending headers?
1079 if (adapted.body_pipe->buf().contentSize() > 0) { // parsed something sometime
1080 disableRepeats("sent adapted content");
a22e6cd3 1081 disableBypass("sent adapted content", true);
3ff65596 1082 }
478cfe99 1083
5f8252d2 1084 if (parsed) {
83c51da9
CT
1085 if (state.readyForUob && bodyParser->useOriginBody >= 0) {
1086 prepPartialBodyEchoing(
1087 static_cast<uint64_t>(bodyParser->useOriginBody));
1088 stopParsing();
1089 return;
1090 }
1091
5f8252d2 1092 stopParsing();
1093 stopSending(true); // the parser succeeds only if all parsed data fits
1094 return;
1095 }
774c051c 1096
c99de607 1097 debugs(93,3,HERE << this << " needsMoreData = " << bodyParser->needsMoreData());
3b299123 1098
1099 if (bodyParser->needsMoreData()) {
c99de607 1100 debugs(93,3,HERE << this);
774c051c 1101 Must(mayReadMore());
3b299123 1102 readMore();
1103 }
774c051c 1104
1105 if (bodyParser->needsMoreSpace()) {
1106 Must(!doneSending()); // can hope for more space
5f8252d2 1107 Must(adapted.body_pipe->buf().contentSize() > 0); // paranoid
1108 // TODO: there should be a timeout in case the sink is broken
1109 // or cannot consume partial content (while we need more space)
774c051c 1110 }
774c051c 1111}
1112
26cc52cb 1113void Adaptation::Icap::ModXact::stopParsing()
774c051c 1114{
1115 if (state.parsing == State::psDone)
1116 return;
1117
192378eb 1118 debugs(93, 7, HERE << "will no longer parse" << status());
774c051c 1119
1120 delete bodyParser;
1121
1122 bodyParser = NULL;
1123
1124 state.parsing = State::psDone;
1125}
1126
1127// HTTP side added virgin body data
26cc52cb 1128void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer)
774c051c 1129{
774c051c 1130 writeMore();
1131
1132 if (state.sending == State::sendingVirgin)
1133 echoMore();
774c051c 1134}
1135
1136// HTTP side sent us all virgin info
26cc52cb 1137void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer)
774c051c 1138{
5f8252d2 1139 Must(virgin.body_pipe->productionEnded());
774c051c 1140
1141 // push writer and sender in case we were waiting for the last-chunk
1142 writeMore();
1143
1144 if (state.sending == State::sendingVirgin)
1145 echoMore();
774c051c 1146}
1147
9e008dda 1148// body producer aborted, but the initiator may still want to know
585ab260 1149// the answer, even though the HTTP message has been truncated
26cc52cb 1150void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer)
774c051c 1151{
585ab260 1152 Must(virgin.body_pipe->productionEnded());
1153
1154 // push writer and sender in case we were waiting for the last-chunk
1155 writeMore();
1156
1157 if (state.sending == State::sendingVirgin)
1158 echoMore();
5f8252d2 1159}
1160
9e008dda 1161// adapted body consumer wants more adapted data and
5f8252d2 1162// possibly freed some buffer space
26cc52cb 1163void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer)
774c051c 1164{
774c051c 1165 if (state.sending == State::sendingVirgin)
1166 echoMore();
3b299123 1167 else if (state.sending == State::sendingAdapted)
1168 parseMore();
774c051c 1169 else
3b299123 1170 Must(state.sending == State::sendingUndecided);
774c051c 1171}
1172
5f8252d2 1173// adapted body consumer aborted
26cc52cb 1174void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer)
774c051c 1175{
64b66b76 1176 detailError(ERR_DETAIL_ICAP_XACT_BODY_CONSUMER_ABORT);
5f8252d2 1177 mustStop("adapted body consumer aborted");
774c051c 1178}
1179
c7d51c86
AR
1180Adaptation::Icap::ModXact::~ModXact()
1181{
1182 delete bodyParser;
1183}
1184
774c051c 1185// internal cleanup
26cc52cb 1186void Adaptation::Icap::ModXact::swanSong()
774c051c 1187{
5f8252d2 1188 debugs(93, 5, HERE << "swan sings" << status());
1189
c99de607 1190 stopWriting(false);
c824c43b 1191 stopSending(false);
774c051c 1192
64b66b76
CT
1193 if (theInitiator.set()) // we have not sent the answer to the initiator
1194 detailError(ERR_DETAIL_ICAP_XACT_OTHER);
1195
3ff65596 1196 // update adaptation history if start was called and we reserved a slot
a22e6cd3 1197 Adaptation::History::Pointer ah = virginRequest().adaptLogHistory();
3ff65596
AR
1198 if (ah != NULL && adaptHistoryId >= 0)
1199 ah->recordXactFinish(adaptHistoryId);
774c051c 1200
26cc52cb 1201 Adaptation::Icap::Xaction::swanSong();
774c051c 1202}
1203
3ff65596
AR
1204void prepareLogWithRequestDetails(HttpRequest *, AccessLogEntry *);
1205
1206void Adaptation::Icap::ModXact::finalizeLogInfo()
1207{
1208 HttpRequest * request_ = NULL;
1209 HttpReply * reply_ = NULL;
e1381638 1210 if (!(request_ = dynamic_cast<HttpRequest*>(adapted.header))) {
3ff65596
AR
1211 request_ = (virgin.cause? virgin.cause: dynamic_cast<HttpRequest*>(virgin.header));
1212 reply_ = dynamic_cast<HttpReply*>(adapted.header);
1213 }
1214
1215 Adaptation::Icap::History::Pointer h = request_->icapHistory();
e1381638
AJ
1216 Must(h != NULL); // ICAPXaction::maybeLog calls only if there is a log
1217 al.icp.opcode = ICP_INVALID;
1218 al.url = h->log_uri.termedBuf();
1219 const Adaptation::Icap::ServiceRep &s = service();
1220 al.icap.reqMethod = s.cfg().method;
3ff65596 1221
e1381638 1222 al.cache.caddr = request_->client_addr;
3ff65596 1223
e1381638
AJ
1224 al.request = HTTPMSGLOCK(request_);
1225 if (reply_)
1226 al.reply = HTTPMSGLOCK(reply_);
1227 else
1228 al.reply = NULL;
3ff65596 1229
e1381638
AJ
1230 if (h->rfc931.size())
1231 al.cache.rfc931 = h->rfc931.termedBuf();
3ff65596
AR
1232
1233#if USE_SSL
e1381638
AJ
1234 if (h->ssluser.size())
1235 al.cache.ssluser = h->ssluser.termedBuf();
3ff65596 1236#endif
e1381638
AJ
1237 al.cache.code = h->logType;
1238 al.cache.requestSize = h->req_sz;
bae917ac
CT
1239
1240 // leave al.icap.bodyBytesRead negative if no body
1241 if (replyHttpHeaderSize >= 0 || replyHttpBodySize >= 0) {
1242 const int64_t zero = 0; // to make max() argument types the same
1243 al.icap.bodyBytesRead =
1244 max(zero, replyHttpHeaderSize) + max(zero, replyHttpBodySize);
1245 }
1246
e1381638
AJ
1247 if (reply_) {
1248 al.http.code = reply_->sline.status;
1249 al.http.content_type = reply_->content_type.termedBuf();
bae917ac
CT
1250 if (replyHttpBodySize >= 0) {
1251 al.cache.replySize = replyHttpBodySize + reply_->hdr_sz;
1252 al.cache.highOffset = replyHttpBodySize;
1253 }
e1381638
AJ
1254 //don't set al.cache.objectSize because it hasn't exist yet
1255
1256 Packer p;
1257 MemBuf mb;
1258
1259 mb.init();
1260 packerToMemInit(&p, &mb);
1261
1262 reply_->header.packInto(&p);
1263 al.headers.reply = xstrdup(mb.buf);
1264
1265 packerClean(&p);
1266 mb.clean();
1267 }
1268 prepareLogWithRequestDetails(request_, &al);
1269 Xaction::finalizeLogInfo();
3ff65596
AR
1270}
1271
1272
26cc52cb 1273void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf &buf)
774c051c 1274{
cc192b50 1275 char ntoabuf[MAX_IPSTRLEN];
12b91c99 1276 /*
1277 * XXX These should use HttpHdr interfaces instead of Printfs
1278 */
0bef8dd7 1279 const Adaptation::ServiceConfig &s = service().cfg();
2c1fd837 1280 buf.Printf("%s " SQUIDSTRINGPH " ICAP/1.0\r\n", s.methodStr(), SQUIDSTRINGPRINT(s.uri));
826a1fed 1281 buf.Printf("Host: " SQUIDSTRINGPH ":%d\r\n", SQUIDSTRINGPRINT(s.host), s.port);
12b91c99 1282 buf.Printf("Date: %s\r\n", mkrfc1123(squid_curtime));
1283
26cc52cb 1284 if (!TheConfig.reuse_connections)
12b91c99 1285 buf.Printf("Connection: close\r\n");
1286
2cdeea82 1287 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1288 // as ICAP headers.
4232c626
FC
1289 if (virgin.header->header.has(HDR_PROXY_AUTHENTICATE)) {
1290 String vh=virgin.header->header.getByName("Proxy-Authenticate");
826a1fed 1291 buf.Printf("Proxy-Authenticate: " SQUIDSTRINGPH "\r\n",SQUIDSTRINGPRINT(vh));
4232c626 1292 }
9e008dda 1293
4232c626
FC
1294 if (virgin.header->header.has(HDR_PROXY_AUTHORIZATION)) {
1295 String vh=virgin.header->header.getByName("Proxy-Authorization");
826a1fed 1296 buf.Printf("Proxy-Authorization: " SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(vh));
4232c626 1297 }
2cdeea82 1298
3ff65596
AR
1299 const HttpRequest *request = &virginRequest();
1300
1301 // share the cross-transactional database records if needed
1302 if (Adaptation::Config::masterx_shared_name) {
5038f9d8 1303 // XXX: do not create history here: there can be no values in empty ah
a22e6cd3 1304 Adaptation::History::Pointer ah = request->adaptHistory(true);
3ff65596
AR
1305 if (ah != NULL) {
1306 String name, value;
1307 if (ah->getXxRecord(name, value)) {
e1381638
AJ
1308 buf.Printf(SQUIDSTRINGPH ": " SQUIDSTRINGPH "\r\n",
1309 SQUIDSTRINGPRINT(name), SQUIDSTRINGPRINT(value));
3ff65596
AR
1310 }
1311 }
1312 }
e1381638 1313
3ff65596 1314
774c051c 1315 buf.Printf("Encapsulated: ");
1316
1317 MemBuf httpBuf;
12b91c99 1318
774c051c 1319 httpBuf.init();
1320
1321 // build HTTP request header, if any
1322 ICAP::Method m = s.method;
1323
5f8252d2 1324 // to simplify, we could assume that request is always available
c99de607 1325
30abd221 1326 String urlPath;
c99de607 1327 if (request) {
1328 urlPath = request->urlpath;
1329 if (ICAP::methodRespmod == m)
1330 encapsulateHead(buf, "req-hdr", httpBuf, request);
e1381638
AJ
1331 else if (ICAP::methodReqmod == m)
1332 encapsulateHead(buf, "req-hdr", httpBuf, virgin.header);
c99de607 1333 }
774c051c 1334
1335 if (ICAP::methodRespmod == m)
5f8252d2 1336 if (const HttpMsg *prime = virgin.header)
774c051c 1337 encapsulateHead(buf, "res-hdr", httpBuf, prime);
1338
1339 if (!virginBody.expected())
1dd6edf2 1340 buf.Printf("null-body=%d", (int) httpBuf.contentSize());
774c051c 1341 else if (ICAP::methodReqmod == m)
1dd6edf2 1342 buf.Printf("req-body=%d", (int) httpBuf.contentSize());
774c051c 1343 else
1dd6edf2 1344 buf.Printf("res-body=%d", (int) httpBuf.contentSize());
774c051c 1345
1346 buf.append(ICAP::crlf, 2); // terminate Encapsulated line
1347
c824c43b 1348 if (preview.enabled()) {
774c051c 1349 buf.Printf("Preview: %d\r\n", (int)preview.ad());
83c51da9 1350 if (!virginBody.expected()) // there is no body to preview
5f8252d2 1351 finishNullOrEmptyBodyPreview(httpBuf);
774c051c 1352 }
1353
83c51da9 1354 makeAllowHeader(buf);
774c051c 1355
a9044668 1356 if (TheConfig.send_client_ip && request) {
b7ac5457 1357 Ip::Address client_addr;
57d76dd4 1358#if FOLLOW_X_FORWARDED_FOR
22fff3bf 1359 if (TheConfig.use_indirect_client) {
a9044668
A
1360 client_addr = request->indirect_client_addr;
1361 } else
57d76dd4 1362#endif
a9044668
A
1363 client_addr = request->client_addr;
1364 if (!client_addr.IsAnyAddr() && !client_addr.IsNoAddr())
1365 buf.Printf("X-Client-IP: %s\r\n", client_addr.NtoA(ntoabuf,MAX_IPSTRLEN));
57d76dd4 1366 }
a97e82a8 1367
22fff3bf 1368 if (TheConfig.send_username && request)
5f8252d2 1369 makeUsernameHeader(request, buf);
a97e82a8 1370
bb790702 1371 // fprintf(stderr, "%s\n", buf.content());
a97e82a8 1372
774c051c 1373 buf.append(ICAP::crlf, 2); // terminate ICAP header
1374
a22e6cd3
AR
1375 // fill icapRequest for logging
1376 Must(icapRequest->parseCharBuf(buf.content(), buf.contentSize()));
1377
774c051c 1378 // start ICAP request body with encapsulated HTTP headers
1379 buf.append(httpBuf.content(), httpBuf.contentSize());
1380
1381 httpBuf.clean();
1382}
1383
83c51da9
CT
1384// decides which Allow values to write and updates the request buffer
1385void Adaptation::Icap::ModXact::makeAllowHeader(MemBuf &buf)
1386{
1387 const bool allow204in = preview.enabled(); // TODO: add shouldAllow204in()
1388 const bool allow204out = state.allowedPostview204 = shouldAllow204();
1389 const bool allow206in = state.allowedPreview206 = shouldAllow206in();
1390 const bool allow206out = state.allowedPostview206 = shouldAllow206out();
1391
1392 debugs(93,9, HERE << "Allows: " << allow204in << allow204out <<
7ddcfbab 1393 allow206in << allow206out);
83c51da9
CT
1394
1395 const bool allow204 = allow204in || allow204out;
1396 const bool allow206 = allow206in || allow206out;
1397
1398 if (!allow204 && !allow206)
1399 return; // nothing to do
1400
1401 if (virginBody.expected()) // if there is a virgin body, plan to send it
1402 virginBodySending.plan();
1403
1404 // writing Preview:... means we will honor 204 inside preview
1405 // writing Allow/204 means we will honor 204 outside preview
1406 // writing Allow:206 means we will honor 206 inside preview
1407 // writing Allow:204,206 means we will honor 206 outside preview
1408 const char *allowHeader = NULL;
1409 if (allow204out && allow206)
1410 allowHeader = "Allow: 204, 206\r\n";
1411 else if (allow204out)
1412 allowHeader = "Allow: 204\r\n";
1413 else if (allow206)
1414 allowHeader = "Allow: 206\r\n";
7ddcfbab 1415
83c51da9
CT
1416 if (allowHeader) { // may be nil if only allow204in is true
1417 buf.append(allowHeader, strlen(allowHeader));
1418 debugs(93,5, HERE << "Will write " << allowHeader);
1419 }
1420}
1421
26cc52cb 1422void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest *request, MemBuf &buf)
9e008dda 1423{
74f6c040 1424#if USE_AUTH
a33a428a 1425 if (request->auth_user_request != NULL) {
9b275e99 1426 char const *name = request->auth_user_request->username();
a33a428a
AJ
1427 if (name) {
1428 const char *value = TheConfig.client_username_encode ? base64_encode(name) : name;
1429 buf.Printf("%s: %s\r\n", TheConfig.client_username_header, value);
5f8252d2 1430 }
1431 }
74f6c040 1432#endif
5f8252d2 1433}
1434
26cc52cb 1435void Adaptation::Icap::ModXact::encapsulateHead(MemBuf &icapBuf, const char *section, MemBuf &httpBuf, const HttpMsg *head)
774c051c 1436{
1437 // update ICAP header
7cab7e9f 1438 icapBuf.Printf("%s=%d, ", section, (int) httpBuf.contentSize());
774c051c 1439
2cdeea82 1440 // begin cloning
c7d51c86 1441 HttpMsg::Pointer headClone;
9e008dda 1442
2cdeea82 1443 if (const HttpRequest* old_request = dynamic_cast<const HttpRequest*>(head)) {
c7d51c86
AR
1444 HttpRequest::Pointer new_request(new HttpRequest);
1445 Must(old_request->canonical);
a22e6cd3 1446 urlParse(old_request->method, old_request->canonical, new_request);
2cdeea82 1447 new_request->http_ver = old_request->http_ver;
2cdeea82 1448 headClone = new_request;
9e008dda 1449 } else if (const HttpReply *old_reply = dynamic_cast<const HttpReply*>(head)) {
c7d51c86 1450 HttpReply::Pointer new_reply(new HttpReply);
2cdeea82 1451 new_reply->sline = old_reply->sline;
1452 headClone = new_reply;
1453 }
c7d51c86 1454 Must(headClone != NULL);
d67acb4e 1455 headClone->inheritProperties(head);
9e008dda 1456
2cdeea82 1457 HttpHeaderPos pos = HttpHeaderInitPos;
1458 HttpHeaderEntry* p_head_entry = NULL;
1459 while (NULL != (p_head_entry = head->header.getEntry(&pos)) )
1460 headClone->header.addEntry(p_head_entry->clone());
1461
1462 // end cloning
9e008dda 1463
2cdeea82 1464 // remove all hop-by-hop headers from the clone
dcf3665b 1465 headClone->header.delById(HDR_PROXY_AUTHENTICATE);
2cdeea82 1466 headClone->header.removeHopByHopEntries();
1467
1468 // pack polished HTTP header
1469 packHead(httpBuf, headClone);
1470
c7d51c86 1471 // headClone unlocks and, hence, deletes the message we packed
774c051c 1472}
1473
26cc52cb 1474void Adaptation::Icap::ModXact::packHead(MemBuf &httpBuf, const HttpMsg *head)
774c051c 1475{
1476 Packer p;
1477 packerToMemInit(&p, &httpBuf);
1478 head->packInto(&p, true);
1479 packerClean(&p);
1480}
1481
1482// decides whether to offer a preview and calculates its size
26cc52cb 1483void Adaptation::Icap::ModXact::decideOnPreview()
774c051c 1484{
26cc52cb 1485 if (!TheConfig.preview_enable) {
7cdbbd47 1486 debugs(93, 5, HERE << "preview disabled by squid.conf");
c824c43b 1487 return;
7cdbbd47 1488 }
1489
3ff65596 1490 const String urlPath = virginRequest().urlpath;
5f8252d2 1491 size_t wantedSize;
c99de607 1492 if (!service().wantsPreview(urlPath, wantedSize)) {
192378eb 1493 debugs(93, 5, HERE << "should not offer preview for " << urlPath);
c824c43b 1494 return;
774c051c 1495 }
1496
c824c43b 1497 // we decided to do preview, now compute its size
1498
774c051c 1499 Must(wantedSize >= 0);
1500
1501 // cannot preview more than we can backup
d85c3078 1502 size_t ad = min(wantedSize, TheBackupLimit);
774c051c 1503
5f8252d2 1504 if (!virginBody.expected())
1505 ad = 0;
e1381638
AJ
1506 else if (virginBody.knownSize())
1507 ad = min(static_cast<uint64_t>(ad), virginBody.size()); // not more than we have
774c051c 1508
192378eb 1509 debugs(93, 5, HERE << "should offer " << ad << "-byte preview " <<
774c051c 1510 "(service wanted " << wantedSize << ")");
1511
1512 preview.enable(ad);
5f8252d2 1513 Must(preview.enabled());
774c051c 1514}
1515
1516// decides whether to allow 204 responses
26cc52cb 1517bool Adaptation::Icap::ModXact::shouldAllow204()
774c051c 1518{
1519 if (!service().allows204())
1520 return false;
1521
c824c43b 1522 return canBackupEverything();
1523}
1524
83c51da9
CT
1525// decides whether to allow 206 responses in some mode
1526bool Adaptation::Icap::ModXact::shouldAllow206any()
1527{
1528 return TheConfig.allow206_enable && service().allows206() &&
7ddcfbab 1529 virginBody.expected(); // no need for 206 without a body
83c51da9
CT
1530}
1531
1532// decides whether to allow 206 responses in preview mode
1533bool Adaptation::Icap::ModXact::shouldAllow206in()
1534{
1535 return shouldAllow206any() && preview.enabled();
1536}
1537
1538// decides whether to allow 206 responses outside of preview
1539bool Adaptation::Icap::ModXact::shouldAllow206out()
1540{
1541 return shouldAllow206any() && canBackupEverything();
1542}
1543
c824c43b 1544// used by shouldAllow204 and decideOnRetries
26cc52cb 1545bool Adaptation::Icap::ModXact::canBackupEverything() const
c824c43b 1546{
774c051c 1547 if (!virginBody.expected())
c824c43b 1548 return true; // no body means no problems with backup
774c051c 1549
c824c43b 1550 // if there is a body, check whether we can backup it all
774c051c 1551
1552 if (!virginBody.knownSize())
1553 return false;
1554
1555 // or should we have a different backup limit?
1556 // note that '<' allows for 0-termination of the "full" backup buffer
1557 return virginBody.size() < TheBackupLimit;
1558}
1559
c824c43b 1560// Decide whether this transaction can be retried if pconn fails
1561// Must be called after decideOnPreview and before openConnection()
26cc52cb 1562void Adaptation::Icap::ModXact::decideOnRetries()
c824c43b 1563{
1564 if (!isRetriable)
1565 return; // no, already decided
1566
1567 if (preview.enabled())
1568 return; // yes, because preview provides enough guarantees
1569
1570 if (canBackupEverything())
1571 return; // yes, because we can back everything up
1572
1573 disableRetries(); // no, because we cannot back everything up
1574}
1575
5f8252d2 1576// Normally, the body-writing code handles preview body. It can deal with
1577// bodies of unexpected size, including those that turn out to be empty.
1578// However, that code assumes that the body was expected and body control
1579// structures were initialized. This is not the case when there is no body
1580// or the body is known to be empty, because the virgin message will lack a
1581// body_pipe. So we handle preview of null-body and zero-size bodies here.
26cc52cb 1582void Adaptation::Icap::ModXact::finishNullOrEmptyBodyPreview(MemBuf &buf)
5f8252d2 1583{
1584 Must(!virginBodyWriting.active()); // one reason we handle it here
1585 Must(!virgin.body_pipe); // another reason we handle it here
1586 Must(!preview.ad());
1587
1588 // do not add last-chunk because our Encapsulated header says null-body
bb790702 1589 // addLastRequestChunk(buf);
5f8252d2 1590 preview.wrote(0, true);
1591
1592 Must(preview.done());
1593 Must(preview.ieof());
1594}
1595
26cc52cb 1596void Adaptation::Icap::ModXact::fillPendingStatus(MemBuf &buf) const
774c051c 1597{
26cc52cb 1598 Adaptation::Icap::Xaction::fillPendingStatus(buf);
c99de607 1599
774c051c 1600 if (state.serviceWaiting)
1601 buf.append("U", 1);
1602
5f8252d2 1603 if (virgin.body_pipe != NULL)
c99de607 1604 buf.append("R", 1);
1605
5f8252d2 1606 if (connection > 0 && !doneReading())
c99de607 1607 buf.append("r", 1);
1608
774c051c 1609 if (!state.doneWriting() && state.writing != State::writingInit)
1610 buf.Printf("w(%d)", state.writing);
1611
1612 if (preview.enabled()) {
1613 if (!preview.done())
1dd6edf2 1614 buf.Printf("P(%d)", (int) preview.debt());
774c051c 1615 }
1616
5f8252d2 1617 if (virginBodySending.active())
774c051c 1618 buf.append("B", 1);
1619
1620 if (!state.doneParsing() && state.parsing != State::psIcapHeader)
1621 buf.Printf("p(%d)", state.parsing);
1622
1623 if (!doneSending() && state.sending != State::sendingUndecided)
1624 buf.Printf("S(%d)", state.sending);
478cfe99 1625
83c51da9
CT
1626 if (state.readyForUob)
1627 buf.append("6", 1);
1628
478cfe99 1629 if (canStartBypass)
9e008dda 1630 buf.append("Y", 1);
a22e6cd3
AR
1631
1632 if (protectGroupBypass)
1633 buf.append("G", 1);
774c051c 1634}
1635
26cc52cb 1636void Adaptation::Icap::ModXact::fillDoneStatus(MemBuf &buf) const
774c051c 1637{
26cc52cb 1638 Adaptation::Icap::Xaction::fillDoneStatus(buf);
c99de607 1639
5f8252d2 1640 if (!virgin.body_pipe)
774c051c 1641 buf.append("R", 1);
1642
1643 if (state.doneWriting())
1644 buf.append("w", 1);
1645
1646 if (preview.enabled()) {
1647 if (preview.done())
1648 buf.Printf("P%s", preview.ieof() ? "(ieof)" : "");
1649 }
1650
1651 if (doneReading())
1652 buf.append("r", 1);
1653
1654 if (state.doneParsing())
1655 buf.append("p", 1);
1656
1657 if (doneSending())
1658 buf.append("S", 1);
1659}
1660
26cc52cb 1661bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section) const
774c051c 1662{
a9925b40 1663 return icapReply->header.getByNameListMember("Encapsulated",
1664 section, ',').size() > 0;
774c051c 1665}
1666
1667// calculate whether there is a virgin HTTP body and
1668// whether its expected size is known
5f8252d2 1669// TODO: rename because we do not just estimate
26cc52cb 1670void Adaptation::Icap::ModXact::estimateVirginBody()
774c051c 1671{
5f8252d2 1672 // note: lack of size info may disable previews and 204s
774c051c 1673
5f8252d2 1674 HttpMsg *msg = virgin.header;
1675 Must(msg);
774c051c 1676
60745f24 1677 HttpRequestMethod method;
774c051c 1678
5f8252d2 1679 if (virgin.cause)
1680 method = virgin.cause->method;
e1381638
AJ
1681 else if (HttpRequest *req = dynamic_cast<HttpRequest*>(msg))
1682 method = req->method;
774c051c 1683 else
e1381638 1684 method = METHOD_NONE;
774c051c 1685
47f6e231 1686 int64_t size;
5f8252d2 1687 // expectingBody returns true for zero-sized bodies, but we will not
1688 // get a pipe for that body, so we treat the message as bodyless
1689 if (method != METHOD_NONE && msg->expectingBody(method, size) && size) {
192378eb 1690 debugs(93, 6, HERE << "expects virgin body from " <<
9e008dda 1691 virgin.body_pipe << "; size: " << size);
5f8252d2 1692
1693 virginBody.expect(size);
1694 virginBodyWriting.plan();
1695
1696 // sign up as a body consumer
1697 Must(msg->body_pipe != NULL);
1698 Must(msg->body_pipe == virgin.body_pipe);
1699 Must(virgin.body_pipe->setConsumerIfNotLate(this));
1700
1701 // make sure TheBackupLimit is in-sync with the buffer size
9c175897 1702 Must(TheBackupLimit <= static_cast<size_t>(msg->body_pipe->buf().max_capacity));
774c051c 1703 } else {
192378eb 1704 debugs(93, 6, HERE << "does not expect virgin body");
5f8252d2 1705 Must(msg->body_pipe == NULL);
1706 checkConsuming();
774c051c 1707 }
1708}
1709
26cc52cb 1710void Adaptation::Icap::ModXact::makeAdaptedBodyPipe(const char *what)
9e008dda 1711{
5f8252d2 1712 Must(!adapted.body_pipe);
1713 Must(!adapted.header->body_pipe);
1714 adapted.header->body_pipe = new BodyPipe(this);
1715 adapted.body_pipe = adapted.header->body_pipe;
1716 debugs(93, 7, HERE << "will supply " << what << " via " <<
9e008dda 1717 adapted.body_pipe << " pipe");
5f8252d2 1718}
1719
774c051c 1720
26cc52cb 1721// TODO: Move SizedEstimate and Preview elsewhere
774c051c 1722
26cc52cb 1723Adaptation::Icap::SizedEstimate::SizedEstimate()
774c051c 1724 : theData(dtUnexpected)
1725{}
1726
26cc52cb 1727void Adaptation::Icap::SizedEstimate::expect(int64_t aSize)
774c051c 1728{
47f6e231 1729 theData = (aSize >= 0) ? aSize : (int64_t)dtUnknown;
774c051c 1730}
1731
26cc52cb 1732bool Adaptation::Icap::SizedEstimate::expected() const
774c051c 1733{
1734 return theData != dtUnexpected;
1735}
1736
26cc52cb 1737bool Adaptation::Icap::SizedEstimate::knownSize() const
774c051c 1738{
1739 Must(expected());
1740 return theData != dtUnknown;
1741}
1742
26cc52cb 1743uint64_t Adaptation::Icap::SizedEstimate::size() const
774c051c 1744{
1745 Must(knownSize());
47f6e231 1746 return static_cast<uint64_t>(theData);
774c051c 1747}
1748
1749
1750
26cc52cb 1751Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided)
774c051c 1752{}
1753
26cc52cb 1754void Adaptation::Icap::VirginBodyAct::plan()
774c051c 1755{
478cfe99 1756 Must(!disabled());
1757 Must(!theStart); // not started
1758 theState = stActive;
774c051c 1759}
1760
26cc52cb 1761void Adaptation::Icap::VirginBodyAct::disable()
774c051c 1762{
478cfe99 1763 theState = stDisabled;
774c051c 1764}
1765
26cc52cb 1766void Adaptation::Icap::VirginBodyAct::progress(size_t size)
774c051c 1767{
1768 Must(active());
1769 Must(size >= 0);
47f6e231 1770 theStart += static_cast<int64_t>(size);
774c051c 1771}
1772
26cc52cb 1773uint64_t Adaptation::Icap::VirginBodyAct::offset() const
774c051c 1774{
1775 Must(active());
47f6e231 1776 return static_cast<uint64_t>(theStart);
774c051c 1777}
1778
774c051c 1779
26cc52cb 1780Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled)
774c051c 1781{}
1782
26cc52cb 1783void Adaptation::Icap::Preview::enable(size_t anAd)
774c051c 1784{
1785 // TODO: check for anAd not exceeding preview size limit
1786 Must(anAd >= 0);
1787 Must(!enabled());
1788 theAd = anAd;
1789 theState = stWriting;
1790}
1791
26cc52cb 1792bool Adaptation::Icap::Preview::enabled() const
774c051c 1793{
1794 return theState != stDisabled;
1795}
1796
26cc52cb 1797size_t Adaptation::Icap::Preview::ad() const
774c051c 1798{
1799 Must(enabled());
1800 return theAd;
1801}
1802
26cc52cb 1803bool Adaptation::Icap::Preview::done() const
774c051c 1804{
1805 Must(enabled());
1806 return theState >= stIeof;
1807}
1808
26cc52cb 1809bool Adaptation::Icap::Preview::ieof() const
774c051c 1810{
1811 Must(enabled());
1812 return theState == stIeof;
1813}
1814
26cc52cb 1815size_t Adaptation::Icap::Preview::debt() const
774c051c 1816{
1817 Must(enabled());
1818 return done() ? 0 : (theAd - theWritten);
1819}
1820
26cc52cb 1821void Adaptation::Icap::Preview::wrote(size_t size, bool wroteEof)
774c051c 1822{
1823 Must(enabled());
5f8252d2 1824
774c051c 1825 theWritten += size;
1826
9e008dda 1827 Must(theWritten <= theAd);
5f8252d2 1828
9e008dda
AJ
1829 if (wroteEof)
1830 theState = stIeof; // written size is irrelevant
e1381638
AJ
1831 else if (theWritten >= theAd)
1832 theState = stDone;
774c051c 1833}
1834
26cc52cb 1835bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf &mb) const
3cfc19b3 1836{
5f8252d2 1837 if (virgin.header == NULL)
3cfc19b3 1838 return false;
1839
5f8252d2 1840 virgin.header->firstLineBuf(mb);
3cfc19b3 1841
1842 return true;
1843}
c824c43b 1844
64b66b76
CT
1845void Adaptation::Icap::ModXact::detailError(int errDetail)
1846{
1847 if (HttpRequest *request = virgin.cause ?
b3c9f64a 1848 virgin.cause : dynamic_cast<HttpRequest*>(virgin.header)) {
64b66b76
CT
1849 request->detailError(ERR_ICAP_FAILURE, errDetail);
1850 }
1851}
c824c43b 1852
26cc52cb 1853/* Adaptation::Icap::ModXactLauncher */
c824c43b 1854
4299f876 1855Adaptation::Icap::ModXactLauncher::ModXactLauncher(HttpMsg *virginHeader, HttpRequest *virginCause, Adaptation::ServicePointer aService):
26cc52cb 1856 AsyncJob("Adaptation::Icap::ModXactLauncher"),
4299f876 1857 Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", aService)
c824c43b 1858{
1859 virgin.setHeader(virginHeader);
1860 virgin.setCause(virginCause);
3ff65596 1861 updateHistory(true);
c824c43b 1862}
1863
26cc52cb 1864Adaptation::Icap::Xaction *Adaptation::Icap::ModXactLauncher::createXaction()
c824c43b 1865{
26cc52cb
AR
1866 Adaptation::Icap::ServiceRep::Pointer s =
1867 dynamic_cast<Adaptation::Icap::ServiceRep*>(theService.getRaw());
0bef8dd7 1868 Must(s != NULL);
4299f876 1869 return new Adaptation::Icap::ModXact(virgin.header, virgin.cause, s);
c824c43b 1870}
3ff65596 1871
e1381638
AJ
1872void Adaptation::Icap::ModXactLauncher::swanSong()
1873{
3ff65596
AR
1874 debugs(93, 5, HERE << "swan sings");
1875 updateHistory(false);
1876 Adaptation::Icap::Launcher::swanSong();
1877}
1878
b0365bd9 1879void Adaptation::Icap::ModXactLauncher::updateHistory(bool doStart)
e1381638
AJ
1880{
1881 HttpRequest *r = virgin.cause ?
1882 virgin.cause : dynamic_cast<HttpRequest*>(virgin.header);
1883
1884 // r should never be NULL but we play safe; TODO: add Should()
1885 if (r) {
1886 Adaptation::Icap::History::Pointer h = r->icapHistory();
1887 if (h != NULL) {
b0365bd9 1888 if (doStart)
e1381638
AJ
1889 h->start("ICAPModXactLauncher");
1890 else
1891 h->stop("ICAPModXactLauncher");
1892 }
1893 }
3ff65596 1894}