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