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