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