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