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