Squid Web Cache master
Loading...
Searching...
No Matches
ModXact.cc
Go to the documentation of this file.
1/*
2 * Copyright (C) 1996-2026 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"
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 "error/Detail.h"
30#include "HttpHeaderTools.h"
31#include "HttpReply.h"
32#include "MasterXaction.h"
33#include "parser/Tokenizer.h"
34#include "sbuf/Stream.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
44
45static constexpr auto TheBackupLimit = BodyPipe::MaxCapacity;
46
48
50{
51 memset(this, 0, sizeof(*this));
52}
53
56 AsyncJob("Adaptation::Icap::ModXact"),
57 Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", aService),
59 bodyParser(nullptr),
60 canStartBypass(false), // too early
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, "initialized." << status());
85}
86
87// initiator wants us to start
89{
91
92 // reserve an adaptation history slot (attempts are known at this time)
93 Adaptation::History::Pointer ah = virginRequest().adaptLogHistory();
94 if (ah != nullptr)
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
110{
111 const char *comment;
112 Must(!state.serviceWaiting);
113
114 if (!service().up()) {
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, "will not wait for the service to be available" <<
135 status());
136
137 throw TexcHere("ICAP service is not available");
138 }
139
142 service().callWhenAvailable(call, state.waitedForService);
143 comment = "to be available";
144 }
145
146 debugs(93, 7, "will wait for the service " << comment << status());
147 state.serviceWaiting = true; // after callWhenReady() which may throw
148 state.waitedForService = true;
149}
150
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
169{
170 Must(state.serviceWaiting);
171 state.serviceWaiting = false;
172
173 if (service().up() && service().availableForOld())
174 startWriting();
175 else
176 waitForService();
177}
178
180{
181 state.writing = State::writingConnect;
182
183 decideOnPreview(); // must be decided before we decideOnRetries
184 decideOnRetries();
185
186 openConnection();
187}
188
190{
191 Must(state.writing == State::writingConnect);
192
193 startReading(); // wait for early errors from the ICAP server
194
195 MemBuf requestBuf;
196 requestBuf.init();
197
198 makeRequestHeaders(requestBuf);
199 debugs(93, 9, "will write" << status() << ":\n" <<
200 (requestBuf.terminate(), requestBuf.content()));
201
202 // write headers
203 state.writing = State::writingHeaders;
204 icap_tio_start = current_time;
205 scheduleWrite(requestBuf);
206}
207
209{
210 debugs(93, 5, "Wrote " << sz << " bytes");
211
212 if (state.writing == State::writingHeaders)
213 handleCommWroteHeaders();
214 else
215 handleCommWroteBody();
216}
217
219{
220 Must(state.writing == State::writingHeaders);
221
222 // determine next step
223 if (preview.enabled()) {
224 if (preview.done())
225 decideWritingAfterPreview("zero-size");
226 else
227 state.writing = State::writingPreview;
228 } else if (virginBody.expected()) {
229 state.writing = State::writingPrime;
230 } else {
231 stopWriting(true);
232 return;
233 }
234
235 writeMore();
236}
237
239{
240 debugs(93, 5, "checking whether to write more" << status());
241
242 if (writer != nullptr) // already writing something
243 return;
244
245 switch (state.writing) {
246
247 case State::writingInit: // waiting for service OPTIONS
248 Must(state.serviceWaiting);
249 return;
250
251 case State::writingConnect: // waiting for the connection to establish
252 case State::writingHeaders: // waiting for the headers to be written
253 case State::writingPaused: // waiting for the ICAP server response
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
275{
276 debugs(93, 8, "will write Preview body from " <<
277 virgin.body_pipe << status());
278 Must(state.writing == State::writingPreview);
279 Must(virgin.body_pipe != nullptr);
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
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, "decided on writing after " << kind << " preview" <<
302 status());
303}
304
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, "wrote entire body");
315 stopWriting(true);
316 }
317}
318
319void Adaptation::Icap::ModXact::writeSomeBody(const char *label, size_t size)
320{
321 Must(!writer && state.writing < state.writingAlmostDone);
322 Must(virgin.body_pipe != nullptr);
323 debugs(93, 8, "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, "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, "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, "will write last-chunk of " << label);
356 addLastRequestChunk(writeBuf);
357 }
358
359 debugs(93, 7, "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
370{
371 const bool ieof = state.writing == State::writingPreview && preview.ieof();
372 openChunk(buf, 0, ieof);
373 closeChunk(buf);
374}
375
376void 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
382{
383 buf.append(ICAP::crlf, 2); // chunk-terminating CRLF
384}
385
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?
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
405{
406 Must(act.active());
407 // absolute 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
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
425{
426 debugs(93, 9, "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 if (wantToPostpone && bp.buf().potentialSpaceSize() > 0) {
439 // Postponing may increase memory footprint and slow the HTTP side
440 // down. Not postponing may increase the number of ICAP errors
441 // if the ICAP service fails. Should the trade-off be configurable?
442 debugs(93, 8, "postponing consumption from " << bp.status());
443 return;
444 }
445
446 const size_t have = static_cast<size_t>(bp.buf().contentSize());
447 const uint64_t end = virginConsumed + have;
448 uint64_t offset = end;
449
450 debugs(93, 9, "max virgin consumption offset=" << offset <<
451 " acts " << virginBodyWriting.active() << virginBodySending.active() <<
452 " consumed=" << virginConsumed <<
453 " from " << virgin.body_pipe->status());
454
455 if (virginBodyWriting.active())
456 offset = min(virginBodyWriting.offset(), offset);
457
458 if (virginBodySending.active())
459 offset = min(virginBodySending.offset(), offset);
460
461 Must(virginConsumed <= offset && offset <= end);
462
463 if (const size_t size = static_cast<size_t>(offset - virginConsumed)) {
464 debugs(93, 8, "consuming " << size << " out of " << have <<
465 " virgin body bytes");
466 bp.consume(size);
467 virginConsumed += size;
468 Must(!isRetriable); // or we should not be consuming
469 disableRepeats("consumed content");
470 disableBypass("consumed content", true);
471 }
472}
473
475{
476 writeMore();
477}
478
479// Called when we do not expect to call comm_write anymore.
480// We may have a pending write though.
481// If stopping nicely, we will just wait for that pending write, if any.
483{
484 if (state.writing == State::writingReallyDone)
485 return;
486
487 if (writer != nullptr) {
488 if (nicely) {
489 debugs(93, 7, "will wait for the last write" << status());
490 state.writing = State::writingAlmostDone; // may already be set
491 checkConsuming();
492 return;
493 }
494 debugs(93, 3, "will NOT wait for the last write" << status());
495
496 // Comm does not have an interface to clear the writer callback nicely,
497 // but without clearing the writer we cannot recycle the connection.
498 // We prevent connection reuse and hope that we can handle a callback
499 // call at any time, usually in the middle of the destruction sequence!
500 // Somebody should add comm_remove_write_handler() to comm API.
501 reuseConnection = false;
502 ignoreLastWrite = true;
503 }
504
505 debugs(93, 7, "will no longer write" << status());
506 if (virginBodyWriting.active()) {
507 virginBodyWriting.disable();
508 virginConsume();
509 }
510 state.writing = State::writingReallyDone;
511 checkConsuming();
512}
513
515{
516 if (!virginBodySending.active())
517 return;
518
519 debugs(93, 7, "will no longer backup" << status());
520 virginBodySending.disable();
521 virginConsume();
522}
523
525{
526 return Adaptation::Icap::Xaction::doneAll() && !state.serviceWaiting &&
527 doneSending() &&
528 doneReading() && state.doneWriting();
529}
530
532{
533 Must(haveConnection());
534 Must(!reader);
535 Must(!adapted.header);
536 Must(!adapted.body_pipe);
537
538 // we use the same buffer for headers and body and then consume headers
539 readMore();
540}
541
543{
544 if (reader != nullptr || doneReading()) {
545 debugs(93,3, "returning from readMore because reader or doneReading()");
546 return;
547 }
548
549 // do not fill readBuf if we have no space to store the result
550 if (adapted.body_pipe != nullptr &&
551 !adapted.body_pipe->buf().hasPotentialSpace()) {
552 debugs(93,3, "not reading because ICAP reply pipe is full");
553 return;
554 }
555
556 if (readBuf.length() < SQUID_TCP_SO_RCVBUF)
557 scheduleRead();
558 else
559 debugs(93,3, "cannot read with a full buffer");
560}
561
562// comm module read a portion of the ICAP response for us
564{
565 Must(!state.doneParsing());
566 icap_tio_finish = current_time;
567 parseMore();
568 readMore();
569}
570
572{
573 Must(state.sending == State::sendingVirgin);
574 Must(adapted.body_pipe != nullptr);
575 Must(virginBodySending.active());
576
577 const size_t sizeMax = virginContentSize(virginBodySending);
578 debugs(93,5, "will echo up to " << sizeMax << " bytes from " <<
579 virgin.body_pipe->status());
580 debugs(93,5, "will echo up to " << sizeMax << " bytes to " <<
581 adapted.body_pipe->status());
582
583 if (sizeMax > 0) {
584 const size_t size = adapted.body_pipe->putMoreData(virginContentData(virginBodySending), sizeMax);
585 debugs(93,5, "echoed " << size << " out of " << sizeMax <<
586 " bytes");
587 virginBodySending.progress(size);
588 disableRepeats("echoed content");
589 disableBypass("echoed content", true);
590 virginConsume();
591 }
592
593 if (virginBodyEndReached(virginBodySending)) {
594 debugs(93, 5, "echoed all" << status());
595 stopSending(true);
596 } else {
597 debugs(93, 5, "has " <<
598 virgin.body_pipe->buf().contentSize() << " bytes " <<
599 "and expects more to echo" << status());
600 // TODO: timeout if virgin or adapted pipes are broken
601 }
602}
603
605{
606 return state.sending == State::sendingDone;
607}
608
609// stop (or do not start) sending adapted message body
611{
612 debugs(93, 7, "Enter stop sending ");
613 if (doneSending())
614 return;
615 debugs(93, 7, "Proceed with stop sending ");
616
617 if (state.sending != State::sendingUndecided) {
618 debugs(93, 7, "will no longer send" << status());
619 if (adapted.body_pipe != nullptr) {
620 virginBodySending.disable();
621 // we may leave debts if we were echoing and the virgin
622 // body_pipe got exhausted before we echoed all planned bytes
623 const bool leftDebts = adapted.body_pipe->needsMoreData();
624 stopProducingFor(adapted.body_pipe, nicely && !leftDebts);
625 }
626 } else {
627 debugs(93, 7, "will not start sending" << status());
628 Must(!adapted.body_pipe);
629 }
630
631 state.sending = State::sendingDone;
632 checkConsuming();
633}
634
635// should be called after certain state.writing or state.sending changes
637{
638 // quit if we already stopped or are still using the pipe
639 if (!virgin.body_pipe || !state.doneConsumingVirgin())
640 return;
641
642 debugs(93, 7, "will stop consuming" << status());
643 stopConsumingFrom(virgin.body_pipe);
644}
645
647{
648 debugs(93, 5, "have " << readBuf.length() << " bytes to parse" << status());
649 debugs(93, 5, "\n" << readBuf);
650
651 if (state.parsingHeaders())
652 parseHeaders();
653
654 if (state.parsing == State::psBody)
655 parseBody();
656
657 if (state.parsing == State::psIcapTrailer)
658 parseIcapTrailer();
659}
660
661void Adaptation::Icap::ModXact::callException(const std::exception &e)
662{
663 if (!canStartBypass || isRetriable) {
664 if (!isRetriable) {
665 if (const TextException *te = dynamic_cast<const TextException *>(&e))
666 detailError(new ExceptionErrorDetail(te->id()));
667 else
668 detailError(new ExceptionErrorDetail(Here().id()));
669 }
671 return;
672 }
673
674 try {
675 debugs(93, 3, "bypassing " << inCall << " exception: " <<
676 e.what() << ' ' << status());
677 bypassFailure();
678 } catch (const TextException &bypassTe) {
679 detailError(new ExceptionErrorDetail(bypassTe.id()));
681 } catch (const std::exception &bypassE) {
682 detailError(new ExceptionErrorDetail(Here().id()));
684 }
685}
686
688{
689 disableBypass("already started to bypass", false);
690
691 Must(!isRetriable); // or we should not be bypassing
692 // TODO: should the same be enforced for isRepeatable? Check icap_repeat??
693
694 prepEchoing();
695
696 startSending();
697
698 // end all activities associated with the ICAP server
699
700 stopParsing(false);
701
702 stopWriting(true); // or should we force it?
703 if (haveConnection()) {
704 reuseConnection = false; // be conservative
705 cancelRead(); // may not work; and we cannot stop connecting either
706 if (!doneWithIo())
707 debugs(93, 7, "Warning: bypass failed to stop I/O" << status());
708 }
709
710 service().noteFailure(); // we are bypassing, but this is still a failure
711}
712
713void Adaptation::Icap::ModXact::disableBypass(const char *reason, bool includingGroupBypass)
714{
715 if (canStartBypass) {
716 debugs(93,7, "will never start bypass because " << reason);
717 canStartBypass = false;
718 }
719 if (protectGroupBypass && includingGroupBypass) {
720 debugs(93,7, "not protecting group bypass because " << reason);
721 protectGroupBypass = false;
722 }
723}
724
725// note that allocation for echoing is done in handle204NoContent()
727{
728 if (adapted.header) // already allocated
729 return;
730
731 if (gotEncapsulated("res-hdr")) {
732 adapted.setHeader(new HttpReply);
733 setOutcome(service().cfg().method == ICAP::methodReqmod ?
735 } else if (gotEncapsulated("req-hdr")) {
736 adapted.setHeader(new HttpRequest(virginRequest().masterXaction));
737 setOutcome(xoModified);
738 } else
739 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
740}
741
743{
744 Must(state.parsingHeaders());
745
746 if (state.parsing == State::psIcapHeader) {
747 debugs(93, 5, "parse ICAP headers");
748 parseIcapHead();
749 }
750
751 if (state.parsing == State::psHttpHeader) {
752 debugs(93, 5, "parse HTTP headers");
753 parseHttpHead();
754 }
755
756 if (state.parsingHeaders()) { // need more data
757 Must(mayReadMore());
758 return;
759 }
760
761 startSending();
762}
763
764// called after parsing all headers or when bypassing an exception
766{
767 disableRepeats("sent headers");
768 disableBypass("sent headers", true);
769 sendAnswer(Answer::Forward(adapted.header));
770
771 if (state.sending == State::sendingVirgin)
772 echoMore();
773 else {
774 // If we are not using the virgin HTTP object update the
775 // Http::Message::sources flag.
776 // The state.sending may set to State::sendingVirgin in the case
777 // of 206 responses too, where we do not want to update Http::Message::sources
778 // flag. However even for 206 responses the state.sending is
779 // not set yet to sendingVirgin. This is done in later step
780 // after the parseBody method called.
781 updateSources();
782 }
783}
784
786{
787 Must(state.sending == State::sendingUndecided);
788
789 if (!parseHead(icapReply.getRaw()))
790 return;
791
792 if (expectIcapTrailers()) {
793 Must(!trailerParser);
794 trailerParser = new TrailerParser;
795 }
796
797 static SBuf close("close", 5);
798 if (httpHeaderHasConnDir(&icapReply->header, close)) {
799 debugs(93, 5, "found connection close");
800 reuseConnection = false;
801 }
802
803 switch (icapReply->sline.status()) {
804
805 case Http::scContinue:
806 handle100Continue();
807 break;
808
809 case Http::scOkay:
810 case Http::scCreated: // Symantec Scan Engine 5.0 and later when modifying HTTP msg
811
812 if (!validate200Ok()) {
813 throw TexcHere("Invalid ICAP Response");
814 } else {
815 handle200Ok();
816 }
817
818 break;
819
821 handle204NoContent();
822 break;
823
825 handle206PartialContent();
826 break;
827
828 default:
829 debugs(93, 5, "ICAP status " << icapReply->sline.status());
830 handleUnknownScode();
831 break;
832 }
833
834 const HttpRequest *request = dynamic_cast<HttpRequest*>(adapted.header);
835 if (!request)
836 request = &virginRequest();
837
838 // update the cross-transactional database if needed (all status codes!)
839 if (const char *xxName = Adaptation::Config::masterx_shared_name) {
840 Adaptation::History::Pointer ah = request->adaptHistory(true);
841 if (ah != nullptr) { // TODO: reorder checks to avoid creating history
842 const String val = icapReply->header.getByName(xxName);
843 if (val.size() > 0) // XXX: HttpHeader lacks empty value detection
844 ah->updateXxRecord(xxName, val);
845 }
846 }
847
848 // update the adaptation plan if needed (all status codes!)
849 if (service().cfg().routing) {
850 String services;
851 if (icapReply->header.getList(Http::HdrType::X_NEXT_SERVICES, &services)) {
852 Adaptation::History::Pointer ah = request->adaptHistory(true);
853 if (ah != nullptr)
854 ah->updateNextServices(services);
855 }
856 } // TODO: else warn (occasionally!) if we got Http::HdrType::X_NEXT_SERVICES
857
858 // We need to store received ICAP headers for <icapLastHeader logformat option.
859 // If we already have stored headers from previous ICAP transaction related to this
860 // request, old headers will be replaced with the new one.
861
863 if (ah != nullptr)
864 ah->recordMeta(&icapReply->header);
865
866 // handle100Continue() manages state.writing on its own.
867 // Non-100 status means the server needs no postPreview data from us.
868 if (state.writing == State::writingPaused)
869 stopWriting(true);
870}
871
875
876 if (parsePart(trailerParser, "trailer")) {
877 for (const auto &e: trailerParser->trailer.entries)
878 debugs(93, 5, "ICAP trailer: " << e->name << ": " << e->value);
879 stopParsing();
880 }
881}
882
884{
885 if (service().cfg().method == ICAP::methodRespmod)
886 return gotEncapsulated("res-hdr");
887
888 return service().cfg().method == ICAP::methodReqmod &&
889 expectHttpHeader();
890}
891
893{
894 Must(state.writing == State::writingPaused);
895 // server must not respond before the end of preview: we may send ieof
896 Must(preview.enabled() && preview.done() && !preview.ieof());
897
898 // 100 "Continue" cancels our Preview commitment,
899 // but not commitment to handle 204 or 206 outside Preview
900 if (!state.allowedPostview204 && !state.allowedPostview206)
901 stopBackup();
902
903 state.parsing = State::psIcapHeader; // eventually
904 icapReply->reset();
905
906 state.writing = State::writingPrime;
907
908 writeMore();
909}
910
912{
913 state.parsing = State::psHttpHeader;
914 state.sending = State::sendingAdapted;
915 stopBackup();
916 checkConsuming();
917}
918
920{
921 stopParsing();
922 prepEchoing();
923}
924
926{
927 if (state.writing == State::writingPaused) {
928 Must(preview.enabled());
929 Must(state.allowedPreview206);
930 debugs(93, 7, "206 inside preview");
931 } else {
932 Must(state.writing > State::writingPaused);
933 Must(state.allowedPostview206);
934 debugs(93, 7, "206 outside preview");
935 }
936 state.parsing = State::psHttpHeader;
937 state.sending = State::sendingAdapted;
938 state.readyForUob = true;
939 checkConsuming();
940}
941
942// Called when we receive a 204 No Content response and
943// when we are trying to bypass a service failure.
944// We actually start sending (echoig or not) in startSending.
946{
947 disableRepeats("preparing to echo content");
948 disableBypass("preparing to echo content", true);
949 setOutcome(xoEcho);
950
951 // We want to clone the HTTP message, but we do not want
952 // to copy some non-HTTP state parts that Http::Message kids carry in them.
953 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
954 // Instead, we simply write the HTTP message and "clone" it by parsing.
955 // TODO: use Http::Message::clone()!
956
957 Http::Message *oldHead = virgin.header;
958 debugs(93, 7, "cloning virgin message " << oldHead);
959
960 MemBuf httpBuf;
961
962 // write the virgin message into a memory buffer
963 httpBuf.init();
964 packHead(httpBuf, oldHead);
965
966 // allocate the adapted message and copy metainfo
967 Must(!adapted.header);
968 {
969 Http::MessagePointer newHead;
970 if (const HttpRequest *r = dynamic_cast<const HttpRequest*>(oldHead)) {
971 newHead = new HttpRequest(r->masterXaction);
972 } else if (dynamic_cast<const HttpReply*>(oldHead)) {
973 newHead = new HttpReply;
974 }
975 Must(newHead);
976
977 newHead->inheritProperties(oldHead);
978
979 adapted.setHeader(newHead.getRaw());
980 }
981
982 // parse the buffer back
984
985 httpBuf.terminate(); // Http::Message::parse requires nil-terminated buffer
986 Must(adapted.header->parse(httpBuf.content(), httpBuf.contentSize(), true, &error));
987 Must(adapted.header->hdr_sz == httpBuf.contentSize()); // no leftovers
988
989 httpBuf.clean();
990
991 debugs(93, 7, "cloned virgin message " << oldHead << " to " <<
992 adapted.header);
993
994 // setup adapted body pipe if needed
995 if (oldHead->body_pipe != nullptr) {
996 debugs(93, 7, "will echo virgin body from " <<
997 oldHead->body_pipe);
998 if (!virginBodySending.active())
999 virginBodySending.plan(); // will throw if not possible
1000 state.sending = State::sendingVirgin;
1001 checkConsuming();
1002
1003 // TODO: optimize: is it possible to just use the oldHead pipe and
1004 // remove ICAP from the loop? This echoing is probably a common case!
1005 makeAdaptedBodyPipe("echoed virgin response");
1006 if (oldHead->body_pipe->bodySizeKnown())
1007 adapted.body_pipe->setBodySize(oldHead->body_pipe->bodySize());
1008 debugs(93, 7, "will echo virgin body to " <<
1009 adapted.body_pipe);
1010 } else {
1011 debugs(93, 7, "no virgin body to echo");
1012 stopSending(true);
1013 }
1014}
1015
1019{
1020 Must(virginBodySending.active());
1021 Must(virgin.header->body_pipe != nullptr);
1022
1023 setOutcome(xoPartEcho);
1024
1025 debugs(93, 7, "will echo virgin body suffix from " <<
1026 virgin.header->body_pipe << " offset " << pos );
1027
1028 // check that use-original-body=N does not point beyond buffered data
1029 const uint64_t virginDataEnd = virginConsumed +
1030 virgin.body_pipe->buf().contentSize();
1031 Must(pos <= virginDataEnd);
1032 virginBodySending.progress(static_cast<size_t>(pos));
1033
1034 state.sending = State::sendingVirgin;
1035 checkConsuming();
1036
1037 if (virgin.header->body_pipe->bodySizeKnown())
1038 adapted.body_pipe->expectProductionEndAfter(virgin.header->body_pipe->bodySize() - pos);
1039
1040 debugs(93, 7, "will echo virgin body suffix to " <<
1041 adapted.body_pipe);
1042
1043 // Start echoing data
1044 echoMore();
1045}
1046
1048{
1049 stopParsing(false);
1050 stopBackup();
1051 // TODO: mark connection as "bad"
1052
1053 // Terminate the transaction; we do not know how to handle this response.
1054 throw TexcHere("Unsupported ICAP status code");
1055}
1056
1058{
1059 if (expectHttpHeader()) {
1060 replyHttpHeaderSize = 0;
1061 maybeAllocateHttpMsg();
1062
1063 if (!parseHead(adapted.header))
1064 return; // need more header data
1065
1066 if (adapted.header)
1067 replyHttpHeaderSize = adapted.header->hdr_sz;
1068
1069 if (dynamic_cast<HttpRequest*>(adapted.header)) {
1070 const HttpRequest *oldR = dynamic_cast<const HttpRequest*>(virgin.header);
1071 Must(oldR);
1072 // TODO: the adapted request did not really originate from the
1073 // client; give proxy admin an option to prevent copying of
1074 // sensitive client information here. See the following thread:
1075 // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html
1076 }
1077
1078 // Maybe adapted.header==NULL if HttpReply and have Http 0.9 ....
1079 if (adapted.header)
1080 adapted.header->inheritProperties(virgin.header);
1081 }
1082
1083 decideOnParsingBody();
1084}
1085
1086template<class Part>
1087bool Adaptation::Icap::ModXact::parsePart(Part *part, const char *description)
1088{
1089 Must(part);
1090 debugs(93, 5, "have " << readBuf.length() << ' ' << description << " bytes to parse; state: " << state.parsing);
1092 // XXX: performance regression. c_str() data copies
1093 // XXX: Http::Message::parse requires a terminated string buffer
1094 const char *tmpBuf = readBuf.c_str();
1095 const bool parsed = part->parse(tmpBuf, readBuf.length(), commEof, &error);
1096 debugs(93, (!parsed && error) ? 2 : 5, description << " parsing result: " << parsed << " detail: " << error);
1097 Must(parsed || !error);
1098 if (parsed)
1099 readBuf.consume(part->hdr_sz);
1100 return parsed;
1101}
1102
1103// parses both HTTP and ICAP headers
1104bool
1106{
1107 if (!parsePart(head, "head")) {
1108 head->reset();
1109 return false;
1110 }
1111 return true;
1112}
1113
1115{
1116 return gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr");
1117}
1118
1120{
1121 return gotEncapsulated("res-body") || gotEncapsulated("req-body");
1122}
1123
1125{
1126 String trailers;
1127 const bool promisesToSendTrailer = icapReply->header.getByIdIfPresent(Http::HdrType::TRAILER, &trailers);
1128 const bool supportsTrailers = icapReply->header.hasListMember(Http::HdrType::ALLOW, "trailers", ',');
1129
1130 // ICAP Trailer extension specification says that "a client receiving a
1131 // Trailer header field without Allow/trailers in a response MAY treat the
1132 // response as syntactically malformed", and that is how we treat it here.
1133 if (promisesToSendTrailer && !supportsTrailers)
1134 throw TextException("ICAP response with an unsupported trailer", Here());
1135
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
1142{
1143 if (expectHttpBody()) {
1144 debugs(93, 5, "expecting a body");
1145 state.parsing = State::psBody;
1146 replyHttpBodySize = 0;
1147 bodyParser = new Http1::TeChunkedParser;
1148 bodyParser->parseExtensionValuesWith(&extensionParser);
1149 makeAdaptedBodyPipe("adapted response from the ICAP server");
1150 Must(state.sending == State::sendingAdapted);
1151 } else {
1152 debugs(93, 5, "not expecting a body");
1153 if (trailerParser)
1154 state.parsing = State::psIcapTrailer;
1155 else
1156 stopParsing();
1157 stopSending(true);
1158 }
1159}
1160
1162{
1163 Must(state.parsing == State::psBody);
1164 Must(bodyParser);
1165
1166 debugs(93, 5, "have " << readBuf.length() << " body bytes to parse");
1167
1168 // the parser will throw on errors
1169 BodyPipeCheckout bpc(*adapted.body_pipe);
1170 bodyParser->setPayloadBuffer(&bpc.buf);
1171 const bool parsed = bodyParser->parse(readBuf);
1172 readBuf = bodyParser->remaining(); // sync buffers after parse
1173 bpc.checkIn();
1174
1175 debugs(93, 5, "have " << readBuf.length() << " body bytes after parsed all: " << parsed);
1176 replyHttpBodySize += adapted.body_pipe->buf().contentSize();
1177
1178 // TODO: expose BodyPipe::putSize() to make this check simpler and clearer
1179 // TODO: do we really need this if we disable when sending headers?
1180 if (adapted.body_pipe->buf().contentSize() > 0) { // parsed something sometime
1181 disableRepeats("sent adapted content");
1182 disableBypass("sent adapted content", true);
1183 }
1184
1185 if (parsed) {
1186 if (state.readyForUob && extensionParser.sawUseOriginalBody())
1187 prepPartialBodyEchoing(extensionParser.useOriginalBody());
1188 else
1189 stopSending(true); // the parser succeeds only if all parsed data fits
1190 if (trailerParser)
1191 state.parsing = State::psIcapTrailer;
1192 else
1193 stopParsing();
1194 return;
1195 }
1196
1197 debugs(93,3, this << " needsMoreData = " << bodyParser->needsMoreData());
1198
1199 if (bodyParser->needsMoreData()) {
1200 debugs(93,3, this);
1201 Must(mayReadMore());
1202 readMore();
1203 }
1204
1205 if (bodyParser->needsMoreSpace()) {
1206 Must(!doneSending()); // can hope for more space
1207 Must(adapted.body_pipe->buf().contentSize() > 0); // paranoid
1208 // TODO: there should be a timeout in case the sink is broken
1209 // or cannot consume partial content (while we need more space)
1210 }
1211}
1212
1213void Adaptation::Icap::ModXact::stopParsing(const bool checkUnparsedData)
1214{
1215 if (state.parsing == State::psDone)
1216 return;
1217
1218 if (checkUnparsedData)
1219 Must(readBuf.isEmpty());
1220
1221 debugs(93, 7, "will no longer parse" << status());
1222
1223 delete bodyParser;
1224 bodyParser = nullptr;
1225
1226 delete trailerParser;
1227 trailerParser = nullptr;
1228
1229 state.parsing = State::psDone;
1230}
1231
1232// HTTP side added virgin body data
1234{
1235 writeMore();
1236
1237 if (state.sending == State::sendingVirgin)
1238 echoMore();
1239}
1240
1241// HTTP side sent us all virgin info
1243{
1244 Must(virgin.body_pipe->productionEnded());
1245
1246 // push writer and sender in case we were waiting for the last-chunk
1247 writeMore();
1248
1249 if (state.sending == State::sendingVirgin)
1250 echoMore();
1251}
1252
1253// body producer aborted, but the initiator may still want to know
1254// the answer, even though the HTTP message has been truncated
1256{
1257 Must(virgin.body_pipe->productionEnded());
1258
1259 // push writer and sender in case we were waiting for the last-chunk
1260 writeMore();
1261
1262 if (state.sending == State::sendingVirgin)
1263 echoMore();
1264}
1265
1266// adapted body consumer wants more adapted data and
1267// possibly freed some buffer space
1269{
1270 if (state.sending == State::sendingVirgin)
1271 echoMore();
1272 else if (state.sending == State::sendingAdapted)
1273 parseMore();
1274 else
1275 Must(state.sending == State::sendingUndecided);
1276}
1277
1278// adapted body consumer aborted
1280{
1281 static const auto d = MakeNamedErrorDetail("ICAP_XACT_BODY_CONSUMER_ABORT");
1282 detailError(d);
1283 mustStop("adapted body consumer aborted");
1284}
1285
1287{
1288 delete bodyParser;
1289 delete trailerParser;
1290}
1291
1292// internal cleanup
1294{
1295 debugs(93, 5, "swan sings" << status());
1296
1297 stopWriting(false);
1298 stopSending(false);
1299
1300 if (theInitiator.set()) { // we have not sent the answer to the initiator
1301 static const auto d = MakeNamedErrorDetail("ICAP_XACT_OTHER");
1302 detailError(d);
1303 }
1304
1305 // update adaptation history if start was called and we reserved a slot
1306 Adaptation::History::Pointer ah = virginRequest().adaptLogHistory();
1307 if (ah != nullptr && adaptHistoryId >= 0)
1308 ah->recordXactFinish(adaptHistoryId);
1309
1311}
1312
1314
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 != nullptr); // 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 USE_OPENSSL
1345 if (h->ssluser.size())
1346 al.cache.ssluser = h->ssluser.termedBuf();
1347#endif
1348 al.cache.code = h->logType;
1349
1350 const Http::Message *virgin_msg = dynamic_cast<HttpReply*>(virgin.header);
1351 if (!virgin_msg)
1352 virgin_msg = virgin_request_;
1353 assert(virgin_msg != virgin.cause);
1354 al.http.clientRequestSz.header = virgin_msg->hdr_sz;
1355 if (virgin_msg->body_pipe != nullptr)
1356 al.http.clientRequestSz.payloadData = virgin_msg->body_pipe->producedSize();
1357
1358 // leave al.icap.bodyBytesRead negative if no body
1359 if (replyHttpHeaderSize >= 0 || replyHttpBodySize >= 0) {
1360 const int64_t zero = 0; // to make max() argument types the same
1361 const uint64_t headerSize = max(zero, replyHttpHeaderSize);
1362 const uint64_t bodySize = max(zero, replyHttpBodySize);
1363 al.icap.bodyBytesRead = headerSize + bodySize;
1364 al.http.clientReplySz.header = headerSize;
1365 al.http.clientReplySz.payloadData = bodySize;
1366 }
1367
1368 if (adapted_reply_) {
1369 al.http.code = adapted_reply_->sline.status();
1370 al.http.content_type = adapted_reply_->content_type.termedBuf();
1371 if (replyHttpBodySize >= 0)
1372 al.cache.highOffset = replyHttpBodySize;
1373 //don't set al.cache.objectSize because it hasn't exist yet
1374 }
1375 prepareLogWithRequestDetails(adapted_request_, alep);
1377}
1378
1380{
1381 char ntoabuf[MAX_IPSTRLEN];
1382 /*
1383 * XXX These should use HttpHdr interfaces instead of Printfs
1384 */
1385 const Adaptation::ServiceConfig &s = service().cfg();
1386 buf.appendf("%s " SQUIDSTRINGPH " ICAP/1.0\r\n", s.methodStr(), SQUIDSTRINGPRINT(s.uri));
1387 buf.appendf("Host: " SQUIDSTRINGPH ":%d\r\n", SQUIDSTRINGPRINT(s.host), s.port);
1388 buf.appendf("Date: %s\r\n", Time::FormatRfc1123(squid_curtime));
1389
1391 buf.appendf("Connection: close\r\n");
1392
1393 const HttpRequest *request = &virginRequest();
1394
1395 // we must forward "Proxy-Authenticate" and "Proxy-Authorization"
1396 // as ICAP headers.
1397 if (virgin.header->header.has(Http::HdrType::PROXY_AUTHENTICATE)) {
1398 String vh=virgin.header->header.getById(Http::HdrType::PROXY_AUTHENTICATE);
1399 buf.appendf("Proxy-Authenticate: " SQUIDSTRINGPH "\r\n",SQUIDSTRINGPRINT(vh));
1400 }
1401
1402 if (virgin.header->header.has(Http::HdrType::PROXY_AUTHORIZATION)) {
1403 String vh=virgin.header->header.getById(Http::HdrType::PROXY_AUTHORIZATION);
1404 buf.appendf("Proxy-Authorization: " SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(vh));
1405 } else if (request->extacl_user.size() > 0 && request->extacl_passwd.size() > 0) {
1406 const auto userLen = request->extacl_user.size();
1407 const auto passwdLen = request->extacl_passwd.size();
1408 // +1 for the ':' separator between user and passwd
1409 const auto plainLen = userLen + 1 + passwdLen;
1410 if (plainLen > MAX_LOGIN_SZ)
1411 throw TextException("extacl credentials too long for Proxy-Authorization", Here());
1412 char base64buf[base64_encode_len(MAX_LOGIN_SZ)];
1413 struct base64_encode_ctx ctx;
1414 base64_encode_init(&ctx);
1415 auto resultLen = base64_encode_update(&ctx, base64buf, userLen, reinterpret_cast<const uint8_t*>(request->extacl_user.rawBuf()));
1416 resultLen += base64_encode_update(&ctx, base64buf+resultLen, 1, reinterpret_cast<const uint8_t*>(":"));
1417 resultLen += base64_encode_update(&ctx, base64buf+resultLen, passwdLen, reinterpret_cast<const uint8_t*>(request->extacl_passwd.rawBuf()));
1418 resultLen += base64_encode_final(&ctx, base64buf+resultLen);
1419 buf.appendf("Proxy-Authorization: Basic %.*s\r\n", (int)resultLen, base64buf);
1420 }
1421
1422 // share the cross-transactional database records if needed
1424 Adaptation::History::Pointer ah = request->adaptHistory(false);
1425 if (ah != nullptr) {
1426 String name, value;
1427 if (ah->getXxRecord(name, value)) {
1429 }
1430 }
1431 }
1432
1433 buf.append("Encapsulated: ", 14);
1434
1435 MemBuf httpBuf;
1436
1437 httpBuf.init();
1438
1439 // build HTTP request header, if any
1440 ICAP::Method m = s.method;
1441
1442 // to simplify, we could assume that request is always available
1443
1444 if (request) {
1445 if (ICAP::methodRespmod == m)
1446 encapsulateHead(buf, "req-hdr", httpBuf, request);
1447 else if (ICAP::methodReqmod == m)
1448 encapsulateHead(buf, "req-hdr", httpBuf, virgin.header);
1449 }
1450
1451 if (ICAP::methodRespmod == m)
1452 if (const Http::Message *prime = virgin.header)
1453 encapsulateHead(buf, "res-hdr", httpBuf, prime);
1454
1455 if (!virginBody.expected())
1456 buf.appendf("null-body=%d", (int) httpBuf.contentSize());
1457 else if (ICAP::methodReqmod == m)
1458 buf.appendf("req-body=%d", (int) httpBuf.contentSize());
1459 else
1460 buf.appendf("res-body=%d", (int) httpBuf.contentSize());
1461
1462 buf.append(ICAP::crlf, 2); // terminate Encapsulated line
1463
1464 if (preview.enabled()) {
1465 buf.appendf("Preview: %d\r\n", (int)preview.ad());
1466 if (!virginBody.expected()) // there is no body to preview
1467 finishNullOrEmptyBodyPreview(httpBuf);
1468 }
1469
1470 makeAllowHeader(buf);
1471
1472 if (TheConfig.send_client_ip && request) {
1473 Ip::Address client_addr;
1474#if FOLLOW_X_FORWARDED_FOR
1476 client_addr = request->indirect_client_addr;
1477 } else
1478#endif
1479 client_addr = request->client_addr;
1480 if (!client_addr.isAnyAddr() && !client_addr.isNoAddr())
1481 buf.appendf("X-Client-IP: %s\r\n", client_addr.toStr(ntoabuf,MAX_IPSTRLEN));
1482 }
1483
1484 if (TheConfig.send_username && request)
1485 makeUsernameHeader(request, buf);
1486
1487 // Adaptation::Config::metaHeaders
1488 for (const auto &h: Adaptation::Config::metaHeaders()) {
1489 HttpRequest *r = virgin.cause ?
1490 virgin.cause : dynamic_cast<HttpRequest*>(virgin.header);
1491 Must(r);
1492
1493 HttpReply *reply = dynamic_cast<HttpReply*>(virgin.header);
1494
1495 SBuf matched;
1496 if (h->match(r, reply, alMaster, matched)) {
1497 buf.append(h->key().rawContent(), h->key().length());
1498 buf.append(": ", 2);
1499 buf.append(matched.rawContent(), matched.length());
1500 buf.append("\r\n", 2);
1501 Adaptation::History::Pointer ah = request->adaptHistory(false);
1502 if (ah != nullptr) {
1503 if (ah->metaHeaders == nullptr)
1504 ah->metaHeaders = new NotePairs;
1505 if (!ah->metaHeaders->hasPair(h->key(), matched))
1506 ah->metaHeaders->add(h->key(), matched);
1507 }
1508 }
1509 }
1510
1511 // fprintf(stderr, "%s\n", buf.content());
1512
1513 buf.append(ICAP::crlf, 2); // terminate ICAP header
1514
1515 // fill icapRequest for logging
1516 Must(icapRequest->parseCharBuf(buf.content(), buf.contentSize()));
1517
1518 // start ICAP request body with encapsulated HTTP headers
1519 buf.append(httpBuf.content(), httpBuf.contentSize());
1520
1521 httpBuf.clean();
1522}
1523
1524// decides which Allow values to write and updates the request buffer
1526{
1527 const bool allow204in = preview.enabled(); // TODO: add shouldAllow204in()
1528 const bool allow204out = state.allowedPostview204 = shouldAllow204();
1529 const bool allow206in = state.allowedPreview206 = shouldAllow206in();
1530 const bool allow206out = state.allowedPostview206 = shouldAllow206out();
1531 const bool allowTrailers = true; // TODO: make configurable
1532
1533 debugs(93, 9, "Allows: " << allow204in << allow204out <<
1534 allow206in << allow206out << allowTrailers);
1535
1536 const bool allow204 = allow204in || allow204out;
1537 const bool allow206 = allow206in || allow206out;
1538
1539 if ((allow204 || allow206) && virginBody.expected())
1540 virginBodySending.plan(); // if there is a virgin body, plan to send it
1541
1542 // writing Preview:... means we will honor 204 inside preview
1543 // writing Allow/204 means we will honor 204 outside preview
1544 // writing Allow:206 means we will honor 206 inside preview
1545 // writing Allow:204,206 means we will honor 206 outside preview
1546 if (allow204 || allow206 || allowTrailers) {
1547 buf.appendf("Allow: ");
1548 if (allow204out)
1549 buf.appendf("204, ");
1550 if (allow206)
1551 buf.appendf("206, ");
1552 if (allowTrailers)
1553 buf.appendf("trailers");
1554 buf.appendf("\r\n");
1555 }
1556}
1557
1559{
1560#if USE_AUTH
1561 struct base64_encode_ctx ctx;
1562 base64_encode_init(&ctx);
1563
1564 const char *value = nullptr;
1565 if (request->auth_user_request != nullptr) {
1566 value = request->auth_user_request->username();
1567 } else if (request->extacl_user.size() > 0) {
1568 value = request->extacl_user.termedBuf();
1569 }
1570
1571 if (value) {
1573 const auto valueLen = strlen(value);
1574 if (valueLen > MAX_LOGIN_SZ)
1575 throw TextException("username too long for X-Client-Username header", Here());
1576 char base64buf[base64_encode_len(MAX_LOGIN_SZ)];
1577 size_t resultLen = base64_encode_update(&ctx, base64buf, valueLen, reinterpret_cast<const uint8_t*>(value));
1578 resultLen += base64_encode_final(&ctx, base64buf+resultLen);
1579 buf.appendf("%s: %.*s\r\n", TheConfig.client_username_header, (int)resultLen, base64buf);
1580 } else
1581 buf.appendf("%s: %s\r\n", TheConfig.client_username_header, value);
1582 }
1583#else
1584 (void)request;
1585 (void)buf;
1586#endif
1587}
1588
1589void
1590Adaptation::Icap::ModXact::encapsulateHead(MemBuf &icapBuf, const char *section, MemBuf &httpBuf, const Http::Message *head)
1591{
1592 // update ICAP header
1593 icapBuf.appendf("%s=%d, ", section, (int) httpBuf.contentSize());
1594
1595 // begin cloning
1596 Http::MessagePointer headClone;
1597
1598 if (const HttpRequest* old_request = dynamic_cast<const HttpRequest*>(head)) {
1599 HttpRequest::Pointer new_request(new HttpRequest(old_request->masterXaction));
1600 // copy the request-line details
1601 new_request->method = old_request->method;
1602 new_request->url = old_request->url;
1603 new_request->http_ver = old_request->http_ver;
1604 headClone = new_request.getRaw();
1605 } else if (const HttpReply *old_reply = dynamic_cast<const HttpReply*>(head)) {
1606 HttpReply::Pointer new_reply(new HttpReply);
1607 new_reply->sline = old_reply->sline;
1608 headClone = new_reply.getRaw();
1609 }
1610 Must(headClone);
1611 headClone->inheritProperties(head);
1612
1614 while (HttpHeaderEntry* p_head_entry = head->header.getEntry(&pos))
1615 headClone->header.addEntry(p_head_entry->clone());
1616
1617 // end cloning
1618
1619 // remove all hop-by-hop headers from the clone
1621 headClone->header.removeHopByHopEntries();
1622
1623 // TODO: modify HttpHeader::removeHopByHopEntries to accept a list of
1624 // excluded hop-by-hop headers
1625 if (head->header.has(Http::HdrType::UPGRADE)) {
1626 const auto upgrade = head->header.getList(Http::HdrType::UPGRADE);
1627 headClone->header.putStr(Http::HdrType::UPGRADE, upgrade.termedBuf());
1628 }
1629
1630 // pack polished HTTP header
1631 packHead(httpBuf, headClone.getRaw());
1632
1633 // headClone unlocks and, hence, deletes the message we packed
1634}
1635
1636void
1638{
1639 head->packInto(&httpBuf, true);
1640}
1641
1642// decides whether to offer a preview and calculates its size
1644{
1646 debugs(93, 5, "preview disabled by squid.conf");
1647 return;
1648 }
1649
1650 size_t wantedSize;
1651 if (!service().wantsPreview(virginRequest().url.absolutePath(), wantedSize)) {
1652 debugs(93, 5, "should not offer preview for " << virginRequest().url.absolutePath());
1653 return;
1654 }
1655
1656 // we decided to do preview, now compute its size
1657
1658 // cannot preview more than we can backup
1659 size_t ad = min(wantedSize, TheBackupLimit);
1660
1661 if (!virginBody.expected())
1662 ad = 0;
1663 else if (virginBody.knownSize())
1664 ad = min(static_cast<uint64_t>(ad), virginBody.size()); // not more than we have
1665
1666 debugs(93, 5, "should offer " << ad << "-byte preview " <<
1667 "(service wanted " << wantedSize << ")");
1668
1669 preview.enable(ad);
1670 Must(preview.enabled());
1671}
1672
1673// decides whether to allow 204 responses
1675{
1676 if (!service().allows204())
1677 return false;
1678
1679 return canBackupEverything();
1680}
1681
1682// decides whether to allow 206 responses in some mode
1684{
1685 return TheConfig.allow206_enable && service().allows206() &&
1686 virginBody.expected(); // no need for 206 without a body
1687}
1688
1689// decides whether to allow 206 responses in preview mode
1691{
1692 return shouldAllow206any() && preview.enabled();
1693}
1694
1695// decides whether to allow 206 responses outside of preview
1697{
1698 return shouldAllow206any() && canBackupEverything();
1699}
1700
1701// used by shouldAllow204 and decideOnRetries
1703{
1704 if (!virginBody.expected())
1705 return true; // no body means no problems with backup
1706
1707 // if there is a body, check whether we can backup it all
1708
1709 if (!virginBody.knownSize())
1710 return false;
1711
1712 // or should we have a different backup limit?
1713 // note that '<' allows for 0-termination of the "full" backup buffer
1714 return virginBody.size() < TheBackupLimit;
1715}
1716
1717// Decide whether this transaction can be retried if pconn fails
1718// Must be called after decideOnPreview and before openConnection()
1720{
1721 if (!isRetriable)
1722 return; // no, already decided
1723
1724 if (preview.enabled())
1725 return; // yes, because preview provides enough guarantees
1726
1727 if (canBackupEverything())
1728 return; // yes, because we can back everything up
1729
1730 disableRetries(); // no, because we cannot back everything up
1731}
1732
1733// Normally, the body-writing code handles preview body. It can deal with
1734// bodies of unexpected size, including those that turn out to be empty.
1735// However, that code assumes that the body was expected and body control
1736// structures were initialized. This is not the case when there is no body
1737// or the body is known to be empty, because the virgin message will lack a
1738// body_pipe. So we handle preview of null-body and zero-size bodies here.
1740{
1741 Must(!virginBodyWriting.active()); // one reason we handle it here
1742 Must(!virgin.body_pipe); // another reason we handle it here
1743 Must(!preview.ad());
1744
1745 // do not add last-chunk because our Encapsulated header says null-body
1746 // addLastRequestChunk(buf);
1747 preview.wrote(0, true);
1748
1749 Must(preview.done());
1750 Must(preview.ieof());
1751}
1752
1754{
1756
1757 if (state.serviceWaiting)
1758 buf.append("U", 1);
1759
1760 if (virgin.body_pipe != nullptr)
1761 buf.append("R", 1);
1762
1763 if (haveConnection() && !doneReading())
1764 buf.append("r", 1);
1765
1766 if (!state.doneWriting() && state.writing != State::writingInit)
1767 buf.appendf("w(%d)", state.writing);
1768
1769 if (preview.enabled()) {
1770 if (!preview.done())
1771 buf.appendf("P(%d)", (int) preview.debt());
1772 }
1773
1774 if (virginBodySending.active())
1775 buf.append("B", 1);
1776
1777 if (!state.doneParsing() && state.parsing != State::psIcapHeader)
1778 buf.appendf("p(%d)", state.parsing);
1779
1780 if (!doneSending() && state.sending != State::sendingUndecided)
1781 buf.appendf("S(%d)", state.sending);
1782
1783 if (state.readyForUob)
1784 buf.append("6", 1);
1785
1786 if (canStartBypass)
1787 buf.append("Y", 1);
1788
1789 if (protectGroupBypass)
1790 buf.append("G", 1);
1791}
1792
1794{
1796
1797 if (!virgin.body_pipe)
1798 buf.append("R", 1);
1799
1800 if (state.doneWriting())
1801 buf.append("w", 1);
1802
1803 if (preview.enabled()) {
1804 if (preview.done())
1805 buf.appendf("P%s", preview.ieof() ? "(ieof)" : "");
1806 }
1807
1808 if (doneReading())
1809 buf.append("r", 1);
1810
1811 if (state.doneParsing())
1812 buf.append("p", 1);
1813
1814 if (doneSending())
1815 buf.append("S", 1);
1816}
1817
1818bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section) const
1819{
1820 return !icapReply->header.getByNameListMember("Encapsulated",
1821 section, ',').isEmpty();
1822}
1823
1824// calculate whether there is a virgin HTTP body and
1825// whether its expected size is known
1826// TODO: rename because we do not just estimate
1828{
1829 // note: lack of size info may disable previews and 204s
1830
1831 Http::Message *msg = virgin.header;
1832 Must(msg);
1833
1834 HttpRequestMethod method;
1835
1836 if (virgin.cause)
1837 method = virgin.cause->method;
1838 else if (HttpRequest *req = dynamic_cast<HttpRequest*>(msg))
1839 method = req->method;
1840 else
1841 method = Http::METHOD_NONE;
1842
1843 int64_t size;
1844 // expectingBody returns true for zero-sized bodies, but we will not
1845 // get a pipe for that body, so we treat the message as bodyless
1846 if (method != Http::METHOD_NONE && msg->expectingBody(method, size) && size) {
1847 debugs(93, 6, "expects virgin body from " <<
1848 virgin.body_pipe << "; size: " << size);
1849
1850 virginBody.expect(size);
1851 virginBodyWriting.plan();
1852
1853 // sign up as a body consumer
1854 Must(msg->body_pipe != nullptr);
1855 Must(msg->body_pipe == virgin.body_pipe);
1856 Must(virgin.body_pipe->setConsumerIfNotLate(this));
1857
1858 // make sure TheBackupLimit is in-sync with the buffer size
1859 Must(TheBackupLimit <= static_cast<size_t>(msg->body_pipe->buf().max_capacity));
1860 } else {
1861 debugs(93, 6, "does not expect virgin body");
1862 Must(msg->body_pipe == nullptr);
1863 checkConsuming();
1864 }
1865}
1866
1868{
1869 Must(!adapted.body_pipe);
1870 Must(!adapted.header->body_pipe);
1871 adapted.header->body_pipe = new BodyPipe(this);
1872 adapted.body_pipe = adapted.header->body_pipe;
1873 debugs(93, 7, "will supply " << what << " via " <<
1874 adapted.body_pipe << " pipe");
1875}
1876
1877// TODO: Move SizedEstimate and Preview elsewhere
1878
1880 : theData(dtUnexpected)
1881{}
1882
1884{
1885 theData = (aSize >= 0) ? aSize : (int64_t)dtUnknown;
1886}
1887
1889{
1890 return theData != dtUnexpected;
1891}
1892
1894{
1895 Must(expected());
1896 return theData != dtUnknown;
1897}
1898
1900{
1901 Must(knownSize());
1902 return static_cast<uint64_t>(theData);
1903}
1904
1905Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided)
1906{}
1907
1909{
1910 Must(!disabled());
1911 Must(!theStart); // not started
1912 theState = stActive;
1913}
1914
1916{
1917 theState = stDisabled;
1918}
1919
1921{
1922 Must(active());
1923#if SIZEOF_SIZE_T > 4
1924 /* always true for smaller size_t's */
1925 Must(static_cast<int64_t>(size) >= 0);
1926#endif
1927 theStart += static_cast<int64_t>(size);
1928}
1929
1931{
1932 Must(active());
1933 return static_cast<uint64_t>(theStart);
1934}
1935
1936Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled)
1937{}
1938
1939void Adaptation::Icap::Preview::enable(size_t anAdvertisedSize)
1940{
1941 // TODO: check for anAdvertisedSize not exceeding preview size limit
1942 Must(!enabled());
1943 theAd = anAdvertisedSize;
1944 theState = stWriting;
1945}
1946
1948{
1949 return theState != stDisabled;
1950}
1951
1953{
1954 Must(enabled());
1955 return theAd;
1956}
1957
1959{
1960 Must(enabled());
1961 return theState >= stIeof;
1962}
1963
1965{
1966 Must(enabled());
1967 return theState == stIeof;
1968}
1969
1971{
1972 Must(enabled());
1973 return done() ? 0 : (theAd - theWritten);
1974}
1975
1976void Adaptation::Icap::Preview::wrote(size_t size, bool wroteEof)
1977{
1978 Must(enabled());
1979
1980 theWritten += size;
1981
1982 Must(theWritten <= theAd);
1983
1984 if (wroteEof)
1985 theState = stIeof; // written size is irrelevant
1986 else if (theWritten >= theAd)
1987 theState = stDone;
1988}
1989
1991{
1992 if (virgin.header == nullptr)
1993 return false;
1994
1995 virgin.header->firstLineBuf(mb);
1996
1997 return true;
1998}
1999
2001{
2002 HttpRequest *request = dynamic_cast<HttpRequest*>(adapted.header);
2003 // if no adapted request, update virgin (and inherit its properties later)
2004 // TODO: make this and HttpRequest::detailError constant, like adaptHistory
2005 if (!request)
2006 request = const_cast<HttpRequest*>(&virginRequest());
2007
2008 if (request)
2009 request->detailError(ERR_ICAP_FAILURE, errDetail);
2010}
2011
2013{
2014 HttpRequest *request = dynamic_cast<HttpRequest*>(adapted.header);
2015 // if no adapted request, update virgin (and inherit its properties later)
2016 if (!request)
2017 request = const_cast<HttpRequest*>(&virginRequest());
2018
2019 if (request)
2020 request->clearError();
2021}
2022
2024{
2025 Must(adapted.header);
2026 adapted.header->sources |= (service().cfg().connectionEncryption ? Http::Message::srcIcaps : Http::Message::srcIcap);
2027}
2028
2029/* Adaptation::Icap::ModXactLauncher */
2030
2032 AsyncJob("Adaptation::Icap::ModXactLauncher"),
2033 Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", aService),
2034 al(alp)
2035{
2036 virgin.setHeader(virginHeader);
2037 virgin.setCause(virginCause);
2038 updateHistory(true);
2039}
2040
2042{
2044 dynamic_cast<Adaptation::Icap::ServiceRep*>(theService.getRaw());
2045 Must(s != nullptr);
2046 return new Adaptation::Icap::ModXact(virgin.header, virgin.cause, al, s);
2047}
2048
2050{
2051 debugs(93, 5, "swan sings");
2052 updateHistory(false);
2054}
2055
2057{
2058 HttpRequest *r = virgin.cause ?
2059 virgin.cause : dynamic_cast<HttpRequest*>(virgin.header);
2060
2061 // r should never be NULL but we play safe; TODO: add Should()
2062 if (r) {
2064 if (h != nullptr) {
2065 if (doStart)
2066 h->start("ICAPModXactLauncher");
2067 else
2068 h->stop("ICAPModXactLauncher");
2069 }
2070 }
2071}
2072
2073bool Adaptation::Icap::TrailerParser::parse(const char *buf, int len, int atEnd, Http::StatusCode *error) {
2075 // RFC 7230 section 4.1.2: MUST NOT generate a trailer that contains
2076 // a field necessary for message framing (e.g., Transfer-Encoding and Content-Length)
2077 clen.applyTrailerRules();
2078 const int parsed = trailer.parse(buf, len, atEnd, hdr_sz, clen);
2079 if (parsed < 0)
2080 *error = Http::scInvalidHeader; // TODO: should we add a new Http::scInvalidTrailer?
2081 return parsed > 0;
2082}
2083
2084void
2086{
2087 if (extName == UseOriginalBodyName) {
2088 useOriginalBody_ = tok.udec64("use-original-body");
2089 assert(useOriginalBody_ >= 0);
2090 } else {
2091 Ignore(tok, extName);
2092 }
2093}
2094
#define JobCallback(dbgSection, dbgLevel, Dialer, job, method)
Convenience macro to create a Dialer-based job callback.
ErrorDetail::Pointer MakeNamedErrorDetail(const char *name)
Definition Detail.cc:54
#define Here()
source code location of the caller
Definition Here.h:15
bool httpHeaderHasConnDir(const HttpHeader *hdr, const SBuf &directive)
ssize_t HttpHeaderPos
Definition HttpHeader.h:45
#define HttpHeaderInitPos
Definition HttpHeader.h:48
int size
Definition ModDevPoll.cc:70
void prepareLogWithRequestDetails(HttpRequest *, const AccessLogEntryPointer &)
static constexpr auto TheBackupLimit
Definition ModXact.cc:45
time_t squid_curtime
#define SQUIDSTRINGPH
Definition SquidString.h:22
#define SQUIDSTRINGPRINT(s)
Definition SquidString.h:23
#define TexcHere(msg)
legacy convenience macro; it is not difficult to type Here() now
#define Must(condition)
void error(char *format,...)
squidaio_request_t * head
Definition aiops.cc:129
#define assert(EX)
Definition assert.h:17
#define SQUID_TCP_SO_RCVBUF
Definition autoconf.h:1445
void base64_encode_init(struct base64_encode_ctx *ctx)
Definition base64.cc:232
size_t base64_encode_update(struct base64_encode_ctx *ctx, char *dst, size_t length, const uint8_t *src)
Definition base64.cc:265
size_t base64_encode_final(struct base64_encode_ctx *ctx, char *dst)
Definition base64.cc:308
#define base64_encode_len(length)
Definition base64.h:161
#define CBDATA_NAMESPACED_CLASS_INIT(namespace, type)
Definition cbdata.h:333
static Answer Forward(Http::Message *aMsg)
create an akForward answer
Definition Answer.cc:26
static int send_client_ip
Definition Config.h:47
static int use_indirect_client
Definition Config.h:49
static int send_username
Definition Config.h:48
static char * masterx_shared_name
Definition Config.h:45
static Notes & metaHeaders()
The list of configured meta headers.
Definition Config.cc:35
int recordXactStart(const String &serviceId, const timeval &when, bool retrying)
record the start of a xact, return xact history ID
Definition History.cc:51
void updateXxRecord(const char *name, const String &value)
sets or resets a cross-transactional database record
Definition History.cc:105
NotePairs::Pointer metaHeaders
Definition History.h:66
bool getXxRecord(String &name, String &value) const
returns true and fills the record fields iff there is a db record
Definition History.cc:111
void updateNextServices(const String &services)
sets or resets next services for the Adaptation::Iterator to notice
Definition History.cc:121
void recordMeta(const HttpHeader *lm)
store the last meta header fields received from the adaptation service
Definition History.cc:140
void recordXactFinish(int hid)
record the end of a xact identified by its history ID
Definition History.cc:61
void parse(Tokenizer &tok, const SBuf &extName) override
extracts and then interprets (or ignores) the extension value
Definition ModXact.cc:2085
char * client_username_header
Definition Config.h:36
String log_uri
the request uri
Definition History.h:44
void start(const char *context)
record the start of an ICAP processing interval
Definition History.cc:23
void stop(const char *context)
note the end of an ICAP processing interval
Definition History.cc:32
String ssluser
the username from SSL
Definition History.h:40
LogTags logType
the squid request status (TCP_MISS etc)
Definition History.h:42
void setHeader(Header *h)
Definition InOut.h:48
void setCause(HttpRequest *r)
Definition InOut.h:38
void swanSong() override
Definition Launcher.cc:105
void updateHistory(bool start)
starts or stops transaction accounting in ICAP history
Definition ModXact.cc:2056
Xaction * createXaction() override
Definition ModXact.cc:2041
ModXactLauncher(Http::Message *virginHeader, HttpRequest *virginCause, AccessLogEntry::Pointer &alp, Adaptation::ServicePointer s)
Definition ModXact.cc:2031
void swanSong() override
Definition ModXact.cc:1293
const char * virginContentData(const VirginBodyAct &act) const
Definition ModXact.cc:416
void openChunk(MemBuf &buf, size_t chunkSize, bool ieof)
Definition ModXact.cc:376
void noteMoreBodyDataAvailable(BodyPipe::Pointer) override
Definition ModXact.cc:1233
void start() override
called by AsyncStart; do not call directly
Definition ModXact.cc:88
void packHead(MemBuf &httpBuf, const Http::Message *head)
Definition ModXact.cc:1637
TrailerParser * trailerParser
Definition ModXact.h:321
void stopWriting(bool nicely)
Definition ModXact.cc:482
void noteBodyProductionEnded(BodyPipe::Pointer) override
Definition ModXact.cc:1242
Http1::TeChunkedParser * bodyParser
Definition ModXact.h:303
bool doneAll() const override
whether positive goal has been reached
Definition ModXact.cc:524
void makeAllowHeader(MemBuf &buf)
Definition ModXact.cc:1525
void clearError() override
clear stored error details, if any; used for retries/repeats
Definition ModXact.cc:2012
void writeSomeBody(const char *label, size_t size)
Definition ModXact.cc:319
void callException(const std::exception &e) override
called when the job throws during an async call
Definition ModXact.cc:661
bool expectHttpBody() const
whether ICAP response header indicates HTTP body presence
Definition ModXact.cc:1119
bool parseHead(Http::Message *head)
Definition ModXact.cc:1105
bool fillVirginHttpHeader(MemBuf &) const override
Definition ModXact.cc:1990
void stopSending(bool nicely)
Definition ModXact.cc:610
bool virginBodyEndReached(const VirginBodyAct &act) const
Definition ModXact.cc:395
bool gotEncapsulated(const char *section) const
Definition ModXact.cc:1818
AccessLogEntry::Pointer alMaster
Master transaction AccessLogEntry.
Definition ModXact.h:373
void updateSources()
Update the Http::Message sources.
Definition ModXact.cc:2023
void stopParsing(const bool checkUnparsedData=true)
Definition ModXact.cc:1213
bool parsePart(Part *part, const char *description)
Definition ModXact.cc:1087
void startShoveling() override
starts sending/receiving ICAP messages
Definition ModXact.cc:189
bool doneSending() const
Definition ModXact.cc:604
void detailError(const ErrorDetail::Pointer &errDetail) override
record error detail in the virgin request if possible
Definition ModXact.cc:2000
int adaptHistoryId
adaptation history slot reservation
Definition ModXact.h:319
void closeChunk(MemBuf &buf)
Definition ModXact.cc:381
void addLastRequestChunk(MemBuf &buf)
Definition ModXact.cc:369
void disableBypass(const char *reason, bool includeGroupBypass)
Definition ModXact.cc:713
bool canBackupEverything() const
Definition ModXact.cc:1702
bool expectHttpHeader() const
whether ICAP response header indicates HTTP header presence
Definition ModXact.cc:1114
void noteBodyConsumerAborted(BodyPipe::Pointer) override
Definition ModXact.cc:1279
ModXact(Http::Message *virginHeader, HttpRequest *virginCause, AccessLogEntry::Pointer &alp, ServiceRep::Pointer &s)
Definition ModXact.cc:54
size_t virginContentSize(const VirginBodyAct &act) const
Definition ModXact.cc:404
void handleCommRead(size_t size) override
Definition ModXact.cc:563
void fillDoneStatus(MemBuf &buf) const override
Definition ModXact.cc:1793
void prepPartialBodyEchoing(uint64_t pos)
Definition ModXact.cc:1018
bool expectIcapTrailers() const
whether ICAP response header indicates ICAP trailers presence
Definition ModXact.cc:1124
void fillPendingStatus(MemBuf &buf) const override
Definition ModXact.cc:1753
void noteMoreBodySpaceAvailable(BodyPipe::Pointer) override
Definition ModXact.cc:1268
void makeRequestHeaders(MemBuf &buf)
Definition ModXact.cc:1379
void encapsulateHead(MemBuf &icapBuf, const char *section, MemBuf &httpBuf, const Http::Message *head)
Definition ModXact.cc:1590
void finishNullOrEmptyBodyPreview(MemBuf &buf)
Definition ModXact.cc:1739
void noteBodyProducerAborted(BodyPipe::Pointer) override
Definition ModXact.cc:1255
void makeAdaptedBodyPipe(const char *what)
Definition ModXact.cc:1867
void makeUsernameHeader(const HttpRequest *request, MemBuf &buf)
Definition ModXact.cc:1558
void handleCommWrote(size_t size) override
Definition ModXact.cc:208
void finalizeLogInfo() override
Definition ModXact.cc:1315
void decideWritingAfterPreview(const char *previewKind)
determine state.writing after we wrote the entire preview
Definition ModXact.cc:292
const HttpRequest & virginRequest() const
locates the request, either as a cause or as a virgin message itself
Definition ModXact.cc:386
void enable(size_t anAdvertisedSize)
Definition ModXact.cc:1939
void wrote(size_t size, bool wroteEof)
Definition ModXact.cc:1976
void expect(int64_t aSize)
Definition ModXact.cc:1883
Parses and stores ICAP trailer header block.
Definition ModXact.h:111
bool parse(const char *buf, int len, int atEnd, Http::StatusCode *error)
Definition ModXact.cc:2073
void start() override
called by AsyncStart; do not call directly
Definition Xaction.cc:131
void callException(const std::exception &e) override
called when the job throws during an async call
Definition Xaction.cc:373
HttpReply::Pointer icapReply
received ICAP reply, if any
Definition Xaction.h:64
bool doneAll() const override
whether positive goal has been reached
Definition Xaction.cc:389
void swanSong() override
Definition Xaction.cc:574
virtual void fillDoneStatus(MemBuf &buf) const
Definition Xaction.cc:668
const char * status() const override
internal cleanup; do not call directly
Definition Xaction.cc:636
virtual void fillPendingStatus(MemBuf &buf) const
Definition Xaction.cc:650
virtual void finalizeLogInfo()
Definition Xaction.cc:613
const char * methodStr() const
const ServiceConfig & cfg() const
Definition Service.h:51
char const * username() const
MemBuf & buf
Definition BodyPipe.h:74
uint64_t producedSize() const
Definition BodyPipe.h:112
const MemBuf & buf() const
Definition BodyPipe.h:137
static constexpr size_t MaxCapacity
Definition BodyPipe.h:100
bool bodySizeKnown() const
Definition BodyPipe.h:109
void consume(size_t size)
Definition BodyPipe.cc:309
const char * status() const
Definition BodyPipe.cc:446
uint64_t bodySize() const
Definition BodyPipe.cc:161
void removeHopByHopEntries()
void putStr(Http::HdrType id, const char *str)
int delById(Http::HdrType id)
void addEntry(HttpHeaderEntry *e)
Http::StatusLine sline
Definition HttpReply.h:56
String content_type
Definition HttpReply.h:46
String protoPrefix
Definition HttpReply.h:60
Adaptation::History::Pointer adaptHistory(bool createIfNone=false) const
Returns possibly nil history, creating it if requested.
void clearError()
clear error details, useful for retries/repeats
HttpRequestMethod method
Ip::Address indirect_client_addr
String extacl_user
String extacl_passwd
void detailError(const err_type c, const ErrorDetail::Pointer &d)
sets error detail if no earlier detail was available
Adaptation::History::Pointer adaptLogHistory() const
Returns possibly nil history, creating it if adapt. logging is enabled.
Auth::UserRequest::Pointer auth_user_request
Adaptation::Icap::History::Pointer icapHistory() const
Returns possibly nil history, creating it if icap logging is enabled.
AnyP::Uri url
the request URI
Ip::Address client_addr
void applyTrailerRules()
prohibits Content-Length in GET/HEAD requests
common parts of HttpRequest and HttpReply
Definition Message.h:26
@ srcIcaps
Secure ICAP service.
Definition Message.h:35
@ srcIcap
traditional ICAP service without encryption
Definition Message.h:41
virtual bool expectingBody(const HttpRequestMethod &, int64_t &) const =0
HttpHeader header
Definition Message.h:74
virtual bool inheritProperties(const Http::Message *)=0
BodyPipe::Pointer body_pipe
optional pipeline to receive message body
Definition Message.h:97
AnyP::ProtocolVersion http_ver
Definition Message.h:72
void parseExtensionValuesWith(ChunkExtensionValueParser *parser)
Http::StatusCode status() const
retrieve the status code for this status line
Definition StatusLine.h:45
char * toStr(char *buf, const unsigned int blen, int force=AF_UNSPEC) const
Definition Address.cc:804
bool isNoAddr() const
Definition Address.cc:304
bool isAnyAddr() const
Definition Address.cc:190
void clean()
Definition MemBuf.cc:110
void append(const char *c, int sz) override
Definition MemBuf.cc:209
void init(mb_size_t szInit, mb_size_t szMax)
Definition MemBuf.cc:93
char * content()
start of the added data
Definition MemBuf.h:41
mb_size_t max_capacity
Definition MemBuf.h:142
mb_size_t contentSize() const
available data size
Definition MemBuf.h:47
mb_size_t potentialSpaceSize() const
Definition MemBuf.cc:161
bool hasContent() const
Definition MemBuf.h:54
void terminate()
Definition MemBuf.cc:241
void add(const SBuf &key, const SBuf &value)
Definition Notes.cc:322
bool hasPair(const SBuf &key, const SBuf &value) const
Definition Notes.cc:375
void appendf(const char *fmt,...) PRINTF_FORMAT_ARG2
Append operation with printf-style arguments.
Definition Packable.h:61
C * getRaw() const
Definition RefCount.h:89
Definition SBuf.h:94
const char * rawContent() const
Definition SBuf.cc:509
size_type length() const
Returns the number of bytes stored in SBuf.
Definition SBuf.h:419
char const * rawBuf() const
Definition SquidString.h:91
char const * termedBuf() const
Definition SquidString.h:97
size_type size() const
Definition SquidString.h:78
an std::runtime_error with thrower location info
SourceLocationId id() const
same-location exceptions have the same ID
A const & max(A const &lhs, A const &rhs)
A const & min(A const &lhs, A const &rhs)
#define DBG_IMPORTANT
Definition Stream.h:38
#define debugs(SECTION, LEVEL, CONTENT)
Definition Stream.h:192
#define MAX_LOGIN_SZ
Definition defines.h:77
@ ERR_ICAP_FAILURE
Definition forward.h:64
@ ICP_INVALID
Definition icp_opcode.h:15
void HTTPMSGLOCK(Http::Message *a)
Definition Message.h:161
#define MAX_IPSTRLEN
Length of buffer that needs to be allocated to old a null-terminated IP-string.
Definition forward.h:25
const XactOutcome xoPartEcho
preserved virgin msg part (ICAP 206)
Definition Elements.cc:24
const XactOutcome xoModified
replaced virgin msg with adapted
Definition Elements.cc:25
Config TheConfig
Definition Config.cc:19
const XactOutcome xoSatisfied
request satisfaction
Definition Elements.cc:26
const XactOutcome xoEcho
preserved virgin message (ICAP 204)
Definition Elements.cc:23
StatusCode
Definition StatusCode.h:20
@ scCreated
Definition StatusCode.h:28
@ scInvalidHeader
Squid header parsing error.
Definition StatusCode.h:88
@ scNone
Definition StatusCode.h:21
@ scOkay
Definition StatusCode.h:27
@ scContinue
Definition StatusCode.h:22
@ scNoContent
Definition StatusCode.h:31
@ scPartialContent
Definition StatusCode.h:33
@ METHOD_NONE
Definition MethodType.h:22
@ PROXY_AUTHORIZATION
@ PROXY_AUTHENTICATE
const char * FormatRfc1123(time_t)
Definition rfc1123.cc:202
Definition parse.c:160
int const char size_t
struct timeval current_time
the current UNIX time in timeval {seconds, microseconds} format
Definition gadgets.cc:18