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