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