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