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