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