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