]> git.ipfire.org Git - thirdparty/squid.git/blame - src/adaptation/icap/ModXact.cc
Make BodyPipe::MaxCapacity constexpr (#1748)
[thirdparty/squid.git] / src / adaptation / icap / ModXact.cc
CommitLineData
774c051c 1/*
b8ae064d 2 * Copyright (C) 1996-2023 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
438 // Why > 2? HttpState does not use the last bytes in the buffer
a928fdfd 439 // because Client::delayRead() 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?
bf95c10a 446 debugs(93, 8, "postponing consumption from " << bp.status());
478cfe99 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
bf95c10a 454 debugs(93, 9, "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)) {
bf95c10a 468 debugs(93, 8, "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
aee3523a 491 if (writer != nullptr) {
c99de607 492 if (nicely) {
bf95c10a 493 debugs(93, 7, "will wait for the last write" << status());
c99de607 494 state.writing = State::writingAlmostDone; // may already be set
5f8252d2 495 checkConsuming();
c99de607 496 return;
497 }
bf95c10a 498 debugs(93, 3, "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
bf95c10a 509 debugs(93, 7, "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
bf95c10a 523 debugs(93, 7, "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{
aee3523a 548 if (reader != nullptr || doneReading()) {
bf95c10a 549 debugs(93,3, "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
aee3523a 554 if (adapted.body_pipe != nullptr &&
9e008dda 555 !adapted.body_pipe->buf().hasPotentialSpace()) {
bf95c10a 556 debugs(93,3, "not reading because ICAP reply pipe is full");
774c051c 557 return;
3b299123 558 }
774c051c 559
2b42f3fd 560 if (readBuf.length() < SQUID_TCP_SO_RCVBUF)
774c051c 561 scheduleRead();
3b299123 562 else
bf95c10a 563 debugs(93,3, "cannot read with a full buffer");
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);
aee3523a 578 Must(adapted.body_pipe != nullptr);
5f8252d2 579 Must(virginBodySending.active());
580
581 const size_t sizeMax = virginContentSize(virginBodySending);
bf95c10a 582 debugs(93,5, "will echo up to " << sizeMax << " bytes from " <<
9e008dda 583 virgin.body_pipe->status());
bf95c10a 584 debugs(93,5, "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);
bf95c10a 589 debugs(93,5, "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)) {
bf95c10a 598 debugs(93, 5, "echoed all" << status());
774c051c 599 stopSending(true);
600 } else {
bf95c10a 601 debugs(93, 5, "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{
bf95c10a 616 debugs(93, 7, "Enter stop sending ");
774c051c 617 if (doneSending())
618 return;
bf95c10a 619 debugs(93, 7, "Proceed with stop sending ");
774c051c 620
621 if (state.sending != State::sendingUndecided) {
bf95c10a 622 debugs(93, 7, "will no longer send" << status());
aee3523a 623 if (adapted.body_pipe != nullptr) {
5f8252d2 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 {
bf95c10a 631 debugs(93, 7, "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
bf95c10a 646 debugs(93, 7, "will stop consuming" << status());
5f8252d2 647 stopConsumingFrom(virgin.body_pipe);
774c051c 648}
649
26cc52cb 650void Adaptation::Icap::ModXact::parseMore()
774c051c 651{
84ae6223
AJ
652 debugs(93, 5, "have " << readBuf.length() << " bytes to parse" << status());
653 debugs(93, 5, "\n" << readBuf);
774c051c 654
655 if (state.parsingHeaders())
656 parseHeaders();
657
658 if (state.parsing == State::psBody)
659 parseBody();
69c698a3
EB
660
661 if (state.parsing == State::psIcapTrailer)
662 parseIcapTrailer();
774c051c 663}
664
26cc52cb 665void Adaptation::Icap::ModXact::callException(const std::exception &e)
478cfe99 666{
667 if (!canStartBypass || isRetriable) {
64b66b76
CT
668 if (!isRetriable) {
669 if (const TextException *te = dynamic_cast<const TextException *>(&e))
83b053a0 670 detailError(new ExceptionErrorDetail(te->id()));
64b66b76 671 else
83b053a0 672 detailError(new ExceptionErrorDetail(Here().id()));
64b66b76 673 }
26cc52cb 674 Adaptation::Icap::Xaction::callException(e);
478cfe99 675 return;
676 }
677
678 try {
bf95c10a 679 debugs(93, 3, "bypassing " << inCall << " exception: " <<
af6a12ee 680 e.what() << ' ' << status());
478cfe99 681 bypassFailure();
64b66b76 682 } catch (const TextException &bypassTe) {
83b053a0 683 detailError(new ExceptionErrorDetail(bypassTe.id()));
64b66b76 684 Adaptation::Icap::Xaction::callException(bypassTe);
9e008dda 685 } catch (const std::exception &bypassE) {
83b053a0 686 detailError(new ExceptionErrorDetail(Here().id()));
26cc52cb 687 Adaptation::Icap::Xaction::callException(bypassE);
478cfe99 688 }
689}
690
26cc52cb 691void Adaptation::Icap::ModXact::bypassFailure()
478cfe99 692{
a22e6cd3 693 disableBypass("already started to bypass", false);
478cfe99 694
695 Must(!isRetriable); // or we should not be bypassing
3ff65596 696 // TODO: should the same be enforced for isRepeatable? Check icap_repeat??
478cfe99 697
698 prepEchoing();
699
700 startSending();
701
702 // end all activities associated with the ICAP server
703
69c698a3 704 stopParsing(false);
478cfe99 705
706 stopWriting(true); // or should we force it?
aed188fd 707 if (haveConnection()) {
478cfe99 708 reuseConnection = false; // be conservative
709 cancelRead(); // may not work; and we cannot stop connecting either
710 if (!doneWithIo())
bf95c10a 711 debugs(93, 7, "Warning: bypass failed to stop I/O" << status());
478cfe99 712 }
61cb3565
AR
713
714 service().noteFailure(); // we are bypassing, but this is still a failure
478cfe99 715}
716
a22e6cd3 717void Adaptation::Icap::ModXact::disableBypass(const char *reason, bool includingGroupBypass)
478cfe99 718{
719 if (canStartBypass) {
bf95c10a 720 debugs(93,7, "will never start bypass because " << reason);
478cfe99 721 canStartBypass = false;
722 }
a22e6cd3 723 if (protectGroupBypass && includingGroupBypass) {
bf95c10a 724 debugs(93,7, "not protecting group bypass because " << reason);
a22e6cd3
AR
725 protectGroupBypass = false;
726 }
478cfe99 727}
728
774c051c 729// note that allocation for echoing is done in handle204NoContent()
26cc52cb 730void Adaptation::Icap::ModXact::maybeAllocateHttpMsg()
774c051c 731{
5f8252d2 732 if (adapted.header) // already allocated
774c051c 733 return;
734
735 if (gotEncapsulated("res-hdr")) {
5f8252d2 736 adapted.setHeader(new HttpReply);
3ff65596 737 setOutcome(service().cfg().method == ICAP::methodReqmod ?
e1381638 738 xoSatisfied : xoModified);
774c051c 739 } else if (gotEncapsulated("req-hdr")) {
5ceaee75 740 adapted.setHeader(new HttpRequest(virginRequest().masterXaction));
3ff65596 741 setOutcome(xoModified);
774c051c 742 } else
743 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
744}
745
26cc52cb 746void Adaptation::Icap::ModXact::parseHeaders()
774c051c 747{
748 Must(state.parsingHeaders());
749
b107a5a5 750 if (state.parsing == State::psIcapHeader) {
bf95c10a 751 debugs(93, 5, "parse ICAP headers");
774c051c 752 parseIcapHead();
b107a5a5 753 }
774c051c 754
b107a5a5 755 if (state.parsing == State::psHttpHeader) {
bf95c10a 756 debugs(93, 5, "parse HTTP headers");
774c051c 757 parseHttpHead();
b107a5a5 758 }
774c051c 759
760 if (state.parsingHeaders()) { // need more data
761 Must(mayReadMore());
762 return;
763 }
764
478cfe99 765 startSending();
766}
767
768// called after parsing all headers or when bypassing an exception
26cc52cb 769void Adaptation::Icap::ModXact::startSending()
478cfe99 770{
3ff65596 771 disableRepeats("sent headers");
a22e6cd3 772 disableBypass("sent headers", true);
3af10ac0 773 sendAnswer(Answer::Forward(adapted.header));
774c051c 774
775 if (state.sending == State::sendingVirgin)
776 echoMore();
88df846b 777 else {
ff89bfa0 778 // If we are not using the virgin HTTP object update the
63df1d28 779 // Http::Message::sources flag.
88df846b 780 // The state.sending may set to State::sendingVirgin in the case
63df1d28 781 // of 206 responses too, where we do not want to update Http::Message::sources
ff89bfa0
SM
782 // flag. However even for 206 responses the state.sending is
783 // not set yet to sendingVirgin. This is done in later step
88df846b
CT
784 // after the parseBody method called.
785 updateSources();
786 }
774c051c 787}
788
26cc52cb 789void Adaptation::Icap::ModXact::parseIcapHead()
774c051c 790{
791 Must(state.sending == State::sendingUndecided);
792
b248c2a3 793 if (!parseHead(icapReply.getRaw()))
774c051c 794 return;
795
69c698a3
EB
796 if (expectIcapTrailers()) {
797 Must(!trailerParser);
798 trailerParser = new TrailerParser;
799 }
800
d5f18517
AJ
801 static SBuf close("close", 5);
802 if (httpHeaderHasConnDir(&icapReply->header, close)) {
bf95c10a 803 debugs(93, 5, "found connection close");
fc764d26 804 reuseConnection = false;
805 }
806
9b769c67 807 switch (icapReply->sline.status()) {
774c051c 808
9b769c67 809 case Http::scContinue:
774c051c 810 handle100Continue();
811 break;
812
9b769c67
AJ
813 case Http::scOkay:
814 case Http::scCreated: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
b559db5d 815
816 if (!validate200Ok()) {
817 throw TexcHere("Invalid ICAP Response");
818 } else {
819 handle200Ok();
820 }
821
774c051c 822 break;
823
9b769c67 824 case Http::scNoContent:
774c051c 825 handle204NoContent();
826 break;
827
9b769c67 828 case Http::scPartialContent:
83c51da9
CT
829 handle206PartialContent();
830 break;
831
774c051c 832 default:
9b769c67 833 debugs(93, 5, "ICAP status " << icapReply->sline.status());
774c051c 834 handleUnknownScode();
835 break;
836 }
837
3ff65596
AR
838 const HttpRequest *request = dynamic_cast<HttpRequest*>(adapted.header);
839 if (!request)
840 request = &virginRequest();
841
842 // update the cross-transactional database if needed (all status codes!)
843 if (const char *xxName = Adaptation::Config::masterx_shared_name) {
a22e6cd3 844 Adaptation::History::Pointer ah = request->adaptHistory(true);
aee3523a 845 if (ah != nullptr) { // TODO: reorder checks to avoid creating history
3ff65596
AR
846 const String val = icapReply->header.getByName(xxName);
847 if (val.size() > 0) // XXX: HttpHeader lacks empty value detection
848 ah->updateXxRecord(xxName, val);
849 }
850 }
851
a22e6cd3
AR
852 // update the adaptation plan if needed (all status codes!)
853 if (service().cfg().routing) {
854 String services;
789217a2 855 if (icapReply->header.getList(Http::HdrType::X_NEXT_SERVICES, &services)) {
a22e6cd3 856 Adaptation::History::Pointer ah = request->adaptHistory(true);
aee3523a 857 if (ah != nullptr)
a22e6cd3
AR
858 ah->updateNextServices(services);
859 }
789217a2 860 } // TODO: else warn (occasionally!) if we got Http::HdrType::X_NEXT_SERVICES
a22e6cd3 861
3ff65596
AR
862 // We need to store received ICAP headers for <icapLastHeader logformat option.
863 // If we already have stored headers from previous ICAP transaction related to this
864 // request, old headers will be replaced with the new one.
e1381638 865
5038f9d8 866 Adaptation::History::Pointer ah = request->adaptLogHistory();
aee3523a 867 if (ah != nullptr)
5038f9d8 868 ah->recordMeta(&icapReply->header);
3ff65596 869
774c051c 870 // handle100Continue() manages state.writing on its own.
871 // Non-100 status means the server needs no postPreview data from us.
872 if (state.writing == State::writingPaused)
c99de607 873 stopWriting(true);
774c051c 874}
875
69c698a3
EB
876/// Parses ICAP trailers and stops parsing, if all trailer data
877/// have been received.
878void Adaptation::Icap::ModXact::parseIcapTrailer() {
b559db5d 879
69c698a3
EB
880 if (parsePart(trailerParser, "trailer")) {
881 for (const auto &e: trailerParser->trailer.entries)
882 debugs(93, 5, "ICAP trailer: " << e->name << ": " << e->value);
883 stopParsing();
b559db5d 884 }
69c698a3 885}
b559db5d 886
69c698a3
EB
887bool Adaptation::Icap::ModXact::validate200Ok()
888{
889 if (service().cfg().method == ICAP::methodRespmod)
890 return gotEncapsulated("res-hdr");
b559db5d 891
69c698a3
EB
892 return service().cfg().method == ICAP::methodReqmod &&
893 expectHttpHeader();
b559db5d 894}
895
26cc52cb 896void Adaptation::Icap::ModXact::handle100Continue()
774c051c 897{
898 Must(state.writing == State::writingPaused);
5f8252d2 899 // server must not respond before the end of preview: we may send ieof
774c051c 900 Must(preview.enabled() && preview.done() && !preview.ieof());
774c051c 901
83c51da9
CT
902 // 100 "Continue" cancels our Preview commitment,
903 // but not commitment to handle 204 or 206 outside Preview
904 if (!state.allowedPostview204 && !state.allowedPostview206)
774c051c 905 stopBackup();
906
c99de607 907 state.parsing = State::psIcapHeader; // eventually
908 icapReply->reset();
774c051c 909
910 state.writing = State::writingPrime;
911
912 writeMore();
913}
914
26cc52cb 915void Adaptation::Icap::ModXact::handle200Ok()
774c051c 916{
917 state.parsing = State::psHttpHeader;
918 state.sending = State::sendingAdapted;
919 stopBackup();
5f8252d2 920 checkConsuming();
774c051c 921}
922
26cc52cb 923void Adaptation::Icap::ModXact::handle204NoContent()
774c051c 924{
925 stopParsing();
478cfe99 926 prepEchoing();
927}
928
83c51da9
CT
929void Adaptation::Icap::ModXact::handle206PartialContent()
930{
931 if (state.writing == State::writingPaused) {
932 Must(preview.enabled());
933 Must(state.allowedPreview206);
bf95c10a 934 debugs(93, 7, "206 inside preview");
83c51da9
CT
935 } else {
936 Must(state.writing > State::writingPaused);
937 Must(state.allowedPostview206);
bf95c10a 938 debugs(93, 7, "206 outside preview");
83c51da9
CT
939 }
940 state.parsing = State::psHttpHeader;
941 state.sending = State::sendingAdapted;
942 state.readyForUob = true;
943 checkConsuming();
944}
945
478cfe99 946// Called when we receive a 204 No Content response and
947// when we are trying to bypass a service failure.
948// We actually start sending (echoig or not) in startSending.
26cc52cb 949void Adaptation::Icap::ModXact::prepEchoing()
478cfe99 950{
3ff65596 951 disableRepeats("preparing to echo content");
a22e6cd3 952 disableBypass("preparing to echo content", true);
3ff65596 953 setOutcome(xoEcho);
774c051c 954
955 // We want to clone the HTTP message, but we do not want
63df1d28 956 // to copy some non-HTTP state parts that Http::Message kids carry in them.
774c051c 957 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
958 // Instead, we simply write the HTTP message and "clone" it by parsing.
63df1d28 959 // TODO: use Http::Message::clone()!
774c051c 960
63df1d28 961 Http::Message *oldHead = virgin.header;
bf95c10a 962 debugs(93, 7, "cloning virgin message " << oldHead);
774c051c 963
964 MemBuf httpBuf;
965
966 // write the virgin message into a memory buffer
967 httpBuf.init();
968 packHead(httpBuf, oldHead);
969
c99de607 970 // allocate the adapted message and copy metainfo
5f8252d2 971 Must(!adapted.header);
c7d51c86 972 {
63df1d28 973 Http::MessagePointer newHead;
5ceaee75
CT
974 if (const HttpRequest *r = dynamic_cast<const HttpRequest*>(oldHead)) {
975 newHead = new HttpRequest(r->masterXaction);
e6f9e263
A
976 } else if (dynamic_cast<const HttpReply*>(oldHead)) {
977 newHead = new HttpReply;
978 }
d39901ed 979 Must(newHead);
774c051c 980
e6f9e263 981 newHead->inheritProperties(oldHead);
774c051c 982
b248c2a3 983 adapted.setHeader(newHead.getRaw());
c7d51c86 984 }
7514268e 985
774c051c 986 // parse the buffer back
955394ce 987 Http::StatusCode error = Http::scNone;
774c051c 988
63df1d28 989 httpBuf.terminate(); // Http::Message::parse requires nil-terminated buffer
84ae6223 990 Must(adapted.header->parse(httpBuf.content(), httpBuf.contentSize(), true, &error));
c7d51c86 991 Must(adapted.header->hdr_sz == httpBuf.contentSize()); // no leftovers
774c051c 992
993 httpBuf.clean();
994
bf95c10a 995 debugs(93, 7, "cloned virgin message " << oldHead << " to " <<
c7d51c86 996 adapted.header);
5f8252d2 997
998 // setup adapted body pipe if needed
aee3523a 999 if (oldHead->body_pipe != nullptr) {
bf95c10a 1000 debugs(93, 7, "will echo virgin body from " <<
9e008dda 1001 oldHead->body_pipe);
478cfe99 1002 if (!virginBodySending.active())
1003 virginBodySending.plan(); // will throw if not possible
5f8252d2 1004 state.sending = State::sendingVirgin;
1005 checkConsuming();
478cfe99 1006
5f8252d2 1007 // TODO: optimize: is it possible to just use the oldHead pipe and
1008 // remove ICAP from the loop? This echoing is probably a common case!
1009 makeAdaptedBodyPipe("echoed virgin response");
1010 if (oldHead->body_pipe->bodySizeKnown())
1011 adapted.body_pipe->setBodySize(oldHead->body_pipe->bodySize());
bf95c10a 1012 debugs(93, 7, "will echo virgin body to " <<
9e008dda 1013 adapted.body_pipe);
5f8252d2 1014 } else {
bf95c10a 1015 debugs(93, 7, "no virgin body to echo");
5f8252d2 1016 stopSending(true);
1017 }
774c051c 1018}
1019
83c51da9
CT
1020/// Called when we received use-original-body chunk extension in 206 response.
1021/// We actually start sending (echoing or not) in startSending().
1022void Adaptation::Icap::ModXact::prepPartialBodyEchoing(uint64_t pos)
1023{
1024 Must(virginBodySending.active());
aee3523a 1025 Must(virgin.header->body_pipe != nullptr);
83c51da9
CT
1026
1027 setOutcome(xoPartEcho);
1028
bf95c10a 1029 debugs(93, 7, "will echo virgin body suffix from " <<
83c51da9
CT
1030 virgin.header->body_pipe << " offset " << pos );
1031
1032 // check that use-original-body=N does not point beyond buffered data
1033 const uint64_t virginDataEnd = virginConsumed +
7ddcfbab 1034 virgin.body_pipe->buf().contentSize();
83c51da9
CT
1035 Must(pos <= virginDataEnd);
1036 virginBodySending.progress(static_cast<size_t>(pos));
1037
1038 state.sending = State::sendingVirgin;
1039 checkConsuming();
1040
1041 if (virgin.header->body_pipe->bodySizeKnown())
1042 adapted.body_pipe->expectProductionEndAfter(virgin.header->body_pipe->bodySize() - pos);
1043
bf95c10a 1044 debugs(93, 7, "will echo virgin body suffix to " <<
83c51da9
CT
1045 adapted.body_pipe);
1046
1047 // Start echoing data
1048 echoMore();
1049}
1050
26cc52cb 1051void Adaptation::Icap::ModXact::handleUnknownScode()
774c051c 1052{
69c698a3 1053 stopParsing(false);
774c051c 1054 stopBackup();
1055 // TODO: mark connection as "bad"
1056
1057 // Terminate the transaction; we do not know how to handle this response.
1058 throw TexcHere("Unsupported ICAP status code");
1059}
1060
26cc52cb 1061void Adaptation::Icap::ModXact::parseHttpHead()
774c051c 1062{
69c698a3 1063 if (expectHttpHeader()) {
bae917ac 1064 replyHttpHeaderSize = 0;
774c051c 1065 maybeAllocateHttpMsg();
1066
5f8252d2 1067 if (!parseHead(adapted.header))
c99de607 1068 return; // need more header data
5f8252d2 1069
bae917ac
CT
1070 if (adapted.header)
1071 replyHttpHeaderSize = adapted.header->hdr_sz;
1072
d67acb4e 1073 if (dynamic_cast<HttpRequest*>(adapted.header)) {
5f8252d2 1074 const HttpRequest *oldR = dynamic_cast<const HttpRequest*>(virgin.header);
1075 Must(oldR);
9e008dda
AJ
1076 // TODO: the adapted request did not really originate from the
1077 // client; give proxy admin an option to prevent copying of
5f8252d2 1078 // sensitive client information here. See the following thread:
1079 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
5f8252d2 1080 }
d67acb4e 1081
9e008dda
AJ
1082 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
1083 if (adapted.header)
1084 adapted.header->inheritProperties(virgin.header);
774c051c 1085 }
1086
5f8252d2 1087 decideOnParsingBody();
774c051c 1088}
1089
69c698a3
EB
1090template<class Part>
1091bool Adaptation::Icap::ModXact::parsePart(Part *part, const char *description)
774c051c 1092{
69c698a3
EB
1093 Must(part);
1094 debugs(93, 5, "have " << readBuf.length() << ' ' << description << " bytes to parse; state: " << state.parsing);
955394ce 1095 Http::StatusCode error = Http::scNone;
84ae6223 1096 // XXX: performance regression. c_str() data copies
63df1d28 1097 // XXX: Http::Message::parse requires a terminated string buffer
84ae6223 1098 const char *tmpBuf = readBuf.c_str();
69c698a3
EB
1099 const bool parsed = part->parse(tmpBuf, readBuf.length(), commEof, &error);
1100 debugs(93, (!parsed && error) ? 2 : 5, description << " parsing result: " << parsed << " detail: " << error);
1101 Must(parsed || !error);
1102 if (parsed)
1103 readBuf.consume(part->hdr_sz);
1104 return parsed;
1105}
774c051c 1106
69c698a3 1107// parses both HTTP and ICAP headers
63df1d28
AJ
1108bool
1109Adaptation::Icap::ModXact::parseHead(Http::Message *head)
69c698a3
EB
1110{
1111 if (!parsePart(head, "head")) {
774c051c 1112 head->reset();
1113 return false;
1114 }
774c051c 1115 return true;
1116}
1117
69c698a3
EB
1118bool Adaptation::Icap::ModXact::expectHttpHeader() const
1119{
1120 return gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr");
1121}
1122
1123bool Adaptation::Icap::ModXact::expectHttpBody() const
1124{
1125 return gotEncapsulated("res-body") || gotEncapsulated("req-body");
1126}
1127
1128bool Adaptation::Icap::ModXact::expectIcapTrailers() const
1129{
1130 String trailers;
f29d429e 1131 const bool promisesToSendTrailer = icapReply->header.getByIdIfPresent(Http::HdrType::TRAILER, &trailers);
69c698a3
EB
1132 const bool supportsTrailers = icapReply->header.hasListMember(Http::HdrType::ALLOW, "trailers", ',');
1133 // ICAP Trailer specs require us to reject transactions having either Trailer
1134 // header or Allow:trailers
1135 Must((promisesToSendTrailer == supportsTrailers) || (!promisesToSendTrailer && supportsTrailers));
1136 if (promisesToSendTrailer && !trailers.size())
1137 debugs(93, DBG_IMPORTANT, "ERROR: ICAP Trailer response header field must not be empty (salvaged)");
1138 return promisesToSendTrailer;
1139}
1140
26cc52cb 1141void Adaptation::Icap::ModXact::decideOnParsingBody()
9e008dda 1142{
69c698a3 1143 if (expectHttpBody()) {
bf95c10a 1144 debugs(93, 5, "expecting a body");
5f8252d2 1145 state.parsing = State::psBody;
bae917ac 1146 replyHttpBodySize = 0;
db1720f8 1147 bodyParser = new Http1::TeChunkedParser;
417da400 1148 bodyParser->parseExtensionValuesWith(&extensionParser);
5f8252d2 1149 makeAdaptedBodyPipe("adapted response from the ICAP server");
1150 Must(state.sending == State::sendingAdapted);
774c051c 1151 } else {
bf95c10a 1152 debugs(93, 5, "not expecting a body");
69c698a3
EB
1153 if (trailerParser)
1154 state.parsing = State::psIcapTrailer;
1155 else
1156 stopParsing();
5f8252d2 1157 stopSending(true);
774c051c 1158 }
774c051c 1159}
1160
26cc52cb 1161void Adaptation::Icap::ModXact::parseBody()
774c051c 1162{
5f8252d2 1163 Must(state.parsing == State::psBody);
1164 Must(bodyParser);
774c051c 1165
84ae6223 1166 debugs(93, 5, "have " << readBuf.length() << " body bytes to parse");
774c051c 1167
5f8252d2 1168 // the parser will throw on errors
1169 BodyPipeCheckout bpc(*adapted.body_pipe);
be29ee33
AJ
1170 bodyParser->setPayloadBuffer(&bpc.buf);
1171 const bool parsed = bodyParser->parse(readBuf);
1172 readBuf = bodyParser->remaining(); // sync buffers after parse
5f8252d2 1173 bpc.checkIn();
774c051c 1174
84ae6223 1175 debugs(93, 5, "have " << readBuf.length() << " body bytes after parsed all: " << parsed);
bae917ac 1176 replyHttpBodySize += adapted.body_pipe->buf().contentSize();
774c051c 1177
478cfe99 1178 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
3ff65596
AR
1179 // TODO: do we really need this if we disable when sending headers?
1180 if (adapted.body_pipe->buf().contentSize() > 0) { // parsed something sometime
1181 disableRepeats("sent adapted content");
a22e6cd3 1182 disableBypass("sent adapted content", true);
3ff65596 1183 }
478cfe99 1184
5f8252d2 1185 if (parsed) {
417da400
EB
1186 if (state.readyForUob && extensionParser.sawUseOriginalBody())
1187 prepPartialBodyEchoing(extensionParser.useOriginalBody());
69c698a3
EB
1188 else
1189 stopSending(true); // the parser succeeds only if all parsed data fits
1190 if (trailerParser)
1191 state.parsing = State::psIcapTrailer;
1192 else
83c51da9 1193 stopParsing();
5f8252d2 1194 return;
1195 }
774c051c 1196
bf95c10a 1197 debugs(93,3, this << " needsMoreData = " << bodyParser->needsMoreData());
3b299123 1198
1199 if (bodyParser->needsMoreData()) {
bf95c10a 1200 debugs(93,3, this);
774c051c 1201 Must(mayReadMore());
3b299123 1202 readMore();
1203 }
774c051c 1204
1205 if (bodyParser->needsMoreSpace()) {
1206 Must(!doneSending()); // can hope for more space
5f8252d2 1207 Must(adapted.body_pipe->buf().contentSize() > 0); // paranoid
1208 // TODO: there should be a timeout in case the sink is broken
1209 // or cannot consume partial content (while we need more space)
774c051c 1210 }
774c051c 1211}
1212
69c698a3 1213void Adaptation::Icap::ModXact::stopParsing(const bool checkUnparsedData)
774c051c 1214{
1215 if (state.parsing == State::psDone)
1216 return;
1217
69c698a3
EB
1218 if (checkUnparsedData)
1219 Must(readBuf.isEmpty());
1220
1221 debugs(93, 7, "will no longer parse" << status());
774c051c 1222
1223 delete bodyParser;
69c698a3 1224 bodyParser = nullptr;
774c051c 1225
69c698a3
EB
1226 delete trailerParser;
1227 trailerParser = nullptr;
774c051c 1228
1229 state.parsing = State::psDone;
1230}
1231
1232// HTTP side added virgin body data
26cc52cb 1233void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer)
774c051c 1234{
774c051c 1235 writeMore();
1236
1237 if (state.sending == State::sendingVirgin)
1238 echoMore();
774c051c 1239}
1240
1241// HTTP side sent us all virgin info
26cc52cb 1242void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer)
774c051c 1243{
5f8252d2 1244 Must(virgin.body_pipe->productionEnded());
774c051c 1245
1246 // push writer and sender in case we were waiting for the last-chunk
1247 writeMore();
1248
1249 if (state.sending == State::sendingVirgin)
1250 echoMore();
774c051c 1251}
1252
9e008dda 1253// body producer aborted, but the initiator may still want to know
585ab260 1254// the answer, even though the HTTP message has been truncated
26cc52cb 1255void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer)
774c051c 1256{
585ab260 1257 Must(virgin.body_pipe->productionEnded());
1258
1259 // push writer and sender in case we were waiting for the last-chunk
1260 writeMore();
1261
1262 if (state.sending == State::sendingVirgin)
1263 echoMore();
5f8252d2 1264}
1265
9e008dda 1266// adapted body consumer wants more adapted data and
5f8252d2 1267// possibly freed some buffer space
26cc52cb 1268void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer)
774c051c 1269{
774c051c 1270 if (state.sending == State::sendingVirgin)
1271 echoMore();
3b299123 1272 else if (state.sending == State::sendingAdapted)
1273 parseMore();
774c051c 1274 else
3b299123 1275 Must(state.sending == State::sendingUndecided);
774c051c 1276}
1277
5f8252d2 1278// adapted body consumer aborted
26cc52cb 1279void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer)
774c051c 1280{
83b053a0
CT
1281 static const auto d = MakeNamedErrorDetail("ICAP_XACT_BODY_CONSUMER_ABORT");
1282 detailError(d);
5f8252d2 1283 mustStop("adapted body consumer aborted");
774c051c 1284}
1285
c7d51c86
AR
1286Adaptation::Icap::ModXact::~ModXact()
1287{
1288 delete bodyParser;
69c698a3 1289 delete trailerParser;
c7d51c86
AR
1290}
1291
774c051c 1292// internal cleanup
26cc52cb 1293void Adaptation::Icap::ModXact::swanSong()
774c051c 1294{
bf95c10a 1295 debugs(93, 5, "swan sings" << status());
5f8252d2 1296
c99de607 1297 stopWriting(false);
c824c43b 1298 stopSending(false);
774c051c 1299
83b053a0
CT
1300 if (theInitiator.set()) { // we have not sent the answer to the initiator
1301 static const auto d = MakeNamedErrorDetail("ICAP_XACT_OTHER");
1302 detailError(d);
1303 }
64b66b76 1304
3ff65596 1305 // update adaptation history if start was called and we reserved a slot
a22e6cd3 1306 Adaptation::History::Pointer ah = virginRequest().adaptLogHistory();
aee3523a 1307 if (ah != nullptr && adaptHistoryId >= 0)
3ff65596 1308 ah->recordXactFinish(adaptHistoryId);
774c051c 1309
26cc52cb 1310 Adaptation::Icap::Xaction::swanSong();
774c051c 1311}
1312
63ed9e8e 1313void prepareLogWithRequestDetails(HttpRequest *, const AccessLogEntryPointer &);
3ff65596
AR
1314
1315void Adaptation::Icap::ModXact::finalizeLogInfo()
1316{
bd59d61c
EB
1317 HttpRequest *adapted_request_ = nullptr;
1318 HttpReply *adapted_reply_ = nullptr;
a2958f2f 1319 HttpRequest *virgin_request_ = const_cast<HttpRequest*>(&virginRequest());
3ecb654f 1320 if (!(adapted_request_ = dynamic_cast<HttpRequest*>(adapted.header))) {
bd59d61c
EB
1321 // if the request was not adapted, use virgin request to simplify
1322 // the code further below
1323 adapted_request_ = virgin_request_;
1324 adapted_reply_ = dynamic_cast<HttpReply*>(adapted.header);
3ff65596
AR
1325 }
1326
a2958f2f 1327 Adaptation::Icap::History::Pointer h = virgin_request_->icapHistory();
aee3523a 1328 Must(h != nullptr); // ICAPXaction::maybeLog calls only if there is a log
e1381638
AJ
1329 al.icp.opcode = ICP_INVALID;
1330 al.url = h->log_uri.termedBuf();
1331 const Adaptation::Icap::ServiceRep &s = service();
1332 al.icap.reqMethod = s.cfg().method;
3ff65596 1333
bd59d61c 1334 al.cache.caddr = virgin_request_->client_addr;
3ff65596 1335
bd59d61c 1336 al.request = virgin_request_;
b248c2a3 1337 HTTPMSGLOCK(al.request);
3ecb654f
CT
1338 al.adapted_request = adapted_request_;
1339 HTTPMSGLOCK(al.adapted_request);
1340
49f57088
EB
1341 // XXX: This reply (and other ALE members!) may have been needed earlier.
1342 al.reply = adapted_reply_;
3ff65596 1343
e1381638
AJ
1344 if (h->rfc931.size())
1345 al.cache.rfc931 = h->rfc931.termedBuf();
3ff65596 1346
cb4f4424 1347#if USE_OPENSSL
e1381638
AJ
1348 if (h->ssluser.size())
1349 al.cache.ssluser = h->ssluser.termedBuf();
3ff65596 1350#endif
e1381638 1351 al.cache.code = h->logType;
bd59d61c 1352
63df1d28 1353 const Http::Message *virgin_msg = dynamic_cast<HttpReply*>(virgin.header);
bd59d61c
EB
1354 if (!virgin_msg)
1355 virgin_msg = virgin_request_;
1356 assert(virgin_msg != virgin.cause);
1357 al.http.clientRequestSz.header = virgin_msg->hdr_sz;
aee3523a 1358 if (virgin_msg->body_pipe != nullptr)
7171d5fb 1359 al.http.clientRequestSz.payloadData = virgin_msg->body_pipe->producedSize();
bae917ac
CT
1360
1361 // leave al.icap.bodyBytesRead negative if no body
1362 if (replyHttpHeaderSize >= 0 || replyHttpBodySize >= 0) {
1363 const int64_t zero = 0; // to make max() argument types the same
bd59d61c
EB
1364 const uint64_t headerSize = max(zero, replyHttpHeaderSize);
1365 const uint64_t bodySize = max(zero, replyHttpBodySize);
1366 al.icap.bodyBytesRead = headerSize + bodySize;
1367 al.http.clientReplySz.header = headerSize;
1368 al.http.clientReplySz.payloadData = bodySize;
bae917ac
CT
1369 }
1370
bd59d61c
EB
1371 if (adapted_reply_) {
1372 al.http.code = adapted_reply_->sline.status();
1373 al.http.content_type = adapted_reply_->content_type.termedBuf();
1374 if (replyHttpBodySize >= 0)
bae917ac 1375 al.cache.highOffset = replyHttpBodySize;
e1381638 1376 //don't set al.cache.objectSize because it hasn't exist yet
e1381638 1377 }
3ecb654f 1378 prepareLogWithRequestDetails(adapted_request_, alep);
e1381638 1379 Xaction::finalizeLogInfo();
3ff65596
AR
1380}
1381
26cc52cb 1382void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf &buf)
774c051c 1383{
cc192b50 1384 char ntoabuf[MAX_IPSTRLEN];
12b91c99 1385 /*
1386 * XXX These should use HttpHdr interfaces instead of Printfs
1387 */
0bef8dd7 1388 const Adaptation::ServiceConfig &s = service().cfg();
4391cd15
AJ
1389 buf.appendf("%s " SQUIDSTRINGPH " ICAP/1.0\r\n", s.methodStr(), SQUIDSTRINGPRINT(s.uri));
1390 buf.appendf("Host: " SQUIDSTRINGPH ":%d\r\n", SQUIDSTRINGPRINT(s.host), s.port);
98cacedb 1391 buf.appendf("Date: %s\r\n", Time::FormatRfc1123(squid_curtime));
12b91c99 1392
26cc52cb 1393 if (!TheConfig.reuse_connections)
4391cd15 1394 buf.appendf("Connection: close\r\n");
12b91c99 1395
cb72cd25
CT
1396 const HttpRequest *request = &virginRequest();
1397
2cdeea82 1398 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1399 // as ICAP headers.
789217a2 1400 if (virgin.header->header.has(Http::HdrType::PROXY_AUTHENTICATE)) {
81ab22b6 1401 String vh=virgin.header->header.getById(Http::HdrType::PROXY_AUTHENTICATE);
4391cd15 1402 buf.appendf("Proxy-Authenticate: " SQUIDSTRINGPH "\r\n",SQUIDSTRINGPRINT(vh));
4232c626 1403 }
9e008dda 1404
789217a2 1405 if (virgin.header->header.has(Http::HdrType::PROXY_AUTHORIZATION)) {
81ab22b6 1406 String vh=virgin.header->header.getById(Http::HdrType::PROXY_AUTHORIZATION);
4391cd15 1407 buf.appendf("Proxy-Authorization: " SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(vh));
b38b26cb 1408 } else if (request->extacl_user.size() > 0 && request->extacl_passwd.size() > 0) {
aadbbd7d
AJ
1409 struct base64_encode_ctx ctx;
1410 base64_encode_init(&ctx);
1d11e9b3 1411 char base64buf[base64_encode_len(MAX_LOGIN_SZ)];
aadbbd7d
AJ
1412 size_t resultLen = base64_encode_update(&ctx, base64buf, request->extacl_user.size(), reinterpret_cast<const uint8_t*>(request->extacl_user.rawBuf()));
1413 resultLen += base64_encode_update(&ctx, base64buf+resultLen, 1, reinterpret_cast<const uint8_t*>(":"));
1414 resultLen += base64_encode_update(&ctx, base64buf+resultLen, request->extacl_passwd.size(), reinterpret_cast<const uint8_t*>(request->extacl_passwd.rawBuf()));
1415 resultLen += base64_encode_final(&ctx, base64buf+resultLen);
4391cd15 1416 buf.appendf("Proxy-Authorization: Basic %.*s\r\n", (int)resultLen, base64buf);
4232c626 1417 }
2cdeea82 1418
3ff65596
AR
1419 // share the cross-transactional database records if needed
1420 if (Adaptation::Config::masterx_shared_name) {
ba8a478d 1421 Adaptation::History::Pointer ah = request->adaptHistory(false);
aee3523a 1422 if (ah != nullptr) {
3ff65596
AR
1423 String name, value;
1424 if (ah->getXxRecord(name, value)) {
4391cd15 1425 buf.appendf(SQUIDSTRINGPH ": " SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(name), SQUIDSTRINGPRINT(value));
3ff65596
AR
1426 }
1427 }
1428 }
e1381638 1429
4391cd15 1430 buf.append("Encapsulated: ", 14);
774c051c 1431
1432 MemBuf httpBuf;
12b91c99 1433
774c051c 1434 httpBuf.init();
1435
1436 // build HTTP request header, if any
1437 ICAP::Method m = s.method;
1438
5f8252d2 1439 // to simplify, we could assume that request is always available
c99de607 1440
c99de607 1441 if (request) {
c99de607 1442 if (ICAP::methodRespmod == m)
1443 encapsulateHead(buf, "req-hdr", httpBuf, request);
e1381638
AJ
1444 else if (ICAP::methodReqmod == m)
1445 encapsulateHead(buf, "req-hdr", httpBuf, virgin.header);
c99de607 1446 }
774c051c 1447
1448 if (ICAP::methodRespmod == m)
63df1d28 1449 if (const Http::Message *prime = virgin.header)
774c051c 1450 encapsulateHead(buf, "res-hdr", httpBuf, prime);
1451
1452 if (!virginBody.expected())
4391cd15 1453 buf.appendf("null-body=%d", (int) httpBuf.contentSize());
774c051c 1454 else if (ICAP::methodReqmod == m)
4391cd15 1455 buf.appendf("req-body=%d", (int) httpBuf.contentSize());
774c051c 1456 else
4391cd15 1457 buf.appendf("res-body=%d", (int) httpBuf.contentSize());
774c051c 1458
1459 buf.append(ICAP::crlf, 2); // terminate Encapsulated line
1460
c824c43b 1461 if (preview.enabled()) {
4391cd15 1462 buf.appendf("Preview: %d\r\n", (int)preview.ad());
83c51da9 1463 if (!virginBody.expected()) // there is no body to preview
5f8252d2 1464 finishNullOrEmptyBodyPreview(httpBuf);
774c051c 1465 }
1466
83c51da9 1467 makeAllowHeader(buf);
774c051c 1468
a9044668 1469 if (TheConfig.send_client_ip && request) {
b7ac5457 1470 Ip::Address client_addr;
57d76dd4 1471#if FOLLOW_X_FORWARDED_FOR
22fff3bf 1472 if (TheConfig.use_indirect_client) {
a9044668
A
1473 client_addr = request->indirect_client_addr;
1474 } else
57d76dd4 1475#endif
a9044668 1476 client_addr = request->client_addr;
4dd643d5 1477 if (!client_addr.isAnyAddr() && !client_addr.isNoAddr())
4391cd15 1478 buf.appendf("X-Client-IP: %s\r\n", client_addr.toStr(ntoabuf,MAX_IPSTRLEN));
57d76dd4 1479 }
a97e82a8 1480
22fff3bf 1481 if (TheConfig.send_username && request)
5f8252d2 1482 makeUsernameHeader(request, buf);
a97e82a8 1483
71be37e0 1484 // Adaptation::Config::metaHeaders
75d47340 1485 for (auto h: Adaptation::Config::metaHeaders) {
71be37e0 1486 HttpRequest *r = virgin.cause ?
71ee0835 1487 virgin.cause : dynamic_cast<HttpRequest*>(virgin.header);
71be37e0
CT
1488 Must(r);
1489
1490 HttpReply *reply = dynamic_cast<HttpReply*>(virgin.header);
1491
75d47340
CT
1492 SBuf matched;
1493 if (h->match(r, reply, alMaster, matched)) {
1494 buf.append(h->key().rawContent(), h->key().length());
1495 buf.append(": ", 2);
1496 buf.append(matched.rawContent(), matched.length());
1497 buf.append("\r\n", 2);
d7f4a0b7 1498 Adaptation::History::Pointer ah = request->adaptHistory(false);
aee3523a
AR
1499 if (ah != nullptr) {
1500 if (ah->metaHeaders == nullptr)
cf9f0261 1501 ah->metaHeaders = new NotePairs;
75d47340
CT
1502 if (!ah->metaHeaders->hasPair(h->key(), matched))
1503 ah->metaHeaders->add(h->key(), matched);
cf9f0261 1504 }
d7f4a0b7 1505 }
71be37e0
CT
1506 }
1507
bb790702 1508 // fprintf(stderr, "%s\n", buf.content());
a97e82a8 1509
774c051c 1510 buf.append(ICAP::crlf, 2); // terminate ICAP header
1511
a22e6cd3
AR
1512 // fill icapRequest for logging
1513 Must(icapRequest->parseCharBuf(buf.content(), buf.contentSize()));
1514
774c051c 1515 // start ICAP request body with encapsulated HTTP headers
1516 buf.append(httpBuf.content(), httpBuf.contentSize());
1517
1518 httpBuf.clean();
1519}
1520
83c51da9
CT
1521// decides which Allow values to write and updates the request buffer
1522void Adaptation::Icap::ModXact::makeAllowHeader(MemBuf &buf)
1523{
1524 const bool allow204in = preview.enabled(); // TODO: add shouldAllow204in()
1525 const bool allow204out = state.allowedPostview204 = shouldAllow204();
1526 const bool allow206in = state.allowedPreview206 = shouldAllow206in();
1527 const bool allow206out = state.allowedPostview206 = shouldAllow206out();
69c698a3 1528 const bool allowTrailers = true; // TODO: make configurable
83c51da9 1529
6fbd6ef2 1530 debugs(93, 9, "Allows: " << allow204in << allow204out <<
69c698a3 1531 allow206in << allow206out << allowTrailers);
83c51da9
CT
1532
1533 const bool allow204 = allow204in || allow204out;
1534 const bool allow206 = allow206in || allow206out;
1535
64df2bff
EB
1536 if ((allow204 || allow206) && virginBody.expected())
1537 virginBodySending.plan(); // if there is a virgin body, plan to send it
83c51da9
CT
1538
1539 // writing Preview:... means we will honor 204 inside preview
1540 // writing Allow/204 means we will honor 204 outside preview
1541 // writing Allow:206 means we will honor 206 inside preview
1542 // writing Allow:204,206 means we will honor 206 outside preview
69c698a3
EB
1543 if (allow204 || allow206 || allowTrailers) {
1544 buf.appendf("Allow: ");
1545 if (allow204out)
1546 buf.appendf("204, ");
1547 if (allow206)
1548 buf.appendf("206, ");
1549 if (allowTrailers)
1550 buf.appendf("trailers");
1551 buf.appendf("\r\n");
83c51da9
CT
1552 }
1553}
1554
26cc52cb 1555void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest *request, MemBuf &buf)
9e008dda 1556{
74f6c040 1557#if USE_AUTH
aadbbd7d
AJ
1558 struct base64_encode_ctx ctx;
1559 base64_encode_init(&ctx);
1560
aee3523a
AR
1561 const char *value = nullptr;
1562 if (request->auth_user_request != nullptr) {
aadbbd7d 1563 value = request->auth_user_request->username();
b38b26cb 1564 } else if (request->extacl_user.size() > 0) {
aadbbd7d
AJ
1565 value = request->extacl_user.termedBuf();
1566 }
1567
1568 if (value) {
1569 if (TheConfig.client_username_encode) {
1d11e9b3 1570 char base64buf[base64_encode_len(MAX_LOGIN_SZ)];
aadbbd7d
AJ
1571 size_t resultLen = base64_encode_update(&ctx, base64buf, strlen(value), reinterpret_cast<const uint8_t*>(value));
1572 resultLen += base64_encode_final(&ctx, base64buf+resultLen);
4391cd15 1573 buf.appendf("%s: %.*s\r\n", TheConfig.client_username_header, (int)resultLen, base64buf);
aadbbd7d 1574 } else
4391cd15 1575 buf.appendf("%s: %s\r\n", TheConfig.client_username_header, value);
5f8252d2 1576 }
8b082ed9
FC
1577#else
1578 (void)request;
1579 (void)buf;
74f6c040 1580#endif
5f8252d2 1581}
1582
63df1d28
AJ
1583void
1584Adaptation::Icap::ModXact::encapsulateHead(MemBuf &icapBuf, const char *section, MemBuf &httpBuf, const Http::Message *head)
774c051c 1585{
1586 // update ICAP header
4391cd15 1587 icapBuf.appendf("%s=%d, ", section, (int) httpBuf.contentSize());
774c051c 1588
2cdeea82 1589 // begin cloning
63df1d28 1590 Http::MessagePointer headClone;
9e008dda 1591
2cdeea82 1592 if (const HttpRequest* old_request = dynamic_cast<const HttpRequest*>(head)) {
5ceaee75 1593 HttpRequest::Pointer new_request(new HttpRequest(old_request->masterXaction));
63df1d28 1594 // copy the request-line details
851feda6
AJ
1595 new_request->method = old_request->method;
1596 new_request->url = old_request->url;
2cdeea82 1597 new_request->http_ver = old_request->http_ver;
b248c2a3 1598 headClone = new_request.getRaw();
9e008dda 1599 } else if (const HttpReply *old_reply = dynamic_cast<const HttpReply*>(head)) {
c7d51c86 1600 HttpReply::Pointer new_reply(new HttpReply);
2cdeea82 1601 new_reply->sline = old_reply->sline;
b248c2a3 1602 headClone = new_reply.getRaw();
2cdeea82 1603 }
02dd0839 1604 Must(headClone);
d67acb4e 1605 headClone->inheritProperties(head);
9e008dda 1606
2cdeea82 1607 HttpHeaderPos pos = HttpHeaderInitPos;
02dd0839 1608 while (HttpHeaderEntry* p_head_entry = head->header.getEntry(&pos))
2cdeea82 1609 headClone->header.addEntry(p_head_entry->clone());
1610
1611 // end cloning
9e008dda 1612
2cdeea82 1613 // remove all hop-by-hop headers from the clone
789217a2 1614 headClone->header.delById(Http::HdrType::PROXY_AUTHENTICATE);
2cdeea82 1615 headClone->header.removeHopByHopEntries();
1616
1c2b4465
CT
1617 // TODO: modify HttpHeader::removeHopByHopEntries to accept a list of
1618 // excluded hop-by-hop headers
1619 if (head->header.has(Http::HdrType::UPGRADE)) {
1620 const auto upgrade = head->header.getList(Http::HdrType::UPGRADE);
1621 headClone->header.putStr(Http::HdrType::UPGRADE, upgrade.termedBuf());
1622 }
1623
2cdeea82 1624 // pack polished HTTP header
b248c2a3 1625 packHead(httpBuf, headClone.getRaw());
2cdeea82 1626
c7d51c86 1627 // headClone unlocks and, hence, deletes the message we packed
774c051c 1628}
1629
63df1d28
AJ
1630void
1631Adaptation::Icap::ModXact::packHead(MemBuf &httpBuf, const Http::Message *head)
774c051c 1632{
10201568 1633 head->packInto(&httpBuf, true);
774c051c 1634}
1635
1636// decides whether to offer a preview and calculates its size
26cc52cb 1637void Adaptation::Icap::ModXact::decideOnPreview()
774c051c 1638{
26cc52cb 1639 if (!TheConfig.preview_enable) {
bf95c10a 1640 debugs(93, 5, "preview disabled by squid.conf");
c824c43b 1641 return;
7cdbbd47 1642 }
1643
51b5dcf5 1644 const SBuf urlPath(virginRequest().url.path());
5f8252d2 1645 size_t wantedSize;
c99de607 1646 if (!service().wantsPreview(urlPath, wantedSize)) {
51b5dcf5 1647 debugs(93, 5, "should not offer preview for " << urlPath);
c824c43b 1648 return;
774c051c 1649 }
1650
c824c43b 1651 // we decided to do preview, now compute its size
1652
774c051c 1653 // cannot preview more than we can backup
d85c3078 1654 size_t ad = min(wantedSize, TheBackupLimit);
774c051c 1655
5f8252d2 1656 if (!virginBody.expected())
1657 ad = 0;
e1381638
AJ
1658 else if (virginBody.knownSize())
1659 ad = min(static_cast<uint64_t>(ad), virginBody.size()); // not more than we have
774c051c 1660
bf95c10a 1661 debugs(93, 5, "should offer " << ad << "-byte preview " <<
774c051c 1662 "(service wanted " << wantedSize << ")");
1663
1664 preview.enable(ad);
5f8252d2 1665 Must(preview.enabled());
774c051c 1666}
1667
1668// decides whether to allow 204 responses
26cc52cb 1669bool Adaptation::Icap::ModXact::shouldAllow204()
774c051c 1670{
1671 if (!service().allows204())
1672 return false;
1673
c824c43b 1674 return canBackupEverything();
1675}
1676
83c51da9
CT
1677// decides whether to allow 206 responses in some mode
1678bool Adaptation::Icap::ModXact::shouldAllow206any()
1679{
1680 return TheConfig.allow206_enable && service().allows206() &&
7ddcfbab 1681 virginBody.expected(); // no need for 206 without a body
83c51da9
CT
1682}
1683
1684// decides whether to allow 206 responses in preview mode
1685bool Adaptation::Icap::ModXact::shouldAllow206in()
1686{
1687 return shouldAllow206any() && preview.enabled();
1688}
1689
1690// decides whether to allow 206 responses outside of preview
1691bool Adaptation::Icap::ModXact::shouldAllow206out()
1692{
1693 return shouldAllow206any() && canBackupEverything();
1694}
1695
c824c43b 1696// used by shouldAllow204 and decideOnRetries
26cc52cb 1697bool Adaptation::Icap::ModXact::canBackupEverything() const
c824c43b 1698{
774c051c 1699 if (!virginBody.expected())
c824c43b 1700 return true; // no body means no problems with backup
774c051c 1701
c824c43b 1702 // if there is a body, check whether we can backup it all
774c051c 1703
1704 if (!virginBody.knownSize())
1705 return false;
1706
1707 // or should we have a different backup limit?
1708 // note that '<' allows for 0-termination of the "full" backup buffer
1709 return virginBody.size() < TheBackupLimit;
1710}
1711
c824c43b 1712// Decide whether this transaction can be retried if pconn fails
1713// Must be called after decideOnPreview and before openConnection()
26cc52cb 1714void Adaptation::Icap::ModXact::decideOnRetries()
c824c43b 1715{
1716 if (!isRetriable)
1717 return; // no, already decided
1718
1719 if (preview.enabled())
1720 return; // yes, because preview provides enough guarantees
1721
1722 if (canBackupEverything())
1723 return; // yes, because we can back everything up
1724
1725 disableRetries(); // no, because we cannot back everything up
1726}
1727
5f8252d2 1728// Normally, the body-writing code handles preview body. It can deal with
1729// bodies of unexpected size, including those that turn out to be empty.
1730// However, that code assumes that the body was expected and body control
1731// structures were initialized. This is not the case when there is no body
1732// or the body is known to be empty, because the virgin message will lack a
1733// body_pipe. So we handle preview of null-body and zero-size bodies here.
ced8def3 1734void Adaptation::Icap::ModXact::finishNullOrEmptyBodyPreview(MemBuf &)
5f8252d2 1735{
1736 Must(!virginBodyWriting.active()); // one reason we handle it here
1737 Must(!virgin.body_pipe); // another reason we handle it here
1738 Must(!preview.ad());
1739
1740 // do not add last-chunk because our Encapsulated header says null-body
bb790702 1741 // addLastRequestChunk(buf);
5f8252d2 1742 preview.wrote(0, true);
1743
1744 Must(preview.done());
1745 Must(preview.ieof());
1746}
1747
26cc52cb 1748void Adaptation::Icap::ModXact::fillPendingStatus(MemBuf &buf) const
774c051c 1749{
26cc52cb 1750 Adaptation::Icap::Xaction::fillPendingStatus(buf);
c99de607 1751
774c051c 1752 if (state.serviceWaiting)
1753 buf.append("U", 1);
1754
aee3523a 1755 if (virgin.body_pipe != nullptr)
c99de607 1756 buf.append("R", 1);
1757
aed188fd 1758 if (haveConnection() && !doneReading())
c99de607 1759 buf.append("r", 1);
1760
774c051c 1761 if (!state.doneWriting() && state.writing != State::writingInit)
4391cd15 1762 buf.appendf("w(%d)", state.writing);
774c051c 1763
1764 if (preview.enabled()) {
1765 if (!preview.done())
4391cd15 1766 buf.appendf("P(%d)", (int) preview.debt());
774c051c 1767 }
1768
5f8252d2 1769 if (virginBodySending.active())
774c051c 1770 buf.append("B", 1);
1771
1772 if (!state.doneParsing() && state.parsing != State::psIcapHeader)
4391cd15 1773 buf.appendf("p(%d)", state.parsing);
774c051c 1774
1775 if (!doneSending() && state.sending != State::sendingUndecided)
4391cd15 1776 buf.appendf("S(%d)", state.sending);
478cfe99 1777
83c51da9
CT
1778 if (state.readyForUob)
1779 buf.append("6", 1);
1780
478cfe99 1781 if (canStartBypass)
9e008dda 1782 buf.append("Y", 1);
a22e6cd3
AR
1783
1784 if (protectGroupBypass)
1785 buf.append("G", 1);
774c051c 1786}
1787
26cc52cb 1788void Adaptation::Icap::ModXact::fillDoneStatus(MemBuf &buf) const
774c051c 1789{
26cc52cb 1790 Adaptation::Icap::Xaction::fillDoneStatus(buf);
c99de607 1791
5f8252d2 1792 if (!virgin.body_pipe)
774c051c 1793 buf.append("R", 1);
1794
1795 if (state.doneWriting())
1796 buf.append("w", 1);
1797
1798 if (preview.enabled()) {
1799 if (preview.done())
4391cd15 1800 buf.appendf("P%s", preview.ieof() ? "(ieof)" : "");
774c051c 1801 }
1802
1803 if (doneReading())
1804 buf.append("r", 1);
1805
1806 if (state.doneParsing())
1807 buf.append("p", 1);
1808
1809 if (doneSending())
1810 buf.append("S", 1);
1811}
1812
26cc52cb 1813bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section) const
774c051c 1814{
36c774f7
EB
1815 return !icapReply->header.getByNameListMember("Encapsulated",
1816 section, ',').isEmpty();
774c051c 1817}
1818
1819// calculate whether there is a virgin HTTP body and
1820// whether its expected size is known
5f8252d2 1821// TODO: rename because we do not just estimate
26cc52cb 1822void Adaptation::Icap::ModXact::estimateVirginBody()
774c051c 1823{
5f8252d2 1824 // note: lack of size info may disable previews and 204s
774c051c 1825
63df1d28 1826 Http::Message *msg = virgin.header;
5f8252d2 1827 Must(msg);
774c051c 1828
60745f24 1829 HttpRequestMethod method;
774c051c 1830
5f8252d2 1831 if (virgin.cause)
1832 method = virgin.cause->method;
e1381638
AJ
1833 else if (HttpRequest *req = dynamic_cast<HttpRequest*>(msg))
1834 method = req->method;
774c051c 1835 else
c2a7cefd 1836 method = Http::METHOD_NONE;
774c051c 1837
47f6e231 1838 int64_t size;
5f8252d2 1839 // expectingBody returns true for zero-sized bodies, but we will not
1840 // get a pipe for that body, so we treat the message as bodyless
c2a7cefd 1841 if (method != Http::METHOD_NONE && msg->expectingBody(method, size) && size) {
bf95c10a 1842 debugs(93, 6, "expects virgin body from " <<
9e008dda 1843 virgin.body_pipe << "; size: " << size);
5f8252d2 1844
1845 virginBody.expect(size);
1846 virginBodyWriting.plan();
1847
1848 // sign up as a body consumer
aee3523a 1849 Must(msg->body_pipe != nullptr);
5f8252d2 1850 Must(msg->body_pipe == virgin.body_pipe);
1851 Must(virgin.body_pipe->setConsumerIfNotLate(this));
1852
1853 // make sure TheBackupLimit is in-sync with the buffer size
9c175897 1854 Must(TheBackupLimit <= static_cast<size_t>(msg->body_pipe->buf().max_capacity));
774c051c 1855 } else {
bf95c10a 1856 debugs(93, 6, "does not expect virgin body");
aee3523a 1857 Must(msg->body_pipe == nullptr);
5f8252d2 1858 checkConsuming();
774c051c 1859 }
1860}
1861
26cc52cb 1862void Adaptation::Icap::ModXact::makeAdaptedBodyPipe(const char *what)
9e008dda 1863{
5f8252d2 1864 Must(!adapted.body_pipe);
1865 Must(!adapted.header->body_pipe);
1866 adapted.header->body_pipe = new BodyPipe(this);
1867 adapted.body_pipe = adapted.header->body_pipe;
bf95c10a 1868 debugs(93, 7, "will supply " << what << " via " <<
9e008dda 1869 adapted.body_pipe << " pipe");
5f8252d2 1870}
1871
26cc52cb 1872// TODO: Move SizedEstimate and Preview elsewhere
774c051c 1873
26cc52cb 1874Adaptation::Icap::SizedEstimate::SizedEstimate()
f53969cc 1875 : theData(dtUnexpected)
774c051c 1876{}
1877
26cc52cb 1878void Adaptation::Icap::SizedEstimate::expect(int64_t aSize)
774c051c 1879{
47f6e231 1880 theData = (aSize >= 0) ? aSize : (int64_t)dtUnknown;
774c051c 1881}
1882
26cc52cb 1883bool Adaptation::Icap::SizedEstimate::expected() const
774c051c 1884{
1885 return theData != dtUnexpected;
1886}
1887
26cc52cb 1888bool Adaptation::Icap::SizedEstimate::knownSize() const
774c051c 1889{
1890 Must(expected());
1891 return theData != dtUnknown;
1892}
1893
26cc52cb 1894uint64_t Adaptation::Icap::SizedEstimate::size() const
774c051c 1895{
1896 Must(knownSize());
47f6e231 1897 return static_cast<uint64_t>(theData);
774c051c 1898}
1899
26cc52cb 1900Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided)
774c051c 1901{}
1902
26cc52cb 1903void Adaptation::Icap::VirginBodyAct::plan()
774c051c 1904{
478cfe99 1905 Must(!disabled());
1906 Must(!theStart); // not started
1907 theState = stActive;
774c051c 1908}
1909
26cc52cb 1910void Adaptation::Icap::VirginBodyAct::disable()
774c051c 1911{
478cfe99 1912 theState = stDisabled;
774c051c 1913}
1914
26cc52cb 1915void Adaptation::Icap::VirginBodyAct::progress(size_t size)
774c051c 1916{
1917 Must(active());
46e172d9
FC
1918#if SIZEOF_SIZE_T > 4
1919 /* always true for smaller size_t's */
d897ae49 1920 Must(static_cast<int64_t>(size) >= 0);
46e172d9 1921#endif
47f6e231 1922 theStart += static_cast<int64_t>(size);
774c051c 1923}
1924
26cc52cb 1925uint64_t Adaptation::Icap::VirginBodyAct::offset() const
774c051c 1926{
1927 Must(active());
47f6e231 1928 return static_cast<uint64_t>(theStart);
774c051c 1929}
1930
26cc52cb 1931Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled)
774c051c 1932{}
1933
26cc52cb 1934void Adaptation::Icap::Preview::enable(size_t anAd)
774c051c 1935{
1936 // TODO: check for anAd not exceeding preview size limit
774c051c 1937 Must(!enabled());
1938 theAd = anAd;
1939 theState = stWriting;
1940}
1941
26cc52cb 1942bool Adaptation::Icap::Preview::enabled() const
774c051c 1943{
1944 return theState != stDisabled;
1945}
1946
26cc52cb 1947size_t Adaptation::Icap::Preview::ad() const
774c051c 1948{
1949 Must(enabled());
1950 return theAd;
1951}
1952
26cc52cb 1953bool Adaptation::Icap::Preview::done() const
774c051c 1954{
1955 Must(enabled());
1956 return theState >= stIeof;
1957}
1958
26cc52cb 1959bool Adaptation::Icap::Preview::ieof() const
774c051c 1960{
1961 Must(enabled());
1962 return theState == stIeof;
1963}
1964
26cc52cb 1965size_t Adaptation::Icap::Preview::debt() const
774c051c 1966{
1967 Must(enabled());
1968 return done() ? 0 : (theAd - theWritten);
1969}
1970
26cc52cb 1971void Adaptation::Icap::Preview::wrote(size_t size, bool wroteEof)
774c051c 1972{
1973 Must(enabled());
5f8252d2 1974
774c051c 1975 theWritten += size;
1976
9e008dda 1977 Must(theWritten <= theAd);
5f8252d2 1978
9e008dda
AJ
1979 if (wroteEof)
1980 theState = stIeof; // written size is irrelevant
e1381638
AJ
1981 else if (theWritten >= theAd)
1982 theState = stDone;
774c051c 1983}
1984
26cc52cb 1985bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf &mb) const
3cfc19b3 1986{
aee3523a 1987 if (virgin.header == nullptr)
3cfc19b3 1988 return false;
1989
5f8252d2 1990 virgin.header->firstLineBuf(mb);
3cfc19b3 1991
1992 return true;
1993}
c824c43b 1994
83b053a0 1995void Adaptation::Icap::ModXact::detailError(const ErrorDetail::Pointer &errDetail)
64b66b76 1996{
e9fa5493
AR
1997 HttpRequest *request = dynamic_cast<HttpRequest*>(adapted.header);
1998 // if no adapted request, update virgin (and inherit its properties later)
1999 // TODO: make this and HttpRequest::detailError constant, like adaptHistory
2000 if (!request)
2001 request = const_cast<HttpRequest*>(&virginRequest());
2002
2003 if (request)
64b66b76 2004 request->detailError(ERR_ICAP_FAILURE, errDetail);
64b66b76 2005}
c824c43b 2006
129fe2a1
CT
2007void Adaptation::Icap::ModXact::clearError()
2008{
87f237a9 2009 HttpRequest *request = dynamic_cast<HttpRequest*>(adapted.header);
129fe2a1
CT
2010 // if no adapted request, update virgin (and inherit its properties later)
2011 if (!request)
2012 request = const_cast<HttpRequest*>(&virginRequest());
2013
2014 if (request)
2015 request->clearError();
2016}
2017
88df846b
CT
2018void Adaptation::Icap::ModXact::updateSources()
2019{
2020 Must(adapted.header);
63df1d28 2021 adapted.header->sources |= (service().cfg().connectionEncryption ? Http::Message::srcIcaps : Http::Message::srcIcap);
88df846b
CT
2022}
2023
26cc52cb 2024/* Adaptation::Icap::ModXactLauncher */
c824c43b 2025
63df1d28 2026Adaptation::Icap::ModXactLauncher::ModXactLauncher(Http::Message *virginHeader, HttpRequest *virginCause, AccessLogEntry::Pointer &alp, Adaptation::ServicePointer aService):
f53969cc
SM
2027 AsyncJob("Adaptation::Icap::ModXactLauncher"),
2028 Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", aService),
2029 al(alp)
c824c43b 2030{
2031 virgin.setHeader(virginHeader);
2032 virgin.setCause(virginCause);
3ff65596 2033 updateHistory(true);
c824c43b 2034}
2035
26cc52cb 2036Adaptation::Icap::Xaction *Adaptation::Icap::ModXactLauncher::createXaction()
c824c43b 2037{
26cc52cb
AR
2038 Adaptation::Icap::ServiceRep::Pointer s =
2039 dynamic_cast<Adaptation::Icap::ServiceRep*>(theService.getRaw());
aee3523a 2040 Must(s != nullptr);
af0ded40 2041 return new Adaptation::Icap::ModXact(virgin.header, virgin.cause, al, s);
c824c43b 2042}
3ff65596 2043
e1381638
AJ
2044void Adaptation::Icap::ModXactLauncher::swanSong()
2045{
bf95c10a 2046 debugs(93, 5, "swan sings");
3ff65596
AR
2047 updateHistory(false);
2048 Adaptation::Icap::Launcher::swanSong();
2049}
2050
b0365bd9 2051void Adaptation::Icap::ModXactLauncher::updateHistory(bool doStart)
e1381638
AJ
2052{
2053 HttpRequest *r = virgin.cause ?
2054 virgin.cause : dynamic_cast<HttpRequest*>(virgin.header);
2055
2056 // r should never be NULL but we play safe; TODO: add Should()
2057 if (r) {
2058 Adaptation::Icap::History::Pointer h = r->icapHistory();
aee3523a 2059 if (h != nullptr) {
b0365bd9 2060 if (doStart)
e1381638
AJ
2061 h->start("ICAPModXactLauncher");
2062 else
2063 h->stop("ICAPModXactLauncher");
2064 }
2065 }
3ff65596 2066}
f53969cc 2067
69c698a3 2068bool Adaptation::Icap::TrailerParser::parse(const char *buf, int len, int atEnd, Http::StatusCode *error) {
4f1c93a7
EB
2069 Http::ContentLengthInterpreter clen;
2070 // RFC 7230 section 4.1.2: MUST NOT generate a trailer that contains
2071 // a field necessary for message framing (e.g., Transfer-Encoding and Content-Length)
2072 clen.applyTrailerRules();
2073 const int parsed = trailer.parse(buf, len, atEnd, hdr_sz, clen);
69c698a3
EB
2074 if (parsed < 0)
2075 *error = Http::scInvalidHeader; // TODO: should we add a new Http::scInvalidTrailer?
2076 return parsed > 0;
2077}
2078
417da400
EB
2079void
2080Adaptation::Icap::ChunkExtensionValueParser::parse(Tokenizer &tok, const SBuf &extName)
2081{
2082 if (extName == UseOriginalBodyName) {
2083 useOriginalBody_ = tok.udec64("use-original-body");
2084 assert(useOriginalBody_ >= 0);
2085 } else {
2086 Ignore(tok, extName);
2087 }
2088}
2089