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