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