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