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