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