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