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