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