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