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