]> git.ipfire.org Git - thirdparty/squid.git/blob - src/adaptation/icap/ModXact.cc
Audit round 2 fallout.
[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 "comm/Connection.h"
20 #include "HttpMsg.h"
21 #include "HttpRequest.h"
22 #include "HttpReply.h"
23 #include "SquidTime.h"
24
25 // flow and terminology:
26 // HTTP| --> receive --> encode --> write --> |network
27 // end | <-- send <-- parse <-- read <-- |end
28
29 // TODO: replace gotEncapsulated() with something faster; we call it often
30
31 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap, ModXact);
32 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap, ModXactLauncher);
33
34 static const size_t TheBackupLimit = BodyPipe::MaxCapacity;
35
36 Adaptation::Icap::ModXact::State::State()
37 {
38 memset(this, 0, sizeof(*this));
39 }
40
41 Adaptation::Icap::ModXact::ModXact(Adaptation::Initiator *anInitiator, HttpMsg *virginHeader,
42 HttpRequest *virginCause, Adaptation::Icap::ServiceRep::Pointer &aService):
43 AsyncJob("Adaptation::Icap::ModXact"),
44 Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", anInitiator, aService),
45 virginConsumed(0),
46 bodyParser(NULL),
47 canStartBypass(false), // too early
48 protectGroupBypass(true),
49 replyBodySize(0),
50 adaptHistoryId(-1)
51 {
52 assert(virginHeader);
53
54 virgin.setHeader(virginHeader); // sets virgin.body_pipe if needed
55 virgin.setCause(virginCause); // may be NULL
56
57 // adapted header and body are initialized when we parse them
58
59 // writing and reading ends are handled by Adaptation::Icap::Xaction
60
61 // encoding
62 // nothing to do because we are using temporary buffers
63
64 // parsing; TODO: do not set until we parse, see ICAPOptXact
65 icapReply = HTTPMSGLOCK(new HttpReply);
66 icapReply->protoPrefix = "ICAP/"; // TODO: make an IcapReply class?
67
68 debugs(93,7, HERE << "initialized." << status());
69 }
70
71 // initiator wants us to start
72 void Adaptation::Icap::ModXact::start()
73 {
74 Adaptation::Icap::Xaction::start();
75
76 // reserve an adaptation history slot (attempts are known at this time)
77 Adaptation::History::Pointer ah = virginRequest().adaptLogHistory();
78 if (ah != NULL)
79 adaptHistoryId = ah->recordXactStart(service().cfg().key, icap_tr_start, attempts > 1);
80
81 estimateVirginBody(); // before virgin disappears!
82
83 canStartBypass = service().cfg().bypass;
84
85 // it is an ICAP violation to send request to a service w/o known OPTIONS
86
87 if (service().up())
88 startWriting();
89 else
90 waitForService();
91 }
92
93 void Adaptation::Icap::ModXact::waitForService()
94 {
95 Must(!state.serviceWaiting);
96 debugs(93, 7, HERE << "will wait for the ICAP service" << status());
97 state.serviceWaiting = true;
98 AsyncCall::Pointer call = asyncCall(93,5, "Adaptation::Icap::ModXact::noteServiceReady",
99 MemFun(this, &Adaptation::Icap::ModXact::noteServiceReady));
100 service().callWhenReady(call);
101 }
102
103 void Adaptation::Icap::ModXact::noteServiceReady()
104 {
105 Must(state.serviceWaiting);
106 state.serviceWaiting = false;
107
108 if (service().up()) {
109 startWriting();
110 } else {
111 disableRetries();
112 disableRepeats("ICAP service is unusable");
113 throw TexcHere("ICAP service is unusable");
114 }
115 }
116
117 void Adaptation::Icap::ModXact::startWriting()
118 {
119 state.writing = State::writingConnect;
120
121 decideOnPreview(); // must be decided before we decideOnRetries
122 decideOnRetries();
123
124 openConnection();
125 }
126
127 // connection with the ICAP service established
128 void Adaptation::Icap::ModXact::handleCommConnected()
129 {
130 Must(state.writing == State::writingConnect);
131
132 startReading(); // wait for early errors from the ICAP server
133
134 MemBuf requestBuf;
135 requestBuf.init();
136
137 makeRequestHeaders(requestBuf);
138 debugs(93, 9, HERE << "will write" << status() << ":\n" <<
139 (requestBuf.terminate(), requestBuf.content()));
140
141 // write headers
142 state.writing = State::writingHeaders;
143 icap_tio_start = current_time;
144 scheduleWrite(requestBuf);
145 }
146
147 void Adaptation::Icap::ModXact::handleCommWrote(size_t sz)
148 {
149 debugs(93, 5, HERE << "Wrote " << sz << " bytes");
150
151 if (state.writing == State::writingHeaders)
152 handleCommWroteHeaders();
153 else
154 handleCommWroteBody();
155 }
156
157 void Adaptation::Icap::ModXact::handleCommWroteHeaders()
158 {
159 Must(state.writing == State::writingHeaders);
160
161 // determine next step
162 if (preview.enabled())
163 state.writing = preview.done() ? State::writingPaused : State::writingPreview;
164 else if (virginBody.expected())
165 state.writing = State::writingPrime;
166 else {
167 stopWriting(true);
168 return;
169 }
170
171 writeMore();
172 }
173
174 void Adaptation::Icap::ModXact::writeMore()
175 {
176 debugs(93, 5, HERE << "checking whether to write more" << status());
177
178 if (writer != NULL) // already writing something
179 return;
180
181 switch (state.writing) {
182
183 case State::writingInit: // waiting for service OPTIONS
184 Must(state.serviceWaiting);
185
186 case State::writingConnect: // waiting for the connection to establish
187
188 case State::writingHeaders: // waiting for the headers to be written
189
190 case State::writingPaused: // waiting for the ICAP server response
191
192 case State::writingReallyDone: // nothing more to write
193 return;
194
195 case State::writingAlmostDone: // was waiting for the last write
196 stopWriting(false);
197 return;
198
199 case State::writingPreview:
200 writePreviewBody();
201 return;
202
203 case State::writingPrime:
204 writePrimeBody();
205 return;
206
207 default:
208 throw TexcHere("Adaptation::Icap::ModXact in bad writing state");
209 }
210 }
211
212 void Adaptation::Icap::ModXact::writePreviewBody()
213 {
214 debugs(93, 8, HERE << "will write Preview body from " <<
215 virgin.body_pipe << status());
216 Must(state.writing == State::writingPreview);
217 Must(virgin.body_pipe != NULL);
218
219 const size_t sizeMax = (size_t)virgin.body_pipe->buf().contentSize();
220 const size_t size = min(preview.debt(), sizeMax);
221 writeSomeBody("preview body", size);
222
223 // change state once preview is written
224
225 if (preview.done()) {
226 debugs(93, 7, HERE << "wrote entire Preview body" << status());
227
228 if (preview.ieof())
229 stopWriting(true);
230 else
231 state.writing = State::writingPaused;
232 }
233 }
234
235 void Adaptation::Icap::ModXact::writePrimeBody()
236 {
237 Must(state.writing == State::writingPrime);
238 Must(virginBodyWriting.active());
239
240 const size_t size = (size_t)virgin.body_pipe->buf().contentSize();
241 writeSomeBody("prime virgin body", size);
242
243 if (virginBodyEndReached(virginBodyWriting)) {
244 debugs(93, 5, HERE << "wrote entire body");
245 stopWriting(true);
246 }
247 }
248
249 void Adaptation::Icap::ModXact::writeSomeBody(const char *label, size_t size)
250 {
251 Must(!writer && state.writing < state.writingAlmostDone);
252 Must(virgin.body_pipe != NULL);
253 debugs(93, 8, HERE << "will write up to " << size << " bytes of " <<
254 label);
255
256 MemBuf writeBuf; // TODO: suggest a min size based on size and lastChunk
257
258 writeBuf.init(); // note: we assume that last-chunk will fit
259
260 const size_t writableSize = virginContentSize(virginBodyWriting);
261 const size_t chunkSize = min(writableSize, size);
262
263 if (chunkSize) {
264 debugs(93, 7, HERE << "will write " << chunkSize <<
265 "-byte chunk of " << label);
266
267 openChunk(writeBuf, chunkSize, false);
268 writeBuf.append(virginContentData(virginBodyWriting), chunkSize);
269 closeChunk(writeBuf);
270
271 virginBodyWriting.progress(chunkSize);
272 virginConsume();
273 } else {
274 debugs(93, 7, HERE << "has no writable " << label << " content");
275 }
276
277 const bool wroteEof = virginBodyEndReached(virginBodyWriting);
278 bool lastChunk = wroteEof;
279 if (state.writing == State::writingPreview) {
280 preview.wrote(chunkSize, wroteEof); // even if wrote nothing
281 lastChunk = lastChunk || preview.done();
282 }
283
284 if (lastChunk) {
285 debugs(93, 8, HERE << "will write last-chunk of " << label);
286 addLastRequestChunk(writeBuf);
287 }
288
289 debugs(93, 7, HERE << "will write " << writeBuf.contentSize()
290 << " raw bytes of " << label);
291
292 if (writeBuf.hasContent()) {
293 scheduleWrite(writeBuf); // comm will free the chunk
294 } else {
295 writeBuf.clean();
296 }
297 }
298
299 void Adaptation::Icap::ModXact::addLastRequestChunk(MemBuf &buf)
300 {
301 const bool ieof = state.writing == State::writingPreview && preview.ieof();
302 openChunk(buf, 0, ieof);
303 closeChunk(buf);
304 }
305
306 void Adaptation::Icap::ModXact::openChunk(MemBuf &buf, size_t chunkSize, bool ieof)
307 {
308 buf.Printf((ieof ? "%x; ieof\r\n" : "%x\r\n"), (int) chunkSize);
309 }
310
311 void Adaptation::Icap::ModXact::closeChunk(MemBuf &buf)
312 {
313 buf.append(ICAP::crlf, 2); // chunk-terminating CRLF
314 }
315
316 const HttpRequest &Adaptation::Icap::ModXact::virginRequest() const
317 {
318 const HttpRequest *request = virgin.cause ?
319 virgin.cause : dynamic_cast<const HttpRequest*>(virgin.header);
320 Must(request);
321 return *request;
322 }
323
324 // did the activity reached the end of the virgin body?
325 bool Adaptation::Icap::ModXact::virginBodyEndReached(const Adaptation::Icap::VirginBodyAct &act) const
326 {
327 return
328 !act.active() || // did all (assuming it was originally planned)
329 !virgin.body_pipe->expectMoreAfter(act.offset()); // wont have more
330 }
331
332 // the size of buffered virgin body data available for the specified activity
333 // if this size is zero, we may be done or may be waiting for more data
334 size_t Adaptation::Icap::ModXact::virginContentSize(const Adaptation::Icap::VirginBodyAct &act) const
335 {
336 Must(act.active());
337 // asbolute start of unprocessed data
338 const uint64_t dataStart = act.offset();
339 // absolute end of buffered data
340 const uint64_t dataEnd = virginConsumed + virgin.body_pipe->buf().contentSize();
341 Must(virginConsumed <= dataStart && dataStart <= dataEnd);
342 return static_cast<size_t>(dataEnd - dataStart);
343 }
344
345 // pointer to buffered virgin body data available for the specified activity
346 const char *Adaptation::Icap::ModXact::virginContentData(const Adaptation::Icap::VirginBodyAct &act) const
347 {
348 Must(act.active());
349 const uint64_t dataStart = act.offset();
350 Must(virginConsumed <= dataStart);
351 return virgin.body_pipe->buf().content() + static_cast<size_t>(dataStart-virginConsumed);
352 }
353
354 void Adaptation::Icap::ModXact::virginConsume()
355 {
356 debugs(93, 9, HERE << "consumption guards: " << !virgin.body_pipe << isRetriable <<
357 isRepeatable << canStartBypass << protectGroupBypass);
358
359 if (!virgin.body_pipe)
360 return; // nothing to consume
361
362 if (isRetriable)
363 return; // do not consume if we may have to retry later
364
365 BodyPipe &bp = *virgin.body_pipe;
366 const bool wantToPostpone = isRepeatable || canStartBypass || protectGroupBypass;
367
368 // Why > 2? HttpState does not use the last bytes in the buffer
369 // because delayAwareRead() is arguably broken. See
370 // HttpStateData::maybeReadVirginBody for more details.
371 if (wantToPostpone && bp.buf().spaceSize() > 2) {
372 // Postponing may increase memory footprint and slow the HTTP side
373 // down. Not postponing may increase the number of ICAP errors
374 // if the ICAP service fails. We may also use "potential" space to
375 // postpone more aggressively. Should the trade-off be configurable?
376 debugs(93, 8, HERE << "postponing consumption from " << bp.status());
377 return;
378 }
379
380 const size_t have = static_cast<size_t>(bp.buf().contentSize());
381 const uint64_t end = virginConsumed + have;
382 uint64_t offset = end;
383
384 debugs(93, 9, HERE << "max virgin consumption offset=" << offset <<
385 " acts " << virginBodyWriting.active() << virginBodySending.active() <<
386 " consumed=" << virginConsumed <<
387 " from " << virgin.body_pipe->status());
388
389 if (virginBodyWriting.active())
390 offset = min(virginBodyWriting.offset(), offset);
391
392 if (virginBodySending.active())
393 offset = min(virginBodySending.offset(), offset);
394
395 Must(virginConsumed <= offset && offset <= end);
396
397 if (const size_t size = static_cast<size_t>(offset - virginConsumed)) {
398 debugs(93, 8, HERE << "consuming " << size << " out of " << have <<
399 " virgin body bytes");
400 bp.consume(size);
401 virginConsumed += size;
402 Must(!isRetriable); // or we should not be consuming
403 disableRepeats("consumed content");
404 disableBypass("consumed content", true);
405 }
406 }
407
408 void Adaptation::Icap::ModXact::handleCommWroteBody()
409 {
410 writeMore();
411 }
412
413 // Called when we do not expect to call comm_write anymore.
414 // We may have a pending write though.
415 // If stopping nicely, we will just wait for that pending write, if any.
416 void Adaptation::Icap::ModXact::stopWriting(bool nicely)
417 {
418 if (state.writing == State::writingReallyDone)
419 return;
420
421 if (writer != NULL) {
422 if (nicely) {
423 debugs(93, 7, HERE << "will wait for the last write" << status());
424 state.writing = State::writingAlmostDone; // may already be set
425 checkConsuming();
426 return;
427 }
428 debugs(93, 3, HERE << "will NOT wait for the last write" << status());
429
430 // Comm does not have an interface to clear the writer callback nicely,
431 // but without clearing the writer we cannot recycle the connection.
432 // We prevent connection reuse and hope that we can handle a callback
433 // call at any time, usually in the middle of the destruction sequence!
434 // Somebody should add comm_remove_write_handler() to comm API.
435 reuseConnection = false;
436 ignoreLastWrite = true;
437 }
438
439 debugs(93, 7, HERE << "will no longer write" << status());
440 if (virginBodyWriting.active()) {
441 virginBodyWriting.disable();
442 virginConsume();
443 }
444 state.writing = State::writingReallyDone;
445 checkConsuming();
446 }
447
448 void Adaptation::Icap::ModXact::stopBackup()
449 {
450 if (!virginBodySending.active())
451 return;
452
453 debugs(93, 7, HERE << "will no longer backup" << status());
454 virginBodySending.disable();
455 virginConsume();
456 }
457
458 bool Adaptation::Icap::ModXact::doneAll() const
459 {
460 return Adaptation::Icap::Xaction::doneAll() && !state.serviceWaiting &&
461 doneSending() &&
462 doneReading() && state.doneWriting();
463 }
464
465 void Adaptation::Icap::ModXact::startReading()
466 {
467 Must(haveConnection());
468 Must(!reader);
469 Must(!adapted.header);
470 Must(!adapted.body_pipe);
471
472 // we use the same buffer for headers and body and then consume headers
473 readMore();
474 }
475
476 void Adaptation::Icap::ModXact::readMore()
477 {
478 if (reader != NULL || doneReading()) {
479 debugs(93,3,HERE << "returning from readMore because reader or doneReading()");
480 return;
481 }
482
483 // do not fill readBuf if we have no space to store the result
484 if (adapted.body_pipe != NULL &&
485 !adapted.body_pipe->buf().hasPotentialSpace()) {
486 debugs(93,3,HERE << "not reading because ICAP reply pipe is full");
487 return;
488 }
489
490 if (readBuf.hasSpace())
491 scheduleRead();
492 else
493 debugs(93,3,HERE << "nothing to do because !readBuf.hasSpace()");
494 }
495
496 // comm module read a portion of the ICAP response for us
497 void Adaptation::Icap::ModXact::handleCommRead(size_t)
498 {
499 Must(!state.doneParsing());
500 icap_tio_finish = current_time;
501 parseMore();
502 readMore();
503 }
504
505 void Adaptation::Icap::ModXact::echoMore()
506 {
507 Must(state.sending == State::sendingVirgin);
508 Must(adapted.body_pipe != NULL);
509 Must(virginBodySending.active());
510
511 const size_t sizeMax = virginContentSize(virginBodySending);
512 debugs(93,5, HERE << "will echo up to " << sizeMax << " bytes from " <<
513 virgin.body_pipe->status());
514 debugs(93,5, HERE << "will echo up to " << sizeMax << " bytes to " <<
515 adapted.body_pipe->status());
516
517 if (sizeMax > 0) {
518 const size_t size = adapted.body_pipe->putMoreData(virginContentData(virginBodySending), sizeMax);
519 debugs(93,5, HERE << "echoed " << size << " out of " << sizeMax <<
520 " bytes");
521 virginBodySending.progress(size);
522 disableRepeats("echoed content");
523 disableBypass("echoed content", true);
524 virginConsume();
525 }
526
527 if (virginBodyEndReached(virginBodySending)) {
528 debugs(93, 5, HERE << "echoed all" << status());
529 stopSending(true);
530 } else {
531 debugs(93, 5, HERE << "has " <<
532 virgin.body_pipe->buf().contentSize() << " bytes " <<
533 "and expects more to echo" << status());
534 // TODO: timeout if virgin or adapted pipes are broken
535 }
536 }
537
538 bool Adaptation::Icap::ModXact::doneSending() const
539 {
540 return state.sending == State::sendingDone;
541 }
542
543 // stop (or do not start) sending adapted message body
544 void Adaptation::Icap::ModXact::stopSending(bool nicely)
545 {
546 debugs(93, 7, HERE << "Enter stop sending ");
547 if (doneSending())
548 return;
549 debugs(93, 7, HERE << "Proceed with stop sending ");
550
551 if (state.sending != State::sendingUndecided) {
552 debugs(93, 7, HERE << "will no longer send" << status());
553 if (adapted.body_pipe != NULL) {
554 virginBodySending.disable();
555 // we may leave debts if we were echoing and the virgin
556 // body_pipe got exhausted before we echoed all planned bytes
557 const bool leftDebts = adapted.body_pipe->needsMoreData();
558 stopProducingFor(adapted.body_pipe, nicely && !leftDebts);
559 }
560 } else {
561 debugs(93, 7, HERE << "will not start sending" << status());
562 Must(!adapted.body_pipe);
563 }
564
565 state.sending = State::sendingDone;
566 checkConsuming();
567 }
568
569 // should be called after certain state.writing or state.sending changes
570 void Adaptation::Icap::ModXact::checkConsuming()
571 {
572 // quit if we already stopped or are still using the pipe
573 if (!virgin.body_pipe || !state.doneConsumingVirgin())
574 return;
575
576 debugs(93, 7, HERE << "will stop consuming" << status());
577 stopConsumingFrom(virgin.body_pipe);
578 }
579
580 void Adaptation::Icap::ModXact::parseMore()
581 {
582 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " bytes to parse" <<
583 status());
584 debugs(93, 5, HERE << "\n" << readBuf.content());
585
586 if (state.parsingHeaders())
587 parseHeaders();
588
589 if (state.parsing == State::psBody)
590 parseBody();
591 }
592
593 void Adaptation::Icap::ModXact::callException(const std::exception &e)
594 {
595 if (!canStartBypass || isRetriable) {
596 Adaptation::Icap::Xaction::callException(e);
597 return;
598 }
599
600 try {
601 debugs(93, 3, HERE << "bypassing " << inCall << " exception: " <<
602 e.what() << ' ' << status());
603 bypassFailure();
604 } catch (const std::exception &bypassE) {
605 Adaptation::Icap::Xaction::callException(bypassE);
606 }
607 }
608
609 void Adaptation::Icap::ModXact::bypassFailure()
610 {
611 disableBypass("already started to bypass", false);
612
613 Must(!isRetriable); // or we should not be bypassing
614 // TODO: should the same be enforced for isRepeatable? Check icap_repeat??
615
616 prepEchoing();
617
618 startSending();
619
620 // end all activities associated with the ICAP server
621
622 stopParsing();
623
624 stopWriting(true); // or should we force it?
625 if (haveConnection()) {
626 reuseConnection = false; // be conservative
627 cancelRead(); // may not work; and we cannot stop connecting either
628 if (!doneWithIo())
629 debugs(93, 7, HERE << "Warning: bypass failed to stop I/O" << status());
630 }
631 }
632
633 void Adaptation::Icap::ModXact::disableBypass(const char *reason, bool includingGroupBypass)
634 {
635 if (canStartBypass) {
636 debugs(93,7, HERE << "will never start bypass because " << reason);
637 canStartBypass = false;
638 }
639 if (protectGroupBypass && includingGroupBypass) {
640 debugs(93,7, HERE << "not protecting group bypass because " << reason);
641 protectGroupBypass = false;
642 }
643 }
644
645
646
647 // note that allocation for echoing is done in handle204NoContent()
648 void Adaptation::Icap::ModXact::maybeAllocateHttpMsg()
649 {
650 if (adapted.header) // already allocated
651 return;
652
653 if (gotEncapsulated("res-hdr")) {
654 adapted.setHeader(new HttpReply);
655 setOutcome(service().cfg().method == ICAP::methodReqmod ?
656 xoSatisfied : xoModified);
657 } else if (gotEncapsulated("req-hdr")) {
658 adapted.setHeader(new HttpRequest);
659 setOutcome(xoModified);
660 } else
661 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
662 }
663
664 void Adaptation::Icap::ModXact::parseHeaders()
665 {
666 Must(state.parsingHeaders());
667
668 if (state.parsing == State::psIcapHeader) {
669 debugs(93, 5, HERE << "parse ICAP headers");
670 parseIcapHead();
671 }
672
673 if (state.parsing == State::psHttpHeader) {
674 debugs(93, 5, HERE << "parse HTTP headers");
675 parseHttpHead();
676 }
677
678 if (state.parsingHeaders()) { // need more data
679 Must(mayReadMore());
680 return;
681 }
682
683 startSending();
684 }
685
686 // called after parsing all headers or when bypassing an exception
687 void Adaptation::Icap::ModXact::startSending()
688 {
689 disableRepeats("sent headers");
690 disableBypass("sent headers", true);
691 sendAnswer(adapted.header);
692
693 if (state.sending == State::sendingVirgin)
694 echoMore();
695 }
696
697 void Adaptation::Icap::ModXact::parseIcapHead()
698 {
699 Must(state.sending == State::sendingUndecided);
700
701 if (!parseHead(icapReply))
702 return;
703
704 if (httpHeaderHasConnDir(&icapReply->header, "close")) {
705 debugs(93, 5, HERE << "found connection close");
706 reuseConnection = false;
707 }
708
709 switch (icapReply->sline.status) {
710
711 case 100:
712 handle100Continue();
713 break;
714
715 case 200:
716 case 201: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
717
718 if (!validate200Ok()) {
719 throw TexcHere("Invalid ICAP Response");
720 } else {
721 handle200Ok();
722 }
723
724 break;
725
726 case 204:
727 handle204NoContent();
728 break;
729
730 default:
731 debugs(93, 5, HERE << "ICAP status " << icapReply->sline.status);
732 handleUnknownScode();
733 break;
734 }
735
736 const HttpRequest *request = dynamic_cast<HttpRequest*>(adapted.header);
737 if (!request)
738 request = &virginRequest();
739
740 // update the cross-transactional database if needed (all status codes!)
741 if (const char *xxName = Adaptation::Config::masterx_shared_name) {
742 Adaptation::History::Pointer ah = request->adaptHistory(true);
743 if (ah != NULL) {
744 const String val = icapReply->header.getByName(xxName);
745 if (val.size() > 0) // XXX: HttpHeader lacks empty value detection
746 ah->updateXxRecord(xxName, val);
747 }
748 }
749
750 // update the adaptation plan if needed (all status codes!)
751 if (service().cfg().routing) {
752 String services;
753 if (icapReply->header.getList(HDR_X_NEXT_SERVICES, &services)) {
754 Adaptation::History::Pointer ah = request->adaptHistory(true);
755 if (ah != NULL)
756 ah->updateNextServices(services);
757 }
758 } // TODO: else warn (occasionally!) if we got HDR_X_NEXT_SERVICES
759
760 // We need to store received ICAP headers for <icapLastHeader logformat option.
761 // If we already have stored headers from previous ICAP transaction related to this
762 // request, old headers will be replaced with the new one.
763
764 Adaptation::Icap::History::Pointer h = request->icapHistory();
765 if (h != NULL) {
766 h->mergeIcapHeaders(&icapReply->header);
767 h->setIcapLastHeader(&icapReply->header);
768 }
769
770 // handle100Continue() manages state.writing on its own.
771 // Non-100 status means the server needs no postPreview data from us.
772 if (state.writing == State::writingPaused)
773 stopWriting(true);
774 }
775
776 bool Adaptation::Icap::ModXact::validate200Ok()
777 {
778 if (ICAP::methodRespmod == service().cfg().method) {
779 if (!gotEncapsulated("res-hdr"))
780 return false;
781
782 return true;
783 }
784
785 if (ICAP::methodReqmod == service().cfg().method) {
786 if (!gotEncapsulated("res-hdr") && !gotEncapsulated("req-hdr"))
787 return false;
788
789 return true;
790 }
791
792 return false;
793 }
794
795 void Adaptation::Icap::ModXact::handle100Continue()
796 {
797 Must(state.writing == State::writingPaused);
798 // server must not respond before the end of preview: we may send ieof
799 Must(preview.enabled() && preview.done() && !preview.ieof());
800
801 // 100 "Continue" cancels our preview commitment, not 204s outside preview
802 if (!state.allowedPostview204)
803 stopBackup();
804
805 state.parsing = State::psIcapHeader; // eventually
806 icapReply->reset();
807
808 state.writing = State::writingPrime;
809
810 writeMore();
811 }
812
813 void Adaptation::Icap::ModXact::handle200Ok()
814 {
815 state.parsing = State::psHttpHeader;
816 state.sending = State::sendingAdapted;
817 stopBackup();
818 checkConsuming();
819 }
820
821 void Adaptation::Icap::ModXact::handle204NoContent()
822 {
823 stopParsing();
824 prepEchoing();
825 }
826
827 // Called when we receive a 204 No Content response and
828 // when we are trying to bypass a service failure.
829 // We actually start sending (echoig or not) in startSending.
830 void Adaptation::Icap::ModXact::prepEchoing()
831 {
832 disableRepeats("preparing to echo content");
833 disableBypass("preparing to echo content", true);
834 setOutcome(xoEcho);
835
836 // We want to clone the HTTP message, but we do not want
837 // to copy some non-HTTP state parts that HttpMsg kids carry in them.
838 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
839 // Instead, we simply write the HTTP message and "clone" it by parsing.
840 // TODO: use HttpMsg::clone()!
841
842 HttpMsg *oldHead = virgin.header;
843 debugs(93, 7, HERE << "cloning virgin message " << oldHead);
844
845 MemBuf httpBuf;
846
847 // write the virgin message into a memory buffer
848 httpBuf.init();
849 packHead(httpBuf, oldHead);
850
851 // allocate the adapted message and copy metainfo
852 Must(!adapted.header);
853 HttpMsg *newHead = NULL;
854 if (const HttpRequest *oldR = dynamic_cast<const HttpRequest*>(oldHead)) {
855 HttpRequest *newR = new HttpRequest;
856 newR->canonical = oldR->canonical ?
857 xstrdup(oldR->canonical) : NULL; // parse() does not set it
858 newHead = newR;
859 } else if (dynamic_cast<const HttpReply*>(oldHead)) {
860 HttpReply *newRep = new HttpReply;
861 newHead = newRep;
862 }
863 Must(newHead);
864 newHead->inheritProperties(oldHead);
865
866 adapted.setHeader(newHead);
867
868 // parse the buffer back
869 http_status error = HTTP_STATUS_NONE;
870
871 Must(newHead->parse(&httpBuf, true, &error));
872
873 Must(newHead->hdr_sz == httpBuf.contentSize()); // no leftovers
874
875 httpBuf.clean();
876
877 debugs(93, 7, HERE << "cloned virgin message " << oldHead << " to " <<
878 newHead);
879
880 // setup adapted body pipe if needed
881 if (oldHead->body_pipe != NULL) {
882 debugs(93, 7, HERE << "will echo virgin body from " <<
883 oldHead->body_pipe);
884 if (!virginBodySending.active())
885 virginBodySending.plan(); // will throw if not possible
886 state.sending = State::sendingVirgin;
887 checkConsuming();
888
889 // TODO: optimize: is it possible to just use the oldHead pipe and
890 // remove ICAP from the loop? This echoing is probably a common case!
891 makeAdaptedBodyPipe("echoed virgin response");
892 if (oldHead->body_pipe->bodySizeKnown())
893 adapted.body_pipe->setBodySize(oldHead->body_pipe->bodySize());
894 debugs(93, 7, HERE << "will echo virgin body to " <<
895 adapted.body_pipe);
896 } else {
897 debugs(93, 7, HERE << "no virgin body to echo");
898 stopSending(true);
899 }
900 }
901
902 void Adaptation::Icap::ModXact::handleUnknownScode()
903 {
904 stopParsing();
905 stopBackup();
906 // TODO: mark connection as "bad"
907
908 // Terminate the transaction; we do not know how to handle this response.
909 throw TexcHere("Unsupported ICAP status code");
910 }
911
912 void Adaptation::Icap::ModXact::parseHttpHead()
913 {
914 if (gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr")) {
915 maybeAllocateHttpMsg();
916
917 if (!parseHead(adapted.header))
918 return; // need more header data
919
920 if (dynamic_cast<HttpRequest*>(adapted.header)) {
921 const HttpRequest *oldR = dynamic_cast<const HttpRequest*>(virgin.header);
922 Must(oldR);
923 // TODO: the adapted request did not really originate from the
924 // client; give proxy admin an option to prevent copying of
925 // sensitive client information here. See the following thread:
926 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
927 }
928
929 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
930 if (adapted.header)
931 adapted.header->inheritProperties(virgin.header);
932 }
933
934 decideOnParsingBody();
935 }
936
937 // parses both HTTP and ICAP headers
938 bool Adaptation::Icap::ModXact::parseHead(HttpMsg *head)
939 {
940 Must(head);
941 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " head bytes to parse" <<
942 "; state: " << state.parsing);
943
944 http_status error = HTTP_STATUS_NONE;
945 const bool parsed = head->parse(&readBuf, commEof, &error);
946 Must(parsed || !error); // success or need more data
947
948 if (!parsed) { // need more data
949 debugs(93, 5, HERE << "parse failed, need more data, return false");
950 head->reset();
951 return false;
952 }
953
954 if (HttpRequest *r = dynamic_cast<HttpRequest*>(head))
955 urlCanonical(r); // parse does not set HttpRequest::canonical
956
957 debugs(93, 5, HERE << "parse success, consume " << head->hdr_sz << " bytes, return true");
958 readBuf.consume(head->hdr_sz);
959 return true;
960 }
961
962 void Adaptation::Icap::ModXact::decideOnParsingBody()
963 {
964 if (gotEncapsulated("res-body") || gotEncapsulated("req-body")) {
965 debugs(93, 5, HERE << "expecting a body");
966 state.parsing = State::psBody;
967 bodyParser = new ChunkedCodingParser;
968 makeAdaptedBodyPipe("adapted response from the ICAP server");
969 Must(state.sending == State::sendingAdapted);
970 } else {
971 debugs(93, 5, HERE << "not expecting a body");
972 stopParsing();
973 stopSending(true);
974 }
975 }
976
977 void Adaptation::Icap::ModXact::parseBody()
978 {
979 Must(state.parsing == State::psBody);
980 Must(bodyParser);
981
982 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " body bytes to parse");
983
984 // the parser will throw on errors
985 BodyPipeCheckout bpc(*adapted.body_pipe);
986 const bool parsed = bodyParser->parse(&readBuf, &bpc.buf);
987 bpc.checkIn();
988
989 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " body bytes after " <<
990 "parse; parsed all: " << parsed);
991 replyBodySize += adapted.body_pipe->buf().contentSize();
992
993 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
994 // TODO: do we really need this if we disable when sending headers?
995 if (adapted.body_pipe->buf().contentSize() > 0) { // parsed something sometime
996 disableRepeats("sent adapted content");
997 disableBypass("sent adapted content", true);
998 }
999
1000 if (parsed) {
1001 stopParsing();
1002 stopSending(true); // the parser succeeds only if all parsed data fits
1003 return;
1004 }
1005
1006 debugs(93,3,HERE << this << " needsMoreData = " << bodyParser->needsMoreData());
1007
1008 if (bodyParser->needsMoreData()) {
1009 debugs(93,3,HERE << this);
1010 Must(mayReadMore());
1011 readMore();
1012 }
1013
1014 if (bodyParser->needsMoreSpace()) {
1015 Must(!doneSending()); // can hope for more space
1016 Must(adapted.body_pipe->buf().contentSize() > 0); // paranoid
1017 // TODO: there should be a timeout in case the sink is broken
1018 // or cannot consume partial content (while we need more space)
1019 }
1020 }
1021
1022 void Adaptation::Icap::ModXact::stopParsing()
1023 {
1024 if (state.parsing == State::psDone)
1025 return;
1026
1027 debugs(93, 7, HERE << "will no longer parse" << status());
1028
1029 delete bodyParser;
1030
1031 bodyParser = NULL;
1032
1033 state.parsing = State::psDone;
1034 }
1035
1036 // HTTP side added virgin body data
1037 void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer)
1038 {
1039 writeMore();
1040
1041 if (state.sending == State::sendingVirgin)
1042 echoMore();
1043 }
1044
1045 // HTTP side sent us all virgin info
1046 void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer)
1047 {
1048 Must(virgin.body_pipe->productionEnded());
1049
1050 // push writer and sender in case we were waiting for the last-chunk
1051 writeMore();
1052
1053 if (state.sending == State::sendingVirgin)
1054 echoMore();
1055 }
1056
1057 // body producer aborted, but the initiator may still want to know
1058 // the answer, even though the HTTP message has been truncated
1059 void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer)
1060 {
1061 Must(virgin.body_pipe->productionEnded());
1062
1063 // push writer and sender in case we were waiting for the last-chunk
1064 writeMore();
1065
1066 if (state.sending == State::sendingVirgin)
1067 echoMore();
1068 }
1069
1070 // adapted body consumer wants more adapted data and
1071 // possibly freed some buffer space
1072 void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer)
1073 {
1074 if (state.sending == State::sendingVirgin)
1075 echoMore();
1076 else if (state.sending == State::sendingAdapted)
1077 parseMore();
1078 else
1079 Must(state.sending == State::sendingUndecided);
1080 }
1081
1082 // adapted body consumer aborted
1083 void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer)
1084 {
1085 mustStop("adapted body consumer aborted");
1086 }
1087
1088 // internal cleanup
1089 void Adaptation::Icap::ModXact::swanSong()
1090 {
1091 debugs(93, 5, HERE << "swan sings" << status());
1092
1093 stopWriting(false);
1094 stopSending(false);
1095
1096 // update adaptation history if start was called and we reserved a slot
1097 Adaptation::History::Pointer ah = virginRequest().adaptLogHistory();
1098 if (ah != NULL && adaptHistoryId >= 0)
1099 ah->recordXactFinish(adaptHistoryId);
1100
1101 Adaptation::Icap::Xaction::swanSong();
1102 }
1103
1104 void prepareLogWithRequestDetails(HttpRequest *, AccessLogEntry *);
1105
1106 void Adaptation::Icap::ModXact::finalizeLogInfo()
1107 {
1108 HttpRequest * request_ = NULL;
1109 HttpReply * reply_ = NULL;
1110 if (!(request_ = dynamic_cast<HttpRequest*>(adapted.header))) {
1111 request_ = (virgin.cause? virgin.cause: dynamic_cast<HttpRequest*>(virgin.header));
1112 reply_ = dynamic_cast<HttpReply*>(adapted.header);
1113 }
1114
1115 Adaptation::Icap::History::Pointer h = request_->icapHistory();
1116 Must(h != NULL); // ICAPXaction::maybeLog calls only if there is a log
1117 al.icp.opcode = ICP_INVALID;
1118 al.url = h->log_uri.termedBuf();
1119 const Adaptation::Icap::ServiceRep &s = service();
1120 al.icap.reqMethod = s.cfg().method;
1121
1122 al.cache.caddr = request_->client_addr;
1123
1124 al.request = HTTPMSGLOCK(request_);
1125 if (reply_)
1126 al.reply = HTTPMSGLOCK(reply_);
1127 else
1128 al.reply = NULL;
1129
1130 if (h->rfc931.size())
1131 al.cache.rfc931 = h->rfc931.termedBuf();
1132
1133 #if USE_SSL
1134 if (h->ssluser.size())
1135 al.cache.ssluser = h->ssluser.termedBuf();
1136 #endif
1137 al.cache.code = h->logType;
1138 al.cache.requestSize = h->req_sz;
1139 if (reply_) {
1140 al.http.code = reply_->sline.status;
1141 al.http.content_type = reply_->content_type.termedBuf();
1142 al.cache.replySize = replyBodySize + reply_->hdr_sz;
1143 al.cache.highOffset = replyBodySize;
1144 //don't set al.cache.objectSize because it hasn't exist yet
1145
1146 Packer p;
1147 MemBuf mb;
1148
1149 mb.init();
1150 packerToMemInit(&p, &mb);
1151
1152 reply_->header.packInto(&p);
1153 al.headers.reply = xstrdup(mb.buf);
1154
1155 packerClean(&p);
1156 mb.clean();
1157 }
1158 prepareLogWithRequestDetails(request_, &al);
1159 Xaction::finalizeLogInfo();
1160 }
1161
1162
1163 void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf &buf)
1164 {
1165 char ntoabuf[MAX_IPSTRLEN];
1166 /*
1167 * XXX These should use HttpHdr interfaces instead of Printfs
1168 */
1169 const Adaptation::ServiceConfig &s = service().cfg();
1170 buf.Printf("%s " SQUIDSTRINGPH " ICAP/1.0\r\n", s.methodStr(), SQUIDSTRINGPRINT(s.uri));
1171 buf.Printf("Host: " SQUIDSTRINGPH ":%d\r\n", SQUIDSTRINGPRINT(s.host), s.port);
1172 buf.Printf("Date: %s\r\n", mkrfc1123(squid_curtime));
1173
1174 if (!TheConfig.reuse_connections)
1175 buf.Printf("Connection: close\r\n");
1176
1177 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1178 // as ICAP headers.
1179 if (virgin.header->header.has(HDR_PROXY_AUTHENTICATE)) {
1180 String vh=virgin.header->header.getByName("Proxy-Authenticate");
1181 buf.Printf("Proxy-Authenticate: " SQUIDSTRINGPH "\r\n",SQUIDSTRINGPRINT(vh));
1182 }
1183
1184 if (virgin.header->header.has(HDR_PROXY_AUTHORIZATION)) {
1185 String vh=virgin.header->header.getByName("Proxy-Authorization");
1186 buf.Printf("Proxy-Authorization: " SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(vh));
1187 }
1188
1189 const HttpRequest *request = &virginRequest();
1190
1191 // share the cross-transactional database records if needed
1192 if (Adaptation::Config::masterx_shared_name) {
1193 Adaptation::History::Pointer ah = request->adaptHistory(true);
1194 if (ah != NULL) {
1195 String name, value;
1196 if (ah->getXxRecord(name, value)) {
1197 buf.Printf(SQUIDSTRINGPH ": " SQUIDSTRINGPH "\r\n",
1198 SQUIDSTRINGPRINT(name), SQUIDSTRINGPRINT(value));
1199 }
1200 }
1201 }
1202
1203
1204 buf.Printf("Encapsulated: ");
1205
1206 MemBuf httpBuf;
1207
1208 httpBuf.init();
1209
1210 // build HTTP request header, if any
1211 ICAP::Method m = s.method;
1212
1213 // to simplify, we could assume that request is always available
1214
1215 String urlPath;
1216 if (request) {
1217 urlPath = request->urlpath;
1218 if (ICAP::methodRespmod == m)
1219 encapsulateHead(buf, "req-hdr", httpBuf, request);
1220 else if (ICAP::methodReqmod == m)
1221 encapsulateHead(buf, "req-hdr", httpBuf, virgin.header);
1222 }
1223
1224 if (ICAP::methodRespmod == m)
1225 if (const HttpMsg *prime = virgin.header)
1226 encapsulateHead(buf, "res-hdr", httpBuf, prime);
1227
1228 if (!virginBody.expected())
1229 buf.Printf("null-body=%d", (int) httpBuf.contentSize());
1230 else if (ICAP::methodReqmod == m)
1231 buf.Printf("req-body=%d", (int) httpBuf.contentSize());
1232 else
1233 buf.Printf("res-body=%d", (int) httpBuf.contentSize());
1234
1235 buf.append(ICAP::crlf, 2); // terminate Encapsulated line
1236
1237 if (preview.enabled()) {
1238 buf.Printf("Preview: %d\r\n", (int)preview.ad());
1239 if (virginBody.expected()) // there is a body to preview
1240 virginBodySending.plan();
1241 else
1242 finishNullOrEmptyBodyPreview(httpBuf);
1243 }
1244
1245 if (shouldAllow204()) {
1246 debugs(93,5, HERE << "will allow 204s outside of preview");
1247 state.allowedPostview204 = true;
1248 buf.Printf("Allow: 204\r\n");
1249 if (virginBody.expected()) // there is a body to echo
1250 virginBodySending.plan();
1251 }
1252
1253 if (TheConfig.send_client_ip && request) {
1254 Ip::Address client_addr;
1255 #if FOLLOW_X_FORWARDED_FOR
1256 if (TheConfig.icap_uses_indirect_client) {
1257 client_addr = request->indirect_client_addr;
1258 } else
1259 #endif
1260 client_addr = request->client_addr;
1261 if (!client_addr.IsAnyAddr() && !client_addr.IsNoAddr())
1262 buf.Printf("X-Client-IP: %s\r\n", client_addr.NtoA(ntoabuf,MAX_IPSTRLEN));
1263 }
1264
1265 if (TheConfig.send_client_username && request)
1266 makeUsernameHeader(request, buf);
1267
1268 // fprintf(stderr, "%s\n", buf.content());
1269
1270 buf.append(ICAP::crlf, 2); // terminate ICAP header
1271
1272 // fill icapRequest for logging
1273 Must(icapRequest->parseCharBuf(buf.content(), buf.contentSize()));
1274
1275 // start ICAP request body with encapsulated HTTP headers
1276 buf.append(httpBuf.content(), httpBuf.contentSize());
1277
1278 httpBuf.clean();
1279 }
1280
1281 void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest *request, MemBuf &buf)
1282 {
1283 if (request->auth_user_request != NULL) {
1284 char const *name = request->auth_user_request->username();
1285 if (name) {
1286 const char *value = TheConfig.client_username_encode ? base64_encode(name) : name;
1287 buf.Printf("%s: %s\r\n", TheConfig.client_username_header, 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 (haveConnection() && !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 }