]> git.ipfire.org Git - thirdparty/squid.git/blame - src/ICAP/ICAPModXact.cc
Real: Fix NO DEFAULT compile errors
[thirdparty/squid.git] / src / ICAP / ICAPModXact.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"
774c051c 11#include "ICAPServiceRep.h"
c824c43b 12#include "ICAPLauncher.h"
774c051c 13#include "ICAPModXact.h"
14#include "ICAPClient.h"
15#include "ChunkedCodingParser.h"
16#include "TextException.h"
a97e82a8 17#include "AuthUserRequest.h"
12b91c99 18#include "ICAPConfig.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
27CBDATA_CLASS_INIT(ICAPModXact);
c824c43b 28CBDATA_CLASS_INIT(ICAPModXactLauncher);
774c051c 29
5f8252d2 30static const size_t TheBackupLimit = BodyPipe::MaxCapacity;
774c051c 31
12b91c99 32extern ICAPConfig TheICAPConfig;
33
774c051c 34
35ICAPModXact::State::State()
36{
09bfe95f 37 memset(this, 0, sizeof(*this));
774c051c 38}
39
0bef8dd7 40ICAPModXact::ICAPModXact(Adaptation::Initiator *anInitiator, HttpMsg *virginHeader,
5f8252d2 41 HttpRequest *virginCause, ICAPServiceRep::Pointer &aService):
bd7f2ede 42 AsyncJob("ICAPModXact"),
c824c43b 43 ICAPXaction("ICAPModXact", anInitiator, aService),
5f8252d2 44 icapReply(NULL),
45 virginConsumed(0),
478cfe99 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
56 // writing and reading ends are handled by ICAPXaction
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
5f8252d2 65 debugs(93,7, "ICAPModXact initialized." << status());
774c051c 66}
67
5f8252d2 68// initiator wants us to start
69void ICAPModXact::start()
774c051c 70{
5f8252d2 71 ICAPXaction::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
85void ICAPModXact::waitForService()
86{
87 Must(!state.serviceWaiting);
5f8252d2 88 debugs(93, 7, "ICAPModXact will wait for the ICAP service" << status());
774c051c 89 state.serviceWaiting = true;
bd7f2ede 90 AsyncCall::Pointer call = asyncCall(93,5, "ICAPModXact::noteServiceReady",
91 MemFun(this, &ICAPModXact::noteServiceReady));
92 service().callWhenReady(call);
774c051c 93}
94
95void ICAPModXact::noteServiceReady()
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
108void ICAPModXact::startWriting()
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
119void ICAPModXact::handleCommConnected()
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);
5f8252d2 129 debugs(93, 9, "ICAPModXact ICAP will write" << status() << ":\n" <<
774c051c 130 (requestBuf.terminate(), requestBuf.content()));
131
132 // write headers
133 state.writing = State::writingHeaders;
134 scheduleWrite(requestBuf);
135}
136
b107a5a5 137void ICAPModXact::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
147void ICAPModXact::handleCommWroteHeaders()
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
155 if (virginBody.expected())
156 state.writing = State::writingPrime;
157 else {
c99de607 158 stopWriting(true);
5f8252d2 159 return;
774c051c 160 }
5f8252d2 161
162 writeMore();
774c051c 163}
164
165void ICAPModXact::writeMore()
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:
199 throw TexcHere("ICAPModXact in bad writing state");
200 }
201}
202
5f8252d2 203void ICAPModXact::writePreviewBody()
774c051c 204{
5f8252d2 205 debugs(93, 8, HERE << "will write Preview body from " <<
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();
211 const size_t size = XMIN(preview.debt(), sizeMax);
774c051c 212 writeSomeBody("preview body", size);
213
214 // change state once preview is written
215
216 if (preview.done()) {
5f8252d2 217 debugs(93, 7, "ICAPModXact 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
226void ICAPModXact::writePrimeBody()
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
240void ICAPModXact::writeSomeBody(const char *label, size_t size)
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);
c99de607 252 const size_t chunkSize = XMIN(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 {
c99de607 265 debugs(93, 7, "ICAPModXact 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
774c051c 290void ICAPModXact::addLastRequestChunk(MemBuf &buf)
291{
c99de607 292 const bool ieof = state.writing == State::writingPreview && preview.ieof();
293 openChunk(buf, 0, ieof);
294 closeChunk(buf);
774c051c 295}
296
c99de607 297void ICAPModXact::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
c99de607 302void ICAPModXact::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?
308bool ICAPModXact::virginBodyEndReached(const VirginBodyAct &act) const
309{
310 return
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
317size_t ICAPModXact::virginContentSize(const 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
329const char *ICAPModXact::virginContentData(const 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
337void ICAPModXact::virginConsume()
338{
478cfe99 339 debugs(93, 9, "consumption guards: " << !virgin.body_pipe << isRetriable);
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
350 // because delayAwareRead() is arguably broken. See
351 // HttpStateData::maybeReadVirginBody for more details.
352 if (canStartBypass && bp.buf().spaceSize() > 2) {
353 // Postponing may increase memory footprint and slow the HTTP side
354 // down. Not postponing may increase the number of ICAP errors
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 <<
366 " acts " << virginBodyWriting.active() << virginBodySending.active() <<
367 " consumed=" << virginConsumed <<
368 " from " << virgin.body_pipe->status());
369
5f8252d2 370 if (virginBodyWriting.active())
371 offset = XMIN(virginBodyWriting.offset(), offset);
774c051c 372
5f8252d2 373 if (virginBodySending.active())
374 offset = XMIN(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
388void ICAPModXact::handleCommWroteBody()
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.
396void ICAPModXact::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
428void ICAPModXact::stopBackup()
429{
5f8252d2 430 if (!virginBodySending.active())
774c051c 431 return;
432
5f8252d2 433 debugs(93, 7, "ICAPModXact will no longer backup" << status());
434 virginBodySending.disable();
774c051c 435 virginConsume();
436}
437
438bool ICAPModXact::doneAll() const
439{
440 return ICAPXaction::doneAll() && !state.serviceWaiting &&
5f8252d2 441 doneSending() &&
774c051c 442 doneReading() && state.doneWriting();
443}
444
445void ICAPModXact::startReading()
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
456void ICAPModXact::readMore()
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 &&
465 !adapted.body_pipe->buf().hasPotentialSpace()) {
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
477void ICAPModXact::handleCommRead(size_t)
478{
479 Must(!state.doneParsing());
480 parseMore();
481 readMore();
482}
483
484void ICAPModXact::echoMore()
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 " <<
492 virgin.body_pipe->status());
493 debugs(93,5, HERE << "will echo up to " << sizeMax << " bytes to " <<
494 adapted.body_pipe->status());
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 <<
774c051c 499 " bytes");
5f8252d2 500 virginBodySending.progress(size);
774c051c 501 virginConsume();
478cfe99 502 disableBypass("echoed content");
774c051c 503 }
504
5f8252d2 505 if (virginBodyEndReached(virginBodySending)) {
506 debugs(93, 5, "ICAPModXact echoed all" << status());
774c051c 507 stopSending(true);
508 } else {
5f8252d2 509 debugs(93, 5, "ICAPModXact has " <<
510 virgin.body_pipe->buf().contentSize() << " bytes " <<
511 "and expects more to echo" << status());
512 // TODO: timeout if virgin or adapted pipes are broken
774c051c 513 }
514}
515
516bool ICAPModXact::doneSending() const
517{
774c051c 518 return state.sending == State::sendingDone;
519}
520
478cfe99 521// stop (or do not start) sending adapted message body
774c051c 522void ICAPModXact::stopSending(bool nicely)
523{
524 if (doneSending())
525 return;
526
527 if (state.sending != State::sendingUndecided) {
5f8252d2 528 debugs(93, 7, "ICAPModXact will no longer send" << status());
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 {
5f8252d2 537 debugs(93, 7, "ICAPModXact will not start sending" << status());
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
546void ICAPModXact::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
556void ICAPModXact::parseMore()
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
0a8bbeeb 569void ICAPModXact::callException(const std::exception &e)
478cfe99 570{
571 if (!canStartBypass || isRetriable) {
572 ICAPXaction::callException(e);
573 return;
574 }
575
576 try {
4932ad93 577 debugs(93, 3, "bypassing ICAPModXact::" << inCall << " exception: " <<
0a8bbeeb 578 e.what() << ' ' << status());
478cfe99 579 bypassFailure();
580 }
0a8bbeeb 581 catch (const std::exception &bypassE) {
478cfe99 582 ICAPXaction::callException(bypassE);
583 }
584}
585
586void ICAPModXact::bypassFailure()
587{
588 disableBypass("already started to bypass");
589
590 Must(!isRetriable); // or we should not be bypassing
591
592 prepEchoing();
593
594 startSending();
595
596 // end all activities associated with the ICAP server
597
598 stopParsing();
599
600 stopWriting(true); // or should we force it?
601 if (connection >= 0) {
602 reuseConnection = false; // be conservative
603 cancelRead(); // may not work; and we cannot stop connecting either
604 if (!doneWithIo())
605 debugs(93, 7, "Warning: bypass failed to stop I/O" << status());
606 }
607}
608
609void ICAPModXact::disableBypass(const char *reason)
610{
611 if (canStartBypass) {
612 debugs(93,7, HERE << "will never start bypass because " << reason);
613 canStartBypass = false;
614 }
615}
616
617
618
774c051c 619// note that allocation for echoing is done in handle204NoContent()
620void ICAPModXact::maybeAllocateHttpMsg()
621{
5f8252d2 622 if (adapted.header) // already allocated
774c051c 623 return;
624
625 if (gotEncapsulated("res-hdr")) {
5f8252d2 626 adapted.setHeader(new HttpReply);
774c051c 627 } else if (gotEncapsulated("req-hdr")) {
5f8252d2 628 adapted.setHeader(new HttpRequest);
774c051c 629 } else
630 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
631}
632
633void ICAPModXact::parseHeaders()
634{
635 Must(state.parsingHeaders());
636
b107a5a5 637 if (state.parsing == State::psIcapHeader) {
638 debugs(93, 5, HERE << "parse ICAP headers");
774c051c 639 parseIcapHead();
b107a5a5 640 }
774c051c 641
b107a5a5 642 if (state.parsing == State::psHttpHeader) {
643 debugs(93, 5, HERE << "parse HTTP headers");
774c051c 644 parseHttpHead();
b107a5a5 645 }
774c051c 646
647 if (state.parsingHeaders()) { // need more data
648 Must(mayReadMore());
649 return;
650 }
651
478cfe99 652 startSending();
653}
654
655// called after parsing all headers or when bypassing an exception
656void ICAPModXact::startSending()
657{
658 disableBypass("sent headers");
c824c43b 659 sendAnswer(adapted.header);
774c051c 660
661 if (state.sending == State::sendingVirgin)
662 echoMore();
663}
664
665void ICAPModXact::parseIcapHead()
666{
667 Must(state.sending == State::sendingUndecided);
668
669 if (!parseHead(icapReply))
670 return;
671
fc764d26 672 if (httpHeaderHasConnDir(&icapReply->header, "close")) {
673 debugs(93, 5, HERE << "found connection close");
674 reuseConnection = false;
675 }
676
774c051c 677 switch (icapReply->sline.status) {
678
679 case 100:
680 handle100Continue();
681 break;
682
683 case 200:
5bd21e1d 684 case 201: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
b559db5d 685
686 if (!validate200Ok()) {
687 throw TexcHere("Invalid ICAP Response");
688 } else {
689 handle200Ok();
690 }
691
774c051c 692 break;
693
694 case 204:
695 handle204NoContent();
696 break;
697
698 default:
b559db5d 699 debugs(93, 5, HERE << "ICAP status " << icapReply->sline.status);
774c051c 700 handleUnknownScode();
701 break;
702 }
703
704 // handle100Continue() manages state.writing on its own.
705 // Non-100 status means the server needs no postPreview data from us.
706 if (state.writing == State::writingPaused)
c99de607 707 stopWriting(true);
774c051c 708}
709
b559db5d 710bool ICAPModXact::validate200Ok()
711{
0bef8dd7 712 if (ICAP::methodRespmod == service().cfg().method) {
b559db5d 713 if (!gotEncapsulated("res-hdr"))
714 return false;
715
716 return true;
717 }
718
0bef8dd7 719 if (ICAP::methodReqmod == service().cfg().method) {
b559db5d 720 if (!gotEncapsulated("res-hdr") && !gotEncapsulated("req-hdr"))
721 return false;
722
723 return true;
724 }
725
726 return false;
727}
728
774c051c 729void ICAPModXact::handle100Continue()
730{
731 Must(state.writing == State::writingPaused);
5f8252d2 732 // server must not respond before the end of preview: we may send ieof
774c051c 733 Must(preview.enabled() && preview.done() && !preview.ieof());
774c051c 734
5f8252d2 735 // 100 "Continue" cancels our preview commitment, not 204s outside preview
736 if (!state.allowedPostview204)
774c051c 737 stopBackup();
738
c99de607 739 state.parsing = State::psIcapHeader; // eventually
740 icapReply->reset();
774c051c 741
742 state.writing = State::writingPrime;
743
744 writeMore();
745}
746
747void ICAPModXact::handle200Ok()
748{
749 state.parsing = State::psHttpHeader;
750 state.sending = State::sendingAdapted;
751 stopBackup();
5f8252d2 752 checkConsuming();
774c051c 753}
754
755void ICAPModXact::handle204NoContent()
756{
757 stopParsing();
478cfe99 758 prepEchoing();
759}
760
761// Called when we receive a 204 No Content response and
762// when we are trying to bypass a service failure.
763// We actually start sending (echoig or not) in startSending.
764void ICAPModXact::prepEchoing()
765{
766 disableBypass("preparing to echo content");
774c051c 767
768 // We want to clone the HTTP message, but we do not want
5f8252d2 769 // to copy some non-HTTP state parts that HttpMsg kids carry in them.
774c051c 770 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
771 // Instead, we simply write the HTTP message and "clone" it by parsing.
772
5f8252d2 773 HttpMsg *oldHead = virgin.header;
774c051c 774 debugs(93, 7, "ICAPModXact cloning virgin message " << oldHead);
775
776 MemBuf httpBuf;
777
778 // write the virgin message into a memory buffer
779 httpBuf.init();
780 packHead(httpBuf, oldHead);
781
c99de607 782 // allocate the adapted message and copy metainfo
5f8252d2 783 Must(!adapted.header);
7514268e 784 HttpMsg *newHead = NULL;
c99de607 785 if (const HttpRequest *oldR = dynamic_cast<const HttpRequest*>(oldHead)) {
786 HttpRequest *newR = new HttpRequest;
5f8252d2 787 inheritVirginProperties(*newR, *oldR);
c99de607 788 newHead = newR;
789 } else
790 if (dynamic_cast<const HttpReply*>(oldHead))
791 newHead = new HttpReply;
774c051c 792 Must(newHead);
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
5f8252d2 805 debugs(93, 7, "ICAPModXact cloned virgin message " << oldHead << " to " <<
806 newHead);
807
808 // setup adapted body pipe if needed
809 if (oldHead->body_pipe != NULL) {
810 debugs(93, 7, HERE << "will echo virgin body from " <<
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 " <<
823 adapted.body_pipe);
824 } else {
825 debugs(93, 7, HERE << "no virgin body to echo");
826 stopSending(true);
827 }
774c051c 828}
829
830void ICAPModXact::handleUnknownScode()
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
840void ICAPModXact::parseHttpHead()
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
848 if (HttpRequest *newHead = dynamic_cast<HttpRequest*>(adapted.header)) {
849 const HttpRequest *oldR = dynamic_cast<const HttpRequest*>(virgin.header);
850 Must(oldR);
851 // TODO: the adapted request did not really originate from the
852 // client; give proxy admin an option to prevent copying of
853 // sensitive client information here. See the following thread:
854 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
855 inheritVirginProperties(*newHead, *oldR);
856 }
774c051c 857 }
858
5f8252d2 859 decideOnParsingBody();
774c051c 860}
861
c99de607 862// parses both HTTP and ICAP headers
774c051c 863bool ICAPModXact::parseHead(HttpMsg *head)
864{
c99de607 865 Must(head);
def17b6a 866 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " head bytes to parse" <<
774c051c 867 "; state: " << state.parsing);
868
869 http_status error = HTTP_STATUS_NONE;
870 const bool parsed = head->parse(&readBuf, commEof, &error);
871 Must(parsed || !error); // success or need more data
872
c99de607 873 if (!parsed) { // need more data
b107a5a5 874 debugs(93, 5, HERE << "parse failed, need more data, return false");
774c051c 875 head->reset();
876 return false;
877 }
878
b107a5a5 879 debugs(93, 5, HERE << "parse success, consume " << head->hdr_sz << " bytes, return true");
774c051c 880 readBuf.consume(head->hdr_sz);
881 return true;
882}
883
5f8252d2 884// TODO: Move this method to HttpRequest?
885void ICAPModXact::inheritVirginProperties(HttpRequest &newR, const HttpRequest &oldR) {
774c051c 886
5f8252d2 887 newR.client_addr = oldR.client_addr;
5f8252d2 888 newR.my_addr = oldR.my_addr;
5f8252d2 889
890 // This may be too conservative for the 204 No Content case
891 // may eventually need cloneNullAdaptationImmune() for that.
892 newR.flags = oldR.flags.cloneAdaptationImmune();
774c051c 893
5f8252d2 894 if (oldR.auth_user_request) {
895 newR.auth_user_request = oldR.auth_user_request;
61527519 896 AUTHUSERREQUESTLOCK(newR.auth_user_request, "newR in ICAPModXact");
5f8252d2 897 }
898}
899
900void ICAPModXact::decideOnParsingBody() {
200ac359 901 if (gotEncapsulated("res-body") || gotEncapsulated("req-body")) {
5f8252d2 902 debugs(93, 5, HERE << "expecting a body");
903 state.parsing = State::psBody;
904 bodyParser = new ChunkedCodingParser;
905 makeAdaptedBodyPipe("adapted response from the ICAP server");
906 Must(state.sending == State::sendingAdapted);
774c051c 907 } else {
b559db5d 908 debugs(93, 5, HERE << "not expecting a body");
5f8252d2 909 stopParsing();
910 stopSending(true);
774c051c 911 }
774c051c 912}
913
5f8252d2 914void ICAPModXact::parseBody()
774c051c 915{
5f8252d2 916 Must(state.parsing == State::psBody);
917 Must(bodyParser);
774c051c 918
5f8252d2 919 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " body bytes to parse");
774c051c 920
5f8252d2 921 // the parser will throw on errors
922 BodyPipeCheckout bpc(*adapted.body_pipe);
923 const bool parsed = bodyParser->parse(&readBuf, &bpc.buf);
924 bpc.checkIn();
774c051c 925
aa761e5f 926 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " body bytes after " <<
774c051c 927 "parse; parsed all: " << parsed);
928
478cfe99 929 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
930 if (adapted.body_pipe->buf().contentSize() > 0) // parsed something sometime
931 disableBypass("sent adapted content");
932
5f8252d2 933 if (parsed) {
934 stopParsing();
935 stopSending(true); // the parser succeeds only if all parsed data fits
936 return;
937 }
774c051c 938
c99de607 939 debugs(93,3,HERE << this << " needsMoreData = " << bodyParser->needsMoreData());
3b299123 940
941 if (bodyParser->needsMoreData()) {
c99de607 942 debugs(93,3,HERE << this);
774c051c 943 Must(mayReadMore());
3b299123 944 readMore();
945 }
774c051c 946
947 if (bodyParser->needsMoreSpace()) {
948 Must(!doneSending()); // can hope for more space
5f8252d2 949 Must(adapted.body_pipe->buf().contentSize() > 0); // paranoid
950 // TODO: there should be a timeout in case the sink is broken
951 // or cannot consume partial content (while we need more space)
774c051c 952 }
774c051c 953}
954
955void ICAPModXact::stopParsing()
956{
957 if (state.parsing == State::psDone)
958 return;
959
5f8252d2 960 debugs(93, 7, "ICAPModXact will no longer parse" << status());
774c051c 961
962 delete bodyParser;
963
964 bodyParser = NULL;
965
966 state.parsing = State::psDone;
967}
968
969// HTTP side added virgin body data
bd7f2ede 970void ICAPModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer)
774c051c 971{
774c051c 972 writeMore();
973
974 if (state.sending == State::sendingVirgin)
975 echoMore();
774c051c 976}
977
978// HTTP side sent us all virgin info
bd7f2ede 979void ICAPModXact::noteBodyProductionEnded(BodyPipe::Pointer)
774c051c 980{
5f8252d2 981 Must(virgin.body_pipe->productionEnded());
774c051c 982
983 // push writer and sender in case we were waiting for the last-chunk
984 writeMore();
985
986 if (state.sending == State::sendingVirgin)
987 echoMore();
774c051c 988}
989
585ab260 990// body producer aborted, but the initiator may still want to know
991// the answer, even though the HTTP message has been truncated
bd7f2ede 992void ICAPModXact::noteBodyProducerAborted(BodyPipe::Pointer)
774c051c 993{
585ab260 994 Must(virgin.body_pipe->productionEnded());
995
996 // push writer and sender in case we were waiting for the last-chunk
997 writeMore();
998
999 if (state.sending == State::sendingVirgin)
1000 echoMore();
5f8252d2 1001}
1002
5f8252d2 1003// adapted body consumer wants more adapted data and
1004// possibly freed some buffer space
bd7f2ede 1005void ICAPModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer)
774c051c 1006{
774c051c 1007 if (state.sending == State::sendingVirgin)
1008 echoMore();
3b299123 1009 else if (state.sending == State::sendingAdapted)
1010 parseMore();
774c051c 1011 else
3b299123 1012 Must(state.sending == State::sendingUndecided);
774c051c 1013}
1014
5f8252d2 1015// adapted body consumer aborted
bd7f2ede 1016void ICAPModXact::noteBodyConsumerAborted(BodyPipe::Pointer)
774c051c 1017{
5f8252d2 1018 mustStop("adapted body consumer aborted");
774c051c 1019}
1020
1021// internal cleanup
5f8252d2 1022void ICAPModXact::swanSong()
774c051c 1023{
5f8252d2 1024 debugs(93, 5, HERE << "swan sings" << status());
1025
c99de607 1026 stopWriting(false);
c824c43b 1027 stopSending(false);
774c051c 1028
1029 if (icapReply) {
1030 delete icapReply;
1031 icapReply = NULL;
1032 }
1033
5f8252d2 1034 ICAPXaction::swanSong();
774c051c 1035}
1036
1037void ICAPModXact::makeRequestHeaders(MemBuf &buf)
1038{
cc192b50 1039 char ntoabuf[MAX_IPSTRLEN];
12b91c99 1040 /*
1041 * XXX These should use HttpHdr interfaces instead of Printfs
1042 */
0bef8dd7 1043 const Adaptation::ServiceConfig &s = service().cfg();
30abd221 1044 buf.Printf("%s %s ICAP/1.0\r\n", s.methodStr(), s.uri.buf());
1045 buf.Printf("Host: %s:%d\r\n", s.host.buf(), s.port);
12b91c99 1046 buf.Printf("Date: %s\r\n", mkrfc1123(squid_curtime));
1047
1048 if (!TheICAPConfig.reuse_connections)
1049 buf.Printf("Connection: close\r\n");
1050
2cdeea82 1051 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1052 // as ICAP headers.
1053 if (virgin.header->header.has(HDR_PROXY_AUTHENTICATE))
1054 buf.Printf("Proxy-Authenticate: %s\r\n",
1055 virgin.header->header.getByName("Proxy-Authenticate").buf());
1056
1057 if (virgin.header->header.has(HDR_PROXY_AUTHORIZATION))
1058 buf.Printf("Proxy-Authorization: %s\r\n",
1059 virgin.header->header.getByName("Proxy-Authorization").buf());
1060
774c051c 1061 buf.Printf("Encapsulated: ");
1062
1063 MemBuf httpBuf;
12b91c99 1064
774c051c 1065 httpBuf.init();
1066
1067 // build HTTP request header, if any
1068 ICAP::Method m = s.method;
1069
5f8252d2 1070 const HttpRequest *request = virgin.cause ?
1071 virgin.cause :
1072 dynamic_cast<const HttpRequest*>(virgin.header);
c99de607 1073
5f8252d2 1074 // to simplify, we could assume that request is always available
c99de607 1075
30abd221 1076 String urlPath;
c99de607 1077 if (request) {
1078 urlPath = request->urlpath;
1079 if (ICAP::methodRespmod == m)
1080 encapsulateHead(buf, "req-hdr", httpBuf, request);
1081 else
1082 if (ICAP::methodReqmod == m)
5f8252d2 1083 encapsulateHead(buf, "req-hdr", httpBuf, virgin.header);
c99de607 1084 }
774c051c 1085
1086 if (ICAP::methodRespmod == m)
5f8252d2 1087 if (const HttpMsg *prime = virgin.header)
774c051c 1088 encapsulateHead(buf, "res-hdr", httpBuf, prime);
1089
1090 if (!virginBody.expected())
1dd6edf2 1091 buf.Printf("null-body=%d", (int) httpBuf.contentSize());
774c051c 1092 else if (ICAP::methodReqmod == m)
1dd6edf2 1093 buf.Printf("req-body=%d", (int) httpBuf.contentSize());
774c051c 1094 else
1dd6edf2 1095 buf.Printf("res-body=%d", (int) httpBuf.contentSize());
774c051c 1096
1097 buf.append(ICAP::crlf, 2); // terminate Encapsulated line
1098
c824c43b 1099 if (preview.enabled()) {
774c051c 1100 buf.Printf("Preview: %d\r\n", (int)preview.ad());
5f8252d2 1101 if (virginBody.expected()) // there is a body to preview
1102 virginBodySending.plan();
1103 else
1104 finishNullOrEmptyBodyPreview(httpBuf);
774c051c 1105 }
1106
1107 if (shouldAllow204()) {
5f8252d2 1108 debugs(93,5, HERE << "will allow 204s outside of preview");
1109 state.allowedPostview204 = true;
774c051c 1110 buf.Printf("Allow: 204\r\n");
5f8252d2 1111 if (virginBody.expected()) // there is a body to echo
1112 virginBodySending.plan();
774c051c 1113 }
1114
c99de607 1115 if (TheICAPConfig.send_client_ip && request)
cc192b50 1116 if (!request->client_addr.IsAnyAddr() && !request->client_addr.IsNoAddr())
1117 buf.Printf("X-Client-IP: %s\r\n", request->client_addr.NtoA(ntoabuf,MAX_IPSTRLEN));
a97e82a8 1118
c99de607 1119 if (TheICAPConfig.send_client_username && request)
5f8252d2 1120 makeUsernameHeader(request, buf);
a97e82a8 1121
2dfede9e 1122 // fprintf(stderr, "%s\n", buf.content());
a97e82a8 1123
774c051c 1124 buf.append(ICAP::crlf, 2); // terminate ICAP header
1125
1126 // start ICAP request body with encapsulated HTTP headers
1127 buf.append(httpBuf.content(), httpBuf.contentSize());
1128
1129 httpBuf.clean();
1130}
1131
5f8252d2 1132void ICAPModXact::makeUsernameHeader(const HttpRequest *request, MemBuf &buf) {
76f142cd 1133 if (const AuthUserRequest *auth = request->auth_user_request) {
5f8252d2 1134 if (char const *name = auth->username()) {
1135 const char *value = TheICAPConfig.client_username_encode ?
1136 base64_encode(name) : name;
1137 buf.Printf("%s: %s\r\n", TheICAPConfig.client_username_header,
1138 value);
1139 }
1140 }
1141}
1142
774c051c 1143void ICAPModXact::encapsulateHead(MemBuf &icapBuf, const char *section, MemBuf &httpBuf, const HttpMsg *head)
1144{
1145 // update ICAP header
7cab7e9f 1146 icapBuf.Printf("%s=%d, ", section, (int) httpBuf.contentSize());
774c051c 1147
2cdeea82 1148 // begin cloning
1149 HttpMsg *headClone = NULL;
1150
1151 if (const HttpRequest* old_request = dynamic_cast<const HttpRequest*>(head)) {
1152 HttpRequest* new_request = new HttpRequest;
1153 urlParse(old_request->method, old_request->canonical,new_request);
1154 new_request->http_ver = old_request->http_ver;
1155 inheritVirginProperties(*new_request, *old_request);
1156 headClone = new_request;
1157 }
1158 else if (const HttpReply *old_reply = dynamic_cast<const HttpReply*>(head)) {
1159 HttpReply* new_reply = new HttpReply;
1160 new_reply->sline = old_reply->sline;
1161 headClone = new_reply;
1162 }
1163
1164 Must(headClone);
1165
1166 HttpHeaderPos pos = HttpHeaderInitPos;
1167 HttpHeaderEntry* p_head_entry = NULL;
1168 while (NULL != (p_head_entry = head->header.getEntry(&pos)) )
1169 headClone->header.addEntry(p_head_entry->clone());
1170
1171 // end cloning
1172
1173 // remove all hop-by-hop headers from the clone
dcf3665b 1174 headClone->header.delById(HDR_PROXY_AUTHENTICATE);
2cdeea82 1175 headClone->header.removeHopByHopEntries();
1176
1177 // pack polished HTTP header
1178 packHead(httpBuf, headClone);
1179
1180 delete headClone;
774c051c 1181}
1182
1183void ICAPModXact::packHead(MemBuf &httpBuf, const HttpMsg *head)
1184{
1185 Packer p;
1186 packerToMemInit(&p, &httpBuf);
1187 head->packInto(&p, true);
1188 packerClean(&p);
1189}
1190
1191// decides whether to offer a preview and calculates its size
c824c43b 1192void ICAPModXact::decideOnPreview()
774c051c 1193{
7cdbbd47 1194 if (!TheICAPConfig.preview_enable) {
1195 debugs(93, 5, HERE << "preview disabled by squid.conf");
c824c43b 1196 return;
7cdbbd47 1197 }
1198
c824c43b 1199 const HttpRequest *request = virgin.cause ?
1200 virgin.cause :
1201 dynamic_cast<const HttpRequest*>(virgin.header);
30abd221 1202 const String urlPath = request ? request->urlpath : String();
5f8252d2 1203 size_t wantedSize;
c99de607 1204 if (!service().wantsPreview(urlPath, wantedSize)) {
1205 debugs(93, 5, "ICAPModXact should not offer preview for " << urlPath);
c824c43b 1206 return;
774c051c 1207 }
1208
c824c43b 1209 // we decided to do preview, now compute its size
1210
774c051c 1211 Must(wantedSize >= 0);
1212
1213 // cannot preview more than we can backup
1214 size_t ad = XMIN(wantedSize, TheBackupLimit);
1215
5f8252d2 1216 if (!virginBody.expected())
1217 ad = 0;
774c051c 1218 else
5f8252d2 1219 if (virginBody.knownSize())
47f6e231 1220 ad = XMIN(static_cast<uint64_t>(ad), virginBody.size()); // not more than we have
774c051c 1221
1222 debugs(93, 5, "ICAPModXact should offer " << ad << "-byte preview " <<
1223 "(service wanted " << wantedSize << ")");
1224
1225 preview.enable(ad);
5f8252d2 1226 Must(preview.enabled());
774c051c 1227}
1228
1229// decides whether to allow 204 responses
1230bool ICAPModXact::shouldAllow204()
1231{
1232 if (!service().allows204())
1233 return false;
1234
c824c43b 1235 return canBackupEverything();
1236}
1237
1238// used by shouldAllow204 and decideOnRetries
1239bool ICAPModXact::canBackupEverything() const
1240{
774c051c 1241 if (!virginBody.expected())
c824c43b 1242 return true; // no body means no problems with backup
774c051c 1243
c824c43b 1244 // if there is a body, check whether we can backup it all
774c051c 1245
1246 if (!virginBody.knownSize())
1247 return false;
1248
1249 // or should we have a different backup limit?
1250 // note that '<' allows for 0-termination of the "full" backup buffer
1251 return virginBody.size() < TheBackupLimit;
1252}
1253
c824c43b 1254// Decide whether this transaction can be retried if pconn fails
1255// Must be called after decideOnPreview and before openConnection()
1256void ICAPModXact::decideOnRetries()
1257{
1258 if (!isRetriable)
1259 return; // no, already decided
1260
1261 if (preview.enabled())
1262 return; // yes, because preview provides enough guarantees
1263
1264 if (canBackupEverything())
1265 return; // yes, because we can back everything up
1266
1267 disableRetries(); // no, because we cannot back everything up
1268}
1269
5f8252d2 1270// Normally, the body-writing code handles preview body. It can deal with
1271// bodies of unexpected size, including those that turn out to be empty.
1272// However, that code assumes that the body was expected and body control
1273// structures were initialized. This is not the case when there is no body
1274// or the body is known to be empty, because the virgin message will lack a
1275// body_pipe. So we handle preview of null-body and zero-size bodies here.
1276void ICAPModXact::finishNullOrEmptyBodyPreview(MemBuf &buf)
1277{
1278 Must(!virginBodyWriting.active()); // one reason we handle it here
1279 Must(!virgin.body_pipe); // another reason we handle it here
1280 Must(!preview.ad());
1281
1282 // do not add last-chunk because our Encapsulated header says null-body
1283 // addLastRequestChunk(buf);
1284 preview.wrote(0, true);
1285
1286 Must(preview.done());
1287 Must(preview.ieof());
1288}
1289
774c051c 1290void ICAPModXact::fillPendingStatus(MemBuf &buf) const
1291{
c99de607 1292 ICAPXaction::fillPendingStatus(buf);
1293
774c051c 1294 if (state.serviceWaiting)
1295 buf.append("U", 1);
1296
5f8252d2 1297 if (virgin.body_pipe != NULL)
c99de607 1298 buf.append("R", 1);
1299
5f8252d2 1300 if (connection > 0 && !doneReading())
c99de607 1301 buf.append("r", 1);
1302
774c051c 1303 if (!state.doneWriting() && state.writing != State::writingInit)
1304 buf.Printf("w(%d)", state.writing);
1305
1306 if (preview.enabled()) {
1307 if (!preview.done())
1dd6edf2 1308 buf.Printf("P(%d)", (int) preview.debt());
774c051c 1309 }
1310
5f8252d2 1311 if (virginBodySending.active())
774c051c 1312 buf.append("B", 1);
1313
1314 if (!state.doneParsing() && state.parsing != State::psIcapHeader)
1315 buf.Printf("p(%d)", state.parsing);
1316
1317 if (!doneSending() && state.sending != State::sendingUndecided)
1318 buf.Printf("S(%d)", state.sending);
478cfe99 1319
1320 if (canStartBypass)
1321 buf.append("Y", 1);
774c051c 1322}
1323
1324void ICAPModXact::fillDoneStatus(MemBuf &buf) const
1325{
c99de607 1326 ICAPXaction::fillDoneStatus(buf);
1327
5f8252d2 1328 if (!virgin.body_pipe)
774c051c 1329 buf.append("R", 1);
1330
1331 if (state.doneWriting())
1332 buf.append("w", 1);
1333
1334 if (preview.enabled()) {
1335 if (preview.done())
1336 buf.Printf("P%s", preview.ieof() ? "(ieof)" : "");
1337 }
1338
1339 if (doneReading())
1340 buf.append("r", 1);
1341
1342 if (state.doneParsing())
1343 buf.append("p", 1);
1344
1345 if (doneSending())
1346 buf.append("S", 1);
1347}
1348
1349bool ICAPModXact::gotEncapsulated(const char *section) const
1350{
a9925b40 1351 return icapReply->header.getByNameListMember("Encapsulated",
1352 section, ',').size() > 0;
774c051c 1353}
1354
1355// calculate whether there is a virgin HTTP body and
1356// whether its expected size is known
5f8252d2 1357// TODO: rename because we do not just estimate
774c051c 1358void ICAPModXact::estimateVirginBody()
1359{
5f8252d2 1360 // note: lack of size info may disable previews and 204s
774c051c 1361
5f8252d2 1362 HttpMsg *msg = virgin.header;
1363 Must(msg);
774c051c 1364
60745f24 1365 HttpRequestMethod method;
774c051c 1366
5f8252d2 1367 if (virgin.cause)
1368 method = virgin.cause->method;
774c051c 1369 else
5f8252d2 1370 if (HttpRequest *req = dynamic_cast<HttpRequest*>(msg))
1371 method = req->method;
1372 else
1373 method = METHOD_NONE;
774c051c 1374
47f6e231 1375 int64_t size;
5f8252d2 1376 // expectingBody returns true for zero-sized bodies, but we will not
1377 // get a pipe for that body, so we treat the message as bodyless
1378 if (method != METHOD_NONE && msg->expectingBody(method, size) && size) {
1379 debugs(93, 6, "ICAPModXact expects virgin body from " <<
1380 virgin.body_pipe << "; size: " << size);
1381
1382 virginBody.expect(size);
1383 virginBodyWriting.plan();
1384
1385 // sign up as a body consumer
1386 Must(msg->body_pipe != NULL);
1387 Must(msg->body_pipe == virgin.body_pipe);
1388 Must(virgin.body_pipe->setConsumerIfNotLate(this));
1389
1390 // make sure TheBackupLimit is in-sync with the buffer size
1391 Must(TheBackupLimit <= static_cast<size_t>(msg->body_pipe->buf().max_capacity));
774c051c 1392 } else {
1393 debugs(93, 6, "ICAPModXact does not expect virgin body");
5f8252d2 1394 Must(msg->body_pipe == NULL);
1395 checkConsuming();
774c051c 1396 }
1397}
1398
5f8252d2 1399void ICAPModXact::makeAdaptedBodyPipe(const char *what) {
1400 Must(!adapted.body_pipe);
1401 Must(!adapted.header->body_pipe);
1402 adapted.header->body_pipe = new BodyPipe(this);
1403 adapted.body_pipe = adapted.header->body_pipe;
1404 debugs(93, 7, HERE << "will supply " << what << " via " <<
1405 adapted.body_pipe << " pipe");
1406}
1407
774c051c 1408
1409// TODO: Move SizedEstimate, MemBufBackup, and ICAPPreview elsewhere
1410
1411SizedEstimate::SizedEstimate()
1412 : theData(dtUnexpected)
1413{}
1414
47f6e231 1415void SizedEstimate::expect(int64_t aSize)
774c051c 1416{
47f6e231 1417 theData = (aSize >= 0) ? aSize : (int64_t)dtUnknown;
774c051c 1418}
1419
1420bool SizedEstimate::expected() const
1421{
1422 return theData != dtUnexpected;
1423}
1424
1425bool SizedEstimate::knownSize() const
1426{
1427 Must(expected());
1428 return theData != dtUnknown;
1429}
1430
47f6e231 1431uint64_t SizedEstimate::size() const
774c051c 1432{
1433 Must(knownSize());
47f6e231 1434 return static_cast<uint64_t>(theData);
774c051c 1435}
1436
1437
1438
478cfe99 1439VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided)
774c051c 1440{}
1441
5f8252d2 1442void VirginBodyAct::plan()
774c051c 1443{
478cfe99 1444 Must(!disabled());
1445 Must(!theStart); // not started
1446 theState = stActive;
774c051c 1447}
1448
5f8252d2 1449void VirginBodyAct::disable()
774c051c 1450{
478cfe99 1451 theState = stDisabled;
774c051c 1452}
1453
5f8252d2 1454void VirginBodyAct::progress(size_t size)
774c051c 1455{
1456 Must(active());
1457 Must(size >= 0);
47f6e231 1458 theStart += static_cast<int64_t>(size);
774c051c 1459}
1460
47f6e231 1461uint64_t VirginBodyAct::offset() const
774c051c 1462{
1463 Must(active());
47f6e231 1464 return static_cast<uint64_t>(theStart);
774c051c 1465}
1466
774c051c 1467
1468ICAPPreview::ICAPPreview(): theWritten(0), theAd(0), theState(stDisabled)
1469{}
1470
1471void ICAPPreview::enable(size_t anAd)
1472{
1473 // TODO: check for anAd not exceeding preview size limit
1474 Must(anAd >= 0);
1475 Must(!enabled());
1476 theAd = anAd;
1477 theState = stWriting;
1478}
1479
1480bool ICAPPreview::enabled() const
1481{
1482 return theState != stDisabled;
1483}
1484
1485size_t ICAPPreview::ad() const
1486{
1487 Must(enabled());
1488 return theAd;
1489}
1490
1491bool ICAPPreview::done() const
1492{
1493 Must(enabled());
1494 return theState >= stIeof;
1495}
1496
1497bool ICAPPreview::ieof() const
1498{
1499 Must(enabled());
1500 return theState == stIeof;
1501}
1502
1503size_t ICAPPreview::debt() const
1504{
1505 Must(enabled());
1506 return done() ? 0 : (theAd - theWritten);
1507}
1508
c99de607 1509void ICAPPreview::wrote(size_t size, bool wroteEof)
774c051c 1510{
1511 Must(enabled());
5f8252d2 1512
774c051c 1513 theWritten += size;
1514
5f8252d2 1515 Must(theWritten <= theAd);
1516
1517 if (wroteEof)
1518 theState = stIeof; // written size is irrelevant
1519 else
774c051c 1520 if (theWritten >= theAd)
5f8252d2 1521 theState = stDone;
774c051c 1522}
1523
3cfc19b3 1524bool ICAPModXact::fillVirginHttpHeader(MemBuf &mb) const
1525{
5f8252d2 1526 if (virgin.header == NULL)
3cfc19b3 1527 return false;
1528
5f8252d2 1529 virgin.header->firstLineBuf(mb);
3cfc19b3 1530
1531 return true;
1532}
c824c43b 1533
1534
1535/* ICAPModXactLauncher */
1536
0bef8dd7 1537ICAPModXactLauncher::ICAPModXactLauncher(Adaptation::Initiator *anInitiator, HttpMsg *virginHeader, HttpRequest *virginCause, Adaptation::ServicePointer aService):
bd7f2ede 1538 AsyncJob("ICAPModXactLauncher"),
c824c43b 1539 ICAPLauncher("ICAPModXactLauncher", anInitiator, aService)
1540{
1541 virgin.setHeader(virginHeader);
1542 virgin.setCause(virginCause);
1543}
1544
1545ICAPXaction *ICAPModXactLauncher::createXaction()
1546{
0bef8dd7
AR
1547 ICAPServiceRep::Pointer s =
1548 dynamic_cast<ICAPServiceRep*>(theService.getRaw());
1549 Must(s != NULL);
1550 return new ICAPModXact(this, virgin.header, virgin.cause, s);
c824c43b 1551}