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