]> git.ipfire.org Git - thirdparty/squid.git/blob - src/http.cc
Bug 4563: duplicate code in httpMakeVaryMark
[thirdparty/squid.git] / src / http.cc
1 /*
2 * Copyright (C) 1996-2016 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 informations.
14 */
15
16 #include "squid.h"
17 #include "acl/FilledChecklist.h"
18 #include "base/AsyncJobCalls.h"
19 #include "base/TextException.h"
20 #include "base64.h"
21 #include "CachePeer.h"
22 #include "client_side.h"
23 #include "comm/Connection.h"
24 #include "comm/Read.h"
25 #include "comm/Write.h"
26 #include "CommRead.h"
27 #include "err_detail_type.h"
28 #include "errorpage.h"
29 #include "fd.h"
30 #include "fde.h"
31 #include "globals.h"
32 #include "http.h"
33 #include "http/one/ResponseParser.h"
34 #include "http/one/TeChunkedParser.h"
35 #include "http/Stream.h"
36 #include "HttpControlMsg.h"
37 #include "HttpHdrCc.h"
38 #include "HttpHdrContRange.h"
39 #include "HttpHdrSc.h"
40 #include "HttpHdrScTarget.h"
41 #include "HttpHeaderTools.h"
42 #include "HttpReply.h"
43 #include "HttpRequest.h"
44 #include "HttpStateFlags.h"
45 #include "log/access_log.h"
46 #include "MemBuf.h"
47 #include "MemObject.h"
48 #include "neighbors.h"
49 #include "peer_proxy_negotiate_auth.h"
50 #include "profiler/Profiler.h"
51 #include "refresh.h"
52 #include "RefreshPattern.h"
53 #include "rfc1738.h"
54 #include "SquidConfig.h"
55 #include "SquidTime.h"
56 #include "StatCounters.h"
57 #include "Store.h"
58 #include "StrList.h"
59 #include "tools.h"
60 #include "URL.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
70 #define SQUID_ENTER_THROWING_CODE() try {
71 #define SQUID_EXIT_THROWING_CODE(status) \
72 status = true; \
73 } \
74 catch (const std::exception &e) { \
75 debugs (11, 1, "Exception error:" << e.what()); \
76 status = false; \
77 }
78
79 CBDATA_CLASS_INIT(HttpStateData);
80
81 static const char *const crlf = "\r\n";
82
83 static void httpMaybeRemovePublic(StoreEntry *, Http::StatusCode);
84 static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request,
85 HttpHeader * hdr_out, const int we_do_ranges, const HttpStateFlags &);
86
87 HttpStateData::HttpStateData(FwdState *theFwdState) :
88 AsyncJob("HttpStateData"),
89 Client(theFwdState),
90 lastChunk(0),
91 httpChunkDecoder(NULL),
92 payloadSeen(0),
93 payloadTruncated(0)
94 {
95 debugs(11,5,HERE << "HttpStateData " << this << " created");
96 ignoreCacheControl = false;
97 surrogateNoStore = false;
98 serverConnection = fwd->serverConnection();
99
100 // reset peer response time stats for %<pt
101 request->hier.peer_http_request_sent.tv_sec = 0;
102 request->hier.peer_http_request_sent.tv_usec = 0;
103
104 if (fwd->serverConnection() != NULL)
105 _peer = cbdataReference(fwd->serverConnection()->getPeer()); /* might be NULL */
106
107 if (_peer) {
108 request->flags.proxying = true;
109 /*
110 * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here.
111 * We might end up getting the object from somewhere else if,
112 * for example, the request to this neighbor fails.
113 */
114 if (_peer->options.proxy_only)
115 entry->releaseRequest();
116
117 #if USE_DELAY_POOLS
118 entry->setNoDelay(_peer->options.no_delay);
119 #endif
120 }
121
122 /*
123 * register the handler to free HTTP state data when the FD closes
124 */
125 typedef CommCbMemFunT<HttpStateData, CommCloseCbParams> Dialer;
126 closeHandler = JobCallback(9, 5, Dialer, this, HttpStateData::httpStateConnClosed);
127 comm_add_close_handler(serverConnection->fd, closeHandler);
128 }
129
130 HttpStateData::~HttpStateData()
131 {
132 /*
133 * don't forget that ~Client() gets called automatically
134 */
135
136 if (httpChunkDecoder)
137 delete httpChunkDecoder;
138
139 cbdataReferenceDone(_peer);
140
141 debugs(11,5, HERE << "HttpStateData " << this << " destroyed; " << serverConnection);
142 }
143
144 const Comm::ConnectionPointer &
145 HttpStateData::dataConnection() const
146 {
147 return serverConnection;
148 }
149
150 void
151 HttpStateData::httpStateConnClosed(const CommCloseCbParams &params)
152 {
153 debugs(11, 5, "httpStateFree: FD " << params.fd << ", httpState=" << params.data);
154 doneWithFwd = "httpStateConnClosed()"; // assume FwdState is monitoring too
155 mustStop("HttpStateData::httpStateConnClosed");
156 }
157
158 void
159 HttpStateData::httpTimeout(const CommTimeoutCbParams &)
160 {
161 debugs(11, 4, serverConnection << ": '" << entry->url() << "'");
162
163 if (entry->store_status == STORE_PENDING) {
164 fwd->fail(new ErrorState(ERR_READ_TIMEOUT, Http::scGatewayTimeout, fwd->request));
165 }
166
167 closeServer();
168 mustStop("HttpStateData::httpTimeout");
169 }
170
171 /// Remove an existing public store entry if the incoming response (to be
172 /// stored in a currently private entry) is going to invalidate it.
173 static void
174 httpMaybeRemovePublic(StoreEntry * e, Http::StatusCode status)
175 {
176 int remove = 0;
177 int forbidden = 0;
178 StoreEntry *pe;
179
180 // If the incoming response already goes into a public entry, then there is
181 // nothing to remove. This protects ready-for-collapsing entries as well.
182 if (!EBIT_TEST(e->flags, KEY_PRIVATE))
183 return;
184
185 switch (status) {
186
187 case Http::scOkay:
188
189 case Http::scNonAuthoritativeInformation:
190
191 case Http::scMultipleChoices:
192
193 case Http::scMovedPermanently:
194
195 case Http::scFound:
196
197 case Http::scGone:
198
199 case Http::scNotFound:
200 remove = 1;
201
202 break;
203
204 case Http::scForbidden:
205
206 case Http::scMethodNotAllowed:
207 forbidden = 1;
208
209 break;
210
211 #if WORK_IN_PROGRESS
212
213 case Http::scUnauthorized:
214 forbidden = 1;
215
216 break;
217
218 #endif
219
220 default:
221 #if QUESTIONABLE
222 /*
223 * Any 2xx response should eject previously cached entities...
224 */
225
226 if (status >= 200 && status < 300)
227 remove = 1;
228
229 #endif
230
231 break;
232 }
233
234 if (!remove && !forbidden)
235 return;
236
237 assert(e->mem_obj);
238
239 if (e->mem_obj->request)
240 pe = storeGetPublicByRequest(e->mem_obj->request);
241 else
242 pe = storeGetPublic(e->mem_obj->storeId(), e->mem_obj->method);
243
244 if (pe != NULL) {
245 assert(e != pe);
246 #if USE_HTCP
247 neighborsHtcpClear(e, NULL, e->mem_obj->request, e->mem_obj->method, HTCP_CLR_INVALIDATION);
248 #endif
249 pe->release();
250 }
251
252 /** \par
253 * Also remove any cached HEAD response in case the object has
254 * changed.
255 */
256 if (e->mem_obj->request)
257 pe = storeGetPublicByRequestMethod(e->mem_obj->request, Http::METHOD_HEAD);
258 else
259 pe = storeGetPublic(e->mem_obj->storeId(), Http::METHOD_HEAD);
260
261 if (pe != NULL) {
262 assert(e != pe);
263 #if USE_HTCP
264 neighborsHtcpClear(e, NULL, e->mem_obj->request, HttpRequestMethod(Http::METHOD_HEAD), HTCP_CLR_INVALIDATION);
265 #endif
266 pe->release();
267 }
268 }
269
270 void
271 HttpStateData::processSurrogateControl(HttpReply *reply)
272 {
273 if (request->flags.accelerated && reply->surrogate_control) {
274 HttpHdrScTarget *sctusable = reply->surrogate_control->getMergedTarget(Config.Accel.surrogate_id);
275
276 if (sctusable) {
277 if (sctusable->noStore() ||
278 (Config.onoff.surrogate_is_remote
279 && sctusable->noStoreRemote())) {
280 surrogateNoStore = true;
281 entry->makePrivate();
282 }
283
284 /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an
285 * accelerated request or not...
286 * Still, this is an abstraction breach. - RC
287 */
288 if (sctusable->hasMaxAge()) {
289 if (sctusable->maxAge() < sctusable->maxStale())
290 reply->expires = reply->date + sctusable->maxAge();
291 else
292 reply->expires = reply->date + sctusable->maxStale();
293
294 /* And update the timestamps */
295 entry->timestampsSet();
296 }
297
298 /* We ignore cache-control directives as per the Surrogate specification */
299 ignoreCacheControl = true;
300
301 delete sctusable;
302 }
303 }
304 }
305
306 int
307 HttpStateData::cacheableReply()
308 {
309 HttpReply const *rep = finalReply();
310 HttpHeader const *hdr = &rep->header;
311 const char *v;
312 #if USE_HTTP_VIOLATIONS
313
314 const RefreshPattern *R = NULL;
315
316 /* This strange looking define first looks up the refresh pattern
317 * and then checks if the specified flag is set. The main purpose
318 * of this is to simplify the refresh pattern lookup and USE_HTTP_VIOLATIONS
319 * condition
320 */
321 #define REFRESH_OVERRIDE(flag) \
322 ((R = (R ? R : refreshLimits(entry->mem_obj->storeId()))) , \
323 (R && R->flags.flag))
324 #else
325 #define REFRESH_OVERRIDE(flag) 0
326 #endif
327
328 if (EBIT_TEST(entry->flags, RELEASE_REQUEST)) {
329 debugs(22, 3, "NO because " << *entry << " has been released.");
330 return 0;
331 }
332
333 // Check for Surrogate/1.0 protocol conditions
334 // NP: reverse-proxy traffic our parent server has instructed us never to cache
335 if (surrogateNoStore) {
336 debugs(22, 3, HERE << "NO because Surrogate-Control:no-store");
337 return 0;
338 }
339
340 // RFC 2616: HTTP/1.1 Cache-Control conditions
341 if (!ignoreCacheControl) {
342 // XXX: check to see if the request headers alone were enough to prevent caching earlier
343 // (ie no-store request header) no need to check those all again here if so.
344 // for now we are not reliably doing that so we waste CPU re-checking request CC
345
346 // RFC 2616 section 14.9.2 - MUST NOT cache any response with request CC:no-store
347 if (request && request->cache_control && request->cache_control->noStore() &&
348 !REFRESH_OVERRIDE(ignore_no_store)) {
349 debugs(22, 3, HERE << "NO because client request Cache-Control:no-store");
350 return 0;
351 }
352
353 // NP: request CC:no-cache only means cache READ is forbidden. STORE is permitted.
354 if (rep->cache_control && rep->cache_control->hasNoCache() && rep->cache_control->noCache().size() > 0) {
355 /* TODO: we are allowed to cache when no-cache= has parameters.
356 * Provided we strip away any of the listed headers unless they are revalidated
357 * successfully (ie, must revalidate AND these headers are prohibited on stale replies).
358 * That is a bit tricky for squid right now so we avoid caching entirely.
359 */
360 debugs(22, 3, HERE << "NO because server reply Cache-Control:no-cache has parameters");
361 return 0;
362 }
363
364 // NP: request CC:private is undefined. We ignore.
365 // NP: other request CC flags are limiters on HIT/MISS. We don't care about here.
366
367 // RFC 2616 section 14.9.2 - MUST NOT cache any response with CC:no-store
368 if (rep->cache_control && rep->cache_control->noStore() &&
369 !REFRESH_OVERRIDE(ignore_no_store)) {
370 debugs(22, 3, HERE << "NO because server reply Cache-Control:no-store");
371 return 0;
372 }
373
374 // RFC 2616 section 14.9.1 - MUST NOT cache any response with CC:private in a shared cache like Squid.
375 // CC:private overrides CC:public when both are present in a response.
376 // TODO: add a shared/private cache configuration possibility.
377 if (rep->cache_control &&
378 rep->cache_control->hasPrivate() &&
379 !REFRESH_OVERRIDE(ignore_private)) {
380 /* TODO: we are allowed to cache when private= has parameters.
381 * Provided we strip away any of the listed headers unless they are revalidated
382 * successfully (ie, must revalidate AND these headers are prohibited on stale replies).
383 * That is a bit tricky for squid right now so we avoid caching entirely.
384 */
385 debugs(22, 3, HERE << "NO because server reply Cache-Control:private");
386 return 0;
387 }
388 }
389
390 // RFC 2068, sec 14.9.4 - MUST NOT cache any response with Authentication UNLESS certain CC controls are present
391 // allow HTTP violations to IGNORE those controls (ie re-block caching Auth)
392 if (request && (request->flags.auth || request->flags.authSent)) {
393 if (!rep->cache_control) {
394 debugs(22, 3, HERE << "NO because Authenticated and server reply missing Cache-Control");
395 return 0;
396 }
397
398 if (ignoreCacheControl) {
399 debugs(22, 3, HERE << "NO because Authenticated and ignoring Cache-Control");
400 return 0;
401 }
402
403 bool mayStore = false;
404 // HTTPbis pt6 section 3.2: a response CC:public is present
405 if (rep->cache_control->Public()) {
406 debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:public");
407 mayStore = true;
408
409 // HTTPbis pt6 section 3.2: a response CC:must-revalidate is present
410 } else if (rep->cache_control->mustRevalidate()) {
411 debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:must-revalidate");
412 mayStore = true;
413
414 #if USE_HTTP_VIOLATIONS
415 // NP: given the must-revalidate exception we should also be able to exempt no-cache.
416 // HTTPbis WG verdict on this is that it is omitted from the spec due to being 'unexpected' by
417 // some. The caching+revalidate is not exactly unsafe though with Squids interpretation of no-cache
418 // (without parameters) as equivalent to must-revalidate in the reply.
419 } else if (rep->cache_control->hasNoCache() && rep->cache_control->noCache().size() == 0) {
420 debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:no-cache (equivalent to must-revalidate)");
421 mayStore = true;
422 #endif
423
424 // HTTPbis pt6 section 3.2: a response CC:s-maxage is present
425 } else if (rep->cache_control->sMaxAge()) {
426 debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:s-maxage");
427 mayStore = true;
428 }
429
430 if (!mayStore) {
431 debugs(22, 3, HERE << "NO because Authenticated transaction");
432 return 0;
433 }
434
435 // NP: response CC:no-cache is equivalent to CC:must-revalidate,max-age=0. We MAY cache, and do so.
436 // NP: other request CC flags are limiters on HIT/MISS/REFRESH. We don't care about here.
437 }
438
439 /* HACK: The "multipart/x-mixed-replace" content type is used for
440 * continuous push replies. These are generally dynamic and
441 * probably should not be cachable
442 */
443 if ((v = hdr->getStr(Http::HdrType::CONTENT_TYPE)))
444 if (!strncasecmp(v, "multipart/x-mixed-replace", 25)) {
445 debugs(22, 3, HERE << "NO because Content-Type:multipart/x-mixed-replace");
446 return 0;
447 }
448
449 switch (rep->sline.status()) {
450 /* Responses that are cacheable */
451
452 case Http::scOkay:
453
454 case Http::scNonAuthoritativeInformation:
455
456 case Http::scMultipleChoices:
457
458 case Http::scMovedPermanently:
459 case Http::scPermanentRedirect:
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 debugs(22, 3, "NO because refreshIsCachable() returned non-cacheable..");
469 return 0;
470 } else {
471 debugs(22, 3, HERE << "YES because HTTP status " << rep->sline.status());
472 return 1;
473 }
474 /* NOTREACHED */
475 break;
476
477 /* Responses that only are cacheable if the server says so */
478
479 case Http::scFound:
480 case Http::scTemporaryRedirect:
481 if (rep->date <= 0) {
482 debugs(22, 3, HERE << "NO because HTTP status " << rep->sline.status() << " and Date missing/invalid");
483 return 0;
484 }
485 if (rep->expires > rep->date) {
486 debugs(22, 3, HERE << "YES because HTTP status " << rep->sline.status() << " and Expires > Date");
487 return 1;
488 } else {
489 debugs(22, 3, HERE << "NO because HTTP status " << rep->sline.status() << " and Expires <= Date");
490 return 0;
491 }
492 /* NOTREACHED */
493 break;
494
495 /* Errors can be negatively cached */
496
497 case Http::scNoContent:
498
499 case Http::scUseProxy:
500
501 case Http::scBadRequest:
502
503 case Http::scForbidden:
504
505 case Http::scNotFound:
506
507 case Http::scMethodNotAllowed:
508
509 case Http::scUriTooLong:
510
511 case Http::scInternalServerError:
512
513 case Http::scNotImplemented:
514
515 case Http::scBadGateway:
516
517 case Http::scServiceUnavailable:
518
519 case Http::scGatewayTimeout:
520 case Http::scMisdirectedRequest:
521
522 debugs(22, 3, "MAYBE because HTTP status " << rep->sline.status());
523 return -1;
524
525 /* NOTREACHED */
526 break;
527
528 /* Some responses can never be cached */
529
530 case Http::scPartialContent: /* Not yet supported */
531
532 case Http::scSeeOther:
533
534 case Http::scNotModified:
535
536 case Http::scUnauthorized:
537
538 case Http::scProxyAuthenticationRequired:
539
540 case Http::scInvalidHeader: /* Squid header parsing error */
541
542 case Http::scHeaderTooLarge:
543
544 case Http::scPaymentRequired:
545 case Http::scNotAcceptable:
546 case Http::scRequestTimeout:
547 case Http::scConflict:
548 case Http::scLengthRequired:
549 case Http::scPreconditionFailed:
550 case Http::scPayloadTooLarge:
551 case Http::scUnsupportedMediaType:
552 case Http::scUnprocessableEntity:
553 case Http::scLocked:
554 case Http::scFailedDependency:
555 case Http::scInsufficientStorage:
556 case Http::scRequestedRangeNotSatisfied:
557 case Http::scExpectationFailed:
558
559 debugs(22, 3, HERE << "NO because HTTP status " << rep->sline.status());
560 return 0;
561
562 default:
563 /* RFC 2616 section 6.1.1: an unrecognized response MUST NOT be cached. */
564 debugs (11, 3, HERE << "NO because unknown HTTP status code " << rep->sline.status());
565 return 0;
566
567 /* NOTREACHED */
568 break;
569 }
570
571 /* NOTREACHED */
572 }
573
574 /// assemble a variant key (vary-mark) from the given Vary header and HTTP request
575 static void
576 assembleVaryKey(String &vary, SBuf &vstr, const HttpRequest &request)
577 {
578 static const SBuf asterisk("*");
579 const char *pos = nullptr;
580 const char *item = nullptr;
581 int ilen = 0;
582
583 while (strListGetItem(&vary, ',', &item, &ilen, &pos)) {
584 SBuf name(item, ilen);
585 if (name == asterisk) {
586 vstr.clear();
587 break;
588 }
589 name.toLower();
590 if (!vstr.isEmpty())
591 vstr.append(", ", 2);
592 vstr.append(name);
593 String hdr(request.header.getByName(name));
594 const char *value = hdr.termedBuf();
595 if (value) {
596 value = rfc1738_escape_part(value);
597 vstr.append("=\"", 2);
598 vstr.append(value);
599 vstr.append("\"", 1);
600 }
601
602 hdr.clean();
603 }
604 }
605
606 /*
607 * For Vary, store the relevant request headers as
608 * virtual headers in the reply
609 * Returns an empty SBuf if the variance cannot be stored
610 */
611 SBuf
612 httpMakeVaryMark(HttpRequest * request, HttpReply const * reply)
613 {
614 SBuf vstr;
615 String vary;
616
617 vary = reply->header.getList(Http::HdrType::VARY);
618 assembleVaryKey(vary, vstr, *request);
619
620 #if X_ACCELERATOR_VARY
621 vary.clean();
622 vary = reply->header.getList(Http::HdrType::HDR_X_ACCELERATOR_VARY);
623 assembleVaryKey(vary, vstr, *request);
624 #endif
625
626 debugs(11, 3, vstr);
627 return vstr;
628 }
629
630 void
631 HttpStateData::keepaliveAccounting(HttpReply *reply)
632 {
633 if (flags.keepalive)
634 if (_peer)
635 ++ _peer->stats.n_keepalives_sent;
636
637 if (reply->keep_alive) {
638 if (_peer)
639 ++ _peer->stats.n_keepalives_recv;
640
641 if (Config.onoff.detect_broken_server_pconns
642 && reply->bodySize(request->method) == -1 && !flags.chunked) {
643 debugs(11, DBG_IMPORTANT, "keepaliveAccounting: Impossible keep-alive header from '" << entry->url() << "'" );
644 // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" );
645 flags.keepalive_broken = true;
646 }
647 }
648 }
649
650 void
651 HttpStateData::checkDateSkew(HttpReply *reply)
652 {
653 if (reply->date > -1 && !_peer) {
654 int skew = abs((int)(reply->date - squid_curtime));
655
656 if (skew > 86400)
657 debugs(11, 3, "" << request->url.host() << "'s clock is skewed by " << skew << " seconds!");
658 }
659 }
660
661 /**
662 * This creates the error page itself.. its likely
663 * that the forward ported reply header max size patch
664 * generates non http conformant error pages - in which
665 * case the errors where should be 'BAD_GATEWAY' etc
666 */
667 void
668 HttpStateData::processReplyHeader()
669 {
670 /** Creates a blank header. If this routine is made incremental, this will not do */
671
672 /* NP: all exit points to this function MUST call ctx_exit(ctx) */
673 Ctx ctx = ctx_enter(entry->mem_obj->urlXXX());
674
675 debugs(11, 3, "processReplyHeader: key '" << entry->getMD5Text() << "'");
676
677 assert(!flags.headers_parsed);
678
679 if (!inBuf.length()) {
680 ctx_exit(ctx);
681 return;
682 }
683
684 /* Attempt to parse the first line; this will define where the protocol, status, reason-phrase and header begin */
685 {
686 if (hp == NULL)
687 hp = new Http1::ResponseParser;
688
689 bool parsedOk = hp->parse(inBuf);
690
691 // sync the buffers after parsing.
692 inBuf = hp->remaining();
693
694 if (hp->needsMoreData()) {
695 if (eof) { // no more data coming
696 /* Bug 2879: Replies may terminate with \r\n then EOF instead of \r\n\r\n.
697 * We also may receive truncated responses.
698 * Ensure here that we have at minimum two \r\n when EOF is seen.
699 */
700 inBuf.append("\r\n\r\n", 4);
701 // retry the parse
702 parsedOk = hp->parse(inBuf);
703 // sync the buffers after parsing.
704 inBuf = hp->remaining();
705 } else {
706 debugs(33, 5, "Incomplete response, waiting for end of response headers");
707 ctx_exit(ctx);
708 return;
709 }
710 }
711
712 if (!parsedOk) {
713 // unrecoverable parsing error
714 // TODO: Use Raw! XXX: inBuf no longer has the [beginning of the] malformed header.
715 debugs(11, 3, "Non-HTTP-compliant header:\n---------\n" << inBuf << "\n----------");
716 flags.headers_parsed = true;
717 HttpReply *newrep = new HttpReply;
718 newrep->sline.set(Http::ProtocolVersion(), hp->parseStatusCode);
719 setVirginReply(newrep);
720 ctx_exit(ctx);
721 return;
722 }
723 }
724
725 /* We know the whole response is in parser now */
726 debugs(11, 2, "HTTP Server " << serverConnection);
727 debugs(11, 2, "HTTP Server RESPONSE:\n---------\n" <<
728 hp->messageProtocol() << " " << hp->messageStatus() << " " << hp->reasonPhrase() << "\n" <<
729 hp->mimeHeader() <<
730 "----------");
731
732 // reset payload tracking to begin after message headers
733 payloadSeen = inBuf.length();
734
735 HttpReply *newrep = new HttpReply;
736 // XXX: RFC 7230 indicates we MAY ignore the reason phrase,
737 // and use an empty string on unknown status.
738 // We do that now to avoid performance regression from using SBuf::c_str()
739 newrep->sline.set(Http::ProtocolVersion(1,1), hp->messageStatus() /* , hp->reasonPhrase() */);
740 newrep->sline.protocol = newrep->sline.version.protocol = hp->messageProtocol().protocol;
741 newrep->sline.version.major = hp->messageProtocol().major;
742 newrep->sline.version.minor = hp->messageProtocol().minor;
743
744 // parse headers
745 if (!newrep->parseHeader(*hp)) {
746 // XXX: when Http::ProtocolVersion is a function, remove this hack. just set with messageProtocol()
747 newrep->sline.set(Http::ProtocolVersion(), Http::scInvalidHeader);
748 newrep->sline.version.protocol = hp->messageProtocol().protocol;
749 newrep->sline.version.major = hp->messageProtocol().major;
750 newrep->sline.version.minor = hp->messageProtocol().minor;
751 debugs(11, 2, "error parsing response headers mime block");
752 }
753
754 // done with Parser, now process using the HttpReply
755 hp = NULL;
756
757 newrep->sources |= request->url.getScheme() == AnyP::PROTO_HTTPS ? HttpMsg::srcHttps : HttpMsg::srcHttp;
758
759 newrep->removeStaleWarnings();
760
761 if (newrep->sline.protocol == AnyP::PROTO_HTTP && newrep->sline.status() >= 100 && newrep->sline.status() < 200) {
762 handle1xx(newrep);
763 ctx_exit(ctx);
764 return;
765 }
766
767 flags.chunked = false;
768 if (newrep->sline.protocol == AnyP::PROTO_HTTP && newrep->header.chunked()) {
769 flags.chunked = true;
770 httpChunkDecoder = new Http1::TeChunkedParser;
771 }
772
773 if (!peerSupportsConnectionPinning())
774 request->flags.connectionAuthDisabled = true;
775
776 HttpReply *vrep = setVirginReply(newrep);
777 flags.headers_parsed = true;
778
779 keepaliveAccounting(vrep);
780
781 checkDateSkew(vrep);
782
783 processSurrogateControl (vrep);
784
785 request->hier.peer_reply_status = newrep->sline.status();
786
787 ctx_exit(ctx);
788 }
789
790 /// ignore or start forwarding the 1xx response (a.k.a., control message)
791 void
792 HttpStateData::handle1xx(HttpReply *reply)
793 {
794 HttpReply::Pointer msg(reply); // will destroy reply if unused
795
796 // one 1xx at a time: we must not be called while waiting for previous 1xx
797 Must(!flags.handling1xx);
798 flags.handling1xx = true;
799
800 if (!request->canHandle1xx() || request->forcedBodyContinuation) {
801 debugs(11, 2, "ignoring 1xx because it is " << (request->forcedBodyContinuation ? "already sent" : "not supported by client"));
802 proceedAfter1xx();
803 return;
804 }
805
806 #if USE_HTTP_VIOLATIONS
807 // check whether the 1xx response forwarding is allowed by squid.conf
808 if (Config.accessList.reply) {
809 ACLFilledChecklist ch(Config.accessList.reply, originalRequest(), NULL);
810 ch.reply = reply;
811 HTTPMSGLOCK(ch.reply);
812 if (ch.fastCheck() != ACCESS_ALLOWED) { // TODO: support slow lookups?
813 debugs(11, 3, HERE << "ignoring denied 1xx");
814 proceedAfter1xx();
815 return;
816 }
817 }
818 #endif // USE_HTTP_VIOLATIONS
819
820 debugs(11, 2, HERE << "forwarding 1xx to client");
821
822 // the Sink will use this to call us back after writing 1xx to the client
823 typedef NullaryMemFunT<HttpStateData> CbDialer;
824 const AsyncCall::Pointer cb = JobCallback(11, 3, CbDialer, this,
825 HttpStateData::proceedAfter1xx);
826 CallJobHere1(11, 4, request->clientConnectionManager, ConnStateData,
827 ConnStateData::sendControlMsg, HttpControlMsg(msg, cb));
828 // If the call is not fired, then the Sink is gone, and HttpStateData
829 // will terminate due to an aborted store entry or another similar error.
830 // If we get stuck, it is not handle1xx fault if we could get stuck
831 // for similar reasons without a 1xx response.
832 }
833
834 /// restores state and resumes processing after 1xx is ignored or forwarded
835 void
836 HttpStateData::proceedAfter1xx()
837 {
838 Must(flags.handling1xx);
839 debugs(11, 2, "continuing with " << payloadSeen << " bytes in buffer after 1xx");
840 CallJobHere(11, 3, this, HttpStateData, HttpStateData::processReply);
841 }
842
843 /**
844 * returns true if the peer can support connection pinning
845 */
846 bool HttpStateData::peerSupportsConnectionPinning() const
847 {
848 const HttpReply *rep = entry->mem_obj->getReply();
849 const HttpHeader *hdr = &rep->header;
850 bool rc;
851 String header;
852
853 if (!_peer)
854 return true;
855
856 /*If this peer does not support connection pinning (authenticated
857 connections) return false
858 */
859 if (!_peer->connection_auth)
860 return false;
861
862 /*The peer supports connection pinning and the http reply status
863 is not unauthorized, so the related connection can be pinned
864 */
865 if (rep->sline.status() != Http::scUnauthorized)
866 return true;
867
868 /*The server respond with Http::scUnauthorized and the peer configured
869 with "connection-auth=on" we know that the peer supports pinned
870 connections
871 */
872 if (_peer->connection_auth == 1)
873 return true;
874
875 /*At this point peer has configured with "connection-auth=auto"
876 parameter so we need some extra checks to decide if we are going
877 to allow pinned connections or not
878 */
879
880 /*if the peer configured with originserver just allow connection
881 pinning (squid 2.6 behaviour)
882 */
883 if (_peer->options.originserver)
884 return true;
885
886 /*if the connections it is already pinned it is OK*/
887 if (request->flags.pinned)
888 return true;
889
890 /*Allow pinned connections only if the Proxy-support header exists in
891 reply and has in its list the "Session-Based-Authentication"
892 which means that the peer supports connection pinning.
893 */
894 if (!hdr->has(Http::HdrType::PROXY_SUPPORT))
895 return false;
896
897 header = hdr->getStrOrList(Http::HdrType::PROXY_SUPPORT);
898 /* XXX This ought to be done in a case-insensitive manner */
899 rc = (strstr(header.termedBuf(), "Session-Based-Authentication") != NULL);
900
901 return rc;
902 }
903
904 // Called when we parsed (and possibly adapted) the headers but
905 // had not starting storing (a.k.a., sending) the body yet.
906 void
907 HttpStateData::haveParsedReplyHeaders()
908 {
909 Client::haveParsedReplyHeaders();
910
911 Ctx ctx = ctx_enter(entry->mem_obj->urlXXX());
912 HttpReply *rep = finalReply();
913
914 entry->timestampsSet();
915
916 /* Check if object is cacheable or not based on reply code */
917 debugs(11, 3, "HTTP CODE: " << rep->sline.status());
918
919 if (neighbors_do_private_keys)
920 httpMaybeRemovePublic(entry, rep->sline.status());
921
922 bool varyFailure = false;
923 if (rep->header.has(Http::HdrType::VARY)
924 #if X_ACCELERATOR_VARY
925 || rep->header.has(Http::HdrType::HDR_X_ACCELERATOR_VARY)
926 #endif
927 ) {
928 const SBuf vary(httpMakeVaryMark(request, rep));
929
930 if (vary.isEmpty()) {
931 entry->makePrivate();
932 if (!fwd->reforwardableStatus(rep->sline.status()))
933 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
934 varyFailure = true;
935 } else {
936 entry->mem_obj->vary_headers = vary;
937 }
938 }
939
940 if (!varyFailure) {
941 /*
942 * If its not a reply that we will re-forward, then
943 * allow the client to get it.
944 */
945 if (!fwd->reforwardableStatus(rep->sline.status()))
946 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
947
948 switch (cacheableReply()) {
949
950 case 1:
951 entry->makePublic();
952 break;
953
954 case 0:
955 entry->makePrivate();
956 break;
957
958 case -1:
959
960 #if USE_HTTP_VIOLATIONS
961 if (Config.negativeTtl > 0)
962 entry->cacheNegatively();
963 else
964 #endif
965 entry->makePrivate();
966 break;
967
968 default:
969 assert(0);
970 break;
971 }
972 }
973
974 if (!ignoreCacheControl) {
975 if (rep->cache_control) {
976 // We are required to revalidate on many conditions.
977 // For security reasons we do so even if storage was caused by refresh_pattern ignore-* option
978
979 // CC:must-revalidate or CC:proxy-revalidate
980 const bool ccMustRevalidate = (rep->cache_control->proxyRevalidate() || rep->cache_control->mustRevalidate());
981
982 // CC:no-cache (only if there are no parameters)
983 const bool ccNoCacheNoParams = (rep->cache_control->hasNoCache() && rep->cache_control->noCache().size()==0);
984
985 // CC:s-maxage=N
986 const bool ccSMaxAge = rep->cache_control->hasSMaxAge();
987
988 // CC:private (yes, these can sometimes be stored)
989 const bool ccPrivate = rep->cache_control->hasPrivate();
990
991 if (ccMustRevalidate || ccNoCacheNoParams || ccSMaxAge || ccPrivate)
992 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
993 }
994 #if USE_HTTP_VIOLATIONS // response header Pragma::no-cache is undefined in HTTP
995 else {
996 // Expensive calculation. So only do it IF the CC: header is not present.
997
998 /* HACK: Pragma: no-cache in _replies_ is not documented in HTTP,
999 * but servers like "Active Imaging Webcast/2.0" sure do use it */
1000 if (rep->header.has(Http::HdrType::PRAGMA) &&
1001 rep->header.hasListMember(Http::HdrType::PRAGMA,"no-cache",','))
1002 EBIT_SET(entry->flags, ENTRY_REVALIDATE);
1003 }
1004 #endif
1005 }
1006
1007 #if HEADERS_LOG
1008 headersLog(1, 0, request->method, rep);
1009
1010 #endif
1011
1012 ctx_exit(ctx);
1013 }
1014
1015 HttpStateData::ConnectionStatus
1016 HttpStateData::statusIfComplete() const
1017 {
1018 const HttpReply *rep = virginReply();
1019 /** \par
1020 * If the reply wants to close the connection, it takes precedence */
1021
1022 if (httpHeaderHasConnDir(&rep->header, "close"))
1023 return COMPLETE_NONPERSISTENT_MSG;
1024
1025 /** \par
1026 * If we didn't send a keep-alive request header, then this
1027 * can not be a persistent connection.
1028 */
1029 if (!flags.keepalive)
1030 return COMPLETE_NONPERSISTENT_MSG;
1031
1032 /** \par
1033 * If we haven't sent the whole request then this can not be a persistent
1034 * connection.
1035 */
1036 if (!flags.request_sent) {
1037 debugs(11, 2, "Request not yet fully sent " << request->method << ' ' << entry->url());
1038 return COMPLETE_NONPERSISTENT_MSG;
1039 }
1040
1041 /** \par
1042 * What does the reply have to say about keep-alive?
1043 */
1044 /**
1045 \bug XXX BUG?
1046 * If the origin server (HTTP/1.0) does not send a keep-alive
1047 * header, but keeps the connection open anyway, what happens?
1048 * We'll return here and http.c waits for an EOF before changing
1049 * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT
1050 * and an error status code, and we might have to wait until
1051 * the server times out the socket.
1052 */
1053 if (!rep->keep_alive)
1054 return COMPLETE_NONPERSISTENT_MSG;
1055
1056 return COMPLETE_PERSISTENT_MSG;
1057 }
1058
1059 HttpStateData::ConnectionStatus
1060 HttpStateData::persistentConnStatus() const
1061 {
1062 debugs(11, 3, HERE << serverConnection << " eof=" << eof);
1063 if (eof) // already reached EOF
1064 return COMPLETE_NONPERSISTENT_MSG;
1065
1066 /* If server fd is closing (but we have not been notified yet), stop Comm
1067 I/O to avoid assertions. TODO: Change Comm API to handle callers that
1068 want more I/O after async closing (usually initiated by others). */
1069 // XXX: add canReceive or s/canSend/canTalkToServer/
1070 if (!Comm::IsConnOpen(serverConnection))
1071 return COMPLETE_NONPERSISTENT_MSG;
1072
1073 /** \par
1074 * In chunked response we do not know the content length but we are absolutely
1075 * sure about the end of response, so we are calling the statusIfComplete to
1076 * decide if we can be persistant
1077 */
1078 if (lastChunk && flags.chunked)
1079 return statusIfComplete();
1080
1081 const HttpReply *vrep = virginReply();
1082 debugs(11, 5, "persistentConnStatus: content_length=" << vrep->content_length);
1083
1084 const int64_t clen = vrep->bodySize(request->method);
1085
1086 debugs(11, 5, "persistentConnStatus: clen=" << clen);
1087
1088 /* If the body size is unknown we must wait for EOF */
1089 if (clen < 0)
1090 return INCOMPLETE_MSG;
1091
1092 /** \par
1093 * If the body size is known, we must wait until we've gotten all of it. */
1094 if (clen > 0) {
1095 debugs(11,5, "payloadSeen=" << payloadSeen << " content_length=" << vrep->content_length);
1096
1097 if (payloadSeen < vrep->content_length)
1098 return INCOMPLETE_MSG;
1099
1100 if (payloadTruncated > 0) // already read more than needed
1101 return COMPLETE_NONPERSISTENT_MSG; // disable pconns
1102 }
1103
1104 /** \par
1105 * If there is no message body or we got it all, we can be persistent */
1106 return statusIfComplete();
1107 }
1108
1109 #if USE_DELAY_POOLS
1110 static void
1111 readDelayed(void *context, CommRead const &)
1112 {
1113 HttpStateData *state = static_cast<HttpStateData*>(context);
1114 state->flags.do_next_read = true;
1115 state->maybeReadVirginBody();
1116 }
1117 #endif
1118
1119 void
1120 HttpStateData::readReply(const CommIoCbParams &io)
1121 {
1122 Must(!flags.do_next_read); // XXX: should have been set false by mayReadVirginBody()
1123 flags.do_next_read = false;
1124
1125 debugs(11, 5, io.conn);
1126
1127 // Bail out early on Comm::ERR_CLOSING - close handlers will tidy up for us
1128 if (io.flag == Comm::ERR_CLOSING) {
1129 debugs(11, 3, "http socket closing");
1130 return;
1131 }
1132
1133 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
1134 abortTransaction("store entry aborted while reading reply");
1135 return;
1136 }
1137
1138 Must(Comm::IsConnOpen(serverConnection));
1139 Must(io.conn->fd == serverConnection->fd);
1140
1141 /*
1142 * Don't reset the timeout value here. The value should be
1143 * counting Config.Timeout.request and applies to the request
1144 * as a whole, not individual read() calls.
1145 * Plus, it breaks our lame *HalfClosed() detection
1146 */
1147
1148 Must(maybeMakeSpaceAvailable(true));
1149 CommIoCbParams rd(this); // will be expanded with ReadNow results
1150 rd.conn = io.conn;
1151 rd.size = entry->bytesWanted(Range<size_t>(0, inBuf.spaceSize()));
1152 #if USE_DELAY_POOLS
1153 if (rd.size < 1) {
1154 assert(entry->mem_obj);
1155
1156 /* read ahead limit */
1157 /* Perhaps these two calls should both live in MemObject */
1158 AsyncCall::Pointer nilCall;
1159 if (!entry->mem_obj->readAheadPolicyCanRead()) {
1160 entry->mem_obj->delayRead(DeferredRead(readDelayed, this, CommRead(io.conn, NULL, 0, nilCall)));
1161 return;
1162 }
1163
1164 /* delay id limit */
1165 entry->mem_obj->mostBytesAllowed().delayRead(DeferredRead(readDelayed, this, CommRead(io.conn, NULL, 0, nilCall)));
1166 return;
1167 }
1168 #endif
1169
1170 switch (Comm::ReadNow(rd, inBuf)) {
1171 case Comm::INPROGRESS:
1172 if (inBuf.isEmpty())
1173 debugs(33, 2, io.conn << ": no data to process, " << xstrerr(rd.xerrno));
1174 flags.do_next_read = true;
1175 maybeReadVirginBody();
1176 return;
1177
1178 case Comm::OK:
1179 {
1180 payloadSeen += rd.size;
1181 #if USE_DELAY_POOLS
1182 DelayId delayId = entry->mem_obj->mostBytesAllowed();
1183 delayId.bytesIn(rd.size);
1184 #endif
1185
1186 statCounter.server.all.kbytes_in += rd.size;
1187 statCounter.server.http.kbytes_in += rd.size;
1188 ++ IOStats.Http.reads;
1189
1190 int bin = 0;
1191 for (int clen = rd.size - 1; clen; ++bin)
1192 clen >>= 1;
1193
1194 ++ IOStats.Http.read_hist[bin];
1195
1196 // update peer response time stats (%<pt)
1197 const timeval &sent = request->hier.peer_http_request_sent;
1198 if (sent.tv_sec)
1199 tvSub(request->hier.peer_response_time, sent, current_time);
1200 else
1201 request->hier.peer_response_time.tv_sec = -1;
1202 }
1203
1204 /* Continue to process previously read data */
1205 break;
1206
1207 case Comm::ENDFILE: // close detected by 0-byte read
1208 eof = 1;
1209 flags.do_next_read = false;
1210
1211 /* Continue to process previously read data */
1212 break;
1213
1214 // case Comm::COMM_ERROR:
1215 default: // no other flags should ever occur
1216 debugs(11, 2, io.conn << ": read failure: " << xstrerr(rd.xerrno));
1217 ErrorState *err = new ErrorState(ERR_READ_ERROR, Http::scBadGateway, fwd->request);
1218 err->xerrno = rd.xerrno;
1219 fwd->fail(err);
1220 flags.do_next_read = false;
1221 closeServer();
1222 mustStop("HttpStateData::readReply");
1223 return;
1224 }
1225
1226 /* Process next response from buffer */
1227 processReply();
1228 }
1229
1230 /// processes the already read and buffered response data, possibly after
1231 /// waiting for asynchronous 1xx control message processing
1232 void
1233 HttpStateData::processReply()
1234 {
1235
1236 if (flags.handling1xx) { // we came back after handling a 1xx response
1237 debugs(11, 5, HERE << "done with 1xx handling");
1238 flags.handling1xx = false;
1239 Must(!flags.headers_parsed);
1240 }
1241
1242 if (!flags.headers_parsed) { // have not parsed headers yet?
1243 PROF_start(HttpStateData_processReplyHeader);
1244 processReplyHeader();
1245 PROF_stop(HttpStateData_processReplyHeader);
1246
1247 if (!continueAfterParsingHeader()) // parsing error or need more data
1248 return; // TODO: send errors to ICAP
1249
1250 adaptOrFinalizeReply(); // may write to, abort, or "close" the entry
1251 }
1252
1253 // kick more reads if needed and/or process the response body, if any
1254 PROF_start(HttpStateData_processReplyBody);
1255 processReplyBody(); // may call serverComplete()
1256 PROF_stop(HttpStateData_processReplyBody);
1257 }
1258
1259 /**
1260 \retval true if we can continue with processing the body or doing ICAP.
1261 */
1262 bool
1263 HttpStateData::continueAfterParsingHeader()
1264 {
1265 if (flags.handling1xx) {
1266 debugs(11, 5, HERE << "wait for 1xx handling");
1267 Must(!flags.headers_parsed);
1268 return false;
1269 }
1270
1271 if (!flags.headers_parsed && !eof) {
1272 debugs(11, 9, "needs more at " << inBuf.length());
1273 flags.do_next_read = true;
1274 /** \retval false If we have not finished parsing the headers and may get more data.
1275 * Schedules more reads to retrieve the missing data.
1276 */
1277 maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename
1278 return false;
1279 }
1280
1281 /** If we are done with parsing, check for errors */
1282
1283 err_type error = ERR_NONE;
1284
1285 if (flags.headers_parsed) { // parsed headers, possibly with errors
1286 // check for header parsing errors
1287 if (HttpReply *vrep = virginReply()) {
1288 const Http::StatusCode s = vrep->sline.status();
1289 const AnyP::ProtocolVersion &v = vrep->sline.version;
1290 if (s == Http::scInvalidHeader && v != Http::ProtocolVersion(0,9)) {
1291 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Bad header encountered from " << entry->url() << " AKA " << request->url);
1292 error = ERR_INVALID_RESP;
1293 } else if (s == Http::scHeaderTooLarge) {
1294 fwd->dontRetry(true);
1295 error = ERR_TOO_BIG;
1296 } else if (vrep->header.conflictingContentLength()) {
1297 fwd->dontRetry(true);
1298 error = ERR_INVALID_RESP;
1299 } else {
1300 return true; // done parsing, got reply, and no error
1301 }
1302 } else {
1303 // parsed headers but got no reply
1304 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: No reply at all for " << entry->url() << " AKA " << request->url);
1305 error = ERR_INVALID_RESP;
1306 }
1307 } else {
1308 assert(eof);
1309 if (inBuf.length()) {
1310 error = ERR_INVALID_RESP;
1311 debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Headers did not parse at all for " << entry->url() << " AKA " << request->url);
1312 } else {
1313 error = ERR_ZERO_SIZE_OBJECT;
1314 debugs(11, (request->flags.accelerated?DBG_IMPORTANT:2), "WARNING: HTTP: Invalid Response: No object data received for " << entry->url() << " AKA " << request->url);
1315 }
1316 }
1317
1318 assert(error != ERR_NONE);
1319 entry->reset();
1320 fwd->fail(new ErrorState(error, Http::scBadGateway, fwd->request));
1321 flags.do_next_read = false;
1322 closeServer();
1323 mustStop("HttpStateData::continueAfterParsingHeader");
1324 return false; // quit on error
1325 }
1326
1327 /** truncate what we read if we read too much so that writeReplyBody()
1328 writes no more than what we should have read */
1329 void
1330 HttpStateData::truncateVirginBody()
1331 {
1332 assert(flags.headers_parsed);
1333
1334 HttpReply *vrep = virginReply();
1335 int64_t clen = -1;
1336 if (!vrep->expectingBody(request->method, clen) || clen < 0)
1337 return; // no body or a body of unknown size, including chunked
1338
1339 if (payloadSeen - payloadTruncated <= clen)
1340 return; // we did not read too much or already took care of the extras
1341
1342 if (const int64_t extras = payloadSeen - payloadTruncated - clen) {
1343 // server sent more that the advertised content length
1344 debugs(11, 5, "payloadSeen=" << payloadSeen <<
1345 " clen=" << clen << '/' << vrep->content_length <<
1346 " trucated=" << payloadTruncated << '+' << extras);
1347
1348 inBuf.chop(0, inBuf.length() - extras);
1349 payloadTruncated += extras;
1350 }
1351 }
1352
1353 /**
1354 * Call this when there is data from the origin server
1355 * which should be sent to either StoreEntry, or to ICAP...
1356 */
1357 void
1358 HttpStateData::writeReplyBody()
1359 {
1360 truncateVirginBody(); // if needed
1361 const char *data = inBuf.rawContent();
1362 int len = inBuf.length();
1363 addVirginReplyBody(data, len);
1364 inBuf.consume(len);
1365 }
1366
1367 bool
1368 HttpStateData::decodeAndWriteReplyBody()
1369 {
1370 const char *data = NULL;
1371 int len;
1372 bool wasThereAnException = false;
1373 assert(flags.chunked);
1374 assert(httpChunkDecoder);
1375 SQUID_ENTER_THROWING_CODE();
1376 MemBuf decodedData;
1377 decodedData.init();
1378 httpChunkDecoder->setPayloadBuffer(&decodedData);
1379 const bool doneParsing = httpChunkDecoder->parse(inBuf);
1380 inBuf = httpChunkDecoder->remaining(); // sync buffers after parse
1381 len = decodedData.contentSize();
1382 data=decodedData.content();
1383 addVirginReplyBody(data, len);
1384 if (doneParsing) {
1385 lastChunk = 1;
1386 flags.do_next_read = false;
1387 }
1388 SQUID_EXIT_THROWING_CODE(wasThereAnException);
1389 return wasThereAnException;
1390 }
1391
1392 /**
1393 * processReplyBody has two purposes:
1394 * 1 - take the reply body data, if any, and put it into either
1395 * the StoreEntry, or give it over to ICAP.
1396 * 2 - see if we made it to the end of the response (persistent
1397 * connections and such)
1398 */
1399 void
1400 HttpStateData::processReplyBody()
1401 {
1402 Ip::Address client_addr;
1403 bool ispinned = false;
1404
1405 if (!flags.headers_parsed) {
1406 flags.do_next_read = true;
1407 maybeReadVirginBody();
1408 return;
1409 }
1410
1411 #if USE_ADAPTATION
1412 debugs(11,5, HERE << "adaptationAccessCheckPending=" << adaptationAccessCheckPending);
1413 if (adaptationAccessCheckPending)
1414 return;
1415
1416 #endif
1417
1418 /*
1419 * At this point the reply headers have been parsed and consumed.
1420 * That means header content has been removed from readBuf and
1421 * it contains only body data.
1422 */
1423 if (entry->isAccepting()) {
1424 if (flags.chunked) {
1425 if (!decodeAndWriteReplyBody()) {
1426 flags.do_next_read = false;
1427 serverComplete();
1428 return;
1429 }
1430 } else
1431 writeReplyBody();
1432 }
1433
1434 // storing/sending methods like earlier adaptOrFinalizeReply() or
1435 // above writeReplyBody() may release/abort the store entry.
1436 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
1437 // TODO: In some cases (e.g., 304), we should keep persistent conn open.
1438 // Detect end-of-reply (and, hence, pool our idle pconn) earlier (ASAP).
1439 abortTransaction("store entry aborted while storing reply");
1440 return;
1441 } else
1442 switch (persistentConnStatus()) {
1443 case INCOMPLETE_MSG: {
1444 debugs(11, 5, "processReplyBody: INCOMPLETE_MSG from " << serverConnection);
1445 /* Wait for more data or EOF condition */
1446 AsyncCall::Pointer nil;
1447 if (flags.keepalive_broken) {
1448 commSetConnTimeout(serverConnection, 10, nil);
1449 } else {
1450 commSetConnTimeout(serverConnection, Config.Timeout.read, nil);
1451 }
1452
1453 flags.do_next_read = true;
1454 }
1455 break;
1456
1457 case COMPLETE_PERSISTENT_MSG:
1458 debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG from " << serverConnection);
1459 /* yes we have to clear all these! */
1460 commUnsetConnTimeout(serverConnection);
1461 flags.do_next_read = false;
1462
1463 comm_remove_close_handler(serverConnection->fd, closeHandler);
1464 closeHandler = NULL;
1465 fwd->unregister(serverConnection);
1466
1467 if (request->flags.spoofClientIp)
1468 client_addr = request->client_addr;
1469
1470 if (request->flags.pinned) {
1471 ispinned = true;
1472 } else if (request->flags.connectionAuth && request->flags.authSent) {
1473 ispinned = true;
1474 }
1475
1476 if (ispinned && request->clientConnectionManager.valid()) {
1477 request->clientConnectionManager->pinConnection(serverConnection, request, _peer,
1478 (request->flags.connectionAuth));
1479 } else {
1480 fwd->pconnPush(serverConnection, request->url.host());
1481 }
1482
1483 serverConnection = NULL;
1484 serverComplete();
1485 return;
1486
1487 case COMPLETE_NONPERSISTENT_MSG:
1488 debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG from " << serverConnection);
1489 serverComplete();
1490 return;
1491 }
1492
1493 maybeReadVirginBody();
1494 }
1495
1496 bool
1497 HttpStateData::mayReadVirginReplyBody() const
1498 {
1499 // TODO: Be more precise here. For example, if/when reading trailer, we may
1500 // not be doneWithServer() yet, but we should return false. Similarly, we
1501 // could still be writing the request body after receiving the whole reply.
1502 return !doneWithServer();
1503 }
1504
1505 void
1506 HttpStateData::maybeReadVirginBody()
1507 {
1508 // too late to read
1509 if (!Comm::IsConnOpen(serverConnection) || fd_table[serverConnection->fd].closing())
1510 return;
1511
1512 if (!maybeMakeSpaceAvailable(false))
1513 return;
1514
1515 // XXX: get rid of the do_next_read flag
1516 // check for the proper reasons preventing read(2)
1517 if (!flags.do_next_read)
1518 return;
1519
1520 flags.do_next_read = false;
1521
1522 // must not already be waiting for read(2) ...
1523 assert(!Comm::MonitorsRead(serverConnection->fd));
1524
1525 // wait for read(2) to be possible.
1526 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
1527 AsyncCall::Pointer call = JobCallback(11, 5, Dialer, this, HttpStateData::readReply);
1528 Comm::Read(serverConnection, call);
1529 }
1530
1531 bool
1532 HttpStateData::maybeMakeSpaceAvailable(bool doGrow)
1533 {
1534 // how much we are allowed to buffer
1535 const int limitBuffer = (flags.headers_parsed ? Config.readAheadGap : Config.maxReplyHeaderSize);
1536
1537 if (limitBuffer < 0 || inBuf.length() >= (SBuf::size_type)limitBuffer) {
1538 // when buffer is at or over limit already
1539 debugs(11, 7, "wont read up to " << limitBuffer << ". buffer has (" << inBuf.length() << "/" << inBuf.spaceSize() << ") from " << serverConnection);
1540 debugs(11, DBG_DATA, "buffer has {" << inBuf << "}");
1541 // Process next response from buffer
1542 processReply();
1543 return false;
1544 }
1545
1546 // how much we want to read
1547 const size_t read_size = calcBufferSpaceToReserve(inBuf.spaceSize(), (limitBuffer - inBuf.length()));
1548
1549 if (!read_size) {
1550 debugs(11, 7, "wont read up to " << read_size << " into buffer (" << inBuf.length() << "/" << inBuf.spaceSize() << ") from " << serverConnection);
1551 return false;
1552 }
1553
1554 // just report whether we could grow or not, dont actually do it
1555 if (doGrow)
1556 return (read_size >= 2);
1557
1558 // we may need to grow the buffer
1559 inBuf.reserveSpace(read_size);
1560 debugs(11, 8, (!flags.do_next_read ? "wont" : "may") <<
1561 " read up to " << read_size << " bytes info buf(" << inBuf.length() << "/" << inBuf.spaceSize() <<
1562 ") from " << serverConnection);
1563
1564 return (inBuf.spaceSize() >= 2); // only read if there is 1+ bytes of space available
1565 }
1566
1567 /// called after writing the very last request byte (body, last-chunk, etc)
1568 void
1569 HttpStateData::wroteLast(const CommIoCbParams &io)
1570 {
1571 debugs(11, 5, HERE << serverConnection << ": size " << io.size << ": errflag " << io.flag << ".");
1572 #if URL_CHECKSUM_DEBUG
1573
1574 entry->mem_obj->checkUrlChecksum();
1575 #endif
1576
1577 if (io.size > 0) {
1578 fd_bytes(io.fd, io.size, FD_WRITE);
1579 statCounter.server.all.kbytes_out += io.size;
1580 statCounter.server.http.kbytes_out += io.size;
1581 }
1582
1583 if (io.flag == Comm::ERR_CLOSING)
1584 return;
1585
1586 if (io.flag) {
1587 ErrorState *err = new ErrorState(ERR_WRITE_ERROR, Http::scBadGateway, fwd->request);
1588 err->xerrno = io.xerrno;
1589 fwd->fail(err);
1590 closeServer();
1591 mustStop("HttpStateData::wroteLast");
1592 return;
1593 }
1594
1595 sendComplete();
1596 }
1597
1598 /// successfully wrote the entire request (including body, last-chunk, etc.)
1599 void
1600 HttpStateData::sendComplete()
1601 {
1602 /*
1603 * Set the read timeout here because it hasn't been set yet.
1604 * We only set the read timeout after the request has been
1605 * fully written to the peer. If we start the timeout
1606 * after connection establishment, then we are likely to hit
1607 * the timeout for POST/PUT requests that have very large
1608 * request bodies.
1609 */
1610 typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer;
1611 AsyncCall::Pointer timeoutCall = JobCallback(11, 5,
1612 TimeoutDialer, this, HttpStateData::httpTimeout);
1613
1614 commSetConnTimeout(serverConnection, Config.Timeout.read, timeoutCall);
1615 flags.request_sent = true;
1616 request->hier.peer_http_request_sent = current_time;
1617 }
1618
1619 void
1620 HttpStateData::closeServer()
1621 {
1622 debugs(11,5, HERE << "closing HTTP server " << serverConnection << " this " << this);
1623
1624 if (Comm::IsConnOpen(serverConnection)) {
1625 fwd->unregister(serverConnection);
1626 comm_remove_close_handler(serverConnection->fd, closeHandler);
1627 closeHandler = NULL;
1628 serverConnection->close();
1629 }
1630 }
1631
1632 bool
1633 HttpStateData::doneWithServer() const
1634 {
1635 return !Comm::IsConnOpen(serverConnection);
1636 }
1637
1638 /*
1639 * Fixup authentication request headers for special cases
1640 */
1641 static void
1642 httpFixupAuthentication(HttpRequest * request, const HttpHeader * hdr_in, HttpHeader * hdr_out, const HttpStateFlags &flags)
1643 {
1644 Http::HdrType header = flags.originpeer ? Http::HdrType::AUTHORIZATION : Http::HdrType::PROXY_AUTHORIZATION;
1645
1646 /* Nothing to do unless we are forwarding to a peer */
1647 if (!request->flags.proxying)
1648 return;
1649
1650 /* Needs to be explicitly enabled */
1651 if (!request->peer_login)
1652 return;
1653
1654 /* Maybe already dealt with? */
1655 if (hdr_out->has(header))
1656 return;
1657
1658 /* Nothing to do here for PASSTHRU */
1659 if (strcmp(request->peer_login, "PASSTHRU") == 0)
1660 return;
1661
1662 /* PROXYPASS is a special case, single-signon to servers with the proxy password (basic only) */
1663 if (flags.originpeer && strcmp(request->peer_login, "PROXYPASS") == 0 && hdr_in->has(Http::HdrType::PROXY_AUTHORIZATION)) {
1664 const char *auth = hdr_in->getStr(Http::HdrType::PROXY_AUTHORIZATION);
1665
1666 if (auth && strncasecmp(auth, "basic ", 6) == 0) {
1667 hdr_out->putStr(header, auth);
1668 return;
1669 }
1670 }
1671
1672 uint8_t loginbuf[base64_encode_len(MAX_LOGIN_SZ)];
1673 size_t blen;
1674 struct base64_encode_ctx ctx;
1675 base64_encode_init(&ctx);
1676
1677 /* Special mode to pass the username to the upstream cache */
1678 if (*request->peer_login == '*') {
1679 const char *username = "-";
1680
1681 if (request->extacl_user.size())
1682 username = request->extacl_user.termedBuf();
1683 #if USE_AUTH
1684 else if (request->auth_user_request != NULL)
1685 username = request->auth_user_request->username();
1686 #endif
1687
1688 blen = base64_encode_update(&ctx, loginbuf, strlen(username), reinterpret_cast<const uint8_t*>(username));
1689 blen += base64_encode_update(&ctx, loginbuf+blen, strlen(request->peer_login +1), reinterpret_cast<const uint8_t*>(request->peer_login +1));
1690 blen += base64_encode_final(&ctx, loginbuf+blen);
1691 httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf);
1692 return;
1693 }
1694
1695 /* external_acl provided credentials */
1696 if (request->extacl_user.size() && request->extacl_passwd.size() &&
1697 (strcmp(request->peer_login, "PASS") == 0 ||
1698 strcmp(request->peer_login, "PROXYPASS") == 0)) {
1699
1700 blen = base64_encode_update(&ctx, loginbuf, request->extacl_user.size(), reinterpret_cast<const uint8_t*>(request->extacl_user.rawBuf()));
1701 blen += base64_encode_update(&ctx, loginbuf+blen, 1, reinterpret_cast<const uint8_t*>(":"));
1702 blen += base64_encode_update(&ctx, loginbuf+blen, request->extacl_passwd.size(), reinterpret_cast<const uint8_t*>(request->extacl_passwd.rawBuf()));
1703 blen += base64_encode_final(&ctx, loginbuf+blen);
1704 httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf);
1705 return;
1706 }
1707 // if no external user credentials are available to fake authentication with PASS acts like PASSTHRU
1708 if (strcmp(request->peer_login, "PASS") == 0)
1709 return;
1710
1711 /* Kerberos login to peer */
1712 #if HAVE_AUTH_MODULE_NEGOTIATE && HAVE_KRB5 && HAVE_GSSAPI
1713 if (strncmp(request->peer_login, "NEGOTIATE",strlen("NEGOTIATE")) == 0) {
1714 char *Token=NULL;
1715 char *PrincipalName=NULL,*p;
1716 int negotiate_flags = 0;
1717
1718 if ((p=strchr(request->peer_login,':')) != NULL ) {
1719 PrincipalName=++p;
1720 }
1721 if (request->flags.auth_no_keytab) {
1722 negotiate_flags |= PEER_PROXY_NEGOTIATE_NOKEYTAB;
1723 }
1724 Token = peer_proxy_negotiate_auth(PrincipalName, request->peer_host, negotiate_flags);
1725 if (Token) {
1726 httpHeaderPutStrf(hdr_out, header, "Negotiate %s",Token);
1727 }
1728 return;
1729 }
1730 #endif /* HAVE_KRB5 && HAVE_GSSAPI */
1731
1732 blen = base64_encode_update(&ctx, loginbuf, strlen(request->peer_login), reinterpret_cast<const uint8_t*>(request->peer_login));
1733 blen += base64_encode_final(&ctx, loginbuf+blen);
1734 httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf);
1735 return;
1736 }
1737
1738 /*
1739 * build request headers and append them to a given MemBuf
1740 * used by buildRequestPrefix()
1741 * note: initialised the HttpHeader, the caller is responsible for Clean()-ing
1742 */
1743 void
1744 HttpStateData::httpBuildRequestHeader(HttpRequest * request,
1745 StoreEntry * entry,
1746 const AccessLogEntryPointer &al,
1747 HttpHeader * hdr_out,
1748 const HttpStateFlags &flags)
1749 {
1750 /* building buffer for complex strings */
1751 #define BBUF_SZ (MAX_URL+32)
1752 LOCAL_ARRAY(char, bbuf, BBUF_SZ);
1753 LOCAL_ARRAY(char, ntoabuf, MAX_IPSTRLEN);
1754 const HttpHeader *hdr_in = &request->header;
1755 const HttpHeaderEntry *e = NULL;
1756 HttpHeaderPos pos = HttpHeaderInitPos;
1757 assert (hdr_out->owner == hoRequest);
1758
1759 /* use our IMS header if the cached entry has Last-Modified time */
1760 if (request->lastmod > -1)
1761 hdr_out->putTime(Http::HdrType::IF_MODIFIED_SINCE, request->lastmod);
1762
1763 // Add our own If-None-Match field if the cached entry has a strong ETag.
1764 // copyOneHeaderFromClientsideRequestToUpstreamRequest() adds client ones.
1765 if (request->etag.size() > 0) {
1766 hdr_out->addEntry(new HttpHeaderEntry(Http::HdrType::IF_NONE_MATCH, NULL,
1767 request->etag.termedBuf()));
1768 }
1769
1770 bool we_do_ranges = decideIfWeDoRanges (request);
1771
1772 String strConnection (hdr_in->getList(Http::HdrType::CONNECTION));
1773
1774 while ((e = hdr_in->getEntry(&pos)))
1775 copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, hdr_out, we_do_ranges, flags);
1776
1777 /* Abstraction break: We should interpret multipart/byterange responses
1778 * into offset-length data, and this works around our inability to do so.
1779 */
1780 if (!we_do_ranges && request->multipartRangeRequest()) {
1781 /* don't cache the result */
1782 request->flags.cachable = false;
1783 /* pretend it's not a range request */
1784 request->ignoreRange("want to request the whole object");
1785 request->flags.isRanged = false;
1786 }
1787
1788 /* append Via */
1789 if (Config.onoff.via) {
1790 String strVia;
1791 strVia = hdr_in->getList(Http::HdrType::VIA);
1792 snprintf(bbuf, BBUF_SZ, "%d.%d %s",
1793 request->http_ver.major,
1794 request->http_ver.minor, ThisCache);
1795 strListAdd(&strVia, bbuf, ',');
1796 hdr_out->putStr(Http::HdrType::VIA, strVia.termedBuf());
1797 strVia.clean();
1798 }
1799
1800 if (request->flags.accelerated) {
1801 /* Append Surrogate-Capabilities */
1802 String strSurrogate(hdr_in->getList(Http::HdrType::SURROGATE_CAPABILITY));
1803 #if USE_SQUID_ESI
1804 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"", Config.Accel.surrogate_id);
1805 #else
1806 snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0\"", Config.Accel.surrogate_id);
1807 #endif
1808 strListAdd(&strSurrogate, bbuf, ',');
1809 hdr_out->putStr(Http::HdrType::SURROGATE_CAPABILITY, strSurrogate.termedBuf());
1810 }
1811
1812 /** \pre Handle X-Forwarded-For */
1813 if (strcmp(opt_forwarded_for, "delete") != 0) {
1814
1815 String strFwd = hdr_in->getList(Http::HdrType::X_FORWARDED_FOR);
1816
1817 // if we cannot double strFwd size, then it grew past 50% of the limit
1818 if (!strFwd.canGrowBy(strFwd.size())) {
1819 // There is probably a forwarding loop with Via detection disabled.
1820 // If we do nothing, String will assert on overflow soon.
1821 // TODO: Terminate all transactions with huge XFF?
1822 strFwd = "error";
1823
1824 static int warnedCount = 0;
1825 if (warnedCount++ < 100) {
1826 const SBuf url(entry ? SBuf(entry->url()) : request->effectiveRequestUri());
1827 debugs(11, DBG_IMPORTANT, "Warning: likely forwarding loop with " << url);
1828 }
1829 }
1830
1831 if (strcmp(opt_forwarded_for, "on") == 0) {
1832 /** If set to ON - append client IP or 'unknown'. */
1833 if ( request->client_addr.isNoAddr() )
1834 strListAdd(&strFwd, "unknown", ',');
1835 else
1836 strListAdd(&strFwd, request->client_addr.toStr(ntoabuf, MAX_IPSTRLEN), ',');
1837 } else if (strcmp(opt_forwarded_for, "off") == 0) {
1838 /** If set to OFF - append 'unknown'. */
1839 strListAdd(&strFwd, "unknown", ',');
1840 } else if (strcmp(opt_forwarded_for, "transparent") == 0) {
1841 /** If set to TRANSPARENT - pass through unchanged. */
1842 } else if (strcmp(opt_forwarded_for, "truncate") == 0) {
1843 /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */
1844 if ( request->client_addr.isNoAddr() )
1845 strFwd = "unknown";
1846 else
1847 strFwd = request->client_addr.toStr(ntoabuf, MAX_IPSTRLEN);
1848 }
1849 if (strFwd.size() > 0)
1850 hdr_out->putStr(Http::HdrType::X_FORWARDED_FOR, strFwd.termedBuf());
1851 }
1852 /** If set to DELETE - do not copy through. */
1853
1854 /* append Host if not there already */
1855 if (!hdr_out->has(Http::HdrType::HOST)) {
1856 if (request->peer_domain) {
1857 hdr_out->putStr(Http::HdrType::HOST, request->peer_domain);
1858 } else {
1859 SBuf authority = request->url.authority();
1860 hdr_out->putStr(Http::HdrType::HOST, authority.c_str());
1861 }
1862 }
1863
1864 /* append Authorization if known in URL, not in header and going direct */
1865 if (!hdr_out->has(Http::HdrType::AUTHORIZATION)) {
1866 if (!request->flags.proxying && !request->url.userInfo().isEmpty()) {
1867 static uint8_t result[base64_encode_len(MAX_URL*2)]; // should be big enough for a single URI segment
1868 struct base64_encode_ctx ctx;
1869 base64_encode_init(&ctx);
1870 size_t blen = base64_encode_update(&ctx, result, request->url.userInfo().length(), reinterpret_cast<const uint8_t*>(request->url.userInfo().rawContent()));
1871 blen += base64_encode_final(&ctx, result+blen);
1872 result[blen] = '\0';
1873 if (blen)
1874 httpHeaderPutStrf(hdr_out, Http::HdrType::AUTHORIZATION, "Basic %.*s", (int)blen, result);
1875 }
1876 }
1877
1878 /* Fixup (Proxy-)Authorization special cases. Plain relaying dealt with above */
1879 httpFixupAuthentication(request, hdr_in, hdr_out, flags);
1880
1881 /* append Cache-Control, add max-age if not there already */
1882 {
1883 HttpHdrCc *cc = hdr_in->getCc();
1884
1885 if (!cc)
1886 cc = new HttpHdrCc();
1887
1888 #if 0 /* see bug 2330 */
1889 /* Set no-cache if determined needed but not found */
1890 if (request->flags.nocache)
1891 EBIT_SET(cc->mask, HttpHdrCcType::CC_NO_CACHE);
1892 #endif
1893
1894 /* Add max-age only without no-cache */
1895 if (!cc->hasMaxAge() && !cc->hasNoCache()) {
1896 // XXX: performance regression. c_str() reallocates
1897 SBuf tmp(request->effectiveRequestUri());
1898 cc->maxAge(getMaxAge(entry ? entry->url() : tmp.c_str()));
1899 }
1900
1901 /* Enforce sibling relations */
1902 if (flags.only_if_cached)
1903 cc->onlyIfCached(true);
1904
1905 hdr_out->putCc(cc);
1906
1907 delete cc;
1908 }
1909
1910 /* maybe append Connection: keep-alive */
1911 if (flags.keepalive) {
1912 hdr_out->putStr(Http::HdrType::CONNECTION, "keep-alive");
1913 }
1914
1915 /* append Front-End-Https */
1916 if (flags.front_end_https) {
1917 if (flags.front_end_https == 1 || request->url.getScheme() == AnyP::PROTO_HTTPS)
1918 hdr_out->putStr(Http::HdrType::FRONT_END_HTTPS, "On");
1919 }
1920
1921 if (flags.chunked_request) {
1922 // Do not just copy the original value so that if the client-side
1923 // starts decode other encodings, this code may remain valid.
1924 hdr_out->putStr(Http::HdrType::TRANSFER_ENCODING, "chunked");
1925 }
1926
1927 /* Now mangle the headers. */
1928 httpHdrMangleList(hdr_out, request, al, ROR_REQUEST);
1929
1930 strConnection.clean();
1931 }
1932
1933 /**
1934 * Decides whether a particular header may be cloned from the received Clients request
1935 * to our outgoing fetch request.
1936 */
1937 void
1938 copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request, HttpHeader * hdr_out, const int we_do_ranges, const HttpStateFlags &flags)
1939 {
1940 debugs(11, 5, "httpBuildRequestHeader: " << e->name << ": " << e->value );
1941
1942 switch (e->id) {
1943
1944 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid should not pass on. */
1945
1946 case Http::HdrType::PROXY_AUTHORIZATION:
1947 /** \par Proxy-Authorization:
1948 * Only pass on proxy authentication to peers for which
1949 * authentication forwarding is explicitly enabled
1950 */
1951 if (!flags.originpeer && flags.proxying && request->peer_login &&
1952 (strcmp(request->peer_login, "PASS") == 0 ||
1953 strcmp(request->peer_login, "PROXYPASS") == 0 ||
1954 strcmp(request->peer_login, "PASSTHRU") == 0)) {
1955 hdr_out->addEntry(e->clone());
1956 }
1957 break;
1958
1959 /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid does not pass on. */
1960
1961 case Http::HdrType::CONNECTION: /** \par Connection: */
1962 case Http::HdrType::TE: /** \par TE: */
1963 case Http::HdrType::KEEP_ALIVE: /** \par Keep-Alive: */
1964 case Http::HdrType::PROXY_AUTHENTICATE: /** \par Proxy-Authenticate: */
1965 case Http::HdrType::TRAILER: /** \par Trailer: */
1966 case Http::HdrType::UPGRADE: /** \par Upgrade: */
1967 case Http::HdrType::TRANSFER_ENCODING: /** \par Transfer-Encoding: */
1968 break;
1969
1970 /** \par OTHER headers I haven't bothered to track down yet. */
1971
1972 case Http::HdrType::AUTHORIZATION:
1973 /** \par WWW-Authorization:
1974 * Pass on WWW authentication */
1975
1976 if (!flags.originpeer) {
1977 hdr_out->addEntry(e->clone());
1978 } else {
1979 /** \note In accelerators, only forward authentication if enabled
1980 * (see also httpFixupAuthentication for special cases)
1981 */
1982 if (request->peer_login &&
1983 (strcmp(request->peer_login, "PASS") == 0 ||
1984 strcmp(request->peer_login, "PASSTHRU") == 0 ||
1985 strcmp(request->peer_login, "PROXYPASS") == 0)) {
1986 hdr_out->addEntry(e->clone());
1987 }
1988 }
1989
1990 break;
1991
1992 case Http::HdrType::HOST:
1993 /** \par Host:
1994 * Normally Squid rewrites the Host: header.
1995 * However, there is one case when we don't: If the URL
1996 * went through our redirector and the admin configured
1997 * 'redir_rewrites_host' to be off.
1998 */
1999 if (request->peer_domain)
2000 hdr_out->putStr(Http::HdrType::HOST, request->peer_domain);
2001 else if (request->flags.redirected && !Config.onoff.redir_rewrites_host)
2002 hdr_out->addEntry(e->clone());
2003 else {
2004 SBuf authority = request->url.authority();
2005 hdr_out->putStr(Http::HdrType::HOST, authority.c_str());
2006 }
2007
2008 break;
2009
2010 case Http::HdrType::IF_MODIFIED_SINCE:
2011 /** \par If-Modified-Since:
2012 * append unless we added our own,
2013 * but only if cache_miss_revalidate is enabled, or
2014 * the request is not cacheable, or
2015 * the request contains authentication credentials.
2016 * \note at most one client's If-Modified-Since header can pass through
2017 */
2018 // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
2019 if (hdr_out->has(Http::HdrType::IF_MODIFIED_SINCE))
2020 break;
2021 else if (Config.onoff.cache_miss_revalidate || !request->flags.cachable || request->flags.auth)
2022 hdr_out->addEntry(e->clone());
2023 break;
2024
2025 case Http::HdrType::IF_NONE_MATCH:
2026 /** \par If-None-Match:
2027 * append if the wildcard '*' special case value is present, or
2028 * cache_miss_revalidate is disabled, or
2029 * the request is not cacheable in this proxy, or
2030 * the request contains authentication credentials.
2031 * \note this header lists a set of responses for the server to elide sending. Squid added values are extending that set.
2032 */
2033 // XXX: need to check and cleanup the auth case so cacheable auth requests get cached.
2034 if (hdr_out->hasListMember(Http::HdrType::IF_MATCH, "*", ',') || Config.onoff.cache_miss_revalidate || !request->flags.cachable || request->flags.auth)
2035 hdr_out->addEntry(e->clone());
2036 break;
2037
2038 case Http::HdrType::MAX_FORWARDS:
2039 /** \par Max-Forwards:
2040 * pass only on TRACE or OPTIONS requests */
2041 if (request->method == Http::METHOD_TRACE || request->method == Http::METHOD_OPTIONS) {
2042 const int64_t hops = e->getInt64();
2043
2044 if (hops > 0)
2045 hdr_out->putInt64(Http::HdrType::MAX_FORWARDS, hops - 1);
2046 }
2047
2048 break;
2049
2050 case Http::HdrType::VIA:
2051 /** \par Via:
2052 * If Via is disabled then forward any received header as-is.
2053 * Otherwise leave for explicit updated addition later. */
2054
2055 if (!Config.onoff.via)
2056 hdr_out->addEntry(e->clone());
2057
2058 break;
2059
2060 case Http::HdrType::RANGE:
2061
2062 case Http::HdrType::IF_RANGE:
2063
2064 case Http::HdrType::REQUEST_RANGE:
2065 /** \par Range:, If-Range:, Request-Range:
2066 * Only pass if we accept ranges */
2067 if (!we_do_ranges)
2068 hdr_out->addEntry(e->clone());
2069
2070 break;
2071
2072 case Http::HdrType::PROXY_CONNECTION: // SHOULD ignore. But doing so breaks things.
2073 break;
2074
2075 case Http::HdrType::CONTENT_LENGTH:
2076 // pass through unless we chunk; also, keeping this away from default
2077 // prevents request smuggling via Connection: Content-Length tricks
2078 if (!flags.chunked_request)
2079 hdr_out->addEntry(e->clone());
2080 break;
2081
2082 case Http::HdrType::X_FORWARDED_FOR:
2083
2084 case Http::HdrType::CACHE_CONTROL:
2085 /** \par X-Forwarded-For:, Cache-Control:
2086 * handled specially by Squid, so leave off for now.
2087 * append these after the loop if needed */
2088 break;
2089
2090 case Http::HdrType::FRONT_END_HTTPS:
2091 /** \par Front-End-Https:
2092 * Pass thru only if peer is configured with front-end-https */
2093 if (!flags.front_end_https)
2094 hdr_out->addEntry(e->clone());
2095
2096 break;
2097
2098 default:
2099 /** \par default.
2100 * pass on all other header fields
2101 * which are NOT listed by the special Connection: header. */
2102
2103 if (strConnection.size()>0 && strListIsMember(&strConnection, e->name.termedBuf(), ',')) {
2104 debugs(11, 2, "'" << e->name << "' header cropped by Connection: definition");
2105 return;
2106 }
2107
2108 hdr_out->addEntry(e->clone());
2109 }
2110 }
2111
2112 bool
2113 HttpStateData::decideIfWeDoRanges (HttpRequest * request)
2114 {
2115 bool result = true;
2116 /* decide if we want to do Ranges ourselves
2117 * and fetch the whole object now)
2118 * We want to handle Ranges ourselves iff
2119 * - we can actually parse client Range specs
2120 * - the specs are expected to be simple enough (e.g. no out-of-order ranges)
2121 * - reply will be cachable
2122 * (If the reply will be uncachable we have to throw it away after
2123 * serving this request, so it is better to forward ranges to
2124 * the server and fetch only the requested content)
2125 */
2126
2127 int64_t roffLimit = request->getRangeOffsetLimit();
2128
2129 if (NULL == request->range || !request->flags.cachable
2130 || request->range->offsetLimitExceeded(roffLimit) || request->flags.connectionAuth)
2131 result = false;
2132
2133 debugs(11, 8, "decideIfWeDoRanges: range specs: " <<
2134 request->range << ", cachable: " <<
2135 request->flags.cachable << "; we_do_ranges: " << result);
2136
2137 return result;
2138 }
2139
2140 /* build request prefix and append it to a given MemBuf;
2141 * return the length of the prefix */
2142 mb_size_t
2143 HttpStateData::buildRequestPrefix(MemBuf * mb)
2144 {
2145 const int offset = mb->size;
2146 /* Uses a local httpver variable to print the HTTP label
2147 * since the HttpRequest may have an older version label.
2148 * XXX: This could create protocol bugs as the headers sent and
2149 * flow control should all be based on the HttpRequest version
2150 * not the one we are sending. Needs checking.
2151 */
2152 const AnyP::ProtocolVersion httpver = Http::ProtocolVersion();
2153 const SBuf url(_peer && !_peer->options.originserver ? request->effectiveRequestUri() : request->url.path());
2154 mb->appendf(SQUIDSBUFPH " " SQUIDSBUFPH " %s/%d.%d\r\n",
2155 SQUIDSBUFPRINT(request->method.image()),
2156 SQUIDSBUFPRINT(url),
2157 AnyP::ProtocolType_str[httpver.protocol],
2158 httpver.major,httpver.minor);
2159 /* build and pack headers */
2160 {
2161 HttpHeader hdr(hoRequest);
2162 httpBuildRequestHeader(request, entry, fwd->al, &hdr, flags);
2163
2164 if (request->flags.pinned && request->flags.connectionAuth)
2165 request->flags.authSent = true;
2166 else if (hdr.has(Http::HdrType::AUTHORIZATION))
2167 request->flags.authSent = true;
2168
2169 hdr.packInto(mb);
2170 hdr.clean();
2171 }
2172 /* append header terminator */
2173 mb->append(crlf, 2);
2174 return mb->size - offset;
2175 }
2176
2177 /* This will be called when connect completes. Write request. */
2178 bool
2179 HttpStateData::sendRequest()
2180 {
2181 MemBuf mb;
2182
2183 debugs(11, 5, HERE << serverConnection << ", request " << request << ", this " << this << ".");
2184
2185 if (!Comm::IsConnOpen(serverConnection)) {
2186 debugs(11,3, HERE << "cannot send request to closing " << serverConnection);
2187 assert(closeHandler != NULL);
2188 return false;
2189 }
2190
2191 typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer;
2192 AsyncCall::Pointer timeoutCall = JobCallback(11, 5,
2193 TimeoutDialer, this, HttpStateData::httpTimeout);
2194 commSetConnTimeout(serverConnection, Config.Timeout.lifetime, timeoutCall);
2195 flags.do_next_read = true;
2196 maybeReadVirginBody();
2197
2198 if (request->body_pipe != NULL) {
2199 if (!startRequestBodyFlow()) // register to receive body data
2200 return false;
2201 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
2202 requestSender = JobCallback(11,5,
2203 Dialer, this, HttpStateData::sentRequestBody);
2204
2205 Must(!flags.chunked_request);
2206 // use chunked encoding if we do not know the length
2207 if (request->content_length < 0)
2208 flags.chunked_request = true;
2209 } else {
2210 assert(!requestBodySource);
2211 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
2212 requestSender = JobCallback(11,5,
2213 Dialer, this, HttpStateData::wroteLast);
2214 }
2215
2216 flags.originpeer = (_peer != NULL && _peer->options.originserver);
2217 flags.proxying = (_peer != NULL && !flags.originpeer);
2218
2219 /*
2220 * Is keep-alive okay for all request methods?
2221 */
2222 if (request->flags.mustKeepalive)
2223 flags.keepalive = true;
2224 else if (request->flags.pinned)
2225 flags.keepalive = request->persistent();
2226 else if (!Config.onoff.server_pconns)
2227 flags.keepalive = false;
2228 else if (_peer == NULL)
2229 flags.keepalive = true;
2230 else if (_peer->stats.n_keepalives_sent < 10)
2231 flags.keepalive = true;
2232 else if ((double) _peer->stats.n_keepalives_recv /
2233 (double) _peer->stats.n_keepalives_sent > 0.50)
2234 flags.keepalive = true;
2235
2236 if (_peer) {
2237 /*The old code here was
2238 if (neighborType(_peer, request->url) == PEER_SIBLING && ...
2239 which is equivalent to:
2240 if (neighborType(_peer, URL()) == PEER_SIBLING && ...
2241 or better:
2242 if (((_peer->type == PEER_MULTICAST && p->options.mcast_siblings) ||
2243 _peer->type == PEER_SIBLINGS ) && _peer->options.allow_miss)
2244 flags.only_if_cached = 1;
2245
2246 But I suppose it was a bug
2247 */
2248 if (neighborType(_peer, request->url) == PEER_SIBLING && !_peer->options.allow_miss)
2249 flags.only_if_cached = true;
2250
2251 flags.front_end_https = _peer->front_end_https;
2252 }
2253
2254 mb.init();
2255 request->peer_host=_peer?_peer->host:NULL;
2256 buildRequestPrefix(&mb);
2257
2258 debugs(11, 2, "HTTP Server " << serverConnection);
2259 debugs(11, 2, "HTTP Server REQUEST:\n---------\n" << mb.buf << "\n----------");
2260
2261 Comm::Write(serverConnection, &mb, requestSender);
2262 return true;
2263 }
2264
2265 bool
2266 HttpStateData::getMoreRequestBody(MemBuf &buf)
2267 {
2268 // parent's implementation can handle the no-encoding case
2269 if (!flags.chunked_request)
2270 return Client::getMoreRequestBody(buf);
2271
2272 MemBuf raw;
2273
2274 Must(requestBodySource != NULL);
2275 if (!requestBodySource->getMoreData(raw))
2276 return false; // no request body bytes to chunk yet
2277
2278 // optimization: pre-allocate buffer size that should be enough
2279 const mb_size_t rawDataSize = raw.contentSize();
2280 // we may need to send: hex-chunk-size CRLF raw-data CRLF last-chunk
2281 buf.init(16 + 2 + rawDataSize + 2 + 5, raw.max_capacity);
2282
2283 buf.appendf("%x\r\n", static_cast<unsigned int>(rawDataSize));
2284 buf.append(raw.content(), rawDataSize);
2285 buf.append("\r\n", 2);
2286
2287 Must(rawDataSize > 0); // we did not accidently created last-chunk above
2288
2289 // Do not send last-chunk unless we successfully received everything
2290 if (receivedWholeRequestBody) {
2291 Must(!flags.sentLastChunk);
2292 flags.sentLastChunk = true;
2293 buf.append("0\r\n\r\n", 5);
2294 }
2295
2296 return true;
2297 }
2298
2299 void
2300 httpStart(FwdState *fwd)
2301 {
2302 debugs(11, 3, fwd->request->method << ' ' << fwd->entry->url());
2303 AsyncJob::Start(new HttpStateData(fwd));
2304 }
2305
2306 void
2307 HttpStateData::start()
2308 {
2309 if (!sendRequest()) {
2310 debugs(11, 3, "httpStart: aborted");
2311 mustStop("HttpStateData::start failed");
2312 return;
2313 }
2314
2315 ++ statCounter.server.all.requests;
2316 ++ statCounter.server.http.requests;
2317
2318 /*
2319 * We used to set the read timeout here, but not any more.
2320 * Now its set in httpSendComplete() after the full request,
2321 * including request body, has been written to the server.
2322 */
2323 }
2324
2325 /// if broken posts are enabled for the request, try to fix and return true
2326 bool
2327 HttpStateData::finishingBrokenPost()
2328 {
2329 #if USE_HTTP_VIOLATIONS
2330 if (!Config.accessList.brokenPosts) {
2331 debugs(11, 5, HERE << "No brokenPosts list");
2332 return false;
2333 }
2334
2335 ACLFilledChecklist ch(Config.accessList.brokenPosts, originalRequest(), NULL);
2336 if (ch.fastCheck() != ACCESS_ALLOWED) {
2337 debugs(11, 5, HERE << "didn't match brokenPosts");
2338 return false;
2339 }
2340
2341 if (!Comm::IsConnOpen(serverConnection)) {
2342 debugs(11, 3, HERE << "ignoring broken POST for closed " << serverConnection);
2343 assert(closeHandler != NULL);
2344 return true; // prevent caller from proceeding as if nothing happened
2345 }
2346
2347 debugs(11, 3, "finishingBrokenPost: fixing broken POST");
2348 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
2349 requestSender = JobCallback(11,5,
2350 Dialer, this, HttpStateData::wroteLast);
2351 Comm::Write(serverConnection, "\r\n", 2, requestSender, NULL);
2352 return true;
2353 #else
2354 return false;
2355 #endif /* USE_HTTP_VIOLATIONS */
2356 }
2357
2358 /// if needed, write last-chunk to end the request body and return true
2359 bool
2360 HttpStateData::finishingChunkedRequest()
2361 {
2362 if (flags.sentLastChunk) {
2363 debugs(11, 5, HERE << "already sent last-chunk");
2364 return false;
2365 }
2366
2367 Must(receivedWholeRequestBody); // or we should not be sending last-chunk
2368 flags.sentLastChunk = true;
2369
2370 typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
2371 requestSender = JobCallback(11,5, Dialer, this, HttpStateData::wroteLast);
2372 Comm::Write(serverConnection, "0\r\n\r\n", 5, requestSender, NULL);
2373 return true;
2374 }
2375
2376 void
2377 HttpStateData::doneSendingRequestBody()
2378 {
2379 Client::doneSendingRequestBody();
2380 debugs(11,5, HERE << serverConnection);
2381
2382 // do we need to write something after the last body byte?
2383 if (flags.chunked_request && finishingChunkedRequest())
2384 return;
2385 if (!flags.chunked_request && finishingBrokenPost())
2386 return;
2387
2388 sendComplete();
2389 }
2390
2391 // more origin request body data is available
2392 void
2393 HttpStateData::handleMoreRequestBodyAvailable()
2394 {
2395 if (eof || !Comm::IsConnOpen(serverConnection)) {
2396 // XXX: we should check this condition in other callbacks then!
2397 // TODO: Check whether this can actually happen: We should unsubscribe
2398 // as a body consumer when the above condition(s) are detected.
2399 debugs(11, DBG_IMPORTANT, HERE << "Transaction aborted while reading HTTP body");
2400 return;
2401 }
2402
2403 assert(requestBodySource != NULL);
2404
2405 if (requestBodySource->buf().hasContent()) {
2406 // XXX: why does not this trigger a debug message on every request?
2407
2408 if (flags.headers_parsed && !flags.abuse_detected) {
2409 flags.abuse_detected = true;
2410 debugs(11, DBG_IMPORTANT, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << request->client_addr << "' -> '" << entry->url() << "'" );
2411
2412 if (virginReply()->sline.status() == Http::scInvalidHeader) {
2413 closeServer();
2414 mustStop("HttpStateData::handleMoreRequestBodyAvailable");
2415 return;
2416 }
2417 }
2418 }
2419
2420 HttpStateData::handleMoreRequestBodyAvailable();
2421 }
2422
2423 // premature end of the request body
2424 void
2425 HttpStateData::handleRequestBodyProducerAborted()
2426 {
2427 Client::handleRequestBodyProducerAborted();
2428 if (entry->isEmpty()) {
2429 debugs(11, 3, "request body aborted: " << serverConnection);
2430 // We usually get here when ICAP REQMOD aborts during body processing.
2431 // We might also get here if client-side aborts, but then our response
2432 // should not matter because either client-side will provide its own or
2433 // there will be no response at all (e.g., if the the client has left).
2434 ErrorState *err = new ErrorState(ERR_ICAP_FAILURE, Http::scInternalServerError, fwd->request);
2435 err->detailError(ERR_DETAIL_SRV_REQMOD_REQ_BODY);
2436 fwd->fail(err);
2437 }
2438
2439 abortTransaction("request body producer aborted");
2440 }
2441
2442 // called when we wrote request headers(!) or a part of the body
2443 void
2444 HttpStateData::sentRequestBody(const CommIoCbParams &io)
2445 {
2446 if (io.size > 0)
2447 statCounter.server.http.kbytes_out += io.size;
2448
2449 Client::sentRequestBody(io);
2450 }
2451
2452 void
2453 HttpStateData::abortAll(const char *reason)
2454 {
2455 debugs(11,5, HERE << "aborting transaction for " << reason <<
2456 "; " << serverConnection << ", this " << this);
2457 mustStop(reason);
2458 }
2459