http.cc
Go to the documentation of this file.
1/*
2 * Copyright (C) 1996-2023 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 11 Hypertext Transfer Protocol (HTTP) */
10
11/*
12 * Anonymizing patch by lutz@as-node.jena.thur.de
13 * have a look into http-anon.c to get more information.
14 */
15
16#include "squid.h"
17#include "acl/FilledChecklist.h"
18#include "base/AsyncJobCalls.h"
20#include "base/Raw.h"
21#include "base/TextException.h"
22#include "base64.h"
23#include "CachePeer.h"
24#include "client_side.h"
25#include "comm/Connection.h"
26#include "comm/Read.h"
27#include "comm/Write.h"
28#include "error/Detail.h"
29#include "errorpage.h"
30#include "fd.h"
31#include "fde.h"
32#include "globals.h"
33#include "http.h"
36#include "http/StatusCode.h"
37#include "http/Stream.h"
38#include "HttpControlMsg.h"
39#include "HttpHdrCc.h"
40#include "HttpHdrContRange.h"
41#include "HttpHdrSc.h"
42#include "HttpHdrScTarget.h"
43#include "HttpHeaderTools.h"
44#include "HttpReply.h"
45#include "HttpRequest.h"
47#include "log/access_log.h"
48#include "MemBuf.h"
49#include "MemObject.h"
50#include "neighbors.h"
51#include "pconn.h"
53#include "refresh.h"
54#include "RefreshPattern.h"
55#include "rfc1738.h"
56#include "SquidConfig.h"
57#include "StatCounters.h"
58#include "Store.h"
59#include "StrList.h"
60#include "tools.h"
61#include "util.h"
62
63#if USE_AUTH
64#include "auth/UserRequest.h"
65#endif
66#if USE_DELAY_POOLS
67#include "DelayPools.h"
68#endif
69
71
72static const char *const crlf = "\r\n";
73
75static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request,
76 HttpHeader * hdr_out, const int we_do_ranges, const Http::StateFlags &);
77
79 AsyncJob("HttpStateData"),
80 Client(theFwdState)
81{
82 debugs(11,5, "HttpStateData " << this << " created");
84
85 if (fwd->serverConnection() != nullptr)
86 _peer = cbdataReference(fwd->serverConnection()->getPeer()); /* might be NULL */
87
91
92 if (_peer) {
93 /*
94 * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here.
95 * We might end up getting the object from somewhere else if,
96 * for example, the request to this neighbor fails.
97 */
99 entry->releaseRequest(true);
100
101#if USE_DELAY_POOLS
103#endif
104 }
105
106 /*
107 * register the handler to free HTTP state data when the FD closes
108 */
112}
113
115{
116 /*
117 * don't forget that ~Client() gets called automatically
118 */
119
121 delete httpChunkDecoder;
122
124
125 delete upgradeHeaderOut;
126
127 debugs(11,5, "HttpStateData " << this << " destroyed; " << serverConnection);
128}
129
132{
133 return serverConnection;
134}
135
136void
138{
139 debugs(11, 5, "httpStateFree: FD " << params.fd << ", httpState=" << params.data);
140 doneWithFwd = "httpStateConnClosed()"; // assume FwdState is monitoring too
141 mustStop("HttpStateData::httpStateConnClosed");
142}
143
144void
146{
147 debugs(11, 4, serverConnection << ": '" << entry->url() << "'");
148
151 }
152
153 closeServer();
154 mustStop("HttpStateData::httpTimeout");
155}
156
157static StoreEntry *
159 assert(newEntry->mem_obj);
160 return newEntry->mem_obj->request ?
162 storeGetPublic(newEntry->mem_obj->storeId(), newEntry->mem_obj->method);
163}
164
167static void
169{
170 int remove = 0;
171 int forbidden = 0;
172
173 // If the incoming response already goes into a public entry, then there is
174 // nothing to remove. This protects ready-for-collapsing entries as well.
175 if (!EBIT_TEST(e->flags, KEY_PRIVATE))
176 return;
177
178 // If the new/incoming response cannot be stored, then it does not
179 // compete with the old stored response for the public key, and the
180 // old stored response should be left as is.
181 if (e->mem_obj->request && !e->mem_obj->request->flags.cachable)
182 return;
183
184 switch (status) {
185
186 case Http::scOkay:
187
189
191
193
194 case Http::scFound:
195
196 case Http::scSeeOther:
197
198 case Http::scGone:
199
200 case Http::scNotFound:
201 remove = 1;
202
203 break;
204
206
208 forbidden = 1;
209
210 break;
211
212#if WORK_IN_PROGRESS
213
215 forbidden = 1;
216
217 break;
218
219#endif
220
221 default:
222 break;
223 }
224
225 if (!remove && !forbidden)
226 return;
227
229
230 if (pe != nullptr) {
231 assert(e != pe);
232#if USE_HTCP
234#endif
235 pe->release(true);
236 }
237
242 if (e->mem_obj->request)
244 else
246
247 if (pe != nullptr) {
248 assert(e != pe);
249#if USE_HTCP
251#endif
252 pe->release(true);
253 }
254}
255
256void
258{
261
262 if (sctusable) {
263 if (sctusable->hasNoStore() ||
265 && sctusable->noStoreRemote())) {
266 surrogateNoStore = true;
267 // Be conservative for now and make it non-shareable because
268 // there is no enough information here to make the decision.
269 entry->makePrivate(false);
270 }
271
272 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
273 * accelerated request or not...
274 * Still, this is an abstraction breach. - RC
275 */
276 if (sctusable->hasMaxAge()) {
277 if (sctusable->maxAge() < sctusable->maxStale())
278 reply->expires = reply->date + sctusable->maxAge();
279 else
280 reply->expires = reply->date + sctusable->maxStale();
281
282 /* And update the timestamps */
284 }
285
286 /* We ignore cache-control directives as per the Surrogate specification */
287 ignoreCacheControl = true;
288
289 delete sctusable;
290 }
291 }
292}
293
296{
297 HttpReply const *rep = finalReply();
298 HttpHeader const *hdr = &rep->header;
299 const char *v;
300#if USE_HTTP_VIOLATIONS
301
302 const RefreshPattern *R = nullptr;
303
304 /* This strange looking define first looks up the refresh pattern
305 * and then checks if the specified flag is set. The main purpose
306 * of this is to simplify the refresh pattern lookup and USE_HTTP_VIOLATIONS
307 * condition
308 */
309#define REFRESH_OVERRIDE(flag) \
310 ((R = (R ? R : refreshLimits(entry->mem_obj->storeId()))) , \
311 (R && R->flags.flag))
312#else
313#define REFRESH_OVERRIDE(flag) 0
314#endif
315
317 return decision.make(ReuseDecision::doNotCacheButShare, "the entry has been released");
318
319 // RFC 9111 section 4:
320 // "When more than one suitable response is stored,
321 // a cache MUST use the most recent one
322 // (as determined by the Date header field)."
323 // TODO: whether such responses could be shareable?
324 if (sawDateGoBack)
325 return decision.make(ReuseDecision::reuseNot, "the response has an older date header");
326
327 // Check for Surrogate/1.0 protocol conditions
328 // NP: reverse-proxy traffic our parent server has instructed us never to cache
330 return decision.make(ReuseDecision::reuseNot, "Surrogate-Control:no-store");
331
332 // RFC 2616: HTTP/1.1 Cache-Control conditions
333 if (!ignoreCacheControl) {
334 // XXX: check to see if the request headers alone were enough to prevent caching earlier
335 // (ie no-store request header) no need to check those all again here if so.
336 // for now we are not reliably doing that so we waste CPU re-checking request CC
337
338 // RFC 2616 section 14.9.2 - MUST NOT cache any response with request CC:no-store
340 !REFRESH_OVERRIDE(ignore_no_store))
341 return decision.make(ReuseDecision::reuseNot,
342 "client request Cache-Control:no-store");
343
344 // NP: request CC:no-cache only means cache READ is forbidden. STORE is permitted.
346 /* TODO: we are allowed to cache when no-cache= has parameters.
347 * Provided we strip away any of the listed headers unless they are revalidated
348 * successfully (ie, must revalidate AND these headers are prohibited on stale replies).
349 * That is a bit tricky for squid right now so we avoid caching entirely.
350 */
351 return decision.make(ReuseDecision::reuseNot,
352 "server reply Cache-Control:no-cache has parameters");
353 }
354
355 // NP: request CC:private is undefined. We ignore.
356 // NP: other request CC flags are limiters on HIT/MISS. We don't care about here.
357
358 // RFC 2616 section 14.9.2 - MUST NOT cache any response with CC:no-store
359 if (rep->cache_control && rep->cache_control->hasNoStore() &&
360 !REFRESH_OVERRIDE(ignore_no_store))
361 return decision.make(ReuseDecision::reuseNot,
362 "server reply Cache-Control:no-store");
363
364 // RFC 2616 section 14.9.1 - MUST NOT cache any response with CC:private in a shared cache like Squid.
365 // CC:private overrides CC:public when both are present in a response.
366 // TODO: add a shared/private cache configuration possibility.
367 if (rep->cache_control &&
368 rep->cache_control->hasPrivate() &&
369 !REFRESH_OVERRIDE(ignore_private)) {
370 /* TODO: we are allowed to cache when private= has parameters.
371 * Provided we strip away any of the listed headers unless they are revalidated
372 * successfully (ie, must revalidate AND these headers are prohibited on stale replies).
373 * That is a bit tricky for squid right now so we avoid caching entirely.
374 */
375 return decision.make(ReuseDecision::reuseNot,
376 "server reply Cache-Control:private");
377 }
378 }
379
380 // RFC 2068, sec 14.9.4 - MUST NOT cache any response with Authentication UNLESS certain CC controls are present
381 // allow HTTP violations to IGNORE those controls (ie re-block caching Auth)
383 if (!rep->cache_control)
384 return decision.make(ReuseDecision::reuseNot,
385 "authenticated and server reply missing Cache-Control");
386
388 return decision.make(ReuseDecision::reuseNot,
389 "authenticated and ignoring Cache-Control");
390
391 bool mayStore = false;
392 // HTTPbis pt6 section 3.2: a response CC:public is present
393 if (rep->cache_control->hasPublic()) {
394 debugs(22, 3, "Authenticated but server reply Cache-Control:public");
395 mayStore = true;
396
397 // HTTPbis pt6 section 3.2: a response CC:must-revalidate is present
398 } else if (rep->cache_control->hasMustRevalidate()) {
399 debugs(22, 3, "Authenticated but server reply Cache-Control:must-revalidate");
400 mayStore = true;
401
402#if USE_HTTP_VIOLATIONS
403 // NP: given the must-revalidate exception we should also be able to exempt no-cache.
404 // HTTPbis WG verdict on this is that it is omitted from the spec due to being 'unexpected' by
405 // some. The caching+revalidate is not exactly unsafe though with Squids interpretation of no-cache
406 // (without parameters) as equivalent to must-revalidate in the reply.
407 } else if (rep->cache_control->hasNoCacheWithoutParameters()) {
408 debugs(22, 3, "Authenticated but server reply Cache-Control:no-cache (equivalent to must-revalidate)");
409 mayStore = true;
410#endif
411
412 // HTTPbis pt6 section 3.2: a response CC:s-maxage is present
413 } else if (rep->cache_control->hasSMaxAge()) {
414 debugs(22, 3, "Authenticated but server reply Cache-Control:s-maxage");
415 mayStore = true;
416 }
417
418 if (!mayStore)
419 return decision.make(ReuseDecision::reuseNot, "authenticated transaction");
420
421 // NP: response CC:no-cache is equivalent to CC:must-revalidate,max-age=0. We MAY cache, and do so.
422 // NP: other request CC flags are limiters on HIT/MISS/REFRESH. We don't care about here.
423 }
424
425 /* HACK: The "multipart/x-mixed-replace" content type is used for
426 * continuous push replies. These are generally dynamic and
427 * probably should not be cachable
428 */
429 if ((v = hdr->getStr(Http::HdrType::CONTENT_TYPE)))
430 if (!strncasecmp(v, "multipart/x-mixed-replace", 25))
431 return decision.make(ReuseDecision::reuseNot, "Content-Type:multipart/x-mixed-replace");
432
433 // TODO: if possible, provide more specific message for each status code
434 static const char *shareableError = "shareable error status code";
435 static const char *nonShareableError = "non-shareable error status code";
437 const char *statusReason = nonShareableError;
438
439 switch (rep->sline.status()) {
440
441 /* There are several situations when a non-cacheable response may be
442 * still shareable (e.g., among collapsed clients). We assume that these
443 * are 3xx and 5xx responses, indicating server problems and some of
444 * 4xx responses, common for all clients with a given cache key (e.g.,
445 * 404 Not Found or 414 URI Too Long). On the other hand, we should not
446 * share non-cacheable client-specific errors, such as 400 Bad Request
447 * or 406 Not Acceptable.
448 */
449
450 /* Responses that are cacheable */
451
452 case Http::scOkay:
453
455
457
460
461 case Http::scGone:
462 /*
463 * Don't cache objects that need to be refreshed on next request,
464 * unless we know how to refresh it.
465 */
466
467 if (refreshIsCachable(entry) || REFRESH_OVERRIDE(store_stale))
468 decision.make(ReuseDecision::cachePositively, "refresh check returned cacheable");
469 else
470 decision.make(ReuseDecision::doNotCacheButShare, "refresh check returned non-cacheable");
471 break;
472
473 /* Responses that only are cacheable if the server says so */
474
475 case Http::scFound:
477 if (rep->date <= 0)
478 decision.make(ReuseDecision::doNotCacheButShare, "Date is missing/invalid");
479 else if (rep->expires > rep->date)
480 decision.make(ReuseDecision::cachePositively, "Expires > Date");
481 else
482 decision.make(ReuseDecision::doNotCacheButShare, "Expires <= Date");
483 break;
484
485 /* These responses can be negatively cached. Most can also be shared. */
487 case Http::scUseProxy:
489 case Http::scNotFound:
499 statusReason = shareableError;
500 [[fallthrough]]; // to the actual decision making below
501
502 case Http::scBadRequest: // no sharing; perhaps the server did not like something specific to this request
503#if USE_HTTP_VIOLATIONS
504 if (Config.negativeTtl > 0)
505 decision.make(ReuseDecision::cacheNegatively, "Config.negativeTtl > 0");
506 else
507#endif
508 decision.make(statusAnswer, statusReason);
509 break;
510
511 /* these responses can never be cached, some
512 of them can be shared though */
513 case Http::scSeeOther:
519 // TODO: use more specific reason for non-error status codes
520 decision.make(ReuseDecision::doNotCacheButShare, shareableError);
521 break;
522
523 case Http::scPartialContent: /* Not yet supported. TODO: make shareable for suitable ranges */
525 case Http::scRequestTimeout: // TODO: is this shareable?
526 case Http::scConflict: // TODO: is this shareable?
532 case Http::scLocked: // TODO: is this shareable?
536 case Http::scInvalidHeader: /* Squid header parsing error */
538 decision.make(ReuseDecision::reuseNot, nonShareableError);
539 break;
540
541 default:
542 /* RFC 2616 section 6.1.1: an unrecognized response MUST NOT be cached. */
543 decision.make(ReuseDecision::reuseNot, "unknown status code");
544 break;
545 }
546
547 return decision.answer;
548}
549
551static void
552assembleVaryKey(String &vary, SBuf &vstr, const HttpRequest &request)
553{
554 static const SBuf asterisk("*");
555 const char *pos = nullptr;
556 const char *item = nullptr;
557 int ilen = 0;
558
559 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
560 SBuf name(item, ilen);
561 if (name == asterisk) {
562 vstr = asterisk;
563 break;
564 }
565 name.toLower();
566 if (!vstr.isEmpty())
567 vstr.append(", ", 2);
568 vstr.append(name);
569 String hdr(request.header.getByName(name));
570 const char *value = hdr.termedBuf();
571 if (value) {
572 value = rfc1738_escape_part(value);
573 vstr.append("=\"", 2);
574 vstr.append(value);
575 vstr.append("\"", 1);
576 }
577
578 hdr.clean();
579 }
580}
581
582/*
583 * For Vary, store the relevant request headers as
584 * virtual headers in the reply
585 * Returns an empty SBuf if the variance cannot be stored
586 */
587SBuf
588httpMakeVaryMark(HttpRequest * request, HttpReply const * reply)
589{
590 SBuf vstr;
591 String vary;
592
593 vary = reply->header.getList(Http::HdrType::VARY);
594 assembleVaryKey(vary, vstr, *request);
595
596#if X_ACCELERATOR_VARY
597 vary.clean();
599 assembleVaryKey(vary, vstr, *request);
600#endif
601
602 debugs(11, 3, vstr);
603 return vstr;
604}
605
606void
608{
609 if (flags.keepalive)
612
613 if (reply->keep_alive) {
616
618 && reply->bodySize(request->method) == -1 && !flags.chunked) {
619 debugs(11, DBG_IMPORTANT, "keepaliveAccounting: Impossible keep-alive header from '" << entry->url() << "'" );
620 // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" );
621 flags.keepalive_broken = true;
622 }
623 }
624}
625
626void
628{
629 if (reply->date > -1 && flags.toOrigin) {
630 int skew = abs((int)(reply->date - squid_curtime));
631
632 if (skew > 86400)
633 debugs(11, 3, "" << request->url.host() << "'s clock is skewed by " << skew << " seconds!");
634 }
635}
636
643void
645{
648 debugs(11, 3, "processReplyHeader: key '" << entry->getMD5Text() << "'");
649
651
652 if (!inBuf.length())
653 return;
654
655 /* Attempt to parse the first line; this will define where the protocol, status, reason-phrase and header begin */
656 {
657 if (hp == nullptr)
659
660 bool parsedOk = hp->parse(inBuf);
661 // remember the actual received status-code before returning on errors,
662 // overwriting any previously stored value from earlier forwarding attempts
663 request->hier.peer_reply_status = hp->messageStatus(); // may still be scNone
664
665 // sync the buffers after parsing.
666 inBuf = hp->remaining();
667
668 if (hp->needsMoreData()) {
669 if (eof) { // no more data coming
670 assert(!parsedOk);
671 // fall through to handle this premature EOF as an error
672 } else {
673 debugs(33, 5, "Incomplete response, waiting for end of response headers");
674 return;
675 }
676 }
677
678 if (!parsedOk) {
679 // unrecoverable parsing error
680 // TODO: Use Raw! XXX: inBuf no longer has the [beginning of the] malformed header.
681 debugs(11, 3, "Non-HTTP-compliant header:\n---------\n" << inBuf << "\n----------");
682 flags.headers_parsed = true;
683 HttpReply *newrep = new HttpReply;
684 // hp->needsMoreData() means hp->parseStatusCode is unusable, but, here,
685 // it also means that the reply header got truncated by a premature EOF
686 assert(!hp->needsMoreData() || eof);
687 const auto scode = hp->needsMoreData() ? Http::scInvalidHeader : hp->parseStatusCode;
688 newrep->sline.set(Http::ProtocolVersion(), scode);
689 setVirginReply(newrep);
690 return;
691 }
692 }
693
694 /* We know the whole response is in parser now */
695 debugs(11, 2, "HTTP Server " << serverConnection);
696 debugs(11, 2, "HTTP Server RESPONSE:\n---------\n" <<
697 hp->messageProtocol() << " " << hp->messageStatus() << " " << hp->reasonPhrase() << "\n" <<
698 hp->mimeHeader() <<
699 "----------");
700
701 // reset payload tracking to begin after message headers
703
704 HttpReply *newrep = new HttpReply;
705 // XXX: RFC 7230 indicates we MAY ignore the reason phrase,
706 // and use an empty string on unknown status.
707 // We do that now to avoid performance regression from using SBuf::c_str()
708 newrep->sline.set(hp->messageProtocol(), hp->messageStatus() /* , hp->reasonPhrase() */);
709
710 // parse headers
711 if (!newrep->parseHeader(*hp)) {
712 newrep->sline.set(hp->messageProtocol(), Http::scInvalidHeader);
713 debugs(11, 2, "error parsing response headers mime block");
714 }
715
716 // done with Parser, now process using the HttpReply
717 hp = nullptr;
718
720
721 if (newrep->sline.version.protocol == AnyP::PROTO_HTTP && Http::Is1xx(newrep->sline.status())) {
722 handle1xx(newrep);
723 return;
724 }
725
726 flags.chunked = false;
727 if (newrep->sline.version.protocol == AnyP::PROTO_HTTP && newrep->header.chunked()) {
728 flags.chunked = true;
730 }
731
734
735 HttpReply *vrep = setVirginReply(newrep);
736 flags.headers_parsed = true;
737
739
740 checkDateSkew(vrep);
741
743}
744
746void
748{
749 if (fwd->al)
750 fwd->al->reply = reply;
751
752 HttpReply::Pointer msg(reply); // will destroy reply if unused
753
754 // one 1xx at a time: we must not be called while waiting for previous 1xx
756 flags.handling1xx = true;
757
758 const auto statusCode = reply->sline.status();
759
760 // drop1xx() needs to handle HTTP 101 (Switching Protocols) responses
761 // specially because they indicate that the server has stopped speaking HTTP
764
765 if (statusCode == Http::scContinue && request->forcedBodyContinuation)
766 return drop1xx("we have sent it already");
767
768 if (!request->canHandle1xx())
769 return drop1xx("the client does not support it");
770
771#if USE_HTTP_VIOLATIONS
772 // check whether the 1xx response forwarding is allowed by squid.conf
773 if (Config.accessList.reply) {
775 ch.al = fwd->al;
776 ch.reply = reply;
777 ch.syncAle(originalRequest().getRaw(), nullptr);
778 HTTPMSGLOCK(ch.reply);
779 if (!ch.fastCheck().allowed()) // TODO: support slow lookups?
780 return drop1xx("http_reply_access blocked it");
781 }
782#endif // USE_HTTP_VIOLATIONS
783
785 if (const auto reason = blockSwitchingProtocols(*reply))
786 return drop1xx(reason);
787 }
788
789 debugs(11, 2, "forwarding 1xx to client");
790
791 // the Sink will use this to call us back after writing 1xx to the client
792 typedef NullaryMemFunT<HttpStateData> CbDialer;
793 const AsyncCall::Pointer cb = JobCallback(11, 3, CbDialer, this,
797 // If the call is not fired, then the Sink is gone, and HttpStateData
798 // will terminate due to an aborted store entry or another similar error.
799 // If we get stuck, it is not handle1xx fault if we could get stuck
800 // for similar reasons without a 1xx response.
801}
802
805void
806HttpStateData::drop1xx(const char *reason)
807{
809 debugs(11, 2, "bad 101 because " << reason);
811 fwd->fail(err);
812 closeServer();
813 mustStop("prohibited HTTP/101 response");
814 return;
815 }
816
817 debugs(11, 2, "ignoring 1xx because " << reason);
819}
820
823const char *
825{
826 if (!upgradeHeaderOut)
827 return "Squid offered no Upgrade at all, but server switched to a tunnel";
828
829 // See RFC 7230 section 6.7 for the corresponding MUSTs
830
832 return "server did not send an Upgrade header field";
833
834 if (!reply.header.hasListMember(Http::HdrType::CONNECTION, "upgrade", ','))
835 return "server did not send 'Connection: upgrade'";
836
837 const auto acceptedProtos = reply.header.getList(Http::HdrType::UPGRADE);
838 const char *pos = nullptr;
839 const char *accepted = nullptr;
840 int acceptedLen = 0;
841 while (strListGetItem(&acceptedProtos, ',', &accepted, &acceptedLen, &pos)) {
842 debugs(11, 5, "server accepted at least" << Raw(nullptr, accepted, acceptedLen));
843 return nullptr; // OK: let the client validate server's selection
844 }
845
846 return "server sent an essentially empty Upgrade header field";
847}
848
850void
852{
854
856 // pass server connection ownership to request->clientConnectionManager
859 AsyncCall::Pointer call = asyncCall(11, 3, "ConnStateData::noteTakeServerConnectionControl",
862 ScheduleCallHere(call);
865 closeHandler = nullptr;
866 serverConnection = nullptr;
867 doneWithFwd = "switched protocols";
869 return;
870 }
871
872 debugs(11, 2, "continuing with " << payloadSeen << " bytes in buffer after 1xx");
874}
875
879bool
881{
882 if (!_peer)
883 return true;
884
885 // we are talking "through" rather than "to" our _peer
886 if (flags.tunneling)
887 return true;
888
889 /*If this peer does not support connection pinning (authenticated
890 connections) return false
891 */
893 return false;
894
895 const auto &rep = entry->mem().freshestReply();
896
897 /*The peer supports connection pinning and the http reply status
898 is not unauthorized, so the related connection can be pinned
899 */
900 if (rep.sline.status() != Http::scUnauthorized)
901 return true;
902
903 /*The server respond with Http::scUnauthorized and the peer configured
904 with "connection-auth=on" we know that the peer supports pinned
905 connections
906 */
907 if (_peer->connection_auth == 1)
908 return true;
909
910 /*At this point peer has configured with "connection-auth=auto"
911 parameter so we need some extra checks to decide if we are going
912 to allow pinned connections or not
913 */
914
915 /*if the peer configured with originserver just allow connection
916 pinning (squid 2.6 behaviour)
917 */
919 return true;
920
921 /*if the connections it is already pinned it is OK*/
922 if (request->flags.pinned)
923 return true;
924
925 /*Allow pinned connections only if the Proxy-support header exists in
926 reply and has in its list the "Session-Based-Authentication"
927 which means that the peer supports connection pinning.
928 */
929 if (rep.header.hasListMember(Http::HdrType::PROXY_SUPPORT, "Session-Based-Authentication", ','))
930 return true;
931
932 return false;
933}
934
935// Called when we parsed (and possibly adapted) the headers but
936// had not starting storing (a.k.a., sending) the body yet.
937void
939{
941
942 HttpReply *rep = finalReply();
943 const Http::StatusCode statusCode = rep->sline.status();
944
946
947 /* Check if object is cacheable or not based on reply code */
948 debugs(11, 3, "HTTP CODE: " << statusCode);
949
950 if (StoreEntry *oldEntry = findPreviouslyCachedEntry(entry)) {
951 oldEntry->lock("HttpStateData::haveParsedReplyHeaders");
952 sawDateGoBack = rep->olderThan(oldEntry->hasFreshestReply());
953 oldEntry->unlock("HttpStateData::haveParsedReplyHeaders");
954 }
955
958
959 bool varyFailure = false;
961#if X_ACCELERATOR_VARY
963#endif
964 ) {
965 const SBuf vary(httpMakeVaryMark(request.getRaw(), rep));
966
967 if (vary.isEmpty()) {
968 // TODO: check whether such responses are shareable.
969 // Do not share for now.
970 entry->makePrivate(false);
973 varyFailure = true;
974 } else {
975 entry->mem_obj->vary_headers = vary;
976
977 // RFC 7231 section 7.1.4
978 // Vary:* can be cached, but has mandatory revalidation
979 static const SBuf asterisk("*");
980 if (vary == asterisk)
982 }
983 }
984
985 if (!varyFailure) {
986 /*
987 * If its not a reply that we will re-forward, then
988 * allow the client to get it.
989 */
992
993 ReuseDecision decision(entry, statusCode);
994
995 switch (reusableReply(decision)) {
996
998 entry->makePrivate(false);
999 break;
1000
1002 if (!entry->makePublic()) {
1003 decision.make(ReuseDecision::doNotCacheButShare, "public key creation error");
1004 entry->makePrivate(true);
1005 }
1006 break;
1007
1009 if (!entry->cacheNegatively()) {
1010 decision.make(ReuseDecision::doNotCacheButShare, "public key creation error");
1011 entry->makePrivate(true);
1012 }
1013 break;
1014
1016 entry->makePrivate(true);
1017 break;
1018
1019 default:
1020 assert(0);
1021 break;
1022 }
1023 debugs(11, 3, "decided: " << decision);
1024 }
1025
1026 if (!ignoreCacheControl) {
1027 if (rep->cache_control) {
1028 // We are required to revalidate on many conditions.
1029 // For security reasons we do so even if storage was caused by refresh_pattern ignore-* option
1030
1031 // CC:must-revalidate or CC:proxy-revalidate
1032 const bool ccMustRevalidate = (rep->cache_control->hasProxyRevalidate() || rep->cache_control->hasMustRevalidate());
1033
1034 // CC:no-cache (only if there are no parameters)
1035 const bool ccNoCacheNoParams = rep->cache_control->hasNoCacheWithoutParameters();
1036
1037 // CC:s-maxage=N
1038 const bool ccSMaxAge = rep->cache_control->hasSMaxAge();
1039
1040 // CC:private (yes, these can sometimes be stored)
1041 const bool ccPrivate = rep->cache_control->hasPrivate();
1042
1043 if (ccNoCacheNoParams || ccPrivate)
1045 else if (ccMustRevalidate || ccSMaxAge)
1047 }
1048#if USE_HTTP_VIOLATIONS // response header Pragma::no-cache is undefined in HTTP
1049 else {
1050 // Expensive calculation. So only do it IF the CC: header is not present.
1051
1052 /* HACK: Pragma: no-cache in _replies_ is not documented in HTTP,
1053 * but servers like "Active Imaging Webcast/2.0" sure do use it */
1054 if (rep->header.has(Http::HdrType::PRAGMA) &&
1055 rep->header.hasListMember(Http::HdrType::PRAGMA,"no-cache",','))
1057 }
1058#endif
1059 }
1060}
1061
1064{
1065 const HttpReply *rep = virginReply();
1069 static SBuf close("close", 5);
1070 if (httpHeaderHasConnDir(&rep->header, close))
1072
1077 if (!flags.keepalive)
1079
1083 if (flags.forceClose)
1085
1090 if (!flags.request_sent) {
1091 debugs(11, 2, "Request not yet fully sent " << request->method << ' ' << entry->url());
1093 }
1094
1098 /* XXX: BUG?
1099 * If the origin server (HTTP/1.0) does not send a keep-alive
1100 * header, but keeps the connection open anyway, what happens?
1101 * We'll return here and wait for an EOF before changing
1102 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
1103 * and an error status code, and we might have to wait until
1104 * the server times out the socket.
1105 */
1106 if (!rep->keep_alive)
1108
1110}
1111
1114{
1115 debugs(11, 3, serverConnection << " eof=" << eof);
1116 if (eof) // already reached EOF
1118
1119 /* If server fd is closing (but we have not been notified yet), stop Comm
1120 I/O to avoid assertions. TODO: Change Comm API to handle callers that
1121 want more I/O after async closing (usually initiated by others). */
1122 // XXX: add canReceive or s/canSend/canTalkToServer/
1125
1131 if (lastChunk && flags.chunked)
1132 return statusIfComplete();
1133
1134 const HttpReply *vrep = virginReply();
1135 debugs(11, 5, "persistentConnStatus: content_length=" << vrep->content_length);
1136
1137 const int64_t clen = vrep->bodySize(request->method);
1138
1139 debugs(11, 5, "persistentConnStatus: clen=" << clen);
1140
1141 /* If the body size is unknown we must wait for EOF */
1142 if (clen < 0)
1143 return INCOMPLETE_MSG;
1144
1147 if (clen > 0) {
1148 debugs(11,5, "payloadSeen=" << payloadSeen << " content_length=" << vrep->content_length);
1149
1150 if (payloadSeen < vrep->content_length)
1151 return INCOMPLETE_MSG;
1152
1153 if (payloadTruncated > 0) // already read more than needed
1154 return COMPLETE_NONPERSISTENT_MSG; // disable pconns
1155 }
1156
1159 return statusIfComplete();
1160}
1161
1162void
1164{
1165 flags.do_next_read = true;
1167}
1168
1169void
1171{
1172 Must(!flags.do_next_read); // XXX: should have been set false by mayReadVirginBody()
1173 flags.do_next_read = false;
1174
1175 debugs(11, 5, io.conn);
1176
1177 // Bail out early on Comm::ERR_CLOSING - close handlers will tidy up for us
1178 if (io.flag == Comm::ERR_CLOSING) {
1179 debugs(11, 3, "http socket closing");
1180 return;
1181 }
1182
1184 abortTransaction("store entry aborted while reading reply");
1185 return;
1186 }
1187
1189 Must(io.conn->fd == serverConnection->fd);
1190
1191 /*
1192 * Don't reset the timeout value here. The value should be
1193 * counting Config.Timeout.request and applies to the request
1194 * as a whole, not individual read() calls.
1195 * Plus, it breaks our lame *HalfClosed() detection
1196 */
1197
1199 CommIoCbParams rd(this); // will be expanded with ReadNow results
1200 rd.conn = io.conn;
1202
1203 if (rd.size <= 0) {
1204 delayRead();
1205 return;
1206 }
1207
1208 switch (Comm::ReadNow(rd, inBuf)) {
1209 case Comm::INPROGRESS:
1210 if (inBuf.isEmpty())
1211 debugs(33, 2, io.conn << ": no data to process, " << xstrerr(rd.xerrno));
1212 flags.do_next_read = true;
1214 return;
1215
1216 case Comm::OK:
1217 {
1218 payloadSeen += rd.size;
1219#if USE_DELAY_POOLS
1220 DelayId delayId = entry->mem_obj->mostBytesAllowed();
1221 delayId.bytesIn(rd.size);
1222#endif
1223
1226 ++ IOStats.Http.reads;
1227
1228 int bin = 0;
1229 for (int clen = rd.size - 1; clen; ++bin)
1230 clen >>= 1;
1231
1232 ++ IOStats.Http.read_hist[bin];
1233
1235 }
1236
1237 /* Continue to process previously read data */
1238 break;
1239
1240 case Comm::ENDFILE: // close detected by 0-byte read
1241 eof = 1;
1242 flags.do_next_read = false;
1243
1244 /* Continue to process previously read data */
1245 break;
1246
1247 // case Comm::COMM_ERROR:
1248 default: // no other flags should ever occur
1249 debugs(11, 2, io.conn << ": read failure: " << xstrerr(rd.xerrno));
1250 const auto err = new ErrorState(ERR_READ_ERROR, Http::scBadGateway, fwd->request, fwd->al);
1251 err->xerrno = rd.xerrno;
1252 fwd->fail(err);
1253 flags.do_next_read = false;
1254 closeServer();
1255 mustStop("HttpStateData::readReply");
1256 return;
1257 }
1258
1259 /* Process next response from buffer */
1260 processReply();
1261}
1262
1265void
1267{
1268
1269 if (flags.handling1xx) { // we came back after handling a 1xx response
1270 debugs(11, 5, "done with 1xx handling");
1271 flags.handling1xx = false;
1273 }
1274
1276 abortTransaction("store entry aborted while we were waiting for processReply()");
1277 return;
1278 }
1279
1280 if (!flags.headers_parsed) { // have not parsed headers yet?
1282
1283 if (!continueAfterParsingHeader()) // parsing error or need more data
1284 return; // TODO: send errors to ICAP
1285
1286 adaptOrFinalizeReply(); // may write to, abort, or "close" the entry
1287 }
1288
1289 // kick more reads if needed and/or process the response body, if any
1290 processReplyBody(); // may call serverComplete()
1291}
1292
1296bool
1298{
1299 if (flags.handling1xx) {
1300 debugs(11, 5, "wait for 1xx handling");
1302 return false;
1303 }
1304
1305 if (!flags.headers_parsed && !eof) {
1306 debugs(11, 9, "needs more at " << inBuf.length());
1307 flags.do_next_read = true;
1311 maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
1312 return false;
1313 }
1314
1318
1319 if (flags.headers_parsed) { // parsed headers, possibly with errors
1320 // check for header parsing errors
1321 if (HttpReply *vrep = virginReply()) {
1322 const Http::StatusCode s = vrep->sline.status();
1323 const AnyP::ProtocolVersion &v = vrep->sline.version;
1324 if (s == Http::scInvalidHeader && v != Http::ProtocolVersion(0,9)) {
1325 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Bad header encountered from " << entry->url() << " AKA " << request->url);
1327 } else if (s == Http::scHeaderTooLarge) {
1328 fwd->dontRetry(true);
1330 } else if (vrep->header.conflictingContentLength()) {
1331 fwd->dontRetry(true);
1333 } else if (vrep->header.unsupportedTe()) {
1334 fwd->dontRetry(true);
1336 } else {
1337 return true; // done parsing, got reply, and no error
1338 }
1339 } else {
1340 // parsed headers but got no reply
1341 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: No reply at all for " << entry->url() << " AKA " << request->url);
1343 }
1344 } else {
1345 assert(eof);
1346 if (inBuf.length()) {
1348 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Headers did not parse at all for " << entry->url() << " AKA " << request->url);
1349 } else {
1351 debugs(11, (request->flags.accelerated?DBG_IMPORTANT:2), "WARNING: HTTP: Invalid Response: No object data received for " << entry->url() << " AKA " << request->url);
1352 }
1353 }
1354
1355 assert(error != ERR_NONE);
1356 entry->reset();
1358 flags.do_next_read = false;
1359 closeServer();
1360 mustStop("HttpStateData::continueAfterParsingHeader");
1361 return false; // quit on error
1362}
1363
1366void
1368{
1370
1371 HttpReply *vrep = virginReply();
1372 int64_t clen = -1;
1373 if (!vrep->expectingBody(request->method, clen) || clen < 0)
1374 return; // no body or a body of unknown size, including chunked
1375
1376 if (payloadSeen - payloadTruncated <= clen)
1377 return; // we did not read too much or already took care of the extras
1378
1379 if (const int64_t extras = payloadSeen - payloadTruncated - clen) {
1380 // server sent more that the advertised content length
1381 debugs(11, 5, "payloadSeen=" << payloadSeen <<
1382 " clen=" << clen << '/' << vrep->content_length <<
1383 " truncated=" << payloadTruncated << '+' << extras);
1384
1385 inBuf.chop(0, inBuf.length() - extras);
1386 payloadTruncated += extras;
1387 }
1388}
1389
1391void
1393{
1394 const auto err = new ErrorState(ERR_READ_ERROR, Http::scBadGateway, fwd->request, fwd->al);
1395 static const auto d = MakeNamedErrorDetail("SRV_PREMATURE_EOF");
1396 err->detailError(d);
1397 fwd->fail(err);
1398}
1399
1404void
1406{
1407 truncateVirginBody(); // if needed
1408 const char *data = inBuf.rawContent();
1409 int len = inBuf.length();
1410 addVirginReplyBody(data, len);
1411 inBuf.consume(len);
1412
1413 // after addVirginReplyBody() wrote (when not adapting) everything we have
1414 // received to Store, check whether we have received/parsed the entire reply
1415 int64_t clen = -1;
1416 const char *parsedWhole = nullptr;
1417 if (!virginReply()->expectingBody(request->method, clen))
1418 parsedWhole = "http parsed header-only reply";
1419 else if (clen >= 0 && clen == payloadSeen - payloadTruncated)
1420 parsedWhole = "http parsed Content-Length body bytes";
1421 else if (clen < 0 && eof)
1422 parsedWhole = "http parsed body ending with expected/required EOF";
1423
1424 if (parsedWhole)
1425 markParsedVirginReplyAsWhole(parsedWhole);
1426 else if (eof)
1428}
1429
1430bool
1432{
1435 try {
1436 MemBuf decodedData;
1437 decodedData.init();
1438 httpChunkDecoder->setPayloadBuffer(&decodedData);
1439 const bool doneParsing = httpChunkDecoder->parse(inBuf);
1440 inBuf = httpChunkDecoder->remaining(); // sync buffers after parse
1441 addVirginReplyBody(decodedData.content(), decodedData.contentSize());
1442 if (doneParsing) {
1443 lastChunk = 1;
1444 flags.do_next_read = false;
1445 markParsedVirginReplyAsWhole("http parsed last-chunk");
1446 } else if (eof) {
1448 }
1449 return true;
1450 }
1451 catch (...) {
1452 debugs (11, 2, "de-chunking failure: " << CurrentException);
1453 }
1454 return false;
1455}
1456
1464void
1466{
1467 if (!flags.headers_parsed) {
1468 flags.do_next_read = true;
1470 return;
1471 }
1472
1473#if USE_ADAPTATION
1474 debugs(11,5, "adaptationAccessCheckPending=" << adaptationAccessCheckPending);
1476 return;
1477
1478#endif
1479
1480 /*
1481 * At this point the reply headers have been parsed and consumed.
1482 * That means header content has been removed from readBuf and
1483 * it contains only body data.
1484 */
1485 if (entry->isAccepting()) {
1486 if (flags.chunked) {
1487 if (!decodeAndWriteReplyBody()) {
1488 flags.do_next_read = false;
1490 return;
1491 }
1492 } else
1494 }
1495
1496 // storing/sending methods like earlier adaptOrFinalizeReply() or
1497 // above writeReplyBody() may release/abort the store entry.
1499 // TODO: In some cases (e.g., 304), we should keep persistent conn open.
1500 // Detect end-of-reply (and, hence, pool our idle pconn) earlier (ASAP).
1501 abortTransaction("store entry aborted while storing reply");
1502 return;
1503 } else
1504 switch (persistentConnStatus()) {
1505 case INCOMPLETE_MSG: {
1506 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG from " << serverConnection);
1507 /* Wait for more data or EOF condition */
1509 if (flags.keepalive_broken) {
1511 } else {
1513 }
1514
1515 flags.do_next_read = true;
1516 }
1517 break;
1518
1520 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG from " << serverConnection);
1521
1522 // TODO: Remove serverConnectionSaved but preserve exception safety.
1523
1525 flags.do_next_read = false;
1526
1528 closeHandler = nullptr;
1529
1530 Ip::Address client_addr; // XXX: Remove as unused. Why was it added?
1532 client_addr = request->client_addr;
1533
1534 auto serverConnectionSaved = serverConnection;
1536 serverConnection = nullptr;
1537
1538 bool ispinned = false; // TODO: Rename to isOrShouldBePinned
1539 if (request->flags.pinned) {
1540 ispinned = true;
1542 ispinned = true;
1543 }
1544
1545 if (ispinned) {
1549 notePinnedConnectionBecameIdle,
1550 ConnStateData::PinnedIdleContext(serverConnectionSaved, request));
1551 } else {
1552 // must not pool/share ispinned connections, even orphaned ones
1553 serverConnectionSaved->close();
1554 }
1555 } else {
1556 fwdPconnPool->push(serverConnectionSaved, request->url.host());
1557 }
1558
1560 return;
1561 }
1562
1564 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG from " << serverConnection);
1565
1567 return;
1568 }
1569
1571}
1572
1573bool
1575{
1576 // TODO: Be more precise here. For example, if/when reading trailer, we may
1577 // not be doneWithServer() yet, but we should return false. Similarly, we
1578 // could still be writing the request body after receiving the whole reply.
1579 return !doneWithServer();
1580}
1581
1582void
1584{
1585 // too late to read
1587 return;
1588
1589 if (!maybeMakeSpaceAvailable(false))
1590 return;
1591
1592 // XXX: get rid of the do_next_read flag
1593 // check for the proper reasons preventing read(2)
1594 if (!flags.do_next_read)
1595 return;
1596
1597 flags.do_next_read = false;
1598
1599 // must not already be waiting for read(2) ...
1601
1602 // wait for read(2) to be possible.
1604 AsyncCall::Pointer call = JobCallback(11, 5, Dialer, this, HttpStateData::readReply);
1606}
1607
1608bool
1610{
1611 // how much we are allowed to buffer
1612 const int limitBuffer = (flags.headers_parsed ? Config.readAheadGap : Config.maxReplyHeaderSize);
1613
1614 if (limitBuffer < 0 || inBuf.length() >= (SBuf::size_type)limitBuffer) {
1615 // when buffer is at or over limit already
1616 debugs(11, 7, "will not read up to " << limitBuffer << ". buffer has (" << inBuf.length() << "/" << inBuf.spaceSize() << ") from " << serverConnection);
1617 debugs(11, DBG_DATA, "buffer has {" << inBuf << "}");
1618 // Process next response from buffer
1619 processReply();
1620 return false;
1621 }
1622
1623 // how much we want to read
1624 const size_t read_size = calcBufferSpaceToReserve(inBuf.spaceSize(), (limitBuffer - inBuf.length()));
1625
1626 if (!read_size) {
1627 debugs(11, 7, "will not read up to " << read_size << " into buffer (" << inBuf.length() << "/" << inBuf.spaceSize() << ") from " << serverConnection);
1628 return false;
1629 }
1630
1631 // just report whether we could grow or not, do not actually do it
1632 if (doGrow)
1633 return (read_size >= 2);
1634
1635 // we may need to grow the buffer
1636 inBuf.reserveSpace(read_size);
1637 debugs(11, 8, (!flags.do_next_read ? "will not" : "may") <<
1638 " read up to " << read_size << " bytes info buf(" << inBuf.length() << "/" << inBuf.spaceSize() <<
1639 ") from " << serverConnection);
1640
1641 return (inBuf.spaceSize() >= 2); // only read if there is 1+ bytes of space available
1642}
1643
1645void
1647{
1648 debugs(11, 5, serverConnection << ": size " << io.size << ": errflag " << io.flag << ".");
1649#if URL_CHECKSUM_DEBUG
1650
1651 entry->mem_obj->checkUrlChecksum();
1652#endif
1653
1654 // XXX: Keep in sync with Client::sentRequestBody().
1655 // TODO: Extract common parts.
1656
1657 if (io.size > 0) {
1658 fd_bytes(io.fd, io.size, FD_WRITE);
1661 }
1662
1663 if (io.flag == Comm::ERR_CLOSING)
1664 return;
1665
1666 // both successful and failed writes affect response times
1668
1669 if (io.flag) {
1670 const auto err = new ErrorState(ERR_WRITE_ERROR, Http::scBadGateway, fwd->request, fwd->al);
1671 err->xerrno = io.xerrno;
1672 fwd->fail(err);
1673 closeServer();
1674 mustStop("HttpStateData::wroteLast");
1675 return;
1676 }
1677
1678 sendComplete();
1679}
1680
1682void
1684{
1685 /*
1686 * Set the read timeout here because it hasn't been set yet.
1687 * We only set the read timeout after the request has been
1688 * fully written to the peer. If we start the timeout
1689 * after connection establishment, then we are likely to hit
1690 * the timeout for POST/PUT requests that have very large
1691 * request bodies.
1692 */
1694 AsyncCall::Pointer timeoutCall = JobCallback(11, 5,
1695 TimeoutDialer, this, HttpStateData::httpTimeout);
1696
1698 flags.request_sent = true;
1699}
1700
1701void
1703{
1704 debugs(11,5, "closing HTTP server " << serverConnection << " this " << this);
1705
1709 closeHandler = nullptr;
1711 }
1712}
1713
1714bool
1716{
1718}
1719
1720/*
1721 * Fixup authentication request headers for special cases
1722 */
1723static void
1724httpFixupAuthentication(HttpRequest * request, const HttpHeader * hdr_in, HttpHeader * hdr_out, const Http::StateFlags &flags)
1725{
1726 /* Nothing to do unless we are forwarding to a peer */
1727 if (!flags.peering)
1728 return;
1729
1730 // This request is going "through" rather than "to" our _peer.
1731 if (flags.tunneling)
1732 return;
1733
1734 /* Needs to be explicitly enabled */
1735 if (!request->peer_login)
1736 return;
1737
1739 /* Maybe already dealt with? */
1740 if (hdr_out->has(header))
1741 return;
1742
1743 /* Nothing to do here for PASSTHRU */
1744 if (strcmp(request->peer_login, "PASSTHRU") == 0)
1745 return;
1746
1747 // Dangerous and undocumented PROXYPASS is a single-signon to servers with
1748 // the proxy password. Only Basic Authentication can work this way. This
1749 // statement forwards a "basic" Proxy-Authorization value from our client
1750 // to an originserver peer. Other PROXYPASS cases are handled lower.
1751 if (flags.toOrigin &&
1752 strcmp(request->peer_login, "PROXYPASS") == 0 &&
1754
1755 const char *auth = hdr_in->getStr(Http::HdrType::PROXY_AUTHORIZATION);
1756
1757 if (auth && strncasecmp(auth, "basic ", 6) == 0) {
1758 hdr_out->putStr(header, auth);
1759 return;
1760 }
1761 }
1762
1763 char loginbuf[base64_encode_len(MAX_LOGIN_SZ)];
1764 size_t blen;
1765 struct base64_encode_ctx ctx;
1766 base64_encode_init(&ctx);
1767
1768 /* Special mode to pass the username to the upstream cache */
1769 if (*request->peer_login == '*') {
1770 const char *username = "-";
1771
1772 if (request->extacl_user.size())
1773 username = request->extacl_user.termedBuf();
1774#if USE_AUTH
1775 else if (request->auth_user_request != nullptr)
1776 username = request->auth_user_request->username();
1777#endif
1778
1779 blen = base64_encode_update(&ctx, loginbuf, strlen(username), reinterpret_cast<const uint8_t*>(username));
1780 blen += base64_encode_update(&ctx, loginbuf+blen, strlen(request->peer_login +1), reinterpret_cast<const uint8_t*>(request->peer_login +1));
1781 blen += base64_encode_final(&ctx, loginbuf+blen);
1782 httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf);
1783 return;
1784 }
1785
1786 /* external_acl provided credentials */
1787 if (request->extacl_user.size() && request->extacl_passwd.size() &&
1788 (strcmp(request->peer_login, "PASS") == 0 ||
1789 strcmp(request->peer_login, "PROXYPASS") == 0)) {
1790
1791 blen = base64_encode_update(&ctx, loginbuf, request->extacl_user.size(), reinterpret_cast<const uint8_t*>(request->extacl_user.rawBuf()));
1792 blen += base64_encode_update(&ctx, loginbuf+blen, 1, reinterpret_cast<const uint8_t*>(":"));
1793 blen += base64_encode_update(&ctx, loginbuf+blen, request->extacl_passwd.size(), reinterpret_cast<const uint8_t*>(request->extacl_passwd.rawBuf()));
1794 blen += base64_encode_final(&ctx, loginbuf+blen);
1795 httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf);
1796 return;
1797 }
1798 // if no external user credentials are available to fake authentication with PASS acts like PASSTHRU
1799 if (strcmp(request->peer_login, "PASS") == 0)
1800 return;
1801
1802 /* Kerberos login to peer */
1803#if HAVE_AUTH_MODULE_NEGOTIATE && HAVE_KRB5 && HAVE_GSSAPI
1804 if (strncmp(request->peer_login, "NEGOTIATE",strlen("NEGOTIATE")) == 0) {
1805 char *Token=nullptr;
1806 char *PrincipalName=nullptr,*p;
1807 int negotiate_flags = 0;
1808
1809 if ((p=strchr(request->peer_login,':')) != nullptr ) {
1810 PrincipalName=++p;
1811 }
1812 if (request->flags.auth_no_keytab) {
1813 negotiate_flags |= PEER_PROXY_NEGOTIATE_NOKEYTAB;
1814 }
1815 Token = peer_proxy_negotiate_auth(PrincipalName, request->peer_host, negotiate_flags);
1816 if (Token) {
1817 httpHeaderPutStrf(hdr_out, header, "Negotiate %s",Token);
1818 }
1819 return;
1820 }
1821#endif /* HAVE_KRB5 && HAVE_GSSAPI */
1822
1823 blen = base64_encode_update(&ctx, loginbuf, strlen(request->peer_login), reinterpret_cast<const uint8_t*>(request->peer_login));
1824 blen += base64_encode_final(&ctx, loginbuf+blen);
1825 httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf);
1826 return;
1827}
1828
1829/*
1830 * build request headers and append them to a given MemBuf
1831 * used by buildRequestPrefix()
1832 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
1833 */
1834void
1836 StoreEntry * entry,
1837 const AccessLogEntryPointer &al,
1838 HttpHeader * hdr_out,
1839 const Http::StateFlags &flags)
1840{
1841 /* building buffer for complex strings */
1842#define BBUF_SZ (MAX_URL+32)
1843 LOCAL_ARRAY(char, bbuf, BBUF_SZ);
1844 LOCAL_ARRAY(char, ntoabuf, MAX_IPSTRLEN);
1845 const HttpHeader *hdr_in = &request->header;
1846 const HttpHeaderEntry *e = nullptr;
1848 assert (hdr_out->owner == hoRequest);
1849
1850 /* use our IMS header if the cached entry has Last-Modified time */
1851 if (request->lastmod > -1)
1853
1854 // Add our own If-None-Match field if the cached entry has a strong ETag.
1855 // copyOneHeaderFromClientsideRequestToUpstreamRequest() adds client ones.
1856 if (request->etag.size() > 0) {
1858 request->etag.termedBuf()));
1859 }
1860
1861 bool we_do_ranges = decideIfWeDoRanges (request);
1862
1863 String strConnection (hdr_in->getList(Http::HdrType::CONNECTION));
1864
1865 while ((e = hdr_in->getEntry(&pos)))
1866 copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, hdr_out, we_do_ranges, flags);
1867
1868 /* Abstraction break: We should interpret multipart/byterange responses
1869 * into offset-length data, and this works around our inability to do so.
1870 */
1871 if (!we_do_ranges && request->multipartRangeRequest()) {
1872 /* don't cache the result */
1874 /* pretend it's not a range request */
1875 request->ignoreRange("want to request the whole object");
1876 request->flags.isRanged = false;
1877 }
1878
1879 hdr_out->addVia(request->http_ver, hdr_in);
1880
1881 if (request->flags.accelerated) {
1882 /* Append Surrogate-Capabilities */
1883 String strSurrogate(hdr_in->getList(Http::HdrType::SURROGATE_CAPABILITY));
1884#if USE_SQUID_ESI
1885 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"", Config.Accel.surrogate_id);
1886#else
1887 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0\"", Config.Accel.surrogate_id);
1888#endif
1889 strListAdd(&strSurrogate, bbuf, ',');
1890 hdr_out->putStr(Http::HdrType::SURROGATE_CAPABILITY, strSurrogate.termedBuf());
1891 }
1892
1894 if (strcmp(opt_forwarded_for, "delete") != 0) {
1895
1897
1898 // if we cannot double strFwd size, then it grew past 50% of the limit
1899 if (!strFwd.canGrowBy(strFwd.size())) {
1900 // There is probably a forwarding loop with Via detection disabled.
1901 // If we do nothing, String will assert on overflow soon.
1902 // TODO: Terminate all transactions with huge XFF?
1903 strFwd = "error";
1904
1905 static int warnedCount = 0;
1906 if (warnedCount++ < 100) {
1907 const SBuf url(entry ? SBuf(entry->url()) : request->effectiveRequestUri());
1908 debugs(11, DBG_IMPORTANT, "WARNING: likely forwarding loop with " << url);
1909 }
1910 }
1911
1912 if (strcmp(opt_forwarded_for, "on") == 0) {
1914 if ( request->client_addr.isNoAddr() )
1915 strListAdd(&strFwd, "unknown", ',');
1916 else
1917 strListAdd(&strFwd, request->client_addr.toStr(ntoabuf, MAX_IPSTRLEN), ',');
1918 } else if (strcmp(opt_forwarded_for, "off") == 0) {
1920 strListAdd(&strFwd, "unknown", ',');
1921 } else if (strcmp(opt_forwarded_for, "transparent") == 0) {
1923 } else if (strcmp(opt_forwarded_for, "truncate") == 0) {
1925 if ( request->client_addr.isNoAddr() )
1926 strFwd = "unknown";
1927 else
1928 strFwd = request->client_addr.toStr(ntoabuf, MAX_IPSTRLEN);
1929 }
1930 if (strFwd.size() > 0)
1932 }
1935 /* append Host if not there already */
1936 if (!hdr_out->has(Http::HdrType::HOST)) {
1937 if (request->peer_domain) {
1939 } else {
1940 SBuf authority = request->url.authority();
1941 hdr_out->putStr(Http::HdrType::HOST, authority.c_str());
1942 }
1943 }
1944
1945 /* append Authorization if known in URL, not in header and going direct */
1946 if (!hdr_out->has(Http::HdrType::AUTHORIZATION)) {
1947 if (flags.toOrigin && !request->url.userInfo().isEmpty()) {
1948 static char result[base64_encode_len(MAX_URL*2)]; // should be big enough for a single URI segment
1949 struct base64_encode_ctx ctx;
1950 base64_encode_init(&ctx);
1951 size_t blen = base64_encode_update(&ctx, result, request->url.userInfo().length(), reinterpret_cast<const uint8_t*>(request->url.userInfo().rawContent()));
1952 blen += base64_encode_final(&ctx, result+blen);
1953 result[blen] = '\0';
1954 if (blen)
1955 httpHeaderPutStrf(hdr_out, Http::HdrType::AUTHORIZATION, "Basic %.*s", (int)blen, result);
1956 }
1957 }
1958
1959 /* Fixup (Proxy-)Authorization special cases. Plain relaying dealt with above */
1960 httpFixupAuthentication(request, hdr_in, hdr_out, flags);
1961
1962 /* append Cache-Control, add max-age if not there already */
1963 {
1964 HttpHdrCc *cc = hdr_in->getCc();
1965
1966 if (!cc)
1967 cc = new HttpHdrCc();
1968
1969 /* Add max-age only without no-cache */
1970 if (!cc->hasMaxAge() && !cc->hasNoCache()) {
1971 // XXX: performance regression. c_str() reallocates
1973 cc->maxAge(getMaxAge(entry ? entry->url() : tmp.c_str()));
1974 }
1975
1976 /* Enforce sibling relations */
1978 cc->onlyIfCached(true);
1979
1980 hdr_out->putCc(*cc);
1981
1982 delete cc;
1983 }
1984
1985 // Always send Connection because HTTP/1.0 servers need explicit
1986 // "keep-alive", HTTP/1.1 servers need explicit "close", Upgrade recipients
1987 // need bare "upgrade", and we do not always know the server expectations.
1988 if (!hdr_out->has(Http::HdrType::CONNECTION)) // forwardUpgrade() may add it
1989 hdr_out->putStr(Http::HdrType::CONNECTION, flags.keepalive ? "keep-alive" : "close");
1990
1991 /* append Front-End-Https */
1992 if (flags.front_end_https) {
1994 hdr_out->putStr(Http::HdrType::FRONT_END_HTTPS, "On");
1995 }
1996
1997 if (flags.chunked_request) {
1998 // Do not just copy the original value so that if the client-side
1999 // starts decode other encodings, this code may remain valid.
2000 hdr_out->putStr(Http::HdrType::TRANSFER_ENCODING, "chunked");
2001 }
2002
2003 /* Now mangle the headers. */
2004 httpHdrMangleList(hdr_out, request, al, ROR_REQUEST);
2005
2006 strConnection.clean();
2007}
2008
2011void
2013{
2015 return; // forward nothing by default
2016
2017 /* RFC 7230 section 6.7 paragraph 10:
2018 * A server MUST ignore an Upgrade header field that is received in
2019 * an HTTP/1.0 request.
2020 */
2022 return;
2023
2024 const auto &hdrIn = request->header;
2025 if (!hdrIn.has(Http::HdrType::UPGRADE))
2026 return;
2027 const auto upgradeIn = hdrIn.getList(Http::HdrType::UPGRADE);
2028
2029 String upgradeOut;
2030
2031 ACLFilledChecklist ch(nullptr, request.getRaw());
2032 ch.al = fwd->al;
2033 const char *pos = nullptr;
2034 const char *offeredStr = nullptr;
2035 int offeredStrLen = 0;
2036 while (strListGetItem(&upgradeIn, ',', &offeredStr, &offeredStrLen, &pos)) {
2037 const ProtocolView offeredProto(offeredStr, offeredStrLen);
2038 debugs(11, 5, "checks all rules applicable to " << offeredProto);
2039 Config.http_upgrade_request_protocols->forApplicable(offeredProto, [&ch, offeredStr, offeredStrLen, &upgradeOut] (const SBuf &cfgProto, const acl_access *guard) {
2040 debugs(11, 5, "checks " << cfgProto << " rule(s)");
2041 ch.changeAcl(guard);
2042 const auto answer = ch.fastCheck();
2043 if (answer.implicit)
2044 return false; // keep looking for an explicit rule match
2045 if (answer.allowed())
2046 strListAdd(upgradeOut, offeredStr, offeredStrLen);
2047 // else drop the offer (explicitly denied cases and ACL errors)
2048 return true; // stop after an explicit rule match or an error
2049 });
2050 }
2051
2052 if (upgradeOut.size()) {
2053 hdrOut.putStr(Http::HdrType::UPGRADE, upgradeOut.termedBuf());
2054
2055 /* RFC 7230 section 6.7 paragraph 10:
2056 * When Upgrade is sent, the sender MUST also send a Connection header
2057 * field that contains an "upgrade" connection option, in
2058 * order to prevent Upgrade from being accidentally forwarded by
2059 * intermediaries that might not implement the listed protocols.
2060 *
2061 * NP: Squid does not truly implement the protocol(s) in this Upgrade.
2062 * For now we are treating an explicit blind tunnel as "implemented"
2063 * regardless of the security implications.
2064 */
2065 hdrOut.putStr(Http::HdrType::CONNECTION, "upgrade");
2066
2067 // Connection:close and Connection:keepalive confuse some Upgrade
2068 // recipients, so we do not send those headers. Our Upgrade request
2069 // implicitly offers connection persistency per HTTP/1.1 defaults.
2070 // Update the keepalive flag to reflect that offer.
2071 // * If the server upgrades, then we would not be talking HTTP past the
2072 // HTTP 101 control message, and HTTP persistence would be irrelevant.
2073 // * Otherwise, our request will contradict onoff.server_pconns=off or
2074 // other no-keepalive conditions (if any). We compensate by copying
2075 // the original no-keepalive decision now and honoring it later.
2077 flags.keepalive = true; // should already be true in most cases
2078 }
2079}
2080
2085void
2086copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request, HttpHeader * hdr_out, const int we_do_ranges, const Http::StateFlags &flags)
2087{
2088 debugs(11, 5, "httpBuildRequestHeader: " << e->name << ": " << e->value );
2089
2090 switch (e->id) {
2091
2099 if (!flags.toOrigin && request->peer_login &&
2100 (strcmp(request->peer_login, "PASS") == 0 ||
2101 strcmp(request->peer_login, "PROXYPASS") == 0 ||
2102 strcmp(request->peer_login, "PASSTHRU") == 0)) {
2103 hdr_out->addEntry(e->clone());
2104 }
2105 break;
2106
2110 case Http::HdrType::TE:
2115 break;
2116
2119 break;
2120
2127 if (!flags.toOriginPeer()) {
2128 hdr_out->addEntry(e->clone());
2129 } else {
2134 if (request->peer_login &&
2135 (strcmp(request->peer_login, "PASS") == 0 ||
2136 strcmp(request->peer_login, "PASSTHRU") == 0 ||
2137 strcmp(request->peer_login, "PROXYPASS") == 0)) {
2138 hdr_out->addEntry(e->clone());
2139 }
2140 }
2141
2142 break;
2143
2151 if (request->peer_domain)
2152 hdr_out->putStr(Http::HdrType::HOST, request->peer_domain);
2153 else if (request->flags.redirected && !Config.onoff.redir_rewrites_host)
2154 hdr_out->addEntry(e->clone());
2155 else {
2156 SBuf authority = request->url.authority();
2157 hdr_out->putStr(Http::HdrType::HOST, authority.c_str());
2158 }
2159
2160 break;
2161
2170 // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
2172 break;
2173 else if (Config.onoff.cache_miss_revalidate || !request->flags.cachable || request->flags.auth)
2174 hdr_out->addEntry(e->clone());
2175 break;
2176
2185 // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
2186 if (hdr_out->hasListMember(Http::HdrType::IF_MATCH, "*", ',') || Config.onoff.cache_miss_revalidate || !request->flags.cachable || request->flags.auth)
2187 hdr_out->addEntry(e->clone());
2188 break;
2189
2193 if (request->method == Http::METHOD_TRACE || request->method == Http::METHOD_OPTIONS) {
2194 const int64_t hops = e->getInt64();
2195
2196 if (hops > 0)
2197 hdr_out->putInt64(Http::HdrType::MAX_FORWARDS, hops - 1);
2198 }
2199
2200 break;
2201
2202 case Http::HdrType::VIA:
2207 if (!Config.onoff.via)
2208 hdr_out->addEntry(e->clone());
2209
2210 break;
2211
2213
2215
2219 if (!we_do_ranges)
2220 hdr_out->addEntry(e->clone());
2221
2222 break;
2223
2224 case Http::HdrType::PROXY_CONNECTION: // SHOULD ignore. But doing so breaks things.
2225 break;
2226
2228 // pass through unless we chunk; also, keeping this away from default
2229 // prevents request smuggling via Connection: Content-Length tricks
2230 if (!flags.chunked_request)
2231 hdr_out->addEntry(e->clone());
2232 break;
2233
2235
2240 break;
2241
2245 if (!flags.front_end_https)
2246 hdr_out->addEntry(e->clone());
2247
2248 break;
2249
2250 default:
2254 if (strConnection.size()>0 && strListIsMember(&strConnection, e->name, ',')) {
2255 debugs(11, 2, "'" << e->name << "' header cropped by Connection: definition");
2256 return;
2257 }
2258
2259 hdr_out->addEntry(e->clone());
2260 }
2261}
2262
2263bool
2265{
2266 bool result = true;
2267 /* decide if we want to do Ranges ourselves
2268 * and fetch the whole object now)
2269 * We want to handle Ranges ourselves iff
2270 * - we can actually parse client Range specs
2271 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
2272 * - reply will be cachable
2273 * (If the reply will be uncachable we have to throw it away after
2274 * serving this request, so it is better to forward ranges to
2275 * the server and fetch only the requested content)
2276 */
2277
2278 int64_t roffLimit = request->getRangeOffsetLimit();
2279
2280 if (nullptr == request->range || !request->flags.cachable
2282 result = false;
2283
2284 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
2285 request->range << ", cachable: " <<
2286 request->flags.cachable << "; we_do_ranges: " << result);
2287
2288 return result;
2289}
2290
2291/* build request prefix and append it to a given MemBuf;
2292 * return the length of the prefix */
2295{
2296 const int offset = mb->size;
2297 /* Uses a local httpver variable to print the HTTP label
2298 * since the HttpRequest may have an older version label.
2299 * XXX: This could create protocol bugs as the headers sent and
2300 * flow control should all be based on the HttpRequest version
2301 * not the one we are sending. Needs checking.
2302 */
2305 mb->appendf(SQUIDSBUFPH " " SQUIDSBUFPH " %s/%d.%d\r\n",
2307 SQUIDSBUFPRINT(url),
2309 httpver.major,httpver.minor);
2310 /* build and pack headers */
2311 {
2312 HttpHeader hdr(hoRequest);
2313 forwardUpgrade(hdr); // before httpBuildRequestHeader() for CONNECTION
2315
2317 request->flags.authSent = true;
2318 else if (hdr.has(Http::HdrType::AUTHORIZATION))
2319 request->flags.authSent = true;
2320
2321 // The late placement of this check supports reply_header_add mangling,
2322 // but also complicates optimizing upgradeHeaderOut-like lookups.
2323 if (hdr.has(Http::HdrType::UPGRADE)) {
2326 }
2327
2328 hdr.packInto(mb);
2329 hdr.clean();
2330 }
2331 /* append header terminator */
2332 mb->append(crlf, 2);
2333 return mb->size - offset;
2334}
2335
2336/* This will be called when connect completes. Write request. */
2337bool
2339{
2340 MemBuf mb;
2341
2342 debugs(11, 5, serverConnection << ", request " << request << ", this " << this << ".");
2343
2345 debugs(11,3, "cannot send request to closing " << serverConnection);
2346 assert(closeHandler != nullptr);
2347 return false;
2348 }
2349
2351 AsyncCall::Pointer timeoutCall = JobCallback(11, 5,
2352 TimeoutDialer, this, HttpStateData::httpTimeout);
2354 flags.do_next_read = true;
2356
2357 if (request->body_pipe != nullptr) {
2358 if (!startRequestBodyFlow()) // register to receive body data
2359 return false;
2362 Dialer, this, HttpStateData::sentRequestBody);
2363
2365 // use chunked encoding if we do not know the length
2366 if (request->content_length < 0)
2367 flags.chunked_request = true;
2368 } else {
2372 Dialer, this, HttpStateData::wroteLast);
2373 }
2374
2375 /*
2376 * Is keep-alive okay for all request methods?
2377 */
2379 flags.keepalive = true;
2380 else if (request->flags.pinned)
2382 else if (!Config.onoff.server_pconns)
2383 flags.keepalive = false;
2384 else if (flags.tunneling)
2385 // tunneled non pinned bumped requests must not keepalive
2387 else if (_peer == nullptr)
2388 flags.keepalive = true;
2389 else if (_peer->stats.n_keepalives_sent < 10)
2390 flags.keepalive = true;
2391 else if ((double) _peer->stats.n_keepalives_recv /
2392 (double) _peer->stats.n_keepalives_sent > 0.50)
2393 flags.keepalive = true;
2394
2395 if (_peer && !flags.tunneling) {
2396 /*The old code here was
2397 if (neighborType(_peer, request->url) == PEER_SIBLING && ...
2398 which is equivalent to:
2399 if (neighborType(_peer, URL()) == PEER_SIBLING && ...
2400 or better:
2401 if (((_peer->type == PEER_MULTICAST && p->options.mcast_siblings) ||
2402 _peer->type == PEER_SIBLINGS ) && _peer->options.allow_miss)
2403 flags.only_if_cached = 1;
2404
2405 But I suppose it was a bug
2406 */
2408 flags.only_if_cached = true;
2409
2411 }
2412
2413 mb.init();
2414 request->peer_host=_peer?_peer->host:nullptr;
2415 buildRequestPrefix(&mb);
2416
2417 debugs(11, 2, "HTTP Server " << serverConnection);
2418 debugs(11, 2, "HTTP Server REQUEST:\n---------\n" << mb.buf << "\n----------");
2419
2421 return true;
2422}
2423
2424bool
2426{
2427 // parent's implementation can handle the no-encoding case
2429 return Client::getMoreRequestBody(buf);
2430
2431 MemBuf raw;
2432
2433 Must(requestBodySource != nullptr);
2434 if (!requestBodySource->getMoreData(raw))
2435 return false; // no request body bytes to chunk yet
2436
2437 // optimization: pre-allocate buffer size that should be enough
2438 const mb_size_t rawDataSize = raw.contentSize();
2439 // we may need to send: hex-chunk-size CRLF raw-data CRLF last-chunk
2440 buf.init(16 + 2 + rawDataSize + 2 + 5, raw.max_capacity);
2441
2442 buf.appendf("%x\r\n", static_cast<unsigned int>(rawDataSize));
2443 buf.append(raw.content(), rawDataSize);
2444 buf.append("\r\n", 2);
2445
2446 Must(rawDataSize > 0); // we did not accidentally created last-chunk above
2447
2448 // Do not send last-chunk unless we successfully received everything
2451 flags.sentLastChunk = true;
2452 buf.append("0\r\n\r\n", 5);
2453 }
2454
2455 return true;
2456}
2457
2458void
2460{
2461 debugs(11, 3, fwd->request->method << ' ' << fwd->entry->url());
2463}
2464
2465void
2467{
2468 if (!sendRequest()) {
2469 debugs(11, 3, "httpStart: aborted");
2470 mustStop("HttpStateData::start failed");
2471 return;
2472 }
2473
2476
2477 /*
2478 * We used to set the read timeout here, but not any more.
2479 * Now its set in httpSendComplete() after the full request,
2480 * including request body, has been written to the server.
2481 */
2482}
2483
2485bool
2487{
2488#if USE_HTTP_VIOLATIONS
2490 debugs(11, 5, "No brokenPosts list");
2491 return false;
2492 }
2493
2495 ch.al = fwd->al;
2496 ch.syncAle(originalRequest().getRaw(), nullptr);
2497 if (!ch.fastCheck().allowed()) {
2498 debugs(11, 5, "didn't match brokenPosts");
2499 return false;
2500 }
2501
2503 debugs(11, 3, "ignoring broken POST for closed " << serverConnection);
2504 assert(closeHandler != nullptr);
2505 return true; // prevent caller from proceeding as if nothing happened
2506 }
2507
2508 debugs(11, 3, "finishingBrokenPost: fixing broken POST");
2511 Dialer, this, HttpStateData::wroteLast);
2512 Comm::Write(serverConnection, "\r\n", 2, requestSender, nullptr);
2513 return true;
2514#else
2515 return false;
2516#endif /* USE_HTTP_VIOLATIONS */
2517}
2518
2520bool
2522{
2523 if (flags.sentLastChunk) {
2524 debugs(11, 5, "already sent last-chunk");
2525 return false;
2526 }
2527
2528 Must(receivedWholeRequestBody); // or we should not be sending last-chunk
2529 flags.sentLastChunk = true;
2530
2532 requestSender = JobCallback(11,5, Dialer, this, HttpStateData::wroteLast);
2533 Comm::Write(serverConnection, "0\r\n\r\n", 5, requestSender, nullptr);
2534 return true;
2535}
2536
2537void
2539{
2541 debugs(11,5, serverConnection);
2542
2543 // do we need to write something after the last body byte?
2545 return;
2547 return;
2548
2549 sendComplete();
2550}
2551
2552// more origin request body data is available
2553void
2555{
2557 // XXX: we should check this condition in other callbacks then!
2558 // TODO: Check whether this can actually happen: We should unsubscribe
2559 // as a body consumer when the above condition(s) are detected.
2560 debugs(11, DBG_IMPORTANT, "Transaction aborted while reading HTTP body");
2561 return;
2562 }
2563
2564 assert(requestBodySource != nullptr);
2565
2566 if (requestBodySource->buf().hasContent()) {
2567 // XXX: why does not this trigger a debug message on every request?
2568
2570 flags.abuse_detected = true;
2571 debugs(11, DBG_IMPORTANT, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << request->client_addr << "' -> '" << entry->url() << "'" );
2572
2573 if (virginReply()->sline.status() == Http::scInvalidHeader) {
2574 closeServer();
2575 mustStop("HttpStateData::handleMoreRequestBodyAvailable");
2576 return;
2577 }
2578 }
2579 }
2580
2582}
2583
2584// premature end of the request body
2585void
2587{
2589 if (entry->isEmpty()) {
2590 debugs(11, 3, "request body aborted: " << serverConnection);
2591 // We usually get here when ICAP REQMOD aborts during body processing.
2592 // We might also get here if client-side aborts, but then our response
2593 // should not matter because either client-side will provide its own or
2594 // there will be no response at all (e.g., if the the client has left).
2596 static const auto d = MakeNamedErrorDetail("SRV_REQMOD_REQ_BODY");
2597 err->detailError(d);
2598 fwd->fail(err);
2599 }
2600
2601 abortTransaction("request body producer aborted");
2602}
2603
2604// called when we wrote request headers(!) or a part of the body
2605void
2607{
2608 if (io.size > 0)
2610
2612}
2613
2614void
2615HttpStateData::abortAll(const char *reason)
2616{
2617 debugs(11,5, "aborting transaction for " << reason <<
2618 "; " << serverConnection << ", this " << this);
2619 mustStop(reason);
2620}
2621
2623 : answer(HttpStateData::ReuseDecision::reuseNot), reason(nullptr), entry(e), statusCode(code) {}
2624
2627{
2628 answer = ans;
2629 reason = why;
2630 return answer;
2631}
2632
2633std::ostream &operator <<(std::ostream &os, const HttpStateData::ReuseDecision &d)
2634{
2635 static const char *ReuseMessages[] = {
2636 "do not cache and do not share", // reuseNot
2637 "cache positively and share", // cachePositively
2638 "cache negatively and share", // cacheNegatively
2639 "do not cache but share" // doNotCacheButShare
2640 };
2641
2644 return os << ReuseMessages[d.answer] << " because " << d.reason <<
2645 "; HTTP status " << d.statusCode << " " << *(d.entry);
2646}
2647
#define ScheduleCallHere(call)
Definition: AsyncCall.h:166
RefCount< AsyncCallT< Dialer > > asyncCall(int aDebugSection, int aDebugLevel, const char *aName, const Dialer &aDialer)
Definition: AsyncCall.h:156
#define JobCallback(dbgSection, dbgLevel, Dialer, job, method)
Convenience macro to create a Dialer-based job callback.
Definition: AsyncJobCalls.h:69
#define CallJobHere(debugSection, debugLevel, job, Class, method)
Definition: AsyncJobCalls.h:58
#define CallJobHere1(debugSection, debugLevel, job, Class, method, arg1)
Definition: AsyncJobCalls.h:63
ErrorDetail::Pointer MakeNamedErrorDetail(const char *name)
Definition: Detail.cc:54
PconnPool * fwdPconnPool
a collection of previously used persistent Squid-to-peer HTTP(S) connections
Definition: FwdState.cc:78
void httpHeaderPutStrf(HttpHeader *hdr, Http::HdrType id, const char *fmt,...)
void httpHdrMangleList(HttpHeader *l, HttpRequest *request, const AccessLogEntryPointer &al, req_or_rep_t req_or_rep)
bool httpHeaderHasConnDir(const HttpHeader *hdr, const SBuf &directive)
@ ROR_REQUEST
@ hoRequest
Definition: HttpHeader.h:36
ssize_t HttpHeaderPos
Definition: HttpHeader.h:45
#define HttpHeaderInitPos
Definition: HttpHeader.h:48
ssize_t mb_size_t
Definition: MemBuf.h:17
time_t squid_curtime
Definition: stub_libtime.cc:20
#define SQUIDSBUFPH
Definition: SBuf.h:31
#define SQUIDSBUFPRINT(s)
Definition: SBuf.h:32
class SquidConfig Config
Definition: SquidConfig.cc:12
StatCounters statCounter
Definition: StatCounters.cc:12
int strListGetItem(const String *str, char del, const char **item, int *ilen, const char **pos)
Definition: StrList.cc:86
void strListAdd(String &str, const char *item, const size_t itemSize, const char delimiter)
Appends the given item of a given size to a delimiter-separated list in str.
Definition: StrList.cc:18
int strListIsMember(const String *list, const SBuf &m, char del)
Definition: StrList.cc:46
std::ostream & CurrentException(std::ostream &os)
prints active (i.e., thrown but not yet handled) exception
#define Must(condition)
Definition: TextException.h:75
void error(char *format,...)
#define acl_access
Definition: forward.h:45
#define assert(EX)
Definition: assert.h:17
void base64_encode_init(struct base64_encode_ctx *ctx)
Definition: base64.c:232
size_t base64_encode_update(struct base64_encode_ctx *ctx, char *dst, size_t length, const uint8_t *src)
Definition: base64.c:265
size_t base64_encode_final(struct base64_encode_ctx *ctx, char *dst)
Definition: base64.c:308
#define base64_encode_len(length)
Definition: base64.h:169
#define cbdataReferenceDone(var)
Definition: cbdata.h:352
#define cbdataReference(var)
Definition: cbdata.h:343
#define CBDATA_CLASS_INIT(type)
Definition: cbdata.h:320
const Acl::Tree * changeAcl(const Acl::Tree *t)
Definition: Checklist.h:176
Acl::Answer const & fastCheck()
Definition: Checklist.cc:332
AccessLogEntry::Pointer al
info for the future access.log, and external ACL
void syncAle(HttpRequest *adaptedRequest, const char *logUri) const override
assigns uninitialized adapted_request and url ALE components
HttpReplyPointer reply
bool allowed() const
Definition: Acl.h:156
unsigned int major
major version number
ProtocolType protocol
which protocol this version is for
unsigned int minor
minor version number
AnyP::UriScheme const & getScheme() const
Definition: Uri.h:67
SBuf & authority(bool requirePort=false) const
Definition: Uri.cc:646
void path(const char *p)
Definition: Uri.h:101
void host(const char *src)
Definition: Uri.cc:100
void userInfo(const SBuf &s)
Definition: Uri.h:79
static void Start(const Pointer &job)
Definition: AsyncJob.cc:37
void mustStop(const char *aReason)
Definition: AsyncJob.cc:85
char const * username() const
Definition: UserRequest.cc:32
size_t getMoreData(MemBuf &buf)
Definition: BodyPipe.cc:294
const MemBuf & buf() const
Definition: BodyPipe.h:137
int n_keepalives_recv
Definition: CachePeer.h:78
int n_keepalives_sent
Definition: CachePeer.h:77
struct CachePeer::@28 options
bool originserver
Definition: CachePeer.h:143
int connection_auth
0 - off, 1 - on, 2 - auto
Definition: CachePeer.h:224
bool proxy_only
Definition: CachePeer.h:108
char * host
Definition: CachePeer.h:65
int front_end_https
0 - off, 1 - on, 2 - auto
Definition: CachePeer.h:223
struct CachePeer::@26 stats
bool allow_miss
Definition: CachePeer.h:129
bool no_delay
Definition: CachePeer.h:127
Cbc * valid() const
was set and is valid
Definition: CbcPointer.h:41
Definition: Client.h:35
const char * doneWithFwd
Definition: Client.h:199
bool adaptationAccessCheckPending
Definition: Client.h:189
bool receivedWholeRequestBody
handleRequestBodyProductionEnded called
Definition: Client.h:195
BodyPipe::Pointer requestBodySource
Definition: Client.h:181
AsyncCall::Pointer requestSender
Definition: Client.h:182
void serverComplete()
Definition: Client.cc:180
void delayRead()
Definition: Client.cc:1029
virtual HttpRequestPointer originalRequest()
a hack to reach HttpStateData::orignal_request
Definition: Client.cc:570
const HttpReply * virginReply() const
Definition: Client.cc:109
virtual bool getMoreRequestBody(MemBuf &buf)
either fill buf with available [encoded] request body bytes or return false
Definition: Client.cc:438
virtual void handleRequestBodyProducerAborted()=0
Definition: Client.cc:351
bool startRequestBodyFlow()
Definition: Client.cc:239
HttpReply * setVirginReply(HttpReply *r)
Definition: Client.cc:116
HttpReply * finalReply()
Definition: Client.cc:129
void adaptOrFinalizeReply()
Definition: Client.cc:996
size_t calcBufferSpaceToReserve(const size_t space, const size_t wantSpace) const
determine how much space the buffer needs to reserve
Definition: Client.cc:1063
void addVirginReplyBody(const char *buf, ssize_t len)
Definition: Client.cc:1038
HttpRequestPointer request
Definition: Client.h:178
void markParsedVirginReplyAsWhole(const char *reasonWeAreSure)
Definition: Client.cc:158
StoreEntry * entry
Definition: Client.h:176
virtual void sentRequestBody(const CommIoCbParams &io)=0
Definition: Client.cc:364
virtual void doneSendingRequestBody()=0
Definition: Client.cc:340
FwdState::Pointer fwd
Definition: Client.h:177
virtual void haveParsedReplyHeaders()
called when we have final (possibly adapted) reply headers; kids extend
Definition: Client.cc:537
int xerrno
The last errno to occur. non-zero if flag is Comm::COMM_ERROR.
Definition: CommCalls.h:83
int fd
FD which the call was about. Set by the async call creator.
Definition: CommCalls.h:85
Comm::Flag flag
comm layer result status.
Definition: CommCalls.h:82
Comm::ConnectionPointer conn
Definition: CommCalls.h:80
CachePeer * getPeer() const
Definition: Connection.cc:124
parameters for the async notePinnedConnectionBecameIdle() call
Definition: client_side.h:183
noteTakeServerConnectionControl() callback parameter
Definition: client_side.h:213
virtual void noteTakeServerConnectionControl(ServerConnectionContext)
Definition: client_side.h:229
void sendControlMsg(HttpControlMsg) override
called to send the 1xx message and notify the Source
void bytesIn(int qty)
Definition: DelayId.cc:151
HttpRequest * request
Definition: FwdState.h:169
void unregister(Comm::ConnectionPointer &conn)
Definition: FwdState.cc:504
Comm::ConnectionPointer const & serverConnection() const
Definition: FwdState.h:104
void fail(ErrorState *err)
Definition: FwdState.cc:463
bool dontRetry()
Definition: FwdState.h:96
StoreEntry * entry
Definition: FwdState.h:168
AccessLogEntryPointer al
info for the future access.log entry
Definition: FwdState.h:170
Http::StatusCode peer_reply_status
last HTTP status code received
bundles HTTP 1xx reply and the "successfully forwarded" callback
bool hasSMaxAge(int32_t *val=nullptr) const
Definition: HttpHdrCc.h:127
bool hasNoStore() const
Definition: HttpHdrCc.h:102
bool hasMustRevalidate() const
Definition: HttpHdrCc.h:112
bool hasNoCache(const String **val=nullptr) const
Definition: HttpHdrCc.h:89
bool hasPrivate(const String **val=nullptr) const
Definition: HttpHdrCc.h:74
bool hasNoCacheWithoutParameters() const
Definition: HttpHdrCc.h:88
void maxAge(int32_t v)
Definition: HttpHdrCc.h:123
bool hasPublic() const
Definition: HttpHdrCc.h:69
void onlyIfCached(bool v)
Definition: HttpHdrCc.h:146
bool hasMaxAge(int32_t *val=nullptr) const
Definition: HttpHdrCc.h:122
bool hasProxyRevalidate() const
Definition: HttpHdrCc.h:117
bool hasNoCacheWithParameters() const
Definition: HttpHdrCc.h:87
bool offsetLimitExceeded(const int64_t limit) const
void maxAge(int v)
bool hasMaxAge() const
bool hasNoStore() const
void noStoreRemote(bool v)
void maxStale(int v)
HttpHdrScTarget * getMergedTarget(const char *ourtarget)
Definition: HttpHdrSc.cc:294
HttpHeaderEntry * clone() const
Definition: HttpHeader.cc:1507
int64_t getInt64() const
Definition: HttpHeader.cc:1535
Http::HdrType id
Definition: HttpHeader.h:66
void putStr(Http::HdrType id, const char *str)
Definition: HttpHeader.cc:996
HttpHdrCc * getCc() const
Definition: HttpHeader.cc:1195
bool chunked() const
Definition: HttpHeader.h:169
void putCc(const HttpHdrCc &cc)
Definition: HttpHeader.cc:1012
http_hdr_owner_type owner
Definition: HttpHeader.h:177
String getList(Http::HdrType id) const
Definition: HttpHeader.cc:789
HttpHeaderEntry * getEntry(HttpHeaderPos *pos) const
Definition: HttpHeader.cc:584
const char * getStr(Http::HdrType id) const
Definition: HttpHeader.cc:1164
void addEntry(HttpHeaderEntry *e)
Definition: HttpHeader.cc:737
void putInt64(Http::HdrType id, int64_t number)
Definition: HttpHeader.cc:978
String getByName(const SBuf &name) const
Definition: HttpHeader.cc:849
void addVia(const AnyP::ProtocolVersion &ver, const HttpHeader *from=nullptr)
Definition: HttpHeader.cc:946
int has(Http::HdrType id) const
Definition: HttpHeader.cc:938
void clean()
Definition: HttpHeader.cc:186
void putTime(Http::HdrType id, time_t htime)
Definition: HttpHeader.cc:987
void packInto(Packable *p, bool mask_sensitive_info=false) const
Definition: HttpHeader.cc:540
int hasListMember(Http::HdrType id, const char *member, const char separator) const
Definition: HttpHeader.cc:1663
Http::StatusLine sline
Definition: HttpReply.h:56
bool olderThan(const HttpReply *them) const
Definition: HttpReply.cc:640
bool expectingBody(const HttpRequestMethod &, int64_t &) const override
Definition: HttpReply.cc:528
bool parseHeader(Http1::Parser &hp)
parses reply header using Parser
Definition: HttpReply.cc:507
HttpHdrSc * surrogate_control
Definition: HttpReply.h:48
int64_t bodySize(const HttpRequestMethod &) const
Definition: HttpReply.cc:377
time_t date
Definition: HttpReply.h:40
short int keep_alive
Definition: HttpReply.h:53
time_t expires
Definition: HttpReply.h:44
const SBuf & image() const
HttpHdrRange * range
Definition: HttpRequest.h:143
CbcPointer< ConnStateData > clientConnectionManager
Definition: HttpRequest.h:232
HttpRequestMethod method
Definition: HttpRequest.h:114
int64_t getRangeOffsetLimit()
Definition: HttpRequest.cc:594
String extacl_user
Definition: HttpRequest.h:178
bool multipartRangeRequest() const
Definition: HttpRequest.cc:434
HierarchyLogEntry hier
Definition: HttpRequest.h:157
time_t lastmod
Definition: HttpRequest.h:167
RequestFlags flags
Definition: HttpRequest.h:141
String extacl_passwd
Definition: HttpRequest.h:180
bool forcedBodyContinuation
whether we have responded with HTTP 100 or FTP 150 already
Definition: HttpRequest.h:194
char * peer_domain
Definition: HttpRequest.h:172
String etag
A strong etag of the cached entry. Used for refreshing that entry.
Definition: HttpRequest.h:191
void ignoreRange(const char *reason)
forgets about the cached Range header (for a reason)
Definition: HttpRequest.cc:621
char * peer_login
Definition: HttpRequest.h:163
Auth::UserRequest::Pointer auth_user_request
Definition: HttpRequest.h:127
bool canHandle1xx() const
whether the client is likely to be able to handle a 1xx reply
Definition: HttpRequest.cc:635
char * peer_host
Definition: HttpRequest.h:165
AnyP::Uri url
the request URI
Definition: HttpRequest.h:115
Ip::Address client_addr
Definition: HttpRequest.h:149
const SBuf & effectiveRequestUri() const
RFC 7230 section 5.5 - Effective Request URI.
Definition: HttpRequest.cc:744
assists in making and relaying entry caching/sharing decision
Definition: http.h:30
const Http::StatusCode statusCode
HTTP status for debugging.
Definition: http.h:41
Answers answer
the decision id
Definition: http.h:38
ReuseDecision(const StoreEntry *e, const Http::StatusCode code)
Definition: http.cc:2622
const StoreEntry * entry
entry for debugging
Definition: http.h:40
Answers make(const Answers ans, const char *why)
stores the corresponding decision
Definition: http.cc:2626
const char * reason
the decision reason
Definition: http.h:39
void httpStateConnClosed(const CommCloseCbParams &params)
Definition: http.cc:137
void handleRequestBodyProducerAborted() override
Definition: http.cc:2586
AsyncCall::Pointer closeHandler
Definition: http.h:93
Http1::ResponseParserPointer hp
Parser being used at present to parse the HTTP/ICY server response.
Definition: http.h:152
String * upgradeHeaderOut
Upgrade header value sent to the origin server or cache peer.
Definition: http.h:73
void handle1xx(HttpReply *msg)
ignore or start forwarding the 1xx response (a.k.a., control message)
Definition: http.cc:747
void start() override
called by AsyncStart; do not call directly
Definition: http.cc:2466
void processReply()
Definition: http.cc:1266
CachePeer * _peer
Definition: http.h:64
const char * blockSwitchingProtocols(const HttpReply &) const
Definition: http.cc:824
static void httpBuildRequestHeader(HttpRequest *request, StoreEntry *entry, const AccessLogEntryPointer &al, HttpHeader *hdr_out, const Http::StateFlags &flags)
Definition: http.cc:1835
static bool decideIfWeDoRanges(HttpRequest *orig_request)
Definition: http.cc:2264
void truncateVirginBody()
Definition: http.cc:1367
ConnectionStatus persistentConnStatus() const
Definition: http.cc:1113
void writeReplyBody()
Definition: http.cc:1405
void sendComplete()
successfully wrote the entire request (including body, last-chunk, etc.)
Definition: http.cc:1683
void httpTimeout(const CommTimeoutCbParams &params)
Definition: http.cc:145
ReuseDecision::Answers reusableReply(ReuseDecision &decision)
Definition: http.cc:295
void checkDateSkew(HttpReply *)
Definition: http.cc:627
bool doneWithServer() const override
Definition: http.cc:1715
int64_t payloadTruncated
positive when we read more than we wanted
Definition: http.h:158
int eof
Definition: http.h:65
void haveParsedReplyHeaders() override
called when we have final (possibly adapted) reply headers; kids extend
Definition: http.cc:938
void abortTransaction(const char *reason)
Definition: http.h:115
mb_size_t buildRequestPrefix(MemBuf *mb)
Definition: http.cc:2294
int lastChunk
Definition: http.h:66
bool sendRequest()
Definition: http.cc:2338
void readReply(const CommIoCbParams &io)
Definition: http.cc:1170
SBuf inBuf
I/O buffer for receiving server responses.
Definition: http.h:68
bool getMoreRequestBody(MemBuf &buf) override
either fill buf with available [encoded] request body bytes or return false
Definition: http.cc:2425
bool surrogateNoStore
Definition: http.h:70
HttpStateData(FwdState *)
Definition: http.cc:78
void abortAll(const char *reason) override
abnormal transaction termination; reason is for debugging only
Definition: http.cc:2615
Http::StateFlags flags
Definition: http.h:67
bool ignoreCacheControl
Definition: http.h:69
void processSurrogateControl(HttpReply *)
Definition: http.cc:257
ConnectionStatus statusIfComplete() const
Definition: http.cc:1063
void processReplyBody() override
Definition: http.cc:1465
bool decodeAndWriteReplyBody()
Definition: http.cc:1431
void markPrematureReplyBodyEofFailure()
called on a premature EOF discovered when reading response body
Definition: http.cc:1392
bool mayReadVirginReplyBody() const override
whether we may receive more virgin response body bytes
Definition: http.cc:1574
bool continueAfterParsingHeader()
Definition: http.cc:1297
void maybeReadVirginBody() override
read response data from the network
Definition: http.cc:1583
int64_t payloadSeen
amount of message payload/body received so far.
Definition: http.h:156
bool maybeMakeSpaceAvailable(bool grow)
Definition: http.cc:1609
ConnectionStatus
Definition: http.h:94
@ COMPLETE_PERSISTENT_MSG
Definition: http.h:96
@ INCOMPLETE_MSG
Definition: http.h:95
@ COMPLETE_NONPERSISTENT_MSG
Definition: http.h:97
bool peerSupportsConnectionPinning() const
Definition: http.cc:880
virtual void handleMoreRequestBodyAvailable()
Definition: http.cc:2554
bool sawDateGoBack
Definition: http.h:162
void closeServer() override
Definition: http.cc:1702
void wroteLast(const CommIoCbParams &io)
called after writing the very last request byte (body, last-chunk, etc)
Definition: http.cc:1646
void processReplyHeader()
Definition: http.cc:644
void noteDelayAwareReadChance() override
Definition: http.cc:1163
const Comm::ConnectionPointer & dataConnection() const override
Definition: http.cc:131
void sentRequestBody(const CommIoCbParams &io) override
Definition: http.cc:2606
Comm::ConnectionPointer serverConnection
Definition: http.h:92
~HttpStateData() override
Definition: http.cc:114
void proceedAfter1xx()
restores state and resumes processing after 1xx is ignored or forwarded
Definition: http.cc:851
bool finishingChunkedRequest()
if needed, write last-chunk to end the request body and return true
Definition: http.cc:2521
void forwardUpgrade(HttpHeader &)
Definition: http.cc:2012
void keepaliveAccounting(HttpReply *)
Definition: http.cc:607
Http1::TeChunkedParser * httpChunkDecoder
Definition: http.h:153
bool finishingBrokenPost()
if broken posts are enabled for the request, try to fix and return true
Definition: http.cc:2486
void drop1xx(const char *reason)
Definition: http.cc:806
void doneSendingRequestBody() override
Definition: http.cc:2538
void forApplicable(const ProtocolView &, const Visitor &) const
@ srcHttp
http_port or HTTP server
Definition: Message.h:39
@ srcHttps
https_port or bumped http_port tunnel; HTTPS server
Definition: Message.h:33
bool persistent() const
Definition: Message.cc:236
uint32_t sources
The message sources.
Definition: Message.h:99
HttpHeader header
Definition: Message.h:74
int64_t content_length
Definition: Message.h:83
BodyPipe::Pointer body_pipe
optional pipeline to receive message body
Definition: Message.h:97
HttpHdrCc * cache_control
Definition: Message.h:76
AnyP::ProtocolVersion http_ver
Definition: Message.h:72
const SBuf & remaining() const
the remaining unprocessed section of buffer
Definition: Parser.h:98
bool parse(const SBuf &) override
void setPayloadBuffer(MemBuf *parsedContent)
set the buffer to be used to store decoded chunk data
bool sentLastChunk
do not try to write last-chunk again
Definition: StateFlags.h:64
bool peering
Whether the next TCP hop is a cache_peer, including originserver.
Definition: StateFlags.h:40
bool chunked_request
writing a chunked request
Definition: StateFlags.h:63
bool serverSwitchedProtocols
Definition: StateFlags.h:35
bool keepalive
whether the Squid-sent request offers to keep the connection persistent
Definition: StateFlags.h:21
bool toOriginPeer() const
Whether the next TCP/HTTP hop is an originserver cache_peer.
Definition: StateFlags.h:56
bool chunked
reading a chunked response; TODO: rename
Definition: StateFlags.h:62
bool handling1xx
Whether we are processing an HTTP 1xx control message.
Definition: StateFlags.h:30
bool keepalive_broken
Definition: StateFlags.h:58
unsigned int front_end_https
send "Front-End-Https: On" header (off/on/auto=2)
Definition: StateFlags.h:18
AnyP::ProtocolVersion version
breakdown of protocol version label: (HTTP/ICY) and (0.9/1.0/1.1)
Definition: StatusLine.h:65
void set(const AnyP::ProtocolVersion &newVersion, Http::StatusCode newStatus, const char *newReason=nullptr)
Definition: StatusLine.cc:35
Http::StatusCode status() const
retrieve the status code for this status line
Definition: StatusLine.h:45
struct IoStats::@75 Http
int read_hist[histSize]
Definition: IoStats.h:21
int reads
Definition: IoStats.h:19
char * toStr(char *buf, const unsigned int blen, int force=AF_UNSPEC) const
Definition: Address.cc:792
bool isNoAddr() const
Definition: Address.cc:284
Definition: MemBuf.h:24
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
mb_size_t size
Definition: MemBuf.h:135
char * buf
Definition: MemBuf.h:134
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
bool hasContent() const
Definition: MemBuf.h:54
DelayId mostBytesAllowed() const
Definition: MemObject.cc:466
HttpRequestMethod method
Definition: MemObject.h:147
HttpRequestPointer request
Definition: MemObject.h:212
SBuf vary_headers
Definition: MemObject.h:228
const HttpReply & freshestReply() const
Definition: MemObject.h:68
const char * storeId() const
Definition: MemObject.cc:53
void appendf(const char *fmt,...) PRINTF_FORMAT_ARG2
Append operation with printf-style arguments.
Definition: Packable.h:61
void push(const Comm::ConnectionPointer &serverConn, const char *domain)
Definition: pconn.cc:412
a reference to a protocol name[/version] string; no 0-termination is assumed
Definition: Range.h:19
Definition: Raw.h:21
C * getRaw() const
Definition: RefCount.h:89
a representation of a refresh pattern.
bool accelerated
Definition: RequestFlags.h:62
bool connectionAuth
Definition: RequestFlags.h:85
bool mustKeepalive
Definition: RequestFlags.h:83
bool auth_no_keytab
Definition: RequestFlags.h:32
bool spoofClientIp
Definition: RequestFlags.h:74
bool connectionAuthDisabled
Definition: RequestFlags.h:87
SupportOrVeto cachable
whether the response may be stored in the cache
Definition: RequestFlags.h:35
Definition: SBuf.h:94
const char * rawContent() const
Definition: SBuf.cc:509
SBuf consume(size_type n=npos)
Definition: SBuf.cc:481
const char * c_str()
Definition: SBuf.cc:516
SBuf & chop(size_type pos, size_type n=npos)
Definition: SBuf.cc:530
size_type length() const
Returns the number of bytes stored in SBuf.
Definition: SBuf.h:415
size_type spaceSize() const
Definition: SBuf.h:393
bool isEmpty() const
Definition: SBuf.h:431
SBuf & append(const SBuf &S)
Definition: SBuf.cc:185
void reserveSpace(size_type minSpace)
Definition: SBuf.h:440
MemBlob::size_type size_type
Definition: SBuf.h:96
void toLower()
converts all characters to lower case;
Definition: SBuf.cc:811
int cache_miss_revalidate
Definition: SquidConfig.h:319
int surrogate_is_remote
Definition: SquidConfig.h:313
int64_t readAheadGap
Definition: SquidConfig.h:98
int server_pconns
Definition: SquidConfig.h:305
struct SquidConfig::@107 accessList
size_t maxReplyHeaderSize
Definition: SquidConfig.h:137
acl_access * reply
Definition: SquidConfig.h:379
struct SquidConfig::@106 onoff
acl_access * brokenPosts
Definition: SquidConfig.h:375
struct SquidConfig::@100 Accel
time_t lifetime
Definition: SquidConfig.h:114
time_t negativeTtl
Definition: SquidConfig.h:102
time_t read
Definition: SquidConfig.h:112
char * surrogate_id
Definition: SquidConfig.h:220
struct SquidConfig::@93 Timeout
int redir_rewrites_host
Definition: SquidConfig.h:297
HttpUpgradeProtocolAccess * http_upgrade_request_protocols
http_upgrade_request_protocols
Definition: SquidConfig.h:469
int detect_broken_server_pconns
Definition: SquidConfig.h:314
struct StatCounters::@123::@133 all
ByteCounter kbytes_out
Definition: StatCounters.h:46
struct StatCounters::@123::@133 http
ByteCounter kbytes_in
Definition: StatCounters.h:45
struct StatCounters::@123 server
size_t bytesWanted(Range< size_t > const aRange, bool ignoreDelayPool=false) const
Definition: store.cc:212
bool isAccepting() const
Definition: store.cc:1975
uint16_t flags
Definition: Store.h:232
MemObject & mem()
Definition: Store.h:51
const char * url() const
Definition: store.cc:1552
void release(const bool shareable=false)
Definition: store.cc:1132
bool makePublic(const KeyScope keyScope=ksDefault)
Definition: store.cc:166
bool timestampsSet()
Definition: store.cc:1373
const char * getMD5Text() const
Definition: store.cc:206
void makePrivate(const bool shareable)
Definition: store.cc:173
MemObject * mem_obj
Definition: Store.h:221
void setNoDelay(bool const)
Definition: store.cc:236
void reset()
Definition: store.cc:1607
store_status_t store_status
Definition: Store.h:244
void releaseRequest(const bool shareable=false)
Definition: store.cc:444
bool isEmpty() const
Definition: Store.h:66
bool cacheNegatively()
Definition: store.cc:187
bool canGrowBy(const size_type growthLen) const
whether appending growthLen characters is safe (i.e., unlikely to assert)
Definition: SquidString.h:124
void clean()
Definition: String.cc:103
char const * rawBuf() const
Definition: SquidString.h:86
char const * termedBuf() const
Definition: SquidString.h:92
size_type size() const
Definition: SquidString.h:73
void veto()
makes decision() false regardless of past or future support() calls
Definition: SupportOrVeto.h:29
int commSetConnTimeout(const Comm::ConnectionPointer &conn, time_t timeout, AsyncCall::Pointer &callback)
Definition: comm.cc:595
AsyncCall::Pointer comm_add_close_handler(int fd, CLCB *handler, void *data)
Definition: comm.cc:949
void comm_remove_close_handler(int fd, CLCB *handler, void *data)
Definition: comm.cc:978
int commUnsetConnTimeout(const Comm::ConnectionPointer &conn)
Definition: comm.cc:621
#define DBG_DATA
Definition: Stream.h:40
#define DBG_IMPORTANT
Definition: Stream.h:38
#define debugs(SECTION, LEVEL, CONTENT)
Definition: Stream.h:194
#define EBIT_SET(flag, bit)
Definition: defines.h:67
#define MAX_LOGIN_SZ
Definition: defines.h:79
#define EBIT_TEST(flag, bit)
Definition: defines.h:69
#define MAX_URL
Definition: defines.h:78
@ HTCP_CLR_INVALIDATION
Definition: enums.h:242
@ PEER_SIBLING
Definition: enums.h:29
@ KEY_PRIVATE
Definition: enums.h:102
@ ENTRY_FWD_HDR_WAIT
Definition: enums.h:111
@ RELEASE_REQUEST
prohibits making the key public
Definition: enums.h:98
@ ENTRY_REVALIDATE_STALE
Definition: enums.h:100
@ ENTRY_ABORTED
Definition: enums.h:115
@ ENTRY_REVALIDATE_ALWAYS
Definition: enums.h:85
@ FD_WRITE
Definition: enums.h:24
@ STORE_PENDING
Definition: enums.h:51
err_type
Definition: forward.h:14
@ ERR_INVALID_RESP
Definition: forward.h:41
@ ERR_READ_TIMEOUT
Definition: forward.h:26
@ ERR_NONE
Definition: forward.h:15
@ ERR_ICAP_FAILURE
Definition: forward.h:64
@ ERR_WRITE_ERROR
Definition: forward.h:29
@ ERR_TOO_BIG
Definition: forward.h:40
@ ERR_ZERO_SIZE_OBJECT
Definition: forward.h:46
@ ERR_READ_ERROR
Definition: forward.h:28
void fd_bytes(int fd, int len, unsigned int type)
Definition: fd.cc:226
#define fd_table
Definition: fde.h:189
char * opt_forwarded_for
int neighbors_do_private_keys
IoStats IOStats
void HTTPMSGLOCK(Http::Message *a)
Definition: Message.h:161
#define REFRESH_OVERRIDE(flag)
static const char *const crlf
Definition: http.cc:72
void httpStart(FwdState *fwd)
Definition: http.cc:2459
static StoreEntry * findPreviouslyCachedEntry(StoreEntry *newEntry)
Definition: http.cc:158
SBuf httpMakeVaryMark(HttpRequest *request, HttpReply const *reply)
Definition: http.cc:588
#define BBUF_SZ
static void httpFixupAuthentication(HttpRequest *request, const HttpHeader *hdr_in, HttpHeader *hdr_out, const Http::StateFlags &flags)
Definition: http.cc:1724
std::ostream & operator<<(std::ostream &os, const HttpStateData::ReuseDecision &d)
Definition: http.cc:2633
static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest *request, HttpHeader *hdr_out, const int we_do_ranges, const Http::StateFlags &)
Definition: http.cc:2086
static void httpMaybeRemovePublic(StoreEntry *, Http::StatusCode)
Definition: http.cc:168
static void assembleVaryKey(String &vary, SBuf &vstr, const HttpRequest &request)
assemble a variant key (vary-mark) from the given Vary header and HTTP request
Definition: http.cc:552
#define MAX_IPSTRLEN
Length of buffer that needs to be allocated to old a null-terminated IP-string.
Definition: forward.h:25
const char * ProtocolType_str[]
@ PROTO_HTTPS
Definition: ProtocolType.h:27
@ PROTO_HTTP
Definition: ProtocolType.h:25
bool MonitorsRead(int fd)
whether the FD socket is being monitored for read
Definition: Read.cc:29
void Read(const Comm::ConnectionPointer &conn, AsyncCall::Pointer &callback)
Definition: Read.cc:40
bool IsConnOpen(const Comm::ConnectionPointer &conn)
Definition: Connection.cc:27
void Write(const Comm::ConnectionPointer &conn, const char *buf, int size, AsyncCall::Pointer &callback, FREE *free_func)
Definition: Write.cc:33
@ OK
Definition: Flag.h:16
@ ENDFILE
Definition: Flag.h:26
@ ERR_CLOSING
Definition: Flag.h:24
@ INPROGRESS
Definition: Flag.h:21
Comm::Flag ReadNow(CommIoCbParams &params, SBuf &buf)
Definition: Read.cc:81
bool Is1xx(const int sc)
whether this is an informational 1xx response status code
Definition: StatusCode.h:92
StatusCode
Definition: StatusCode.h:20
@ scInsufficientStorage
Definition: StatusCode.h:78
@ scUriTooLong
Definition: StatusCode.h:58
@ scGone
Definition: StatusCode.h:54
@ scGatewayTimeout
Definition: StatusCode.h:75
@ scNotAcceptable
Definition: StatusCode.h:50
@ scHeaderTooLarge
Definition: StatusCode.h:87
@ scLocked
Definition: StatusCode.h:64
@ scUseProxy
Definition: StatusCode.h:41
@ scForbidden
Definition: StatusCode.h:47
@ scUnauthorized
Definition: StatusCode.h:45
@ scNotImplemented
Definition: StatusCode.h:72
@ scUnsupportedMediaType
Definition: StatusCode.h:59
@ scUnprocessableEntity
Definition: StatusCode.h:63
@ scFound
Definition: StatusCode.h:38
@ scMultipleChoices
Definition: StatusCode.h:36
@ scInternalServerError
Definition: StatusCode.h:71
@ scBadRequest
Definition: StatusCode.h:44
@ scInvalidHeader
Definition: StatusCode.h:86
@ scConflict
Definition: StatusCode.h:53
@ scFailedDependency
Definition: StatusCode.h:65
@ scExpectationFailed
Definition: StatusCode.h:61
@ scNotFound
Definition: StatusCode.h:48
@ scMethodNotAllowed
Definition: StatusCode.h:49
@ scPermanentRedirect
Definition: StatusCode.h:43
@ scSeeOther
Definition: StatusCode.h:39
@ scRequestTimeout
Definition: StatusCode.h:52
@ scProxyAuthenticationRequired
Definition: StatusCode.h:51
@ scPaymentRequired
Definition: StatusCode.h:46
@ scLengthRequired
Definition: StatusCode.h:55
@ scNotModified
Definition: StatusCode.h:40
@ scOkay
Definition: StatusCode.h:26
@ scTemporaryRedirect
Definition: StatusCode.h:42
@ scContinue
Definition: StatusCode.h:22
@ scNoContent
Definition: StatusCode.h:30
@ scRequestedRangeNotSatisfied
Definition: StatusCode.h:60
@ scSwitchingProtocols
Definition: StatusCode.h:23
@ scMovedPermanently
Definition: StatusCode.h:37
@ scNonAuthoritativeInformation
Definition: StatusCode.h:29
@ scPreconditionFailed
Definition: StatusCode.h:56
@ scBadGateway
Definition: StatusCode.h:73
@ scMisdirectedRequest
Definition: StatusCode.h:62
@ scContentTooLarge
Definition: StatusCode.h:57
@ scPartialContent
Definition: StatusCode.h:32
@ scServiceUnavailable
Definition: StatusCode.h:74
bool IsReforwardableStatus(StatusCode)
whether to send the request to another peer based on the current response status code
Definition: StatusCode.cc:281
@ METHOD_TRACE
Definition: MethodType.h:30
@ METHOD_OPTIONS
Definition: MethodType.h:31
@ METHOD_HEAD
Definition: MethodType.h:28
@ PROXY_CONNECTION
@ PROXY_AUTHORIZATION
@ IF_MODIFIED_SINCE
@ TRANSFER_ENCODING
@ SURROGATE_CAPABILITY
@ HDR_X_ACCELERATOR_VARY
@ PROXY_AUTHENTICATE
@ CONTENT_LENGTH
AnyP::ProtocolVersion ProtocolVersion(unsigned int aMajor, unsigned int aMinor)
HTTP version label information.
void Controller::create() STUB void Controller Controller nil
void neighborsHtcpClear(StoreEntry *e, HttpRequest *req, const HttpRequestMethod &method, htcp_clr_reason reason)
Definition: neighbors.cc:1673
peer_t neighborType(const CachePeer *p, const AnyP::Uri &url)
Definition: neighbors.cc:114
#define PEER_PROXY_NEGOTIATE_NOKEYTAB
time_t getMaxAge(const char *url)
Definition: refresh.cc:633
bool refreshIsCachable(const StoreEntry *entry)
Definition: refresh.cc:519
#define rfc1738_escape_part(x)
Definition: rfc1738.h:55
int code
Definition: smb-errors.c:145
#define LOCAL_ARRAY(type, name, size)
Definition: squid.h:68
StoreEntry * storeGetPublicByRequestMethod(HttpRequest *req, const HttpRequestMethod &method, const KeyScope keyScope)
Definition: store.cc:496
StoreEntry * storeGetPublicByRequest(HttpRequest *req, const KeyScope keyScope)
Definition: store.cc:502
StoreEntry * storeGetPublic(const char *uri, const HttpRequestMethod &method)
Definition: store.cc:490
const char * xstrerr(int error)
Definition: xstrerror.cc:83

 

Introduction

Documentation

Support

Miscellaneous

Web Site Translations

Mirrors