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