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