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