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