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