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