]> git.ipfire.org Git - thirdparty/squid.git/blame - src/adaptation/icap/ModXact.cc
Simplify appending SBuf to String (#2108)
[thirdparty/squid.git] / src / adaptation / icap / ModXact.cc
CommitLineData
774c051c 1/*
1f7b830e 2 * Copyright (C) 1996-2025 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"
83b053a0
CT
27#include "error/Detail.h"
28#include "error/ExceptionErrorDetail.h"
4f1c93a7 29#include "http/ContentLengthInterpreter.h"
a5bac1d2 30#include "HttpHeaderTools.h"
774c051c 31#include "HttpReply.h"
5ceaee75 32#include "MasterXaction.h"
417da400
EB
33#include "parser/Tokenizer.h"
34#include "sbuf/Stream.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
0c060c02 45static constexpr auto TheBackupLimit = BodyPipe::MaxCapacity;
774c051c 46
417da400
EB
47const SBuf Adaptation::Icap::ChunkExtensionValueParser::UseOriginalBodyName("use-original-body");
48
26cc52cb 49Adaptation::Icap::ModXact::State::State()
774c051c 50{
09bfe95f 51 memset(this, 0, sizeof(*this));
774c051c 52}
53
63df1d28 54Adaptation::Icap::ModXact::ModXact(Http::Message *virginHeader,
af0ded40 55 HttpRequest *virginCause, AccessLogEntry::Pointer &alp, Adaptation::Icap::ServiceRep::Pointer &aService):
f53969cc
SM
56 AsyncJob("Adaptation::Icap::ModXact"),
57 Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", aService),
58 virginConsumed(0),
aee3523a 59 bodyParser(nullptr),
f53969cc
SM
60 canStartBypass(false), // too early
61 protectGroupBypass(true),
62 replyHttpHeaderSize(-1),
63 replyHttpBodySize(-1),
64 adaptHistoryId(-1),
69c698a3 65 trailerParser(nullptr),
f53969cc 66 alMaster(alp)
774c051c 67{
5f8252d2 68 assert(virginHeader);
774c051c 69
5f8252d2 70 virgin.setHeader(virginHeader); // sets virgin.body_pipe if needed
71 virgin.setCause(virginCause); // may be NULL
774c051c 72
5f8252d2 73 // adapted header and body are initialized when we parse them
774c051c 74
26cc52cb 75 // writing and reading ends are handled by Adaptation::Icap::Xaction
774c051c 76
77 // encoding
78 // nothing to do because we are using temporary buffers
79
3ff65596 80 // parsing; TODO: do not set until we parse, see ICAPOptXact
c7d51c86 81 icapReply = new HttpReply;
774c051c 82 icapReply->protoPrefix = "ICAP/"; // TODO: make an IcapReply class?
83
bf95c10a 84 debugs(93,7, "initialized." << status());
774c051c 85}
86
5f8252d2 87// initiator wants us to start
26cc52cb 88void Adaptation::Icap::ModXact::start()
774c051c 89{
26cc52cb 90 Adaptation::Icap::Xaction::start();
774c051c 91
3ff65596 92 // reserve an adaptation history slot (attempts are known at this time)
a22e6cd3 93 Adaptation::History::Pointer ah = virginRequest().adaptLogHistory();
aee3523a 94 if (ah != nullptr)
3ff65596
AR
95 adaptHistoryId = ah->recordXactStart(service().cfg().key, icap_tr_start, attempts > 1);
96
774c051c 97 estimateVirginBody(); // before virgin disappears!
98
0bef8dd7 99 canStartBypass = service().cfg().bypass;
478cfe99 100
774c051c 101 // it is an ICAP violation to send request to a service w/o known OPTIONS
2dba5b8e
CT
102 // and the service may is too busy for us: honor Max-Connections and such
103 if (service().up() && service().availableForNew())
774c051c 104 startWriting();
105 else
106 waitForService();
774c051c 107}
108
26cc52cb 109void Adaptation::Icap::ModXact::waitForService()
774c051c 110{
2dba5b8e 111 const char *comment;
774c051c 112 Must(!state.serviceWaiting);
2dba5b8e
CT
113
114 if (!service().up()) {
115 AsyncCall::Pointer call = JobCallback(93,5,
116 ConnWaiterDialer, this, Adaptation::Icap::ModXact::noteServiceReady);
117
118 service().callWhenReady(call);
119 comment = "to be up";
120 } else {
121 //The service is unavailable because of max-connection or other reason
122
123 if (service().cfg().onOverload != srvWait) {
124 // The service is overloaded, but waiting to be available prohibited by
125 // user configuration (onOverload is set to "block" or "bypass")
126 if (service().cfg().onOverload == srvBlock)
127 disableBypass("not available", true);
128 else //if (service().cfg().onOverload == srvBypass)
129 canStartBypass = true;
130
131 disableRetries();
132 disableRepeats("ICAP service is not available");
133
bf95c10a 134 debugs(93, 7, "will not wait for the service to be available" <<
2dba5b8e
CT
135 status());
136
137 throw TexcHere("ICAP service is not available");
138 }
139
140 AsyncCall::Pointer call = JobCallback(93,5,
141 ConnWaiterDialer, this, Adaptation::Icap::ModXact::noteServiceAvailable);
142 service().callWhenAvailable(call, state.waitedForService);
143 comment = "to be available";
144 }
145
bf95c10a 146 debugs(93, 7, "will wait for the service " << comment << status());
c7d51c86 147 state.serviceWaiting = true; // after callWhenReady() which may throw
2dba5b8e 148 state.waitedForService = true;
774c051c 149}
150
26cc52cb 151void Adaptation::Icap::ModXact::noteServiceReady()
774c051c 152{
774c051c 153 Must(state.serviceWaiting);
154 state.serviceWaiting = false;
c99de607 155
2dba5b8e 156 if (!service().up()) {
c824c43b 157 disableRetries();
3ff65596 158 disableRepeats("ICAP service is unusable");
478cfe99 159 throw TexcHere("ICAP service is unusable");
c824c43b 160 }
2dba5b8e
CT
161
162 if (service().availableForOld())
163 startWriting();
164 else
165 waitForService();
166}
167
168void Adaptation::Icap::ModXact::noteServiceAvailable()
169{
170 Must(state.serviceWaiting);
171 state.serviceWaiting = false;
172
173 if (service().up() && service().availableForOld())
174 startWriting();
175 else
176 waitForService();
774c051c 177}
178
26cc52cb 179void Adaptation::Icap::ModXact::startWriting()
774c051c 180{
774c051c 181 state.writing = State::writingConnect;
c824c43b 182
183 decideOnPreview(); // must be decided before we decideOnRetries
184 decideOnRetries();
185
774c051c 186 openConnection();
774c051c 187}
188
2b6b1bcb 189void Adaptation::Icap::ModXact::startShoveling()
774c051c 190{
191 Must(state.writing == State::writingConnect);
192
193 startReading(); // wait for early errors from the ICAP server
194
195 MemBuf requestBuf;
196 requestBuf.init();
197
198 makeRequestHeaders(requestBuf);
bf95c10a 199 debugs(93, 9, "will write" << status() << ":\n" <<
774c051c 200 (requestBuf.terminate(), requestBuf.content()));
201
202 // write headers
203 state.writing = State::writingHeaders;
3ff65596 204 icap_tio_start = current_time;
774c051c 205 scheduleWrite(requestBuf);
206}
207
26cc52cb 208void Adaptation::Icap::ModXact::handleCommWrote(size_t sz)
774c051c 209{
bf95c10a 210 debugs(93, 5, "Wrote " << sz << " bytes");
b107a5a5 211
774c051c 212 if (state.writing == State::writingHeaders)
213 handleCommWroteHeaders();
214 else
215 handleCommWroteBody();
216}
217
26cc52cb 218void Adaptation::Icap::ModXact::handleCommWroteHeaders()
774c051c 219{
220 Must(state.writing == State::writingHeaders);
221
5f8252d2 222 // determine next step
23e05fb1
AR
223 if (preview.enabled()) {
224 if (preview.done())
225 decideWritingAfterPreview("zero-size");
226 else
227 state.writing = State::writingPreview;
228 } else if (virginBody.expected()) {
e1381638 229 state.writing = State::writingPrime;
23e05fb1 230 } else {
e1381638
AJ
231 stopWriting(true);
232 return;
233 }
5f8252d2 234
235 writeMore();
774c051c 236}
237
26cc52cb 238void Adaptation::Icap::ModXact::writeMore()
774c051c 239{
bf95c10a 240 debugs(93, 5, "checking whether to write more" << status());
5f8252d2 241
aee3523a 242 if (writer != nullptr) // already writing something
774c051c 243 return;
244
245 switch (state.writing) {
246
247 case State::writingInit: // waiting for service OPTIONS
248 Must(state.serviceWaiting);
8b082ed9 249 return;
774c051c 250
251 case State::writingConnect: // waiting for the connection to establish
774c051c 252 case State::writingHeaders: // waiting for the headers to be written
774c051c 253 case State::writingPaused: // waiting for the ICAP server response
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{
bf95c10a 276 debugs(93, 8, "will write Preview body from " <<
9e008dda 277 virgin.body_pipe << status());
774c051c 278 Must(state.writing == State::writingPreview);
aee3523a 279 Must(virgin.body_pipe != nullptr);
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
bf95c10a 301 debugs(93, 6, "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)) {
bf95c10a 314 debugs(93, 5, "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);
aee3523a 322 Must(virgin.body_pipe != nullptr);
bf95c10a 323 debugs(93, 8, "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) {
bf95c10a 334 debugs(93, 7, "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 {
bf95c10a 344 debugs(93, 7, "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) {
bf95c10a 355 debugs(93, 8, "will write last-chunk of " << label);
774c051c 356 addLastRequestChunk(writeBuf);
357 }
358
bf95c10a 359 debugs(93, 7, "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{
4391cd15 378 buf.appendf((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)
61beade2 399 !virgin.body_pipe->expectMoreAfter(act.offset()); // will not have more
5f8252d2 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{
bf95c10a 426 debugs(93, 9, "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
cfee98c8 438 if (wantToPostpone && bp.buf().potentialSpaceSize() > 0) {
478cfe99 439 // Postponing may increase memory footprint and slow the HTTP side
9e008dda 440 // down. Not postponing may increase the number of ICAP errors
cfee98c8 441 // if the ICAP service fails. Should the trade-off be configurable?
bf95c10a 442 debugs(93, 8, "postponing consumption from " << bp.status());
478cfe99 443 return;
444 }
445
5f8252d2 446 const size_t have = static_cast<size_t>(bp.buf().contentSize());
47f6e231 447 const uint64_t end = virginConsumed + have;
448 uint64_t offset = end;
774c051c 449
bf95c10a 450 debugs(93, 9, "max virgin consumption offset=" << offset <<
9e008dda
AJ
451 " acts " << virginBodyWriting.active() << virginBodySending.active() <<
452 " consumed=" << virginConsumed <<
453 " from " << virgin.body_pipe->status());
478cfe99 454
5f8252d2 455 if (virginBodyWriting.active())
d85c3078 456 offset = min(virginBodyWriting.offset(), offset);
774c051c 457
5f8252d2 458 if (virginBodySending.active())
d85c3078 459 offset = min(virginBodySending.offset(), offset);
774c051c 460
461 Must(virginConsumed <= offset && offset <= end);
462
47f6e231 463 if (const size_t size = static_cast<size_t>(offset - virginConsumed)) {
bf95c10a 464 debugs(93, 8, "consuming " << size << " out of " << have <<
774c051c 465 " virgin body bytes");
5f8252d2 466 bp.consume(size);
774c051c 467 virginConsumed += size;
c824c43b 468 Must(!isRetriable); // or we should not be consuming
3ff65596 469 disableRepeats("consumed content");
a22e6cd3 470 disableBypass("consumed content", true);
774c051c 471 }
472}
473
26cc52cb 474void Adaptation::Icap::ModXact::handleCommWroteBody()
774c051c 475{
476 writeMore();
477}
478
c99de607 479// Called when we do not expect to call comm_write anymore.
480// We may have a pending write though.
481// If stopping nicely, we will just wait for that pending write, if any.
26cc52cb 482void Adaptation::Icap::ModXact::stopWriting(bool nicely)
774c051c 483{
c99de607 484 if (state.writing == State::writingReallyDone)
774c051c 485 return;
486
aee3523a 487 if (writer != nullptr) {
c99de607 488 if (nicely) {
bf95c10a 489 debugs(93, 7, "will wait for the last write" << status());
c99de607 490 state.writing = State::writingAlmostDone; // may already be set
5f8252d2 491 checkConsuming();
c99de607 492 return;
493 }
bf95c10a 494 debugs(93, 3, "will NOT wait for the last write" << status());
774c051c 495
c99de607 496 // Comm does not have an interface to clear the writer callback nicely,
497 // but without clearing the writer we cannot recycle the connection.
498 // We prevent connection reuse and hope that we can handle a callback
5f8252d2 499 // call at any time, usually in the middle of the destruction sequence!
500 // Somebody should add comm_remove_write_handler() to comm API.
c99de607 501 reuseConnection = false;
478cfe99 502 ignoreLastWrite = true;
c99de607 503 }
504
bf95c10a 505 debugs(93, 7, "will no longer write" << status());
5f8252d2 506 if (virginBodyWriting.active()) {
507 virginBodyWriting.disable();
508 virginConsume();
509 }
478cfe99 510 state.writing = State::writingReallyDone;
511 checkConsuming();
774c051c 512}
513
26cc52cb 514void Adaptation::Icap::ModXact::stopBackup()
774c051c 515{
5f8252d2 516 if (!virginBodySending.active())
774c051c 517 return;
518
bf95c10a 519 debugs(93, 7, "will no longer backup" << status());
5f8252d2 520 virginBodySending.disable();
774c051c 521 virginConsume();
522}
523
26cc52cb 524bool Adaptation::Icap::ModXact::doneAll() const
774c051c 525{
26cc52cb 526 return Adaptation::Icap::Xaction::doneAll() && !state.serviceWaiting &&
5f8252d2 527 doneSending() &&
774c051c 528 doneReading() && state.doneWriting();
529}
530
26cc52cb 531void Adaptation::Icap::ModXact::startReading()
774c051c 532{
aed188fd 533 Must(haveConnection());
774c051c 534 Must(!reader);
5f8252d2 535 Must(!adapted.header);
536 Must(!adapted.body_pipe);
774c051c 537
538 // we use the same buffer for headers and body and then consume headers
539 readMore();
540}
541
26cc52cb 542void Adaptation::Icap::ModXact::readMore()
774c051c 543{
aee3523a 544 if (reader != nullptr || doneReading()) {
bf95c10a 545 debugs(93,3, "returning from readMore because reader or doneReading()");
774c051c 546 return;
3b299123 547 }
774c051c 548
549 // do not fill readBuf if we have no space to store the result
aee3523a 550 if (adapted.body_pipe != nullptr &&
9e008dda 551 !adapted.body_pipe->buf().hasPotentialSpace()) {
bf95c10a 552 debugs(93,3, "not reading because ICAP reply pipe is full");
774c051c 553 return;
3b299123 554 }
774c051c 555
2b42f3fd 556 if (readBuf.length() < SQUID_TCP_SO_RCVBUF)
774c051c 557 scheduleRead();
3b299123 558 else
bf95c10a 559 debugs(93,3, "cannot read with a full buffer");
774c051c 560}
561
562// comm module read a portion of the ICAP response for us
26cc52cb 563void Adaptation::Icap::ModXact::handleCommRead(size_t)
774c051c 564{
565 Must(!state.doneParsing());
3ff65596 566 icap_tio_finish = current_time;
774c051c 567 parseMore();
568 readMore();
569}
570
26cc52cb 571void Adaptation::Icap::ModXact::echoMore()
774c051c 572{
573 Must(state.sending == State::sendingVirgin);
aee3523a 574 Must(adapted.body_pipe != nullptr);
5f8252d2 575 Must(virginBodySending.active());
576
577 const size_t sizeMax = virginContentSize(virginBodySending);
bf95c10a 578 debugs(93,5, "will echo up to " << sizeMax << " bytes from " <<
9e008dda 579 virgin.body_pipe->status());
bf95c10a 580 debugs(93,5, "will echo up to " << sizeMax << " bytes to " <<
9e008dda 581 adapted.body_pipe->status());
5f8252d2 582
583 if (sizeMax > 0) {
584 const size_t size = adapted.body_pipe->putMoreData(virginContentData(virginBodySending), sizeMax);
bf95c10a 585 debugs(93,5, "echoed " << size << " out of " << sizeMax <<
9e008dda 586 " bytes");
5f8252d2 587 virginBodySending.progress(size);
3ff65596 588 disableRepeats("echoed content");
a22e6cd3
AR
589 disableBypass("echoed content", true);
590 virginConsume();
774c051c 591 }
592
5f8252d2 593 if (virginBodyEndReached(virginBodySending)) {
bf95c10a 594 debugs(93, 5, "echoed all" << status());
774c051c 595 stopSending(true);
596 } else {
bf95c10a 597 debugs(93, 5, "has " <<
9e008dda
AJ
598 virgin.body_pipe->buf().contentSize() << " bytes " <<
599 "and expects more to echo" << status());
5f8252d2 600 // TODO: timeout if virgin or adapted pipes are broken
774c051c 601 }
602}
603
26cc52cb 604bool Adaptation::Icap::ModXact::doneSending() const
774c051c 605{
774c051c 606 return state.sending == State::sendingDone;
607}
608
478cfe99 609// stop (or do not start) sending adapted message body
26cc52cb 610void Adaptation::Icap::ModXact::stopSending(bool nicely)
774c051c 611{
bf95c10a 612 debugs(93, 7, "Enter stop sending ");
774c051c 613 if (doneSending())
614 return;
bf95c10a 615 debugs(93, 7, "Proceed with stop sending ");
774c051c 616
617 if (state.sending != State::sendingUndecided) {
bf95c10a 618 debugs(93, 7, "will no longer send" << status());
aee3523a 619 if (adapted.body_pipe != nullptr) {
5f8252d2 620 virginBodySending.disable();
621 // we may leave debts if we were echoing and the virgin
622 // body_pipe got exhausted before we echoed all planned bytes
623 const bool leftDebts = adapted.body_pipe->needsMoreData();
624 stopProducingFor(adapted.body_pipe, nicely && !leftDebts);
625 }
774c051c 626 } else {
bf95c10a 627 debugs(93, 7, "will not start sending" << status());
5f8252d2 628 Must(!adapted.body_pipe);
774c051c 629 }
630
631 state.sending = State::sendingDone;
5f8252d2 632 checkConsuming();
774c051c 633}
634
5f8252d2 635// should be called after certain state.writing or state.sending changes
26cc52cb 636void Adaptation::Icap::ModXact::checkConsuming()
774c051c 637{
5f8252d2 638 // quit if we already stopped or are still using the pipe
639 if (!virgin.body_pipe || !state.doneConsumingVirgin())
774c051c 640 return;
641
bf95c10a 642 debugs(93, 7, "will stop consuming" << status());
5f8252d2 643 stopConsumingFrom(virgin.body_pipe);
774c051c 644}
645
26cc52cb 646void Adaptation::Icap::ModXact::parseMore()
774c051c 647{
84ae6223
AJ
648 debugs(93, 5, "have " << readBuf.length() << " bytes to parse" << status());
649 debugs(93, 5, "\n" << readBuf);
774c051c 650
651 if (state.parsingHeaders())
652 parseHeaders();
653
654 if (state.parsing == State::psBody)
655 parseBody();
69c698a3
EB
656
657 if (state.parsing == State::psIcapTrailer)
658 parseIcapTrailer();
774c051c 659}
660
26cc52cb 661void Adaptation::Icap::ModXact::callException(const std::exception &e)
478cfe99 662{
663 if (!canStartBypass || isRetriable) {
64b66b76
CT
664 if (!isRetriable) {
665 if (const TextException *te = dynamic_cast<const TextException *>(&e))
83b053a0 666 detailError(new ExceptionErrorDetail(te->id()));
64b66b76 667 else
83b053a0 668 detailError(new ExceptionErrorDetail(Here().id()));
64b66b76 669 }
26cc52cb 670 Adaptation::Icap::Xaction::callException(e);
478cfe99 671 return;
672 }
673
674 try {
bf95c10a 675 debugs(93, 3, "bypassing " << inCall << " exception: " <<
af6a12ee 676 e.what() << ' ' << status());
478cfe99 677 bypassFailure();
64b66b76 678 } catch (const TextException &bypassTe) {
83b053a0 679 detailError(new ExceptionErrorDetail(bypassTe.id()));
64b66b76 680 Adaptation::Icap::Xaction::callException(bypassTe);
9e008dda 681 } catch (const std::exception &bypassE) {
83b053a0 682 detailError(new ExceptionErrorDetail(Here().id()));
26cc52cb 683 Adaptation::Icap::Xaction::callException(bypassE);
478cfe99 684 }
685}
686
26cc52cb 687void Adaptation::Icap::ModXact::bypassFailure()
478cfe99 688{
a22e6cd3 689 disableBypass("already started to bypass", false);
478cfe99 690
691 Must(!isRetriable); // or we should not be bypassing
3ff65596 692 // TODO: should the same be enforced for isRepeatable? Check icap_repeat??
478cfe99 693
694 prepEchoing();
695
696 startSending();
697
698 // end all activities associated with the ICAP server
699
69c698a3 700 stopParsing(false);
478cfe99 701
702 stopWriting(true); // or should we force it?
aed188fd 703 if (haveConnection()) {
478cfe99 704 reuseConnection = false; // be conservative
705 cancelRead(); // may not work; and we cannot stop connecting either
706 if (!doneWithIo())
bf95c10a 707 debugs(93, 7, "Warning: bypass failed to stop I/O" << status());
478cfe99 708 }
61cb3565
AR
709
710 service().noteFailure(); // we are bypassing, but this is still a failure
478cfe99 711}
712
a22e6cd3 713void Adaptation::Icap::ModXact::disableBypass(const char *reason, bool includingGroupBypass)
478cfe99 714{
715 if (canStartBypass) {
bf95c10a 716 debugs(93,7, "will never start bypass because " << reason);
478cfe99 717 canStartBypass = false;
718 }
a22e6cd3 719 if (protectGroupBypass && includingGroupBypass) {
bf95c10a 720 debugs(93,7, "not protecting group bypass because " << reason);
a22e6cd3
AR
721 protectGroupBypass = false;
722 }
478cfe99 723}
724
774c051c 725// note that allocation for echoing is done in handle204NoContent()
26cc52cb 726void Adaptation::Icap::ModXact::maybeAllocateHttpMsg()
774c051c 727{
5f8252d2 728 if (adapted.header) // already allocated
774c051c 729 return;
730
731 if (gotEncapsulated("res-hdr")) {
5f8252d2 732 adapted.setHeader(new HttpReply);
3ff65596 733 setOutcome(service().cfg().method == ICAP::methodReqmod ?
e1381638 734 xoSatisfied : xoModified);
774c051c 735 } else if (gotEncapsulated("req-hdr")) {
5ceaee75 736 adapted.setHeader(new HttpRequest(virginRequest().masterXaction));
3ff65596 737 setOutcome(xoModified);
774c051c 738 } else
739 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
740}
741
26cc52cb 742void Adaptation::Icap::ModXact::parseHeaders()
774c051c 743{
744 Must(state.parsingHeaders());
745
b107a5a5 746 if (state.parsing == State::psIcapHeader) {
bf95c10a 747 debugs(93, 5, "parse ICAP headers");
774c051c 748 parseIcapHead();
b107a5a5 749 }
774c051c 750
b107a5a5 751 if (state.parsing == State::psHttpHeader) {
bf95c10a 752 debugs(93, 5, "parse HTTP headers");
774c051c 753 parseHttpHead();
b107a5a5 754 }
774c051c 755
756 if (state.parsingHeaders()) { // need more data
757 Must(mayReadMore());
758 return;
759 }
760
478cfe99 761 startSending();
762}
763
764// called after parsing all headers or when bypassing an exception
26cc52cb 765void Adaptation::Icap::ModXact::startSending()
478cfe99 766{
3ff65596 767 disableRepeats("sent headers");
a22e6cd3 768 disableBypass("sent headers", true);
3af10ac0 769 sendAnswer(Answer::Forward(adapted.header));
774c051c 770
771 if (state.sending == State::sendingVirgin)
772 echoMore();
88df846b 773 else {
ff89bfa0 774 // If we are not using the virgin HTTP object update the
63df1d28 775 // Http::Message::sources flag.
88df846b 776 // The state.sending may set to State::sendingVirgin in the case
63df1d28 777 // of 206 responses too, where we do not want to update Http::Message::sources
ff89bfa0
SM
778 // flag. However even for 206 responses the state.sending is
779 // not set yet to sendingVirgin. This is done in later step
88df846b
CT
780 // after the parseBody method called.
781 updateSources();
782 }
774c051c 783}
784
26cc52cb 785void Adaptation::Icap::ModXact::parseIcapHead()
774c051c 786{
787 Must(state.sending == State::sendingUndecided);
788
b248c2a3 789 if (!parseHead(icapReply.getRaw()))
774c051c 790 return;
791
69c698a3
EB
792 if (expectIcapTrailers()) {
793 Must(!trailerParser);
794 trailerParser = new TrailerParser;
795 }
796
d5f18517
AJ
797 static SBuf close("close", 5);
798 if (httpHeaderHasConnDir(&icapReply->header, close)) {
bf95c10a 799 debugs(93, 5, "found connection close");
fc764d26 800 reuseConnection = false;
801 }
802
9b769c67 803 switch (icapReply->sline.status()) {
774c051c 804
9b769c67 805 case Http::scContinue:
774c051c 806 handle100Continue();
807 break;
808
9b769c67
AJ
809 case Http::scOkay:
810 case Http::scCreated: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
b559db5d 811
812 if (!validate200Ok()) {
813 throw TexcHere("Invalid ICAP Response");
814 } else {
815 handle200Ok();
816 }
817
774c051c 818 break;
819
9b769c67 820 case Http::scNoContent:
774c051c 821 handle204NoContent();
822 break;
823
9b769c67 824 case Http::scPartialContent:
83c51da9
CT
825 handle206PartialContent();
826 break;
827
774c051c 828 default:
9b769c67 829 debugs(93, 5, "ICAP status " << icapReply->sline.status());
774c051c 830 handleUnknownScode();
831 break;
832 }
833
3ff65596
AR
834 const HttpRequest *request = dynamic_cast<HttpRequest*>(adapted.header);
835 if (!request)
836 request = &virginRequest();
837
838 // update the cross-transactional database if needed (all status codes!)
839 if (const char *xxName = Adaptation::Config::masterx_shared_name) {
a22e6cd3 840 Adaptation::History::Pointer ah = request->adaptHistory(true);
aee3523a 841 if (ah != nullptr) { // TODO: reorder checks to avoid creating history
3ff65596
AR
842 const String val = icapReply->header.getByName(xxName);
843 if (val.size() > 0) // XXX: HttpHeader lacks empty value detection
844 ah->updateXxRecord(xxName, val);
845 }
846 }
847
a22e6cd3
AR
848 // update the adaptation plan if needed (all status codes!)
849 if (service().cfg().routing) {
850 String services;
789217a2 851 if (icapReply->header.getList(Http::HdrType::X_NEXT_SERVICES, &services)) {
a22e6cd3 852 Adaptation::History::Pointer ah = request->adaptHistory(true);
aee3523a 853 if (ah != nullptr)
a22e6cd3
AR
854 ah->updateNextServices(services);
855 }
789217a2 856 } // TODO: else warn (occasionally!) if we got Http::HdrType::X_NEXT_SERVICES
a22e6cd3 857
3ff65596
AR
858 // We need to store received ICAP headers for <icapLastHeader logformat option.
859 // If we already have stored headers from previous ICAP transaction related to this
860 // request, old headers will be replaced with the new one.
e1381638 861
5038f9d8 862 Adaptation::History::Pointer ah = request->adaptLogHistory();
aee3523a 863 if (ah != nullptr)
5038f9d8 864 ah->recordMeta(&icapReply->header);
3ff65596 865
774c051c 866 // handle100Continue() manages state.writing on its own.
867 // Non-100 status means the server needs no postPreview data from us.
868 if (state.writing == State::writingPaused)
c99de607 869 stopWriting(true);
774c051c 870}
871
69c698a3
EB
872/// Parses ICAP trailers and stops parsing, if all trailer data
873/// have been received.
874void Adaptation::Icap::ModXact::parseIcapTrailer() {
b559db5d 875
69c698a3
EB
876 if (parsePart(trailerParser, "trailer")) {
877 for (const auto &e: trailerParser->trailer.entries)
878 debugs(93, 5, "ICAP trailer: " << e->name << ": " << e->value);
879 stopParsing();
b559db5d 880 }
69c698a3 881}
b559db5d 882
69c698a3
EB
883bool Adaptation::Icap::ModXact::validate200Ok()
884{
885 if (service().cfg().method == ICAP::methodRespmod)
886 return gotEncapsulated("res-hdr");
b559db5d 887
69c698a3
EB
888 return service().cfg().method == ICAP::methodReqmod &&
889 expectHttpHeader();
b559db5d 890}
891
26cc52cb 892void Adaptation::Icap::ModXact::handle100Continue()
774c051c 893{
894 Must(state.writing == State::writingPaused);
5f8252d2 895 // server must not respond before the end of preview: we may send ieof
774c051c 896 Must(preview.enabled() && preview.done() && !preview.ieof());
774c051c 897
83c51da9
CT
898 // 100 "Continue" cancels our Preview commitment,
899 // but not commitment to handle 204 or 206 outside Preview
900 if (!state.allowedPostview204 && !state.allowedPostview206)
774c051c 901 stopBackup();
902
c99de607 903 state.parsing = State::psIcapHeader; // eventually
904 icapReply->reset();
774c051c 905
906 state.writing = State::writingPrime;
907
908 writeMore();
909}
910
26cc52cb 911void Adaptation::Icap::ModXact::handle200Ok()
774c051c 912{
913 state.parsing = State::psHttpHeader;
914 state.sending = State::sendingAdapted;
915 stopBackup();
5f8252d2 916 checkConsuming();
774c051c 917}
918
26cc52cb 919void Adaptation::Icap::ModXact::handle204NoContent()
774c051c 920{
921 stopParsing();
478cfe99 922 prepEchoing();
923}
924
83c51da9
CT
925void Adaptation::Icap::ModXact::handle206PartialContent()
926{
927 if (state.writing == State::writingPaused) {
928 Must(preview.enabled());
929 Must(state.allowedPreview206);
bf95c10a 930 debugs(93, 7, "206 inside preview");
83c51da9
CT
931 } else {
932 Must(state.writing > State::writingPaused);
933 Must(state.allowedPostview206);
bf95c10a 934 debugs(93, 7, "206 outside preview");
83c51da9
CT
935 }
936 state.parsing = State::psHttpHeader;
937 state.sending = State::sendingAdapted;
938 state.readyForUob = true;
939 checkConsuming();
940}
941
478cfe99 942// Called when we receive a 204 No Content response and
943// when we are trying to bypass a service failure.
944// We actually start sending (echoig or not) in startSending.
26cc52cb 945void Adaptation::Icap::ModXact::prepEchoing()
478cfe99 946{
3ff65596 947 disableRepeats("preparing to echo content");
a22e6cd3 948 disableBypass("preparing to echo content", true);
3ff65596 949 setOutcome(xoEcho);
774c051c 950
951 // We want to clone the HTTP message, but we do not want
63df1d28 952 // to copy some non-HTTP state parts that Http::Message kids carry in them.
774c051c 953 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
954 // Instead, we simply write the HTTP message and "clone" it by parsing.
63df1d28 955 // TODO: use Http::Message::clone()!
774c051c 956
63df1d28 957 Http::Message *oldHead = virgin.header;
bf95c10a 958 debugs(93, 7, "cloning virgin message " << oldHead);
774c051c 959
960 MemBuf httpBuf;
961
962 // write the virgin message into a memory buffer
963 httpBuf.init();
964 packHead(httpBuf, oldHead);
965
c99de607 966 // allocate the adapted message and copy metainfo
5f8252d2 967 Must(!adapted.header);
c7d51c86 968 {
63df1d28 969 Http::MessagePointer newHead;
5ceaee75
CT
970 if (const HttpRequest *r = dynamic_cast<const HttpRequest*>(oldHead)) {
971 newHead = new HttpRequest(r->masterXaction);
e6f9e263
A
972 } else if (dynamic_cast<const HttpReply*>(oldHead)) {
973 newHead = new HttpReply;
974 }
d39901ed 975 Must(newHead);
774c051c 976
e6f9e263 977 newHead->inheritProperties(oldHead);
774c051c 978
b248c2a3 979 adapted.setHeader(newHead.getRaw());
c7d51c86 980 }
7514268e 981
774c051c 982 // parse the buffer back
955394ce 983 Http::StatusCode error = Http::scNone;
774c051c 984
63df1d28 985 httpBuf.terminate(); // Http::Message::parse requires nil-terminated buffer
84ae6223 986 Must(adapted.header->parse(httpBuf.content(), httpBuf.contentSize(), true, &error));
c7d51c86 987 Must(adapted.header->hdr_sz == httpBuf.contentSize()); // no leftovers
774c051c 988
989 httpBuf.clean();
990
bf95c10a 991 debugs(93, 7, "cloned virgin message " << oldHead << " to " <<
c7d51c86 992 adapted.header);
5f8252d2 993
994 // setup adapted body pipe if needed
aee3523a 995 if (oldHead->body_pipe != nullptr) {
bf95c10a 996 debugs(93, 7, "will echo virgin body from " <<
9e008dda 997 oldHead->body_pipe);
478cfe99 998 if (!virginBodySending.active())
999 virginBodySending.plan(); // will throw if not possible
5f8252d2 1000 state.sending = State::sendingVirgin;
1001 checkConsuming();
478cfe99 1002
5f8252d2 1003 // TODO: optimize: is it possible to just use the oldHead pipe and
1004 // remove ICAP from the loop? This echoing is probably a common case!
1005 makeAdaptedBodyPipe("echoed virgin response");
1006 if (oldHead->body_pipe->bodySizeKnown())
1007 adapted.body_pipe->setBodySize(oldHead->body_pipe->bodySize());
bf95c10a 1008 debugs(93, 7, "will echo virgin body to " <<
9e008dda 1009 adapted.body_pipe);
5f8252d2 1010 } else {
bf95c10a 1011 debugs(93, 7, "no virgin body to echo");
5f8252d2 1012 stopSending(true);
1013 }
774c051c 1014}
1015
83c51da9
CT
1016/// Called when we received use-original-body chunk extension in 206 response.
1017/// We actually start sending (echoing or not) in startSending().
1018void Adaptation::Icap::ModXact::prepPartialBodyEchoing(uint64_t pos)
1019{
1020 Must(virginBodySending.active());
aee3523a 1021 Must(virgin.header->body_pipe != nullptr);
83c51da9
CT
1022
1023 setOutcome(xoPartEcho);
1024
bf95c10a 1025 debugs(93, 7, "will echo virgin body suffix from " <<
83c51da9
CT
1026 virgin.header->body_pipe << " offset " << pos );
1027
1028 // check that use-original-body=N does not point beyond buffered data
1029 const uint64_t virginDataEnd = virginConsumed +
7ddcfbab 1030 virgin.body_pipe->buf().contentSize();
83c51da9
CT
1031 Must(pos <= virginDataEnd);
1032 virginBodySending.progress(static_cast<size_t>(pos));
1033
1034 state.sending = State::sendingVirgin;
1035 checkConsuming();
1036
1037 if (virgin.header->body_pipe->bodySizeKnown())
1038 adapted.body_pipe->expectProductionEndAfter(virgin.header->body_pipe->bodySize() - pos);
1039
bf95c10a 1040 debugs(93, 7, "will echo virgin body suffix to " <<
83c51da9
CT
1041 adapted.body_pipe);
1042
1043 // Start echoing data
1044 echoMore();
1045}
1046
26cc52cb 1047void Adaptation::Icap::ModXact::handleUnknownScode()
774c051c 1048{
69c698a3 1049 stopParsing(false);
774c051c 1050 stopBackup();
1051 // TODO: mark connection as "bad"
1052
1053 // Terminate the transaction; we do not know how to handle this response.
1054 throw TexcHere("Unsupported ICAP status code");
1055}
1056
26cc52cb 1057void Adaptation::Icap::ModXact::parseHttpHead()
774c051c 1058{
69c698a3 1059 if (expectHttpHeader()) {
bae917ac 1060 replyHttpHeaderSize = 0;
774c051c 1061 maybeAllocateHttpMsg();
1062
5f8252d2 1063 if (!parseHead(adapted.header))
c99de607 1064 return; // need more header data
5f8252d2 1065
bae917ac
CT
1066 if (adapted.header)
1067 replyHttpHeaderSize = adapted.header->hdr_sz;
1068
d67acb4e 1069 if (dynamic_cast<HttpRequest*>(adapted.header)) {
5f8252d2 1070 const HttpRequest *oldR = dynamic_cast<const HttpRequest*>(virgin.header);
1071 Must(oldR);
9e008dda
AJ
1072 // TODO: the adapted request did not really originate from the
1073 // client; give proxy admin an option to prevent copying of
5f8252d2 1074 // sensitive client information here. See the following thread:
1075 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
5f8252d2 1076 }
d67acb4e 1077
9e008dda
AJ
1078 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
1079 if (adapted.header)
1080 adapted.header->inheritProperties(virgin.header);
774c051c 1081 }
1082
5f8252d2 1083 decideOnParsingBody();
774c051c 1084}
1085
69c698a3
EB
1086template<class Part>
1087bool Adaptation::Icap::ModXact::parsePart(Part *part, const char *description)
774c051c 1088{
69c698a3
EB
1089 Must(part);
1090 debugs(93, 5, "have " << readBuf.length() << ' ' << description << " bytes to parse; state: " << state.parsing);
955394ce 1091 Http::StatusCode error = Http::scNone;
84ae6223 1092 // XXX: performance regression. c_str() data copies
63df1d28 1093 // XXX: Http::Message::parse requires a terminated string buffer
84ae6223 1094 const char *tmpBuf = readBuf.c_str();
69c698a3
EB
1095 const bool parsed = part->parse(tmpBuf, readBuf.length(), commEof, &error);
1096 debugs(93, (!parsed && error) ? 2 : 5, description << " parsing result: " << parsed << " detail: " << error);
1097 Must(parsed || !error);
1098 if (parsed)
1099 readBuf.consume(part->hdr_sz);
1100 return parsed;
1101}
774c051c 1102
69c698a3 1103// parses both HTTP and ICAP headers
63df1d28
AJ
1104bool
1105Adaptation::Icap::ModXact::parseHead(Http::Message *head)
69c698a3
EB
1106{
1107 if (!parsePart(head, "head")) {
774c051c 1108 head->reset();
1109 return false;
1110 }
774c051c 1111 return true;
1112}
1113
69c698a3
EB
1114bool Adaptation::Icap::ModXact::expectHttpHeader() const
1115{
1116 return gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr");
1117}
1118
1119bool Adaptation::Icap::ModXact::expectHttpBody() const
1120{
1121 return gotEncapsulated("res-body") || gotEncapsulated("req-body");
1122}
1123
1124bool Adaptation::Icap::ModXact::expectIcapTrailers() const
1125{
1126 String trailers;
f29d429e 1127 const bool promisesToSendTrailer = icapReply->header.getByIdIfPresent(Http::HdrType::TRAILER, &trailers);
69c698a3
EB
1128 const bool supportsTrailers = icapReply->header.hasListMember(Http::HdrType::ALLOW, "trailers", ',');
1129 // ICAP Trailer specs require us to reject transactions having either Trailer
1130 // header or Allow:trailers
1131 Must((promisesToSendTrailer == supportsTrailers) || (!promisesToSendTrailer && supportsTrailers));
1132 if (promisesToSendTrailer && !trailers.size())
1133 debugs(93, DBG_IMPORTANT, "ERROR: ICAP Trailer response header field must not be empty (salvaged)");
1134 return promisesToSendTrailer;
1135}
1136
26cc52cb 1137void Adaptation::Icap::ModXact::decideOnParsingBody()
9e008dda 1138{
69c698a3 1139 if (expectHttpBody()) {
bf95c10a 1140 debugs(93, 5, "expecting a body");
5f8252d2 1141 state.parsing = State::psBody;
bae917ac 1142 replyHttpBodySize = 0;
db1720f8 1143 bodyParser = new Http1::TeChunkedParser;
417da400 1144 bodyParser->parseExtensionValuesWith(&extensionParser);
5f8252d2 1145 makeAdaptedBodyPipe("adapted response from the ICAP server");
1146 Must(state.sending == State::sendingAdapted);
774c051c 1147 } else {
bf95c10a 1148 debugs(93, 5, "not expecting a body");
69c698a3
EB
1149 if (trailerParser)
1150 state.parsing = State::psIcapTrailer;
1151 else
1152 stopParsing();
5f8252d2 1153 stopSending(true);
774c051c 1154 }
774c051c 1155}
1156
26cc52cb 1157void Adaptation::Icap::ModXact::parseBody()
774c051c 1158{
5f8252d2 1159 Must(state.parsing == State::psBody);
1160 Must(bodyParser);
774c051c 1161
84ae6223 1162 debugs(93, 5, "have " << readBuf.length() << " body bytes to parse");
774c051c 1163
5f8252d2 1164 // the parser will throw on errors
1165 BodyPipeCheckout bpc(*adapted.body_pipe);
be29ee33
AJ
1166 bodyParser->setPayloadBuffer(&bpc.buf);
1167 const bool parsed = bodyParser->parse(readBuf);
1168 readBuf = bodyParser->remaining(); // sync buffers after parse
5f8252d2 1169 bpc.checkIn();
774c051c 1170
84ae6223 1171 debugs(93, 5, "have " << readBuf.length() << " body bytes after parsed all: " << parsed);
bae917ac 1172 replyHttpBodySize += adapted.body_pipe->buf().contentSize();
774c051c 1173
478cfe99 1174 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
3ff65596
AR
1175 // TODO: do we really need this if we disable when sending headers?
1176 if (adapted.body_pipe->buf().contentSize() > 0) { // parsed something sometime
1177 disableRepeats("sent adapted content");
a22e6cd3 1178 disableBypass("sent adapted content", true);
3ff65596 1179 }
478cfe99 1180
5f8252d2 1181 if (parsed) {
417da400
EB
1182 if (state.readyForUob && extensionParser.sawUseOriginalBody())
1183 prepPartialBodyEchoing(extensionParser.useOriginalBody());
69c698a3
EB
1184 else
1185 stopSending(true); // the parser succeeds only if all parsed data fits
1186 if (trailerParser)
1187 state.parsing = State::psIcapTrailer;
1188 else
83c51da9 1189 stopParsing();
5f8252d2 1190 return;
1191 }
774c051c 1192
bf95c10a 1193 debugs(93,3, this << " needsMoreData = " << bodyParser->needsMoreData());
3b299123 1194
1195 if (bodyParser->needsMoreData()) {
bf95c10a 1196 debugs(93,3, this);
774c051c 1197 Must(mayReadMore());
3b299123 1198 readMore();
1199 }
774c051c 1200
1201 if (bodyParser->needsMoreSpace()) {
1202 Must(!doneSending()); // can hope for more space
5f8252d2 1203 Must(adapted.body_pipe->buf().contentSize() > 0); // paranoid
1204 // TODO: there should be a timeout in case the sink is broken
1205 // or cannot consume partial content (while we need more space)
774c051c 1206 }
774c051c 1207}
1208
69c698a3 1209void Adaptation::Icap::ModXact::stopParsing(const bool checkUnparsedData)
774c051c 1210{
1211 if (state.parsing == State::psDone)
1212 return;
1213
69c698a3
EB
1214 if (checkUnparsedData)
1215 Must(readBuf.isEmpty());
1216
1217 debugs(93, 7, "will no longer parse" << status());
774c051c 1218
1219 delete bodyParser;
69c698a3 1220 bodyParser = nullptr;
774c051c 1221
69c698a3
EB
1222 delete trailerParser;
1223 trailerParser = nullptr;
774c051c 1224
1225 state.parsing = State::psDone;
1226}
1227
1228// HTTP side added virgin body data
26cc52cb 1229void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer)
774c051c 1230{
774c051c 1231 writeMore();
1232
1233 if (state.sending == State::sendingVirgin)
1234 echoMore();
774c051c 1235}
1236
1237// HTTP side sent us all virgin info
26cc52cb 1238void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer)
774c051c 1239{
5f8252d2 1240 Must(virgin.body_pipe->productionEnded());
774c051c 1241
1242 // push writer and sender in case we were waiting for the last-chunk
1243 writeMore();
1244
1245 if (state.sending == State::sendingVirgin)
1246 echoMore();
774c051c 1247}
1248
9e008dda 1249// body producer aborted, but the initiator may still want to know
585ab260 1250// the answer, even though the HTTP message has been truncated
26cc52cb 1251void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer)
774c051c 1252{
585ab260 1253 Must(virgin.body_pipe->productionEnded());
1254
1255 // push writer and sender in case we were waiting for the last-chunk
1256 writeMore();
1257
1258 if (state.sending == State::sendingVirgin)
1259 echoMore();
5f8252d2 1260}
1261
9e008dda 1262// adapted body consumer wants more adapted data and
5f8252d2 1263// possibly freed some buffer space
26cc52cb 1264void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer)
774c051c 1265{
774c051c 1266 if (state.sending == State::sendingVirgin)
1267 echoMore();
3b299123 1268 else if (state.sending == State::sendingAdapted)
1269 parseMore();
774c051c 1270 else
3b299123 1271 Must(state.sending == State::sendingUndecided);
774c051c 1272}
1273
5f8252d2 1274// adapted body consumer aborted
26cc52cb 1275void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer)
774c051c 1276{
83b053a0
CT
1277 static const auto d = MakeNamedErrorDetail("ICAP_XACT_BODY_CONSUMER_ABORT");
1278 detailError(d);
5f8252d2 1279 mustStop("adapted body consumer aborted");
774c051c 1280}
1281
c7d51c86
AR
1282Adaptation::Icap::ModXact::~ModXact()
1283{
1284 delete bodyParser;
69c698a3 1285 delete trailerParser;
c7d51c86
AR
1286}
1287
774c051c 1288// internal cleanup
26cc52cb 1289void Adaptation::Icap::ModXact::swanSong()
774c051c 1290{
bf95c10a 1291 debugs(93, 5, "swan sings" << status());
5f8252d2 1292
c99de607 1293 stopWriting(false);
c824c43b 1294 stopSending(false);
774c051c 1295
83b053a0
CT
1296 if (theInitiator.set()) { // we have not sent the answer to the initiator
1297 static const auto d = MakeNamedErrorDetail("ICAP_XACT_OTHER");
1298 detailError(d);
1299 }
64b66b76 1300
3ff65596 1301 // update adaptation history if start was called and we reserved a slot
a22e6cd3 1302 Adaptation::History::Pointer ah = virginRequest().adaptLogHistory();
aee3523a 1303 if (ah != nullptr && adaptHistoryId >= 0)
3ff65596 1304 ah->recordXactFinish(adaptHistoryId);
774c051c 1305
26cc52cb 1306 Adaptation::Icap::Xaction::swanSong();
774c051c 1307}
1308
63ed9e8e 1309void prepareLogWithRequestDetails(HttpRequest *, const AccessLogEntryPointer &);
3ff65596
AR
1310
1311void Adaptation::Icap::ModXact::finalizeLogInfo()
1312{
bd59d61c
EB
1313 HttpRequest *adapted_request_ = nullptr;
1314 HttpReply *adapted_reply_ = nullptr;
a2958f2f 1315 HttpRequest *virgin_request_ = const_cast<HttpRequest*>(&virginRequest());
3ecb654f 1316 if (!(adapted_request_ = dynamic_cast<HttpRequest*>(adapted.header))) {
bd59d61c
EB
1317 // if the request was not adapted, use virgin request to simplify
1318 // the code further below
1319 adapted_request_ = virgin_request_;
1320 adapted_reply_ = dynamic_cast<HttpReply*>(adapted.header);
3ff65596
AR
1321 }
1322
a2958f2f 1323 Adaptation::Icap::History::Pointer h = virgin_request_->icapHistory();
aee3523a 1324 Must(h != nullptr); // ICAPXaction::maybeLog calls only if there is a log
e1381638
AJ
1325 al.icp.opcode = ICP_INVALID;
1326 al.url = h->log_uri.termedBuf();
1327 const Adaptation::Icap::ServiceRep &s = service();
1328 al.icap.reqMethod = s.cfg().method;
3ff65596 1329
bd59d61c 1330 al.cache.caddr = virgin_request_->client_addr;
3ff65596 1331
bd59d61c 1332 al.request = virgin_request_;
b248c2a3 1333 HTTPMSGLOCK(al.request);
3ecb654f
CT
1334 al.adapted_request = adapted_request_;
1335 HTTPMSGLOCK(al.adapted_request);
1336
49f57088
EB
1337 // XXX: This reply (and other ALE members!) may have been needed earlier.
1338 al.reply = adapted_reply_;
3ff65596 1339
cb4f4424 1340#if USE_OPENSSL
e1381638
AJ
1341 if (h->ssluser.size())
1342 al.cache.ssluser = h->ssluser.termedBuf();
3ff65596 1343#endif
e1381638 1344 al.cache.code = h->logType;
bd59d61c 1345
63df1d28 1346 const Http::Message *virgin_msg = dynamic_cast<HttpReply*>(virgin.header);
bd59d61c
EB
1347 if (!virgin_msg)
1348 virgin_msg = virgin_request_;
1349 assert(virgin_msg != virgin.cause);
1350 al.http.clientRequestSz.header = virgin_msg->hdr_sz;
aee3523a 1351 if (virgin_msg->body_pipe != nullptr)
7171d5fb 1352 al.http.clientRequestSz.payloadData = virgin_msg->body_pipe->producedSize();
bae917ac
CT
1353
1354 // leave al.icap.bodyBytesRead negative if no body
1355 if (replyHttpHeaderSize >= 0 || replyHttpBodySize >= 0) {
1356 const int64_t zero = 0; // to make max() argument types the same
bd59d61c
EB
1357 const uint64_t headerSize = max(zero, replyHttpHeaderSize);
1358 const uint64_t bodySize = max(zero, replyHttpBodySize);
1359 al.icap.bodyBytesRead = headerSize + bodySize;
1360 al.http.clientReplySz.header = headerSize;
1361 al.http.clientReplySz.payloadData = bodySize;
bae917ac
CT
1362 }
1363
bd59d61c
EB
1364 if (adapted_reply_) {
1365 al.http.code = adapted_reply_->sline.status();
1366 al.http.content_type = adapted_reply_->content_type.termedBuf();
1367 if (replyHttpBodySize >= 0)
bae917ac 1368 al.cache.highOffset = replyHttpBodySize;
e1381638 1369 //don't set al.cache.objectSize because it hasn't exist yet
e1381638 1370 }
3ecb654f 1371 prepareLogWithRequestDetails(adapted_request_, alep);
e1381638 1372 Xaction::finalizeLogInfo();
3ff65596
AR
1373}
1374
26cc52cb 1375void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf &buf)
774c051c 1376{
cc192b50 1377 char ntoabuf[MAX_IPSTRLEN];
12b91c99 1378 /*
1379 * XXX These should use HttpHdr interfaces instead of Printfs
1380 */
0bef8dd7 1381 const Adaptation::ServiceConfig &s = service().cfg();
4391cd15
AJ
1382 buf.appendf("%s " SQUIDSTRINGPH " ICAP/1.0\r\n", s.methodStr(), SQUIDSTRINGPRINT(s.uri));
1383 buf.appendf("Host: " SQUIDSTRINGPH ":%d\r\n", SQUIDSTRINGPRINT(s.host), s.port);
98cacedb 1384 buf.appendf("Date: %s\r\n", Time::FormatRfc1123(squid_curtime));
12b91c99 1385
26cc52cb 1386 if (!TheConfig.reuse_connections)
4391cd15 1387 buf.appendf("Connection: close\r\n");
12b91c99 1388
cb72cd25
CT
1389 const HttpRequest *request = &virginRequest();
1390
2cdeea82 1391 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1392 // as ICAP headers.
789217a2 1393 if (virgin.header->header.has(Http::HdrType::PROXY_AUTHENTICATE)) {
81ab22b6 1394 String vh=virgin.header->header.getById(Http::HdrType::PROXY_AUTHENTICATE);
4391cd15 1395 buf.appendf("Proxy-Authenticate: " SQUIDSTRINGPH "\r\n",SQUIDSTRINGPRINT(vh));
4232c626 1396 }
9e008dda 1397
789217a2 1398 if (virgin.header->header.has(Http::HdrType::PROXY_AUTHORIZATION)) {
81ab22b6 1399 String vh=virgin.header->header.getById(Http::HdrType::PROXY_AUTHORIZATION);
4391cd15 1400 buf.appendf("Proxy-Authorization: " SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(vh));
b38b26cb 1401 } else if (request->extacl_user.size() > 0 && request->extacl_passwd.size() > 0) {
aadbbd7d
AJ
1402 struct base64_encode_ctx ctx;
1403 base64_encode_init(&ctx);
1d11e9b3 1404 char base64buf[base64_encode_len(MAX_LOGIN_SZ)];
aadbbd7d
AJ
1405 size_t resultLen = base64_encode_update(&ctx, base64buf, request->extacl_user.size(), reinterpret_cast<const uint8_t*>(request->extacl_user.rawBuf()));
1406 resultLen += base64_encode_update(&ctx, base64buf+resultLen, 1, reinterpret_cast<const uint8_t*>(":"));
1407 resultLen += base64_encode_update(&ctx, base64buf+resultLen, request->extacl_passwd.size(), reinterpret_cast<const uint8_t*>(request->extacl_passwd.rawBuf()));
1408 resultLen += base64_encode_final(&ctx, base64buf+resultLen);
4391cd15 1409 buf.appendf("Proxy-Authorization: Basic %.*s\r\n", (int)resultLen, base64buf);
4232c626 1410 }
2cdeea82 1411
3ff65596
AR
1412 // share the cross-transactional database records if needed
1413 if (Adaptation::Config::masterx_shared_name) {
ba8a478d 1414 Adaptation::History::Pointer ah = request->adaptHistory(false);
aee3523a 1415 if (ah != nullptr) {
3ff65596
AR
1416 String name, value;
1417 if (ah->getXxRecord(name, value)) {
4391cd15 1418 buf.appendf(SQUIDSTRINGPH ": " SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(name), SQUIDSTRINGPRINT(value));
3ff65596
AR
1419 }
1420 }
1421 }
e1381638 1422
4391cd15 1423 buf.append("Encapsulated: ", 14);
774c051c 1424
1425 MemBuf httpBuf;
12b91c99 1426
774c051c 1427 httpBuf.init();
1428
1429 // build HTTP request header, if any
1430 ICAP::Method m = s.method;
1431
5f8252d2 1432 // to simplify, we could assume that request is always available
c99de607 1433
c99de607 1434 if (request) {
c99de607 1435 if (ICAP::methodRespmod == m)
1436 encapsulateHead(buf, "req-hdr", httpBuf, request);
e1381638
AJ
1437 else if (ICAP::methodReqmod == m)
1438 encapsulateHead(buf, "req-hdr", httpBuf, virgin.header);
c99de607 1439 }
774c051c 1440
1441 if (ICAP::methodRespmod == m)
63df1d28 1442 if (const Http::Message *prime = virgin.header)
774c051c 1443 encapsulateHead(buf, "res-hdr", httpBuf, prime);
1444
1445 if (!virginBody.expected())
4391cd15 1446 buf.appendf("null-body=%d", (int) httpBuf.contentSize());
774c051c 1447 else if (ICAP::methodReqmod == m)
4391cd15 1448 buf.appendf("req-body=%d", (int) httpBuf.contentSize());
774c051c 1449 else
4391cd15 1450 buf.appendf("res-body=%d", (int) httpBuf.contentSize());
774c051c 1451
1452 buf.append(ICAP::crlf, 2); // terminate Encapsulated line
1453
c824c43b 1454 if (preview.enabled()) {
4391cd15 1455 buf.appendf("Preview: %d\r\n", (int)preview.ad());
83c51da9 1456 if (!virginBody.expected()) // there is no body to preview
5f8252d2 1457 finishNullOrEmptyBodyPreview(httpBuf);
774c051c 1458 }
1459
83c51da9 1460 makeAllowHeader(buf);
774c051c 1461
a9044668 1462 if (TheConfig.send_client_ip && request) {
b7ac5457 1463 Ip::Address client_addr;
57d76dd4 1464#if FOLLOW_X_FORWARDED_FOR
22fff3bf 1465 if (TheConfig.use_indirect_client) {
a9044668
A
1466 client_addr = request->indirect_client_addr;
1467 } else
57d76dd4 1468#endif
a9044668 1469 client_addr = request->client_addr;
4dd643d5 1470 if (!client_addr.isAnyAddr() && !client_addr.isNoAddr())
4391cd15 1471 buf.appendf("X-Client-IP: %s\r\n", client_addr.toStr(ntoabuf,MAX_IPSTRLEN));
57d76dd4 1472 }
a97e82a8 1473
22fff3bf 1474 if (TheConfig.send_username && request)
5f8252d2 1475 makeUsernameHeader(request, buf);
a97e82a8 1476
71be37e0 1477 // Adaptation::Config::metaHeaders
984577ac 1478 for (const auto &h: Adaptation::Config::metaHeaders()) {
71be37e0 1479 HttpRequest *r = virgin.cause ?
71ee0835 1480 virgin.cause : dynamic_cast<HttpRequest*>(virgin.header);
71be37e0
CT
1481 Must(r);
1482
1483 HttpReply *reply = dynamic_cast<HttpReply*>(virgin.header);
1484
75d47340
CT
1485 SBuf matched;
1486 if (h->match(r, reply, alMaster, matched)) {
1487 buf.append(h->key().rawContent(), h->key().length());
1488 buf.append(": ", 2);
1489 buf.append(matched.rawContent(), matched.length());
1490 buf.append("\r\n", 2);
d7f4a0b7 1491 Adaptation::History::Pointer ah = request->adaptHistory(false);
aee3523a
AR
1492 if (ah != nullptr) {
1493 if (ah->metaHeaders == nullptr)
cf9f0261 1494 ah->metaHeaders = new NotePairs;
75d47340
CT
1495 if (!ah->metaHeaders->hasPair(h->key(), matched))
1496 ah->metaHeaders->add(h->key(), matched);
cf9f0261 1497 }
d7f4a0b7 1498 }
71be37e0
CT
1499 }
1500
bb790702 1501 // fprintf(stderr, "%s\n", buf.content());
a97e82a8 1502
774c051c 1503 buf.append(ICAP::crlf, 2); // terminate ICAP header
1504
a22e6cd3
AR
1505 // fill icapRequest for logging
1506 Must(icapRequest->parseCharBuf(buf.content(), buf.contentSize()));
1507
774c051c 1508 // start ICAP request body with encapsulated HTTP headers
1509 buf.append(httpBuf.content(), httpBuf.contentSize());
1510
1511 httpBuf.clean();
1512}
1513
83c51da9
CT
1514// decides which Allow values to write and updates the request buffer
1515void Adaptation::Icap::ModXact::makeAllowHeader(MemBuf &buf)
1516{
1517 const bool allow204in = preview.enabled(); // TODO: add shouldAllow204in()
1518 const bool allow204out = state.allowedPostview204 = shouldAllow204();
1519 const bool allow206in = state.allowedPreview206 = shouldAllow206in();
1520 const bool allow206out = state.allowedPostview206 = shouldAllow206out();
69c698a3 1521 const bool allowTrailers = true; // TODO: make configurable
83c51da9 1522
6fbd6ef2 1523 debugs(93, 9, "Allows: " << allow204in << allow204out <<
69c698a3 1524 allow206in << allow206out << allowTrailers);
83c51da9
CT
1525
1526 const bool allow204 = allow204in || allow204out;
1527 const bool allow206 = allow206in || allow206out;
1528
64df2bff
EB
1529 if ((allow204 || allow206) && virginBody.expected())
1530 virginBodySending.plan(); // if there is a virgin body, plan to send it
83c51da9
CT
1531
1532 // writing Preview:... means we will honor 204 inside preview
1533 // writing Allow/204 means we will honor 204 outside preview
1534 // writing Allow:206 means we will honor 206 inside preview
1535 // writing Allow:204,206 means we will honor 206 outside preview
69c698a3
EB
1536 if (allow204 || allow206 || allowTrailers) {
1537 buf.appendf("Allow: ");
1538 if (allow204out)
1539 buf.appendf("204, ");
1540 if (allow206)
1541 buf.appendf("206, ");
1542 if (allowTrailers)
1543 buf.appendf("trailers");
1544 buf.appendf("\r\n");
83c51da9
CT
1545 }
1546}
1547
26cc52cb 1548void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest *request, MemBuf &buf)
9e008dda 1549{
74f6c040 1550#if USE_AUTH
aadbbd7d
AJ
1551 struct base64_encode_ctx ctx;
1552 base64_encode_init(&ctx);
1553
aee3523a
AR
1554 const char *value = nullptr;
1555 if (request->auth_user_request != nullptr) {
aadbbd7d 1556 value = request->auth_user_request->username();
b38b26cb 1557 } else if (request->extacl_user.size() > 0) {
aadbbd7d
AJ
1558 value = request->extacl_user.termedBuf();
1559 }
1560
1561 if (value) {
1562 if (TheConfig.client_username_encode) {
1d11e9b3 1563 char base64buf[base64_encode_len(MAX_LOGIN_SZ)];
aadbbd7d
AJ
1564 size_t resultLen = base64_encode_update(&ctx, base64buf, strlen(value), reinterpret_cast<const uint8_t*>(value));
1565 resultLen += base64_encode_final(&ctx, base64buf+resultLen);
4391cd15 1566 buf.appendf("%s: %.*s\r\n", TheConfig.client_username_header, (int)resultLen, base64buf);
aadbbd7d 1567 } else
4391cd15 1568 buf.appendf("%s: %s\r\n", TheConfig.client_username_header, value);
5f8252d2 1569 }
8b082ed9
FC
1570#else
1571 (void)request;
1572 (void)buf;
74f6c040 1573#endif
5f8252d2 1574}
1575
63df1d28
AJ
1576void
1577Adaptation::Icap::ModXact::encapsulateHead(MemBuf &icapBuf, const char *section, MemBuf &httpBuf, const Http::Message *head)
774c051c 1578{
1579 // update ICAP header
4391cd15 1580 icapBuf.appendf("%s=%d, ", section, (int) httpBuf.contentSize());
774c051c 1581
2cdeea82 1582 // begin cloning
63df1d28 1583 Http::MessagePointer headClone;
9e008dda 1584
2cdeea82 1585 if (const HttpRequest* old_request = dynamic_cast<const HttpRequest*>(head)) {
5ceaee75 1586 HttpRequest::Pointer new_request(new HttpRequest(old_request->masterXaction));
63df1d28 1587 // copy the request-line details
851feda6
AJ
1588 new_request->method = old_request->method;
1589 new_request->url = old_request->url;
2cdeea82 1590 new_request->http_ver = old_request->http_ver;
b248c2a3 1591 headClone = new_request.getRaw();
9e008dda 1592 } else if (const HttpReply *old_reply = dynamic_cast<const HttpReply*>(head)) {
c7d51c86 1593 HttpReply::Pointer new_reply(new HttpReply);
2cdeea82 1594 new_reply->sline = old_reply->sline;
b248c2a3 1595 headClone = new_reply.getRaw();
2cdeea82 1596 }
02dd0839 1597 Must(headClone);
d67acb4e 1598 headClone->inheritProperties(head);
9e008dda 1599
2cdeea82 1600 HttpHeaderPos pos = HttpHeaderInitPos;
02dd0839 1601 while (HttpHeaderEntry* p_head_entry = head->header.getEntry(&pos))
2cdeea82 1602 headClone->header.addEntry(p_head_entry->clone());
1603
1604 // end cloning
9e008dda 1605
2cdeea82 1606 // remove all hop-by-hop headers from the clone
789217a2 1607 headClone->header.delById(Http::HdrType::PROXY_AUTHENTICATE);
2cdeea82 1608 headClone->header.removeHopByHopEntries();
1609
1c2b4465
CT
1610 // TODO: modify HttpHeader::removeHopByHopEntries to accept a list of
1611 // excluded hop-by-hop headers
1612 if (head->header.has(Http::HdrType::UPGRADE)) {
1613 const auto upgrade = head->header.getList(Http::HdrType::UPGRADE);
1614 headClone->header.putStr(Http::HdrType::UPGRADE, upgrade.termedBuf());
1615 }
1616
2cdeea82 1617 // pack polished HTTP header
b248c2a3 1618 packHead(httpBuf, headClone.getRaw());
2cdeea82 1619
c7d51c86 1620 // headClone unlocks and, hence, deletes the message we packed
774c051c 1621}
1622
63df1d28
AJ
1623void
1624Adaptation::Icap::ModXact::packHead(MemBuf &httpBuf, const Http::Message *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) {
bf95c10a 1633 debugs(93, 5, "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
bf95c10a 1654 debugs(93, 5, "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
aee3523a 1748 if (virgin.body_pipe != nullptr)
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{
36c774f7
EB
1808 return !icapReply->header.getByNameListMember("Encapsulated",
1809 section, ',').isEmpty();
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
63df1d28 1819 Http::Message *msg = virgin.header;
5f8252d2 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) {
bf95c10a 1835 debugs(93, 6, "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
aee3523a 1842 Must(msg->body_pipe != nullptr);
5f8252d2 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 {
bf95c10a 1849 debugs(93, 6, "does not expect virgin body");
aee3523a 1850 Must(msg->body_pipe == nullptr);
5f8252d2 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;
bf95c10a 1861 debugs(93, 7, "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{
aee3523a 1980 if (virgin.header == nullptr)
3cfc19b3 1981 return false;
1982
5f8252d2 1983 virgin.header->firstLineBuf(mb);
3cfc19b3 1984
1985 return true;
1986}
c824c43b 1987
83b053a0 1988void Adaptation::Icap::ModXact::detailError(const ErrorDetail::Pointer &errDetail)
64b66b76 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);
63df1d28 2014 adapted.header->sources |= (service().cfg().connectionEncryption ? Http::Message::srcIcaps : Http::Message::srcIcap);
88df846b
CT
2015}
2016
26cc52cb 2017/* Adaptation::Icap::ModXactLauncher */
c824c43b 2018
63df1d28 2019Adaptation::Icap::ModXactLauncher::ModXactLauncher(Http::Message *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());
aee3523a 2033 Must(s != nullptr);
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{
bf95c10a 2039 debugs(93, 5, "swan sings");
3ff65596
AR
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();
aee3523a 2052 if (h != nullptr) {
b0365bd9 2053 if (doStart)
e1381638
AJ
2054 h->start("ICAPModXactLauncher");
2055 else
2056 h->stop("ICAPModXactLauncher");
2057 }
2058 }
3ff65596 2059}
f53969cc 2060
69c698a3 2061bool Adaptation::Icap::TrailerParser::parse(const char *buf, int len, int atEnd, Http::StatusCode *error) {
4f1c93a7
EB
2062 Http::ContentLengthInterpreter clen;
2063 // RFC 7230 section 4.1.2: MUST NOT generate a trailer that contains
2064 // a field necessary for message framing (e.g., Transfer-Encoding and Content-Length)
2065 clen.applyTrailerRules();
2066 const int parsed = trailer.parse(buf, len, atEnd, hdr_sz, clen);
69c698a3
EB
2067 if (parsed < 0)
2068 *error = Http::scInvalidHeader; // TODO: should we add a new Http::scInvalidTrailer?
2069 return parsed > 0;
2070}
2071
417da400
EB
2072void
2073Adaptation::Icap::ChunkExtensionValueParser::parse(Tokenizer &tok, const SBuf &extName)
2074{
2075 if (extName == UseOriginalBodyName) {
2076 useOriginalBody_ = tok.udec64("use-original-body");
2077 assert(useOriginalBody_ >= 0);
2078 } else {
2079 Ignore(tok, extName);
2080 }
2081}
2082