]> git.ipfire.org Git - thirdparty/squid.git/blame - src/adaptation/icap/ModXact.cc
Added Pointer typedefs.
[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
AR
64 // parsing; TODO: do not set until we parse, see ICAPOptXact
65 icapReply = HTTPMSGLOCK(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());
774c051c 97 state.serviceWaiting = true;
4299f876
AR
98 typedef NullaryMemFunT<ModXact> Dialer;
99 AsyncCall::Pointer call = JobCallback(93,5,
4cb2536f 100 Dialer, this, Adaptation::Icap::ModXact::noteServiceReady);
bd7f2ede 101 service().callWhenReady(call);
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);
7514268e 876 HttpMsg *newHead = NULL;
a22e6cd3 877 if (const HttpRequest *oldR = dynamic_cast<const HttpRequest*>(oldHead)) {
c99de607 878 HttpRequest *newR = new HttpRequest;
a22e6cd3 879 newR->canonical = oldR->canonical ?
e1381638 880 xstrdup(oldR->canonical) : NULL; // parse() does not set it
c99de607 881 newHead = newR;
9e008dda
AJ
882 } else if (dynamic_cast<const HttpReply*>(oldHead)) {
883 HttpReply *newRep = new HttpReply;
884 newHead = newRep;
d67acb4e 885 }
774c051c 886 Must(newHead);
d67acb4e 887 newHead->inheritProperties(oldHead);
774c051c 888
5f8252d2 889 adapted.setHeader(newHead);
7514268e 890
774c051c 891 // parse the buffer back
892 http_status error = HTTP_STATUS_NONE;
893
894 Must(newHead->parse(&httpBuf, true, &error));
895
896 Must(newHead->hdr_sz == httpBuf.contentSize()); // no leftovers
897
898 httpBuf.clean();
899
192378eb 900 debugs(93, 7, HERE << "cloned virgin message " << oldHead << " to " <<
9e008dda 901 newHead);
5f8252d2 902
903 // setup adapted body pipe if needed
904 if (oldHead->body_pipe != NULL) {
905 debugs(93, 7, HERE << "will echo virgin body from " <<
9e008dda 906 oldHead->body_pipe);
478cfe99 907 if (!virginBodySending.active())
908 virginBodySending.plan(); // will throw if not possible
5f8252d2 909 state.sending = State::sendingVirgin;
910 checkConsuming();
478cfe99 911
5f8252d2 912 // TODO: optimize: is it possible to just use the oldHead pipe and
913 // remove ICAP from the loop? This echoing is probably a common case!
914 makeAdaptedBodyPipe("echoed virgin response");
915 if (oldHead->body_pipe->bodySizeKnown())
916 adapted.body_pipe->setBodySize(oldHead->body_pipe->bodySize());
917 debugs(93, 7, HERE << "will echo virgin body to " <<
9e008dda 918 adapted.body_pipe);
5f8252d2 919 } else {
920 debugs(93, 7, HERE << "no virgin body to echo");
921 stopSending(true);
922 }
774c051c 923}
924
83c51da9
CT
925/// Called when we received use-original-body chunk extension in 206 response.
926/// We actually start sending (echoing or not) in startSending().
927void Adaptation::Icap::ModXact::prepPartialBodyEchoing(uint64_t pos)
928{
929 Must(virginBodySending.active());
930 Must(virgin.header->body_pipe != NULL);
931
932 setOutcome(xoPartEcho);
933
934 debugs(93, 7, HERE << "will echo virgin body suffix from " <<
935 virgin.header->body_pipe << " offset " << pos );
936
937 // check that use-original-body=N does not point beyond buffered data
938 const uint64_t virginDataEnd = virginConsumed +
7ddcfbab 939 virgin.body_pipe->buf().contentSize();
83c51da9
CT
940 Must(pos <= virginDataEnd);
941 virginBodySending.progress(static_cast<size_t>(pos));
942
943 state.sending = State::sendingVirgin;
944 checkConsuming();
945
946 if (virgin.header->body_pipe->bodySizeKnown())
947 adapted.body_pipe->expectProductionEndAfter(virgin.header->body_pipe->bodySize() - pos);
948
949 debugs(93, 7, HERE << "will echo virgin body suffix to " <<
950 adapted.body_pipe);
951
952 // Start echoing data
953 echoMore();
954}
955
26cc52cb 956void Adaptation::Icap::ModXact::handleUnknownScode()
774c051c 957{
958 stopParsing();
959 stopBackup();
960 // TODO: mark connection as "bad"
961
962 // Terminate the transaction; we do not know how to handle this response.
963 throw TexcHere("Unsupported ICAP status code");
964}
965
26cc52cb 966void Adaptation::Icap::ModXact::parseHttpHead()
774c051c 967{
968 if (gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr")) {
bae917ac 969 replyHttpHeaderSize = 0;
774c051c 970 maybeAllocateHttpMsg();
971
5f8252d2 972 if (!parseHead(adapted.header))
c99de607 973 return; // need more header data
5f8252d2 974
bae917ac
CT
975 if (adapted.header)
976 replyHttpHeaderSize = adapted.header->hdr_sz;
977
d67acb4e 978 if (dynamic_cast<HttpRequest*>(adapted.header)) {
5f8252d2 979 const HttpRequest *oldR = dynamic_cast<const HttpRequest*>(virgin.header);
980 Must(oldR);
9e008dda
AJ
981 // TODO: the adapted request did not really originate from the
982 // client; give proxy admin an option to prevent copying of
5f8252d2 983 // sensitive client information here. See the following thread:
984 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
5f8252d2 985 }
d67acb4e 986
9e008dda
AJ
987 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
988 if (adapted.header)
989 adapted.header->inheritProperties(virgin.header);
774c051c 990 }
991
5f8252d2 992 decideOnParsingBody();
774c051c 993}
994
c99de607 995// parses both HTTP and ICAP headers
26cc52cb 996bool Adaptation::Icap::ModXact::parseHead(HttpMsg *head)
774c051c 997{
c99de607 998 Must(head);
def17b6a 999 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " head bytes to parse" <<
774c051c 1000 "; state: " << state.parsing);
1001
1002 http_status error = HTTP_STATUS_NONE;
1003 const bool parsed = head->parse(&readBuf, commEof, &error);
1004 Must(parsed || !error); // success or need more data
1005
c99de607 1006 if (!parsed) { // need more data
b107a5a5 1007 debugs(93, 5, HERE << "parse failed, need more data, return false");
774c051c 1008 head->reset();
1009 return false;
1010 }
1011
a22e6cd3
AR
1012 if (HttpRequest *r = dynamic_cast<HttpRequest*>(head))
1013 urlCanonical(r); // parse does not set HttpRequest::canonical
1014
b107a5a5 1015 debugs(93, 5, HERE << "parse success, consume " << head->hdr_sz << " bytes, return true");
774c051c 1016 readBuf.consume(head->hdr_sz);
1017 return true;
1018}
1019
26cc52cb 1020void Adaptation::Icap::ModXact::decideOnParsingBody()
9e008dda 1021{
200ac359 1022 if (gotEncapsulated("res-body") || gotEncapsulated("req-body")) {
5f8252d2 1023 debugs(93, 5, HERE << "expecting a body");
1024 state.parsing = State::psBody;
bae917ac 1025 replyHttpBodySize = 0;
5f8252d2 1026 bodyParser = new ChunkedCodingParser;
1027 makeAdaptedBodyPipe("adapted response from the ICAP server");
1028 Must(state.sending == State::sendingAdapted);
774c051c 1029 } else {
b559db5d 1030 debugs(93, 5, HERE << "not expecting a body");
5f8252d2 1031 stopParsing();
1032 stopSending(true);
774c051c 1033 }
774c051c 1034}
1035
26cc52cb 1036void Adaptation::Icap::ModXact::parseBody()
774c051c 1037{
5f8252d2 1038 Must(state.parsing == State::psBody);
1039 Must(bodyParser);
774c051c 1040
5f8252d2 1041 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " body bytes to parse");
774c051c 1042
5f8252d2 1043 // the parser will throw on errors
1044 BodyPipeCheckout bpc(*adapted.body_pipe);
1045 const bool parsed = bodyParser->parse(&readBuf, &bpc.buf);
1046 bpc.checkIn();
774c051c 1047
aa761e5f 1048 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " body bytes after " <<
774c051c 1049 "parse; parsed all: " << parsed);
bae917ac 1050 replyHttpBodySize += adapted.body_pipe->buf().contentSize();
774c051c 1051
478cfe99 1052 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
3ff65596
AR
1053 // TODO: do we really need this if we disable when sending headers?
1054 if (adapted.body_pipe->buf().contentSize() > 0) { // parsed something sometime
1055 disableRepeats("sent adapted content");
a22e6cd3 1056 disableBypass("sent adapted content", true);
3ff65596 1057 }
478cfe99 1058
5f8252d2 1059 if (parsed) {
83c51da9
CT
1060 if (state.readyForUob && bodyParser->useOriginBody >= 0) {
1061 prepPartialBodyEchoing(
1062 static_cast<uint64_t>(bodyParser->useOriginBody));
1063 stopParsing();
1064 return;
1065 }
1066
5f8252d2 1067 stopParsing();
1068 stopSending(true); // the parser succeeds only if all parsed data fits
1069 return;
1070 }
774c051c 1071
c99de607 1072 debugs(93,3,HERE << this << " needsMoreData = " << bodyParser->needsMoreData());
3b299123 1073
1074 if (bodyParser->needsMoreData()) {
c99de607 1075 debugs(93,3,HERE << this);
774c051c 1076 Must(mayReadMore());
3b299123 1077 readMore();
1078 }
774c051c 1079
1080 if (bodyParser->needsMoreSpace()) {
1081 Must(!doneSending()); // can hope for more space
5f8252d2 1082 Must(adapted.body_pipe->buf().contentSize() > 0); // paranoid
1083 // TODO: there should be a timeout in case the sink is broken
1084 // or cannot consume partial content (while we need more space)
774c051c 1085 }
774c051c 1086}
1087
26cc52cb 1088void Adaptation::Icap::ModXact::stopParsing()
774c051c 1089{
1090 if (state.parsing == State::psDone)
1091 return;
1092
192378eb 1093 debugs(93, 7, HERE << "will no longer parse" << status());
774c051c 1094
1095 delete bodyParser;
1096
1097 bodyParser = NULL;
1098
1099 state.parsing = State::psDone;
1100}
1101
1102// HTTP side added virgin body data
26cc52cb 1103void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer)
774c051c 1104{
774c051c 1105 writeMore();
1106
1107 if (state.sending == State::sendingVirgin)
1108 echoMore();
774c051c 1109}
1110
1111// HTTP side sent us all virgin info
26cc52cb 1112void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer)
774c051c 1113{
5f8252d2 1114 Must(virgin.body_pipe->productionEnded());
774c051c 1115
1116 // push writer and sender in case we were waiting for the last-chunk
1117 writeMore();
1118
1119 if (state.sending == State::sendingVirgin)
1120 echoMore();
774c051c 1121}
1122
9e008dda 1123// body producer aborted, but the initiator may still want to know
585ab260 1124// the answer, even though the HTTP message has been truncated
26cc52cb 1125void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer)
774c051c 1126{
585ab260 1127 Must(virgin.body_pipe->productionEnded());
1128
1129 // push writer and sender in case we were waiting for the last-chunk
1130 writeMore();
1131
1132 if (state.sending == State::sendingVirgin)
1133 echoMore();
5f8252d2 1134}
1135
9e008dda 1136// adapted body consumer wants more adapted data and
5f8252d2 1137// possibly freed some buffer space
26cc52cb 1138void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer)
774c051c 1139{
774c051c 1140 if (state.sending == State::sendingVirgin)
1141 echoMore();
3b299123 1142 else if (state.sending == State::sendingAdapted)
1143 parseMore();
774c051c 1144 else
3b299123 1145 Must(state.sending == State::sendingUndecided);
774c051c 1146}
1147
5f8252d2 1148// adapted body consumer aborted
26cc52cb 1149void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer)
774c051c 1150{
5f8252d2 1151 mustStop("adapted body consumer aborted");
774c051c 1152}
1153
1154// internal cleanup
26cc52cb 1155void Adaptation::Icap::ModXact::swanSong()
774c051c 1156{
5f8252d2 1157 debugs(93, 5, HERE << "swan sings" << status());
1158
c99de607 1159 stopWriting(false);
c824c43b 1160 stopSending(false);
774c051c 1161
3ff65596 1162 // update adaptation history if start was called and we reserved a slot
a22e6cd3 1163 Adaptation::History::Pointer ah = virginRequest().adaptLogHistory();
3ff65596
AR
1164 if (ah != NULL && adaptHistoryId >= 0)
1165 ah->recordXactFinish(adaptHistoryId);
774c051c 1166
26cc52cb 1167 Adaptation::Icap::Xaction::swanSong();
774c051c 1168}
1169
3ff65596
AR
1170void prepareLogWithRequestDetails(HttpRequest *, AccessLogEntry *);
1171
1172void Adaptation::Icap::ModXact::finalizeLogInfo()
1173{
1174 HttpRequest * request_ = NULL;
1175 HttpReply * reply_ = NULL;
e1381638 1176 if (!(request_ = dynamic_cast<HttpRequest*>(adapted.header))) {
3ff65596
AR
1177 request_ = (virgin.cause? virgin.cause: dynamic_cast<HttpRequest*>(virgin.header));
1178 reply_ = dynamic_cast<HttpReply*>(adapted.header);
1179 }
1180
1181 Adaptation::Icap::History::Pointer h = request_->icapHistory();
e1381638
AJ
1182 Must(h != NULL); // ICAPXaction::maybeLog calls only if there is a log
1183 al.icp.opcode = ICP_INVALID;
1184 al.url = h->log_uri.termedBuf();
1185 const Adaptation::Icap::ServiceRep &s = service();
1186 al.icap.reqMethod = s.cfg().method;
3ff65596 1187
e1381638 1188 al.cache.caddr = request_->client_addr;
3ff65596 1189
e1381638
AJ
1190 al.request = HTTPMSGLOCK(request_);
1191 if (reply_)
1192 al.reply = HTTPMSGLOCK(reply_);
1193 else
1194 al.reply = NULL;
3ff65596 1195
e1381638
AJ
1196 if (h->rfc931.size())
1197 al.cache.rfc931 = h->rfc931.termedBuf();
3ff65596
AR
1198
1199#if USE_SSL
e1381638
AJ
1200 if (h->ssluser.size())
1201 al.cache.ssluser = h->ssluser.termedBuf();
3ff65596 1202#endif
e1381638
AJ
1203 al.cache.code = h->logType;
1204 al.cache.requestSize = h->req_sz;
bae917ac
CT
1205
1206 // leave al.icap.bodyBytesRead negative if no body
1207 if (replyHttpHeaderSize >= 0 || replyHttpBodySize >= 0) {
1208 const int64_t zero = 0; // to make max() argument types the same
1209 al.icap.bodyBytesRead =
1210 max(zero, replyHttpHeaderSize) + max(zero, replyHttpBodySize);
1211 }
1212
e1381638
AJ
1213 if (reply_) {
1214 al.http.code = reply_->sline.status;
1215 al.http.content_type = reply_->content_type.termedBuf();
bae917ac
CT
1216 if (replyHttpBodySize >= 0) {
1217 al.cache.replySize = replyHttpBodySize + reply_->hdr_sz;
1218 al.cache.highOffset = replyHttpBodySize;
1219 }
e1381638
AJ
1220 //don't set al.cache.objectSize because it hasn't exist yet
1221
1222 Packer p;
1223 MemBuf mb;
1224
1225 mb.init();
1226 packerToMemInit(&p, &mb);
1227
1228 reply_->header.packInto(&p);
1229 al.headers.reply = xstrdup(mb.buf);
1230
1231 packerClean(&p);
1232 mb.clean();
1233 }
1234 prepareLogWithRequestDetails(request_, &al);
1235 Xaction::finalizeLogInfo();
3ff65596
AR
1236}
1237
1238
26cc52cb 1239void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf &buf)
774c051c 1240{
cc192b50 1241 char ntoabuf[MAX_IPSTRLEN];
12b91c99 1242 /*
1243 * XXX These should use HttpHdr interfaces instead of Printfs
1244 */
0bef8dd7 1245 const Adaptation::ServiceConfig &s = service().cfg();
2c1fd837 1246 buf.Printf("%s " SQUIDSTRINGPH " ICAP/1.0\r\n", s.methodStr(), SQUIDSTRINGPRINT(s.uri));
826a1fed 1247 buf.Printf("Host: " SQUIDSTRINGPH ":%d\r\n", SQUIDSTRINGPRINT(s.host), s.port);
12b91c99 1248 buf.Printf("Date: %s\r\n", mkrfc1123(squid_curtime));
1249
26cc52cb 1250 if (!TheConfig.reuse_connections)
12b91c99 1251 buf.Printf("Connection: close\r\n");
1252
2cdeea82 1253 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1254 // as ICAP headers.
4232c626
FC
1255 if (virgin.header->header.has(HDR_PROXY_AUTHENTICATE)) {
1256 String vh=virgin.header->header.getByName("Proxy-Authenticate");
826a1fed 1257 buf.Printf("Proxy-Authenticate: " SQUIDSTRINGPH "\r\n",SQUIDSTRINGPRINT(vh));
4232c626 1258 }
9e008dda 1259
4232c626
FC
1260 if (virgin.header->header.has(HDR_PROXY_AUTHORIZATION)) {
1261 String vh=virgin.header->header.getByName("Proxy-Authorization");
826a1fed 1262 buf.Printf("Proxy-Authorization: " SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(vh));
4232c626 1263 }
2cdeea82 1264
3ff65596
AR
1265 const HttpRequest *request = &virginRequest();
1266
1267 // share the cross-transactional database records if needed
1268 if (Adaptation::Config::masterx_shared_name) {
a22e6cd3 1269 Adaptation::History::Pointer ah = request->adaptHistory(true);
3ff65596
AR
1270 if (ah != NULL) {
1271 String name, value;
1272 if (ah->getXxRecord(name, value)) {
e1381638
AJ
1273 buf.Printf(SQUIDSTRINGPH ": " SQUIDSTRINGPH "\r\n",
1274 SQUIDSTRINGPRINT(name), SQUIDSTRINGPRINT(value));
3ff65596
AR
1275 }
1276 }
1277 }
e1381638 1278
3ff65596 1279
774c051c 1280 buf.Printf("Encapsulated: ");
1281
1282 MemBuf httpBuf;
12b91c99 1283
774c051c 1284 httpBuf.init();
1285
1286 // build HTTP request header, if any
1287 ICAP::Method m = s.method;
1288
5f8252d2 1289 // to simplify, we could assume that request is always available
c99de607 1290
30abd221 1291 String urlPath;
c99de607 1292 if (request) {
1293 urlPath = request->urlpath;
1294 if (ICAP::methodRespmod == m)
1295 encapsulateHead(buf, "req-hdr", httpBuf, request);
e1381638
AJ
1296 else if (ICAP::methodReqmod == m)
1297 encapsulateHead(buf, "req-hdr", httpBuf, virgin.header);
c99de607 1298 }
774c051c 1299
1300 if (ICAP::methodRespmod == m)
5f8252d2 1301 if (const HttpMsg *prime = virgin.header)
774c051c 1302 encapsulateHead(buf, "res-hdr", httpBuf, prime);
1303
1304 if (!virginBody.expected())
1dd6edf2 1305 buf.Printf("null-body=%d", (int) httpBuf.contentSize());
774c051c 1306 else if (ICAP::methodReqmod == m)
1dd6edf2 1307 buf.Printf("req-body=%d", (int) httpBuf.contentSize());
774c051c 1308 else
1dd6edf2 1309 buf.Printf("res-body=%d", (int) httpBuf.contentSize());
774c051c 1310
1311 buf.append(ICAP::crlf, 2); // terminate Encapsulated line
1312
c824c43b 1313 if (preview.enabled()) {
774c051c 1314 buf.Printf("Preview: %d\r\n", (int)preview.ad());
83c51da9 1315 if (!virginBody.expected()) // there is no body to preview
5f8252d2 1316 finishNullOrEmptyBodyPreview(httpBuf);
774c051c 1317 }
1318
83c51da9 1319 makeAllowHeader(buf);
774c051c 1320
a9044668 1321 if (TheConfig.send_client_ip && request) {
b7ac5457 1322 Ip::Address client_addr;
57d76dd4 1323#if FOLLOW_X_FORWARDED_FOR
a9044668
A
1324 if (TheConfig.icap_uses_indirect_client) {
1325 client_addr = request->indirect_client_addr;
1326 } else
57d76dd4 1327#endif
a9044668
A
1328 client_addr = request->client_addr;
1329 if (!client_addr.IsAnyAddr() && !client_addr.IsNoAddr())
1330 buf.Printf("X-Client-IP: %s\r\n", client_addr.NtoA(ntoabuf,MAX_IPSTRLEN));
57d76dd4 1331 }
a97e82a8 1332
26cc52cb 1333 if (TheConfig.send_client_username && request)
5f8252d2 1334 makeUsernameHeader(request, buf);
a97e82a8 1335
bb790702 1336 // fprintf(stderr, "%s\n", buf.content());
a97e82a8 1337
774c051c 1338 buf.append(ICAP::crlf, 2); // terminate ICAP header
1339
a22e6cd3
AR
1340 // fill icapRequest for logging
1341 Must(icapRequest->parseCharBuf(buf.content(), buf.contentSize()));
1342
774c051c 1343 // start ICAP request body with encapsulated HTTP headers
1344 buf.append(httpBuf.content(), httpBuf.contentSize());
1345
1346 httpBuf.clean();
1347}
1348
83c51da9
CT
1349// decides which Allow values to write and updates the request buffer
1350void Adaptation::Icap::ModXact::makeAllowHeader(MemBuf &buf)
1351{
1352 const bool allow204in = preview.enabled(); // TODO: add shouldAllow204in()
1353 const bool allow204out = state.allowedPostview204 = shouldAllow204();
1354 const bool allow206in = state.allowedPreview206 = shouldAllow206in();
1355 const bool allow206out = state.allowedPostview206 = shouldAllow206out();
1356
1357 debugs(93,9, HERE << "Allows: " << allow204in << allow204out <<
7ddcfbab 1358 allow206in << allow206out);
83c51da9
CT
1359
1360 const bool allow204 = allow204in || allow204out;
1361 const bool allow206 = allow206in || allow206out;
1362
1363 if (!allow204 && !allow206)
1364 return; // nothing to do
1365
1366 if (virginBody.expected()) // if there is a virgin body, plan to send it
1367 virginBodySending.plan();
1368
1369 // writing Preview:... means we will honor 204 inside preview
1370 // writing Allow/204 means we will honor 204 outside preview
1371 // writing Allow:206 means we will honor 206 inside preview
1372 // writing Allow:204,206 means we will honor 206 outside preview
1373 const char *allowHeader = NULL;
1374 if (allow204out && allow206)
1375 allowHeader = "Allow: 204, 206\r\n";
1376 else if (allow204out)
1377 allowHeader = "Allow: 204\r\n";
1378 else if (allow206)
1379 allowHeader = "Allow: 206\r\n";
7ddcfbab 1380
83c51da9
CT
1381 if (allowHeader) { // may be nil if only allow204in is true
1382 buf.append(allowHeader, strlen(allowHeader));
1383 debugs(93,5, HERE << "Will write " << allowHeader);
1384 }
1385}
1386
26cc52cb 1387void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest *request, MemBuf &buf)
9e008dda 1388{
a33a428a 1389 if (request->auth_user_request != NULL) {
9b275e99 1390 char const *name = request->auth_user_request->username();
a33a428a
AJ
1391 if (name) {
1392 const char *value = TheConfig.client_username_encode ? base64_encode(name) : name;
1393 buf.Printf("%s: %s\r\n", TheConfig.client_username_header, value);
5f8252d2 1394 }
1395 }
1396}
1397
26cc52cb 1398void Adaptation::Icap::ModXact::encapsulateHead(MemBuf &icapBuf, const char *section, MemBuf &httpBuf, const HttpMsg *head)
774c051c 1399{
1400 // update ICAP header
7cab7e9f 1401 icapBuf.Printf("%s=%d, ", section, (int) httpBuf.contentSize());
774c051c 1402
2cdeea82 1403 // begin cloning
1404 HttpMsg *headClone = NULL;
9e008dda 1405
2cdeea82 1406 if (const HttpRequest* old_request = dynamic_cast<const HttpRequest*>(head)) {
1407 HttpRequest* new_request = new HttpRequest;
a22e6cd3
AR
1408 assert(old_request->canonical);
1409 urlParse(old_request->method, old_request->canonical, new_request);
2cdeea82 1410 new_request->http_ver = old_request->http_ver;
2cdeea82 1411 headClone = new_request;
9e008dda 1412 } else if (const HttpReply *old_reply = dynamic_cast<const HttpReply*>(head)) {
2cdeea82 1413 HttpReply* new_reply = new HttpReply;
1414 new_reply->sline = old_reply->sline;
1415 headClone = new_reply;
1416 }
9e008dda 1417
2cdeea82 1418 Must(headClone);
d67acb4e 1419 headClone->inheritProperties(head);
9e008dda 1420
2cdeea82 1421 HttpHeaderPos pos = HttpHeaderInitPos;
1422 HttpHeaderEntry* p_head_entry = NULL;
1423 while (NULL != (p_head_entry = head->header.getEntry(&pos)) )
1424 headClone->header.addEntry(p_head_entry->clone());
1425
1426 // end cloning
9e008dda 1427
2cdeea82 1428 // remove all hop-by-hop headers from the clone
dcf3665b 1429 headClone->header.delById(HDR_PROXY_AUTHENTICATE);
2cdeea82 1430 headClone->header.removeHopByHopEntries();
1431
1432 // pack polished HTTP header
1433 packHead(httpBuf, headClone);
1434
1435 delete headClone;
774c051c 1436}
1437
26cc52cb 1438void Adaptation::Icap::ModXact::packHead(MemBuf &httpBuf, const HttpMsg *head)
774c051c 1439{
1440 Packer p;
1441 packerToMemInit(&p, &httpBuf);
1442 head->packInto(&p, true);
1443 packerClean(&p);
1444}
1445
1446// decides whether to offer a preview and calculates its size
26cc52cb 1447void Adaptation::Icap::ModXact::decideOnPreview()
774c051c 1448{
26cc52cb 1449 if (!TheConfig.preview_enable) {
7cdbbd47 1450 debugs(93, 5, HERE << "preview disabled by squid.conf");
c824c43b 1451 return;
7cdbbd47 1452 }
1453
3ff65596 1454 const String urlPath = virginRequest().urlpath;
5f8252d2 1455 size_t wantedSize;
c99de607 1456 if (!service().wantsPreview(urlPath, wantedSize)) {
192378eb 1457 debugs(93, 5, HERE << "should not offer preview for " << urlPath);
c824c43b 1458 return;
774c051c 1459 }
1460
c824c43b 1461 // we decided to do preview, now compute its size
1462
774c051c 1463 Must(wantedSize >= 0);
1464
1465 // cannot preview more than we can backup
d85c3078 1466 size_t ad = min(wantedSize, TheBackupLimit);
774c051c 1467
5f8252d2 1468 if (!virginBody.expected())
1469 ad = 0;
e1381638
AJ
1470 else if (virginBody.knownSize())
1471 ad = min(static_cast<uint64_t>(ad), virginBody.size()); // not more than we have
774c051c 1472
192378eb 1473 debugs(93, 5, HERE << "should offer " << ad << "-byte preview " <<
774c051c 1474 "(service wanted " << wantedSize << ")");
1475
1476 preview.enable(ad);
5f8252d2 1477 Must(preview.enabled());
774c051c 1478}
1479
1480// decides whether to allow 204 responses
26cc52cb 1481bool Adaptation::Icap::ModXact::shouldAllow204()
774c051c 1482{
1483 if (!service().allows204())
1484 return false;
1485
c824c43b 1486 return canBackupEverything();
1487}
1488
83c51da9
CT
1489// decides whether to allow 206 responses in some mode
1490bool Adaptation::Icap::ModXact::shouldAllow206any()
1491{
1492 return TheConfig.allow206_enable && service().allows206() &&
7ddcfbab 1493 virginBody.expected(); // no need for 206 without a body
83c51da9
CT
1494}
1495
1496// decides whether to allow 206 responses in preview mode
1497bool Adaptation::Icap::ModXact::shouldAllow206in()
1498{
1499 return shouldAllow206any() && preview.enabled();
1500}
1501
1502// decides whether to allow 206 responses outside of preview
1503bool Adaptation::Icap::ModXact::shouldAllow206out()
1504{
1505 return shouldAllow206any() && canBackupEverything();
1506}
1507
c824c43b 1508// used by shouldAllow204 and decideOnRetries
26cc52cb 1509bool Adaptation::Icap::ModXact::canBackupEverything() const
c824c43b 1510{
774c051c 1511 if (!virginBody.expected())
c824c43b 1512 return true; // no body means no problems with backup
774c051c 1513
c824c43b 1514 // if there is a body, check whether we can backup it all
774c051c 1515
1516 if (!virginBody.knownSize())
1517 return false;
1518
1519 // or should we have a different backup limit?
1520 // note that '<' allows for 0-termination of the "full" backup buffer
1521 return virginBody.size() < TheBackupLimit;
1522}
1523
c824c43b 1524// Decide whether this transaction can be retried if pconn fails
1525// Must be called after decideOnPreview and before openConnection()
26cc52cb 1526void Adaptation::Icap::ModXact::decideOnRetries()
c824c43b 1527{
1528 if (!isRetriable)
1529 return; // no, already decided
1530
1531 if (preview.enabled())
1532 return; // yes, because preview provides enough guarantees
1533
1534 if (canBackupEverything())
1535 return; // yes, because we can back everything up
1536
1537 disableRetries(); // no, because we cannot back everything up
1538}
1539
5f8252d2 1540// Normally, the body-writing code handles preview body. It can deal with
1541// bodies of unexpected size, including those that turn out to be empty.
1542// However, that code assumes that the body was expected and body control
1543// structures were initialized. This is not the case when there is no body
1544// or the body is known to be empty, because the virgin message will lack a
1545// body_pipe. So we handle preview of null-body and zero-size bodies here.
26cc52cb 1546void Adaptation::Icap::ModXact::finishNullOrEmptyBodyPreview(MemBuf &buf)
5f8252d2 1547{
1548 Must(!virginBodyWriting.active()); // one reason we handle it here
1549 Must(!virgin.body_pipe); // another reason we handle it here
1550 Must(!preview.ad());
1551
1552 // do not add last-chunk because our Encapsulated header says null-body
bb790702 1553 // addLastRequestChunk(buf);
5f8252d2 1554 preview.wrote(0, true);
1555
1556 Must(preview.done());
1557 Must(preview.ieof());
1558}
1559
26cc52cb 1560void Adaptation::Icap::ModXact::fillPendingStatus(MemBuf &buf) const
774c051c 1561{
26cc52cb 1562 Adaptation::Icap::Xaction::fillPendingStatus(buf);
c99de607 1563
774c051c 1564 if (state.serviceWaiting)
1565 buf.append("U", 1);
1566
5f8252d2 1567 if (virgin.body_pipe != NULL)
c99de607 1568 buf.append("R", 1);
1569
5f8252d2 1570 if (connection > 0 && !doneReading())
c99de607 1571 buf.append("r", 1);
1572
774c051c 1573 if (!state.doneWriting() && state.writing != State::writingInit)
1574 buf.Printf("w(%d)", state.writing);
1575
1576 if (preview.enabled()) {
1577 if (!preview.done())
1dd6edf2 1578 buf.Printf("P(%d)", (int) preview.debt());
774c051c 1579 }
1580
5f8252d2 1581 if (virginBodySending.active())
774c051c 1582 buf.append("B", 1);
1583
1584 if (!state.doneParsing() && state.parsing != State::psIcapHeader)
1585 buf.Printf("p(%d)", state.parsing);
1586
1587 if (!doneSending() && state.sending != State::sendingUndecided)
1588 buf.Printf("S(%d)", state.sending);
478cfe99 1589
83c51da9
CT
1590 if (state.readyForUob)
1591 buf.append("6", 1);
1592
478cfe99 1593 if (canStartBypass)
9e008dda 1594 buf.append("Y", 1);
a22e6cd3
AR
1595
1596 if (protectGroupBypass)
1597 buf.append("G", 1);
774c051c 1598}
1599
26cc52cb 1600void Adaptation::Icap::ModXact::fillDoneStatus(MemBuf &buf) const
774c051c 1601{
26cc52cb 1602 Adaptation::Icap::Xaction::fillDoneStatus(buf);
c99de607 1603
5f8252d2 1604 if (!virgin.body_pipe)
774c051c 1605 buf.append("R", 1);
1606
1607 if (state.doneWriting())
1608 buf.append("w", 1);
1609
1610 if (preview.enabled()) {
1611 if (preview.done())
1612 buf.Printf("P%s", preview.ieof() ? "(ieof)" : "");
1613 }
1614
1615 if (doneReading())
1616 buf.append("r", 1);
1617
1618 if (state.doneParsing())
1619 buf.append("p", 1);
1620
1621 if (doneSending())
1622 buf.append("S", 1);
1623}
1624
26cc52cb 1625bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section) const
774c051c 1626{
a9925b40 1627 return icapReply->header.getByNameListMember("Encapsulated",
1628 section, ',').size() > 0;
774c051c 1629}
1630
1631// calculate whether there is a virgin HTTP body and
1632// whether its expected size is known
5f8252d2 1633// TODO: rename because we do not just estimate
26cc52cb 1634void Adaptation::Icap::ModXact::estimateVirginBody()
774c051c 1635{
5f8252d2 1636 // note: lack of size info may disable previews and 204s
774c051c 1637
5f8252d2 1638 HttpMsg *msg = virgin.header;
1639 Must(msg);
774c051c 1640
60745f24 1641 HttpRequestMethod method;
774c051c 1642
5f8252d2 1643 if (virgin.cause)
1644 method = virgin.cause->method;
e1381638
AJ
1645 else if (HttpRequest *req = dynamic_cast<HttpRequest*>(msg))
1646 method = req->method;
774c051c 1647 else
e1381638 1648 method = METHOD_NONE;
774c051c 1649
47f6e231 1650 int64_t size;
5f8252d2 1651 // expectingBody returns true for zero-sized bodies, but we will not
1652 // get a pipe for that body, so we treat the message as bodyless
1653 if (method != METHOD_NONE && msg->expectingBody(method, size) && size) {
192378eb 1654 debugs(93, 6, HERE << "expects virgin body from " <<
9e008dda 1655 virgin.body_pipe << "; size: " << size);
5f8252d2 1656
1657 virginBody.expect(size);
1658 virginBodyWriting.plan();
1659
1660 // sign up as a body consumer
1661 Must(msg->body_pipe != NULL);
1662 Must(msg->body_pipe == virgin.body_pipe);
1663 Must(virgin.body_pipe->setConsumerIfNotLate(this));
1664
1665 // make sure TheBackupLimit is in-sync with the buffer size
9c175897 1666 Must(TheBackupLimit <= static_cast<size_t>(msg->body_pipe->buf().max_capacity));
774c051c 1667 } else {
192378eb 1668 debugs(93, 6, HERE << "does not expect virgin body");
5f8252d2 1669 Must(msg->body_pipe == NULL);
1670 checkConsuming();
774c051c 1671 }
1672}
1673
26cc52cb 1674void Adaptation::Icap::ModXact::makeAdaptedBodyPipe(const char *what)
9e008dda 1675{
5f8252d2 1676 Must(!adapted.body_pipe);
1677 Must(!adapted.header->body_pipe);
1678 adapted.header->body_pipe = new BodyPipe(this);
1679 adapted.body_pipe = adapted.header->body_pipe;
1680 debugs(93, 7, HERE << "will supply " << what << " via " <<
9e008dda 1681 adapted.body_pipe << " pipe");
5f8252d2 1682}
1683
774c051c 1684
26cc52cb 1685// TODO: Move SizedEstimate and Preview elsewhere
774c051c 1686
26cc52cb 1687Adaptation::Icap::SizedEstimate::SizedEstimate()
774c051c 1688 : theData(dtUnexpected)
1689{}
1690
26cc52cb 1691void Adaptation::Icap::SizedEstimate::expect(int64_t aSize)
774c051c 1692{
47f6e231 1693 theData = (aSize >= 0) ? aSize : (int64_t)dtUnknown;
774c051c 1694}
1695
26cc52cb 1696bool Adaptation::Icap::SizedEstimate::expected() const
774c051c 1697{
1698 return theData != dtUnexpected;
1699}
1700
26cc52cb 1701bool Adaptation::Icap::SizedEstimate::knownSize() const
774c051c 1702{
1703 Must(expected());
1704 return theData != dtUnknown;
1705}
1706
26cc52cb 1707uint64_t Adaptation::Icap::SizedEstimate::size() const
774c051c 1708{
1709 Must(knownSize());
47f6e231 1710 return static_cast<uint64_t>(theData);
774c051c 1711}
1712
1713
1714
26cc52cb 1715Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided)
774c051c 1716{}
1717
26cc52cb 1718void Adaptation::Icap::VirginBodyAct::plan()
774c051c 1719{
478cfe99 1720 Must(!disabled());
1721 Must(!theStart); // not started
1722 theState = stActive;
774c051c 1723}
1724
26cc52cb 1725void Adaptation::Icap::VirginBodyAct::disable()
774c051c 1726{
478cfe99 1727 theState = stDisabled;
774c051c 1728}
1729
26cc52cb 1730void Adaptation::Icap::VirginBodyAct::progress(size_t size)
774c051c 1731{
1732 Must(active());
1733 Must(size >= 0);
47f6e231 1734 theStart += static_cast<int64_t>(size);
774c051c 1735}
1736
26cc52cb 1737uint64_t Adaptation::Icap::VirginBodyAct::offset() const
774c051c 1738{
1739 Must(active());
47f6e231 1740 return static_cast<uint64_t>(theStart);
774c051c 1741}
1742
774c051c 1743
26cc52cb 1744Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled)
774c051c 1745{}
1746
26cc52cb 1747void Adaptation::Icap::Preview::enable(size_t anAd)
774c051c 1748{
1749 // TODO: check for anAd not exceeding preview size limit
1750 Must(anAd >= 0);
1751 Must(!enabled());
1752 theAd = anAd;
1753 theState = stWriting;
1754}
1755
26cc52cb 1756bool Adaptation::Icap::Preview::enabled() const
774c051c 1757{
1758 return theState != stDisabled;
1759}
1760
26cc52cb 1761size_t Adaptation::Icap::Preview::ad() const
774c051c 1762{
1763 Must(enabled());
1764 return theAd;
1765}
1766
26cc52cb 1767bool Adaptation::Icap::Preview::done() const
774c051c 1768{
1769 Must(enabled());
1770 return theState >= stIeof;
1771}
1772
26cc52cb 1773bool Adaptation::Icap::Preview::ieof() const
774c051c 1774{
1775 Must(enabled());
1776 return theState == stIeof;
1777}
1778
26cc52cb 1779size_t Adaptation::Icap::Preview::debt() const
774c051c 1780{
1781 Must(enabled());
1782 return done() ? 0 : (theAd - theWritten);
1783}
1784
26cc52cb 1785void Adaptation::Icap::Preview::wrote(size_t size, bool wroteEof)
774c051c 1786{
1787 Must(enabled());
5f8252d2 1788
774c051c 1789 theWritten += size;
1790
9e008dda 1791 Must(theWritten <= theAd);
5f8252d2 1792
9e008dda
AJ
1793 if (wroteEof)
1794 theState = stIeof; // written size is irrelevant
e1381638
AJ
1795 else if (theWritten >= theAd)
1796 theState = stDone;
774c051c 1797}
1798
26cc52cb 1799bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf &mb) const
3cfc19b3 1800{
5f8252d2 1801 if (virgin.header == NULL)
3cfc19b3 1802 return false;
1803
5f8252d2 1804 virgin.header->firstLineBuf(mb);
3cfc19b3 1805
1806 return true;
1807}
c824c43b 1808
1809
26cc52cb 1810/* Adaptation::Icap::ModXactLauncher */
c824c43b 1811
4299f876 1812Adaptation::Icap::ModXactLauncher::ModXactLauncher(HttpMsg *virginHeader, HttpRequest *virginCause, Adaptation::ServicePointer aService):
26cc52cb 1813 AsyncJob("Adaptation::Icap::ModXactLauncher"),
4299f876 1814 Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", aService)
c824c43b 1815{
1816 virgin.setHeader(virginHeader);
1817 virgin.setCause(virginCause);
3ff65596 1818 updateHistory(true);
c824c43b 1819}
1820
26cc52cb 1821Adaptation::Icap::Xaction *Adaptation::Icap::ModXactLauncher::createXaction()
c824c43b 1822{
26cc52cb
AR
1823 Adaptation::Icap::ServiceRep::Pointer s =
1824 dynamic_cast<Adaptation::Icap::ServiceRep*>(theService.getRaw());
0bef8dd7 1825 Must(s != NULL);
4299f876 1826 return new Adaptation::Icap::ModXact(virgin.header, virgin.cause, s);
c824c43b 1827}
3ff65596 1828
e1381638
AJ
1829void Adaptation::Icap::ModXactLauncher::swanSong()
1830{
3ff65596
AR
1831 debugs(93, 5, HERE << "swan sings");
1832 updateHistory(false);
1833 Adaptation::Icap::Launcher::swanSong();
1834}
1835
b0365bd9 1836void Adaptation::Icap::ModXactLauncher::updateHistory(bool doStart)
e1381638
AJ
1837{
1838 HttpRequest *r = virgin.cause ?
1839 virgin.cause : dynamic_cast<HttpRequest*>(virgin.header);
1840
1841 // r should never be NULL but we play safe; TODO: add Should()
1842 if (r) {
1843 Adaptation::Icap::History::Pointer h = r->icapHistory();
1844 if (h != NULL) {
b0365bd9 1845 if (doStart)
e1381638
AJ
1846 h->start("ICAPModXactLauncher");
1847 else
1848 h->stop("ICAPModXactLauncher");
1849 }
1850 }
3ff65596 1851}