]> git.ipfire.org Git - thirdparty/squid.git/blob - src/client_side_request.cc
Detail client closures of CONNECT tunnels during TLS handshake (#691)
[thirdparty/squid.git] / src / client_side_request.cc
1 /*
2 * Copyright (C) 1996-2020 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 85 Client-side Request Routines */
10
11 /*
12 * General logic of request processing:
13 *
14 * We run a series of tests to determine if access will be permitted, and to do
15 * any redirection. Then we call into the result clientStream to retrieve data.
16 * From that point on it's up to reply management.
17 */
18
19 #include "squid.h"
20 #include "acl/FilledChecklist.h"
21 #include "acl/Gadgets.h"
22 #include "anyp/PortCfg.h"
23 #include "base/AsyncJobCalls.h"
24 #include "client_side.h"
25 #include "client_side_reply.h"
26 #include "client_side_request.h"
27 #include "ClientRequestContext.h"
28 #include "clientStream.h"
29 #include "comm/Connection.h"
30 #include "comm/Write.h"
31 #include "error/Detail.h"
32 #include "errorpage.h"
33 #include "fd.h"
34 #include "fde.h"
35 #include "format/Token.h"
36 #include "gopher.h"
37 #include "helper.h"
38 #include "helper/Reply.h"
39 #include "http.h"
40 #include "http/Stream.h"
41 #include "HttpHdrCc.h"
42 #include "HttpReply.h"
43 #include "HttpRequest.h"
44 #include "ip/NfMarkConfig.h"
45 #include "ip/QosConfig.h"
46 #include "ipcache.h"
47 #include "log/access_log.h"
48 #include "MemObject.h"
49 #include "Parsing.h"
50 #include "profiler/Profiler.h"
51 #include "proxyp/Header.h"
52 #include "redirect.h"
53 #include "rfc1738.h"
54 #include "SquidConfig.h"
55 #include "SquidTime.h"
56 #include "Store.h"
57 #include "StrList.h"
58 #include "tools.h"
59 #include "wordlist.h"
60 #if USE_AUTH
61 #include "auth/UserRequest.h"
62 #endif
63 #if USE_ADAPTATION
64 #include "adaptation/AccessCheck.h"
65 #include "adaptation/Answer.h"
66 #include "adaptation/Iterator.h"
67 #include "adaptation/Service.h"
68 #if ICAP_CLIENT
69 #include "adaptation/icap/History.h"
70 #endif
71 #endif
72 #if USE_OPENSSL
73 #include "ssl/ServerBump.h"
74 #include "ssl/support.h"
75 #endif
76
77 #if LINGERING_CLOSE
78 #define comm_close comm_lingering_close
79 #endif
80
81 static const char *const crlf = "\r\n";
82
83 #if FOLLOW_X_FORWARDED_FOR
84 static void clientFollowXForwardedForCheck(Acl::Answer answer, void *data);
85 #endif /* FOLLOW_X_FORWARDED_FOR */
86
87 ErrorState *clientBuildError(err_type, Http::StatusCode, char const *url, const ConnStateData *, HttpRequest *, const AccessLogEntry::Pointer &);
88
89 CBDATA_CLASS_INIT(ClientRequestContext);
90
91 /* Local functions */
92 /* other */
93 static void clientAccessCheckDoneWrapper(Acl::Answer, void *);
94 #if USE_OPENSSL
95 static void sslBumpAccessCheckDoneWrapper(Acl::Answer, void *);
96 #endif
97 static int clientHierarchical(ClientHttpRequest * http);
98 static void clientInterpretRequestHeaders(ClientHttpRequest * http);
99 static HLPCB clientRedirectDoneWrapper;
100 static HLPCB clientStoreIdDoneWrapper;
101 static void checkNoCacheDoneWrapper(Acl::Answer, void *);
102 SQUIDCEXTERN CSR clientGetMoreData;
103 SQUIDCEXTERN CSS clientReplyStatus;
104 SQUIDCEXTERN CSD clientReplyDetach;
105 static void checkFailureRatio(err_type, hier_code);
106
107 ClientRequestContext::~ClientRequestContext()
108 {
109 /*
110 * Release our "lock" on our parent, ClientHttpRequest, if we
111 * still have one
112 */
113
114 if (http)
115 cbdataReferenceDone(http);
116
117 delete error;
118 debugs(85,3, "ClientRequestContext destructed, this=" << this);
119 }
120
121 ClientRequestContext::ClientRequestContext(ClientHttpRequest *anHttp) :
122 http(cbdataReference(anHttp)),
123 acl_checklist(NULL),
124 redirect_state(REDIRECT_NONE),
125 store_id_state(REDIRECT_NONE),
126 host_header_verify_done(false),
127 http_access_done(false),
128 adapted_http_access_done(false),
129 #if USE_ADAPTATION
130 adaptation_acl_check_done(false),
131 #endif
132 redirect_done(false),
133 store_id_done(false),
134 no_cache_done(false),
135 interpreted_req_hdrs(false),
136 toClientMarkingDone(false),
137 #if USE_OPENSSL
138 sslBumpCheckDone(false),
139 #endif
140 error(NULL),
141 readNextRequest(false)
142 {
143 debugs(85, 3, "ClientRequestContext constructed, this=" << this);
144 }
145
146 CBDATA_CLASS_INIT(ClientHttpRequest);
147
148 ClientHttpRequest::ClientHttpRequest(ConnStateData * aConn) :
149 #if USE_ADAPTATION
150 AsyncJob("ClientHttpRequest"),
151 #endif
152 request(NULL),
153 uri(NULL),
154 log_uri(NULL),
155 req_sz(0),
156 calloutContext(NULL),
157 maxReplyBodySize_(0),
158 entry_(NULL),
159 loggingEntry_(NULL),
160 conn_(cbdataReference(aConn))
161 #if USE_OPENSSL
162 , sslBumpNeed_(Ssl::bumpEnd)
163 #endif
164 #if USE_ADAPTATION
165 , request_satisfaction_mode(false)
166 , request_satisfaction_offset(0)
167 #endif
168 {
169 al = new AccessLogEntry;
170 CodeContext::Reset(al);
171 al->cache.start_time = current_time;
172 if (aConn) {
173 al->tcpClient = clientConnection = aConn->clientConnection;
174 al->cache.port = aConn->port;
175 al->cache.caddr = aConn->log_addr;
176 al->proxyProtocolHeader = aConn->proxyProtocolHeader();
177 al->updateError(aConn->bareError);
178
179 #if USE_OPENSSL
180 if (aConn->clientConnection != NULL && aConn->clientConnection->isOpen()) {
181 if (auto ssl = fd_table[aConn->clientConnection->fd].ssl.get())
182 al->cache.sslClientCert.resetWithoutLocking(SSL_get_peer_certificate(ssl));
183 }
184 #endif
185 }
186 dlinkAdd(this, &active, &ClientActiveRequests);
187 }
188
189 /*
190 * returns true if client specified that the object must come from the cache
191 * without contacting origin server
192 */
193 bool
194 ClientHttpRequest::onlyIfCached()const
195 {
196 assert(request);
197 return request->cache_control &&
198 request->cache_control->hasOnlyIfCached();
199 }
200
201 /**
202 * This function is designed to serve a fairly specific purpose.
203 * Occasionally our vBNS-connected caches can talk to each other, but not
204 * the rest of the world. Here we try to detect frequent failures which
205 * make the cache unusable (e.g. DNS lookup and connect() failures). If
206 * the failure:success ratio goes above 1.0 then we go into "hit only"
207 * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
208 * will only fetch HITs from us if they are using the ICP protocol. We
209 * stay in this mode for 5 minutes.
210 *
211 * Duane W., Sept 16, 1996
212 */
213 static void
214 checkFailureRatio(err_type etype, hier_code hcode)
215 {
216 // Can be set at compile time with -D compiler flag
217 #ifndef FAILURE_MODE_TIME
218 #define FAILURE_MODE_TIME 300
219 #endif
220
221 if (hcode == HIER_NONE)
222 return;
223
224 // don't bother when ICP is disabled.
225 if (Config.Port.icp <= 0)
226 return;
227
228 static double magic_factor = 100.0;
229 double n_good;
230 double n_bad;
231
232 n_good = magic_factor / (1.0 + request_failure_ratio);
233
234 n_bad = magic_factor - n_good;
235
236 switch (etype) {
237
238 case ERR_DNS_FAIL:
239
240 case ERR_CONNECT_FAIL:
241 case ERR_SECURE_CONNECT_FAIL:
242
243 case ERR_READ_ERROR:
244 ++n_bad;
245 break;
246
247 default:
248 ++n_good;
249 }
250
251 request_failure_ratio = n_bad / n_good;
252
253 if (hit_only_mode_until > squid_curtime)
254 return;
255
256 if (request_failure_ratio < 1.0)
257 return;
258
259 debugs(33, DBG_CRITICAL, "WARNING: Failure Ratio at "<< std::setw(4)<<
260 std::setprecision(3) << request_failure_ratio);
261
262 debugs(33, DBG_CRITICAL, "WARNING: ICP going into HIT-only mode for " <<
263 FAILURE_MODE_TIME / 60 << " minutes...");
264
265 hit_only_mode_until = squid_curtime + FAILURE_MODE_TIME;
266
267 request_failure_ratio = 0.8; /* reset to something less than 1.0 */
268 }
269
270 ClientHttpRequest::~ClientHttpRequest()
271 {
272 debugs(33, 3, "httpRequestFree: " << uri);
273 PROF_start(httpRequestFree);
274
275 // Even though freeResources() below may destroy the request,
276 // we no longer set request->body_pipe to NULL here
277 // because we did not initiate that pipe (ConnStateData did)
278
279 /* the ICP check here was erroneous
280 * - StoreEntry::releaseRequest was always called if entry was valid
281 */
282
283 logRequest();
284
285 loggingEntry(NULL);
286
287 if (request)
288 checkFailureRatio(request->error.category, al->hier.code);
289
290 freeResources();
291
292 #if USE_ADAPTATION
293 announceInitiatorAbort(virginHeadSource);
294
295 if (adaptedBodySource != NULL)
296 stopConsumingFrom(adaptedBodySource);
297 #endif
298
299 if (calloutContext)
300 delete calloutContext;
301
302 clientConnection = NULL;
303
304 if (conn_)
305 cbdataReferenceDone(conn_);
306
307 /* moving to the next connection is handled by the context free */
308 dlinkDelete(&active, &ClientActiveRequests);
309
310 PROF_stop(httpRequestFree);
311 }
312
313 /**
314 * Create a request and kick it off
315 *
316 * \retval 0 success
317 * \retval -1 failure
318 *
319 * TODO: Pass in the buffers to be used in the initial Read request, as they are
320 * determined by the user
321 */
322 int
323 clientBeginRequest(const HttpRequestMethod& method, char const *url, CSCB * streamcallback,
324 CSD * streamdetach, ClientStreamData streamdata, HttpHeader const *header,
325 char *tailbuf, size_t taillen, const MasterXaction::Pointer &mx)
326 {
327 size_t url_sz;
328 ClientHttpRequest *http = new ClientHttpRequest(NULL);
329 HttpRequest *request;
330 StoreIOBuffer tempBuffer;
331 if (http->al != NULL)
332 http->al->cache.start_time = current_time;
333 /* this is only used to adjust the connection offset in client_side.c */
334 http->req_sz = 0;
335 tempBuffer.length = taillen;
336 tempBuffer.data = tailbuf;
337 /* client stream setup */
338 clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach,
339 clientReplyStatus, new clientReplyContext(http), streamcallback,
340 streamdetach, streamdata, tempBuffer);
341 /* make it visible in the 'current acctive requests list' */
342 /* Set flags */
343 /* internal requests only makes sense in an
344 * accelerator today. TODO: accept flags ? */
345 http->flags.accel = true;
346 /* allow size for url rewriting */
347 url_sz = strlen(url) + Config.appendDomainLen + 5;
348 http->uri = (char *)xcalloc(url_sz, 1);
349 strcpy(http->uri, url); // XXX: polluting http->uri before parser validation
350
351 request = HttpRequest::FromUrlXXX(http->uri, mx, method);
352 if (!request) {
353 debugs(85, 5, "Invalid URL: " << http->uri);
354 return -1;
355 }
356
357 /*
358 * now update the headers in request with our supplied headers.
359 * HttpRequest::FromUrl() should return a blank header set, but
360 * we use Update to be sure of correctness.
361 */
362 if (header)
363 request->header.update(header);
364
365 /* http struct now ready */
366
367 /*
368 * build new header list *? TODO
369 */
370 request->flags.accelerated = http->flags.accel;
371
372 /* this is an internally created
373 * request, not subject to acceleration
374 * target overrides */
375 // TODO: detect and handle internal requests of internal objects?
376
377 /* Internally created requests cannot have bodies today */
378 request->content_length = 0;
379
380 request->client_addr.setNoAddr();
381
382 #if FOLLOW_X_FORWARDED_FOR
383 request->indirect_client_addr.setNoAddr();
384 #endif /* FOLLOW_X_FORWARDED_FOR */
385
386 request->my_addr.setNoAddr(); /* undefined for internal requests */
387
388 request->my_addr.port(0);
389
390 request->http_ver = Http::ProtocolVersion();
391
392 http->initRequest(request);
393
394 /* optional - skip the access check ? */
395 http->calloutContext = new ClientRequestContext(http);
396
397 http->calloutContext->http_access_done = false;
398
399 http->calloutContext->redirect_done = true;
400
401 http->calloutContext->no_cache_done = true;
402
403 http->doCallouts();
404
405 return 0;
406 }
407
408 bool
409 ClientRequestContext::httpStateIsValid()
410 {
411 ClientHttpRequest *http_ = http;
412
413 if (cbdataReferenceValid(http_))
414 return true;
415
416 http = NULL;
417
418 cbdataReferenceDone(http_);
419
420 return false;
421 }
422
423 #if FOLLOW_X_FORWARDED_FOR
424 /**
425 * clientFollowXForwardedForCheck() checks the content of X-Forwarded-For:
426 * against the followXFF ACL, or cleans up and passes control to
427 * clientAccessCheck().
428 *
429 * The trust model here is a little ambiguous. So to clarify the logic:
430 * - we may always use the direct client address as the client IP.
431 * - these trust tests merey tell whether we trust given IP enough to believe the
432 * IP string which it appended to the X-Forwarded-For: header.
433 * - if at any point we don't trust what an IP adds we stop looking.
434 * - at that point the current contents of indirect_client_addr are the value set
435 * by the last previously trusted IP.
436 * ++ indirect_client_addr contains the remote direct client from the trusted peers viewpoint.
437 */
438 static void
439 clientFollowXForwardedForCheck(Acl::Answer answer, void *data)
440 {
441 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
442
443 if (!calloutContext->httpStateIsValid())
444 return;
445
446 ClientHttpRequest *http = calloutContext->http;
447 HttpRequest *request = http->request;
448
449 if (answer.allowed() && request->x_forwarded_for_iterator.size() != 0) {
450
451 /*
452 * Remove the last comma-delimited element from the
453 * x_forwarded_for_iterator and use it to repeat the cycle.
454 */
455 const char *p;
456 const char *asciiaddr;
457 int l;
458 Ip::Address addr;
459 p = request->x_forwarded_for_iterator.termedBuf();
460 l = request->x_forwarded_for_iterator.size();
461
462 /*
463 * XXX x_forwarded_for_iterator should really be a list of
464 * IP addresses, but it's a String instead. We have to
465 * walk backwards through the String, biting off the last
466 * comma-delimited part each time. As long as the data is in
467 * a String, we should probably implement and use a variant of
468 * strListGetItem() that walks backwards instead of forwards
469 * through a comma-separated list. But we don't even do that;
470 * we just do the work in-line here.
471 */
472 /* skip trailing space and commas */
473 while (l > 0 && (p[l-1] == ',' || xisspace(p[l-1])))
474 --l;
475 request->x_forwarded_for_iterator.cut(l);
476 /* look for start of last item in list */
477 while (l > 0 && ! (p[l-1] == ',' || xisspace(p[l-1])))
478 --l;
479 asciiaddr = p+l;
480 if ((addr = asciiaddr)) {
481 request->indirect_client_addr = addr;
482 request->x_forwarded_for_iterator.cut(l);
483 calloutContext->acl_checklist = clientAclChecklistCreate(Config.accessList.followXFF, http);
484 if (!Config.onoff.acl_uses_indirect_client) {
485 /* override the default src_addr tested if we have to go deeper than one level into XFF */
486 Filled(calloutContext->acl_checklist)->src_addr = request->indirect_client_addr;
487 }
488 calloutContext->acl_checklist->nonBlockingCheck(clientFollowXForwardedForCheck, data);
489 return;
490 }
491 }
492
493 /* clean up, and pass control to clientAccessCheck */
494 if (Config.onoff.log_uses_indirect_client) {
495 /*
496 * Ensure that the access log shows the indirect client
497 * instead of the direct client.
498 */
499 http->al->cache.caddr = request->indirect_client_addr;
500 if (ConnStateData *conn = http->getConn())
501 conn->log_addr = request->indirect_client_addr;
502 }
503 request->x_forwarded_for_iterator.clean();
504 request->flags.done_follow_x_forwarded_for = true;
505
506 if (answer.conflicted()) {
507 debugs(28, DBG_CRITICAL, "ERROR: Processing X-Forwarded-For. Stopping at IP address: " << request->indirect_client_addr );
508 }
509
510 /* process actual access ACL as normal. */
511 calloutContext->clientAccessCheck();
512 }
513 #endif /* FOLLOW_X_FORWARDED_FOR */
514
515 static void
516 hostHeaderIpVerifyWrapper(const ipcache_addrs* ia, const Dns::LookupDetails &dns, void *data)
517 {
518 ClientRequestContext *c = static_cast<ClientRequestContext*>(data);
519 c->hostHeaderIpVerify(ia, dns);
520 }
521
522 void
523 ClientRequestContext::hostHeaderIpVerify(const ipcache_addrs* ia, const Dns::LookupDetails &dns)
524 {
525 Comm::ConnectionPointer clientConn = http->getConn()->clientConnection;
526
527 // note the DNS details for the transaction stats.
528 http->request->recordLookup(dns);
529
530 // Is the NAT destination IP in DNS?
531 if (ia && ia->have(clientConn->local)) {
532 debugs(85, 3, "validate IP " << clientConn->local << " possible from Host:");
533 http->request->flags.hostVerified = true;
534 http->doCallouts();
535 return;
536 }
537 debugs(85, 3, HERE << "FAIL: validate IP " << clientConn->local << " possible from Host:");
538 hostHeaderVerifyFailed("local IP", "any domain IP");
539 }
540
541 void
542 ClientRequestContext::hostHeaderVerifyFailed(const char *A, const char *B)
543 {
544 // IP address validation for Host: failed. Admin wants to ignore them.
545 // NP: we do not yet handle CONNECT tunnels well, so ignore for them
546 if (!Config.onoff.hostStrictVerify && http->request->method != Http::METHOD_CONNECT) {
547 debugs(85, 3, "SECURITY ALERT: Host header forgery detected on " << http->getConn()->clientConnection <<
548 " (" << A << " does not match " << B << ") on URL: " << http->request->effectiveRequestUri());
549
550 // NP: it is tempting to use 'flags.noCache' but that is all about READing cache data.
551 // The problems here are about WRITE for new cache content, which means flags.cachable
552 http->request->flags.cachable = false; // MUST NOT cache (for now)
553 // XXX: when we have updated the cache key to base on raw-IP + URI this cacheable limit can go.
554 http->request->flags.hierarchical = false; // MUST NOT pass to peers (for now)
555 // XXX: when we have sorted out the best way to relay requests properly to peers this hierarchical limit can go.
556 http->doCallouts();
557 return;
558 }
559
560 debugs(85, DBG_IMPORTANT, "SECURITY ALERT: Host header forgery detected on " <<
561 http->getConn()->clientConnection << " (" << A << " does not match " << B << ")");
562 if (const char *ua = http->request->header.getStr(Http::HdrType::USER_AGENT))
563 debugs(85, DBG_IMPORTANT, "SECURITY ALERT: By user agent: " << ua);
564 debugs(85, DBG_IMPORTANT, "SECURITY ALERT: on URL: " << http->request->effectiveRequestUri());
565
566 // IP address validation for Host: failed. reject the connection.
567 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->prev->data;
568 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
569 assert (repContext);
570 repContext->setReplyToError(ERR_CONFLICT_HOST, Http::scConflict,
571 http->request->method, NULL,
572 http->getConn(),
573 http->request,
574 NULL,
575 #if USE_AUTH
576 http->getConn() != NULL && http->getConn()->getAuth() != NULL ?
577 http->getConn()->getAuth() : http->request->auth_user_request);
578 #else
579 NULL);
580 #endif
581 node = (clientStreamNode *)http->client_stream.tail->data;
582 clientStreamRead(node, http, node->readBuffer);
583 }
584
585 void
586 ClientRequestContext::hostHeaderVerify()
587 {
588 // Require a Host: header.
589 const char *host = http->request->header.getStr(Http::HdrType::HOST);
590
591 if (!host) {
592 // TODO: dump out the HTTP/1.1 error about missing host header.
593 // otherwise this is fine, can't forge a header value when its not even set.
594 debugs(85, 3, HERE << "validate skipped with no Host: header present.");
595 http->doCallouts();
596 return;
597 }
598
599 if (http->request->flags.internal) {
600 // TODO: kill this when URL handling allows partial URLs out of accel mode
601 // and we no longer screw with the URL just to add our internal host there
602 debugs(85, 6, HERE << "validate skipped due to internal composite URL.");
603 http->doCallouts();
604 return;
605 }
606
607 // Locate if there is a port attached, strip ready for IP lookup
608 char *portStr = NULL;
609 char *hostB = xstrdup(host);
610 host = hostB;
611 if (host[0] == '[') {
612 // IPv6 literal.
613 portStr = strchr(hostB, ']');
614 if (portStr && *(++portStr) != ':') {
615 portStr = NULL;
616 }
617 } else {
618 // Domain or IPv4 literal with port
619 portStr = strrchr(hostB, ':');
620 }
621
622 uint16_t port = 0;
623 if (portStr) {
624 *portStr = '\0'; // strip the ':'
625 if (*(++portStr) != '\0') {
626 char *end = NULL;
627 int64_t ret = strtoll(portStr, &end, 10);
628 if (end == portStr || *end != '\0' || ret < 1 || ret > 0xFFFF) {
629 // invalid port details. Replace the ':'
630 *(--portStr) = ':';
631 portStr = NULL;
632 } else
633 port = (ret & 0xFFFF);
634 }
635 }
636
637 debugs(85, 3, "validate host=" << host << ", port=" << port << ", portStr=" << (portStr?portStr:"NULL"));
638 if (http->request->flags.intercepted || http->request->flags.interceptTproxy) {
639 // verify the Host: port (if any) matches the apparent destination
640 if (portStr && port != http->getConn()->clientConnection->local.port()) {
641 debugs(85, 3, "FAIL on validate port " << http->getConn()->clientConnection->local.port() <<
642 " matches Host: port " << port << " (" << portStr << ")");
643 hostHeaderVerifyFailed("intercepted port", portStr);
644 } else {
645 // XXX: match the scheme default port against the apparent destination
646
647 // verify the destination DNS is one of the Host: headers IPs
648 ipcache_nbgethostbyname(host, hostHeaderIpVerifyWrapper, this);
649 }
650 } else if (!Config.onoff.hostStrictVerify) {
651 debugs(85, 3, "validate skipped.");
652 http->doCallouts();
653 } else if (strlen(host) != strlen(http->request->url.host())) {
654 // Verify forward-proxy requested URL domain matches the Host: header
655 debugs(85, 3, "FAIL on validate URL domain length " << http->request->url.host() << " matches Host: " << host);
656 hostHeaderVerifyFailed(host, http->request->url.host());
657 } else if (matchDomainName(host, http->request->url.host()) != 0) {
658 // Verify forward-proxy requested URL domain matches the Host: header
659 debugs(85, 3, "FAIL on validate URL domain " << http->request->url.host() << " matches Host: " << host);
660 hostHeaderVerifyFailed(host, http->request->url.host());
661 } else if (portStr && port != http->request->url.port()) {
662 // Verify forward-proxy requested URL domain matches the Host: header
663 debugs(85, 3, "FAIL on validate URL port " << http->request->url.port() << " matches Host: port " << portStr);
664 hostHeaderVerifyFailed("URL port", portStr);
665 } else if (!portStr && http->request->method != Http::METHOD_CONNECT && http->request->url.port() != http->request->url.getScheme().defaultPort()) {
666 // Verify forward-proxy requested URL domain matches the Host: header
667 // Special case: we don't have a default-port to check for CONNECT. Assume URL is correct.
668 debugs(85, 3, "FAIL on validate URL port " << http->request->url.port() << " matches Host: default port " << http->request->url.getScheme().defaultPort());
669 hostHeaderVerifyFailed("URL port", "default port");
670 } else {
671 // Okay no problem.
672 debugs(85, 3, "validate passed.");
673 http->request->flags.hostVerified = true;
674 http->doCallouts();
675 }
676 safe_free(hostB);
677 }
678
679 /* This is the entry point for external users of the client_side routines */
680 void
681 ClientRequestContext::clientAccessCheck()
682 {
683 #if FOLLOW_X_FORWARDED_FOR
684 if (!http->request->flags.doneFollowXff() &&
685 Config.accessList.followXFF &&
686 http->request->header.has(Http::HdrType::X_FORWARDED_FOR)) {
687
688 /* we always trust the direct client address for actual use */
689 http->request->indirect_client_addr = http->request->client_addr;
690 http->request->indirect_client_addr.port(0);
691
692 /* setup the XFF iterator for processing */
693 http->request->x_forwarded_for_iterator = http->request->header.getList(Http::HdrType::X_FORWARDED_FOR);
694
695 /* begin by checking to see if we trust direct client enough to walk XFF */
696 acl_checklist = clientAclChecklistCreate(Config.accessList.followXFF, http);
697 acl_checklist->nonBlockingCheck(clientFollowXForwardedForCheck, this);
698 return;
699 }
700 #endif
701
702 if (Config.accessList.http) {
703 acl_checklist = clientAclChecklistCreate(Config.accessList.http, http);
704 acl_checklist->nonBlockingCheck(clientAccessCheckDoneWrapper, this);
705 } else {
706 debugs(0, DBG_CRITICAL, "No http_access configuration found. This will block ALL traffic");
707 clientAccessCheckDone(ACCESS_DENIED);
708 }
709 }
710
711 /**
712 * Identical in operation to clientAccessCheck() but performed later using different configured ACL list.
713 * The default here is to allow all. Since the earlier http_access should do a default deny all.
714 * This check is just for a last-minute denial based on adapted request headers.
715 */
716 void
717 ClientRequestContext::clientAccessCheck2()
718 {
719 if (Config.accessList.adapted_http) {
720 acl_checklist = clientAclChecklistCreate(Config.accessList.adapted_http, http);
721 acl_checklist->nonBlockingCheck(clientAccessCheckDoneWrapper, this);
722 } else {
723 debugs(85, 2, HERE << "No adapted_http_access configuration. default: ALLOW");
724 clientAccessCheckDone(ACCESS_ALLOWED);
725 }
726 }
727
728 void
729 clientAccessCheckDoneWrapper(Acl::Answer answer, void *data)
730 {
731 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
732
733 if (!calloutContext->httpStateIsValid())
734 return;
735
736 calloutContext->clientAccessCheckDone(answer);
737 }
738
739 void
740 ClientRequestContext::clientAccessCheckDone(const Acl::Answer &answer)
741 {
742 acl_checklist = NULL;
743 err_type page_id;
744 Http::StatusCode status;
745 debugs(85, 2, "The request " << http->request->method << ' ' <<
746 http->uri << " is " << answer <<
747 "; last ACL checked: " << (AclMatchedName ? AclMatchedName : "[none]"));
748
749 #if USE_AUTH
750 char const *proxy_auth_msg = "<null>";
751 if (http->getConn() != NULL && http->getConn()->getAuth() != NULL)
752 proxy_auth_msg = http->getConn()->getAuth()->denyMessage("<null>");
753 else if (http->request->auth_user_request != NULL)
754 proxy_auth_msg = http->request->auth_user_request->denyMessage("<null>");
755 #endif
756
757 if (!answer.allowed()) {
758 // auth has a grace period where credentials can be expired but okay not to challenge.
759
760 /* Send an auth challenge or error */
761 // XXX: do we still need aclIsProxyAuth() ?
762 bool auth_challenge = (answer == ACCESS_AUTH_REQUIRED || aclIsProxyAuth(AclMatchedName));
763 debugs(85, 5, "Access Denied: " << http->uri);
764 debugs(85, 5, "AclMatchedName = " << (AclMatchedName ? AclMatchedName : "<null>"));
765 #if USE_AUTH
766 if (auth_challenge)
767 debugs(33, 5, "Proxy Auth Message = " << (proxy_auth_msg ? proxy_auth_msg : "<null>"));
768 #endif
769
770 /*
771 * NOTE: get page_id here, based on AclMatchedName because if
772 * USE_DELAY_POOLS is enabled, then AclMatchedName gets clobbered in
773 * the clientCreateStoreEntry() call just below. Pedro Ribeiro
774 * <pribeiro@isel.pt>
775 */
776 page_id = aclGetDenyInfoPage(&Config.denyInfoList, AclMatchedName, answer != ACCESS_AUTH_REQUIRED);
777
778 http->logType.update(LOG_TCP_DENIED);
779
780 if (auth_challenge) {
781 #if USE_AUTH
782 if (http->request->flags.sslBumped) {
783 /*SSL Bumped request, authentication is not possible*/
784 status = Http::scForbidden;
785 } else if (!http->flags.accel) {
786 /* Proxy authorisation needed */
787 status = Http::scProxyAuthenticationRequired;
788 } else {
789 /* WWW authorisation needed */
790 status = Http::scUnauthorized;
791 }
792 #else
793 // need auth, but not possible to do.
794 status = Http::scForbidden;
795 #endif
796 if (page_id == ERR_NONE)
797 page_id = ERR_CACHE_ACCESS_DENIED;
798 } else {
799 status = Http::scForbidden;
800
801 if (page_id == ERR_NONE)
802 page_id = ERR_ACCESS_DENIED;
803 }
804
805 error = clientBuildError(page_id, status, nullptr, http->getConn(), http->request, http->al);
806
807 #if USE_AUTH
808 error->auth_user_request =
809 http->getConn() != NULL && http->getConn()->getAuth() != NULL ?
810 http->getConn()->getAuth() : http->request->auth_user_request;
811 #endif
812
813 readNextRequest = true;
814 }
815
816 /* ACCESS_ALLOWED continues here ... */
817 xfree(http->uri);
818 http->uri = SBufToCstring(http->request->effectiveRequestUri());
819 http->doCallouts();
820 }
821
822 #if USE_ADAPTATION
823 void
824 ClientHttpRequest::noteAdaptationAclCheckDone(Adaptation::ServiceGroupPointer g)
825 {
826 debugs(93,3,HERE << this << " adaptationAclCheckDone called");
827
828 #if ICAP_CLIENT
829 Adaptation::Icap::History::Pointer ih = request->icapHistory();
830 if (ih != NULL) {
831 if (getConn() != NULL && getConn()->clientConnection != NULL) {
832 ih->rfc931 = getConn()->clientConnection->rfc931;
833 #if USE_OPENSSL
834 if (getConn()->clientConnection->isOpen()) {
835 ih->ssluser = sslGetUserEmail(fd_table[getConn()->clientConnection->fd].ssl.get());
836 }
837 #endif
838 }
839 ih->log_uri = log_uri;
840 ih->req_sz = req_sz;
841 }
842 #endif
843
844 if (!g) {
845 debugs(85,3, HERE << "no adaptation needed");
846 doCallouts();
847 return;
848 }
849
850 startAdaptation(g);
851 }
852
853 #endif
854
855 static void
856 clientRedirectAccessCheckDone(Acl::Answer answer, void *data)
857 {
858 ClientRequestContext *context = (ClientRequestContext *)data;
859 ClientHttpRequest *http = context->http;
860 context->acl_checklist = NULL;
861
862 if (answer.allowed())
863 redirectStart(http, clientRedirectDoneWrapper, context);
864 else {
865 Helper::Reply const nilReply(Helper::Error);
866 context->clientRedirectDone(nilReply);
867 }
868 }
869
870 void
871 ClientRequestContext::clientRedirectStart()
872 {
873 debugs(33, 5, HERE << "'" << http->uri << "'");
874 http->al->syncNotes(http->request);
875 if (Config.accessList.redirector) {
876 acl_checklist = clientAclChecklistCreate(Config.accessList.redirector, http);
877 acl_checklist->nonBlockingCheck(clientRedirectAccessCheckDone, this);
878 } else
879 redirectStart(http, clientRedirectDoneWrapper, this);
880 }
881
882 /**
883 * This methods handles Access checks result of StoreId access list.
884 * Will handle as "ERR" (no change) in a case Access is not allowed.
885 */
886 static void
887 clientStoreIdAccessCheckDone(Acl::Answer answer, void *data)
888 {
889 ClientRequestContext *context = static_cast<ClientRequestContext *>(data);
890 ClientHttpRequest *http = context->http;
891 context->acl_checklist = NULL;
892
893 if (answer.allowed())
894 storeIdStart(http, clientStoreIdDoneWrapper, context);
895 else {
896 debugs(85, 3, "access denied expected ERR reply handling: " << answer);
897 Helper::Reply const nilReply(Helper::Error);
898 context->clientStoreIdDone(nilReply);
899 }
900 }
901
902 /**
903 * Start locating an alternative storage ID string (if any) from admin
904 * configured helper program. This is an asynchronous operation terminating in
905 * ClientRequestContext::clientStoreIdDone() when completed.
906 */
907 void
908 ClientRequestContext::clientStoreIdStart()
909 {
910 debugs(33, 5,"'" << http->uri << "'");
911
912 if (Config.accessList.store_id) {
913 acl_checklist = clientAclChecklistCreate(Config.accessList.store_id, http);
914 acl_checklist->nonBlockingCheck(clientStoreIdAccessCheckDone, this);
915 } else
916 storeIdStart(http, clientStoreIdDoneWrapper, this);
917 }
918
919 static int
920 clientHierarchical(ClientHttpRequest * http)
921 {
922 HttpRequest *request = http->request;
923 HttpRequestMethod method = request->method;
924
925 // intercepted requests MUST NOT (yet) be sent to peers unless verified
926 if (!request->flags.hostVerified && (request->flags.intercepted || request->flags.interceptTproxy))
927 return 0;
928
929 /*
930 * IMS needs a private key, so we can use the hierarchy for IMS only if our
931 * neighbors support private keys
932 */
933
934 if (request->flags.ims && !neighbors_do_private_keys)
935 return 0;
936
937 /*
938 * This is incorrect: authenticating requests can be sent via a hierarchy
939 * (they can even be cached if the correct headers are set on the reply)
940 */
941 if (request->flags.auth)
942 return 0;
943
944 if (method == Http::METHOD_TRACE)
945 return 1;
946
947 if (method != Http::METHOD_GET)
948 return 0;
949
950 if (request->flags.loopDetected)
951 return 0;
952
953 if (request->url.getScheme() == AnyP::PROTO_HTTP)
954 return method.respMaybeCacheable();
955
956 if (request->url.getScheme() == AnyP::PROTO_GOPHER)
957 return gopherCachable(request);
958
959 if (request->url.getScheme() == AnyP::PROTO_CACHE_OBJECT)
960 return 0;
961
962 return 1;
963 }
964
965 static void
966 clientCheckPinning(ClientHttpRequest * http)
967 {
968 HttpRequest *request = http->request;
969 HttpHeader *req_hdr = &request->header;
970 ConnStateData *http_conn = http->getConn();
971
972 /* Internal requests such as those from ESI includes may be without
973 * a client connection
974 */
975 if (!http_conn)
976 return;
977
978 request->flags.connectionAuthDisabled = http_conn->port->connection_auth_disabled;
979 if (!request->flags.connectionAuthDisabled) {
980 if (Comm::IsConnOpen(http_conn->pinning.serverConnection)) {
981 if (http_conn->pinning.auth) {
982 request->flags.connectionAuth = true;
983 request->flags.auth = true;
984 } else {
985 request->flags.connectionProxyAuth = true;
986 }
987 // These should already be linked correctly.
988 assert(request->clientConnectionManager == http_conn);
989 }
990 }
991
992 /* check if connection auth is used, and flag as candidate for pinning
993 * in such case.
994 * Note: we may need to set flags.connectionAuth even if the connection
995 * is already pinned if it was pinned earlier due to proxy auth
996 */
997 if (!request->flags.connectionAuth) {
998 if (req_hdr->has(Http::HdrType::AUTHORIZATION) || req_hdr->has(Http::HdrType::PROXY_AUTHORIZATION)) {
999 HttpHeaderPos pos = HttpHeaderInitPos;
1000 HttpHeaderEntry *e;
1001 int may_pin = 0;
1002 while ((e = req_hdr->getEntry(&pos))) {
1003 if (e->id == Http::HdrType::AUTHORIZATION || e->id == Http::HdrType::PROXY_AUTHORIZATION) {
1004 const char *value = e->value.rawBuf();
1005 if (strncasecmp(value, "NTLM ", 5) == 0
1006 ||
1007 strncasecmp(value, "Negotiate ", 10) == 0
1008 ||
1009 strncasecmp(value, "Kerberos ", 9) == 0) {
1010 if (e->id == Http::HdrType::AUTHORIZATION) {
1011 request->flags.connectionAuth = true;
1012 may_pin = 1;
1013 } else {
1014 request->flags.connectionProxyAuth = true;
1015 may_pin = 1;
1016 }
1017 }
1018 }
1019 }
1020 if (may_pin && !request->pinnedConnection()) {
1021 // These should already be linked correctly. Just need the ServerConnection to pinn.
1022 assert(request->clientConnectionManager == http_conn);
1023 }
1024 }
1025 }
1026 }
1027
1028 static void
1029 clientInterpretRequestHeaders(ClientHttpRequest * http)
1030 {
1031 HttpRequest *request = http->request;
1032 HttpHeader *req_hdr = &request->header;
1033 bool no_cache = false;
1034
1035 request->imslen = -1;
1036 request->ims = req_hdr->getTime(Http::HdrType::IF_MODIFIED_SINCE);
1037
1038 if (request->ims > 0)
1039 request->flags.ims = true;
1040
1041 if (!request->flags.ignoreCc) {
1042 if (request->cache_control) {
1043 if (request->cache_control->hasNoCache())
1044 no_cache=true;
1045
1046 // RFC 2616: treat Pragma:no-cache as if it was Cache-Control:no-cache when Cache-Control is missing
1047 } else if (req_hdr->has(Http::HdrType::PRAGMA))
1048 no_cache = req_hdr->hasListMember(Http::HdrType::PRAGMA,"no-cache",',');
1049 }
1050
1051 if (request->method == Http::METHOD_OTHER) {
1052 no_cache=true;
1053 }
1054
1055 if (no_cache) {
1056 #if USE_HTTP_VIOLATIONS
1057
1058 if (Config.onoff.reload_into_ims)
1059 request->flags.nocacheHack = true;
1060 else if (refresh_nocache_hack)
1061 request->flags.nocacheHack = true;
1062 else
1063 #endif
1064
1065 request->flags.noCache = true;
1066 }
1067
1068 /* ignore range header in non-GETs or non-HEADs */
1069 if (request->method == Http::METHOD_GET || request->method == Http::METHOD_HEAD) {
1070 // XXX: initialize if we got here without HttpRequest::parseHeader()
1071 if (!request->range)
1072 request->range = req_hdr->getRange();
1073
1074 if (request->range) {
1075 request->flags.isRanged = true;
1076 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->data;
1077 /* XXX: This is suboptimal. We should give the stream the range set,
1078 * and thereby let the top of the stream set the offset when the
1079 * size becomes known. As it is, we will end up requesting from 0
1080 * for evey -X range specification.
1081 * RBC - this may be somewhat wrong. We should probably set the range
1082 * iter up at this point.
1083 */
1084 node->readBuffer.offset = request->range->lowestOffset(0);
1085 http->range_iter.pos = request->range->begin();
1086 http->range_iter.end = request->range->end();
1087 http->range_iter.valid = true;
1088 }
1089 }
1090
1091 /* Only HEAD and GET requests permit a Range or Request-Range header.
1092 * If these headers appear on any other type of request, delete them now.
1093 */
1094 else {
1095 req_hdr->delById(Http::HdrType::RANGE);
1096 req_hdr->delById(Http::HdrType::REQUEST_RANGE);
1097 request->ignoreRange("neither HEAD nor GET");
1098 }
1099
1100 if (req_hdr->has(Http::HdrType::AUTHORIZATION))
1101 request->flags.auth = true;
1102
1103 clientCheckPinning(http);
1104
1105 if (!request->url.userInfo().isEmpty())
1106 request->flags.auth = true;
1107
1108 if (req_hdr->has(Http::HdrType::VIA)) {
1109 String s = req_hdr->getList(Http::HdrType::VIA);
1110 /*
1111 * ThisCache cannot be a member of Via header, "1.1 ThisCache" can.
1112 * Note ThisCache2 has a space prepended to the hostname so we don't
1113 * accidentally match super-domains.
1114 */
1115
1116 if (strListIsSubstr(&s, ThisCache2, ',')) {
1117 request->flags.loopDetected = true;
1118 }
1119
1120 #if USE_FORW_VIA_DB
1121 fvdbCountVia(s.termedBuf());
1122
1123 #endif
1124
1125 s.clean();
1126 }
1127
1128 // headers only relevant to reverse-proxy
1129 if (request->flags.accelerated) {
1130 // check for a cdn-info member with a cdn-id matching surrogate_id
1131 // XXX: HttpHeader::hasListMember() does not handle OWS around ";" yet
1132 if (req_hdr->hasListMember(Http::HdrType::CDN_LOOP, Config.Accel.surrogate_id, ','))
1133 request->flags.loopDetected = true;
1134 }
1135
1136 if (request->flags.loopDetected) {
1137 debugObj(33, DBG_IMPORTANT, "WARNING: Forwarding loop detected for:\n",
1138 request, (ObjPackMethod) & httpRequestPack);
1139 }
1140
1141 #if USE_FORW_VIA_DB
1142
1143 if (req_hdr->has(Http::HdrType::X_FORWARDED_FOR)) {
1144 String s = req_hdr->getList(Http::HdrType::X_FORWARDED_FOR);
1145 fvdbCountForw(s.termedBuf());
1146 s.clean();
1147 }
1148
1149 #endif
1150
1151 request->flags.cachable = http->request->maybeCacheable();
1152
1153 if (clientHierarchical(http))
1154 request->flags.hierarchical = true;
1155
1156 debugs(85, 5, "clientInterpretRequestHeaders: REQ_NOCACHE = " <<
1157 (request->flags.noCache ? "SET" : "NOT SET"));
1158 debugs(85, 5, "clientInterpretRequestHeaders: REQ_CACHABLE = " <<
1159 (request->flags.cachable ? "SET" : "NOT SET"));
1160 debugs(85, 5, "clientInterpretRequestHeaders: REQ_HIERARCHICAL = " <<
1161 (request->flags.hierarchical ? "SET" : "NOT SET"));
1162
1163 }
1164
1165 void
1166 clientRedirectDoneWrapper(void *data, const Helper::Reply &result)
1167 {
1168 ClientRequestContext *calloutContext = (ClientRequestContext *)data;
1169
1170 if (!calloutContext->httpStateIsValid())
1171 return;
1172
1173 calloutContext->clientRedirectDone(result);
1174 }
1175
1176 void
1177 clientStoreIdDoneWrapper(void *data, const Helper::Reply &result)
1178 {
1179 ClientRequestContext *calloutContext = (ClientRequestContext *)data;
1180
1181 if (!calloutContext->httpStateIsValid())
1182 return;
1183
1184 calloutContext->clientStoreIdDone(result);
1185 }
1186
1187 void
1188 ClientRequestContext::clientRedirectDone(const Helper::Reply &reply)
1189 {
1190 HttpRequest *old_request = http->request;
1191 debugs(85, 5, HERE << "'" << http->uri << "' result=" << reply);
1192 assert(redirect_state == REDIRECT_PENDING);
1193 redirect_state = REDIRECT_DONE;
1194
1195 // Put helper response Notes into the transaction state record (ALE) eventually
1196 // do it early to ensure that no matter what the outcome the notes are present.
1197 if (http->al)
1198 http->al->syncNotes(old_request);
1199
1200 UpdateRequestNotes(http->getConn(), *old_request, reply.notes);
1201
1202 switch (reply.result) {
1203 case Helper::TimedOut:
1204 if (Config.onUrlRewriteTimeout.action != toutActBypass) {
1205 static const auto d = MakeNamedErrorDetail("REDIRECTOR_TIMEDOUT");
1206 http->calloutsError(ERR_GATEWAY_FAILURE, d);
1207 debugs(85, DBG_IMPORTANT, "ERROR: URL rewrite helper: Timedout");
1208 }
1209 break;
1210
1211 case Helper::Unknown:
1212 case Helper::TT:
1213 // Handler in redirect.cc should have already mapped Unknown
1214 // IF it contained valid entry for the old URL-rewrite helper protocol
1215 debugs(85, DBG_IMPORTANT, "ERROR: URL rewrite helper returned invalid result code. Wrong helper? " << reply);
1216 break;
1217
1218 case Helper::BrokenHelper:
1219 debugs(85, DBG_IMPORTANT, "ERROR: URL rewrite helper: " << reply);
1220 break;
1221
1222 case Helper::Error:
1223 // no change to be done.
1224 break;
1225
1226 case Helper::Okay: {
1227 // #1: redirect with a specific status code OK status=NNN url="..."
1228 // #2: redirect with a default status code OK url="..."
1229 // #3: re-write the URL OK rewrite-url="..."
1230
1231 const char *statusNote = reply.notes.findFirst("status");
1232 const char *urlNote = reply.notes.findFirst("url");
1233
1234 if (urlNote != NULL) {
1235 // HTTP protocol redirect to be done.
1236
1237 // TODO: change default redirect status for appropriate requests
1238 // Squid defaults to 302 status for now for better compatibility with old clients.
1239 // HTTP/1.0 client should get 302 (Http::scFound)
1240 // HTTP/1.1 client contacting reverse-proxy should get 307 (Http::scTemporaryRedirect)
1241 // HTTP/1.1 client being diverted by forward-proxy should get 303 (Http::scSeeOther)
1242 Http::StatusCode status = Http::scFound;
1243 if (statusNote != NULL) {
1244 const char * result = statusNote;
1245 status = static_cast<Http::StatusCode>(atoi(result));
1246 }
1247
1248 if (status == Http::scMovedPermanently
1249 || status == Http::scFound
1250 || status == Http::scSeeOther
1251 || status == Http::scPermanentRedirect
1252 || status == Http::scTemporaryRedirect) {
1253 http->redirect.status = status;
1254 http->redirect.location = xstrdup(urlNote);
1255 // TODO: validate the URL produced here is RFC 2616 compliant absolute URI
1256 } else {
1257 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid " << status << " redirect Location: " << urlNote);
1258 }
1259 } else {
1260 // URL-rewrite wanted. Ew.
1261 urlNote = reply.notes.findFirst("rewrite-url");
1262
1263 // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
1264 if (urlNote != NULL && strcmp(urlNote, http->uri)) {
1265 AnyP::Uri tmpUrl;
1266 if (tmpUrl.parse(old_request->method, SBuf(urlNote))) {
1267 HttpRequest *new_request = old_request->clone();
1268 new_request->url = tmpUrl;
1269 debugs(61, 2, "URL-rewriter diverts URL from " << old_request->effectiveRequestUri() << " to " << new_request->effectiveRequestUri());
1270
1271 // update the new request to flag the re-writing was done on it
1272 new_request->flags.redirected = true;
1273
1274 // unlink bodypipe from the old request. Not needed there any longer.
1275 if (old_request->body_pipe != NULL) {
1276 old_request->body_pipe = NULL;
1277 debugs(61,2, HERE << "URL-rewriter diverts body_pipe " << new_request->body_pipe <<
1278 " from request " << old_request << " to " << new_request);
1279 }
1280
1281 http->resetRequest(new_request);
1282 old_request = nullptr;
1283 } else {
1284 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid request: " <<
1285 old_request->method << " " << urlNote << " " << old_request->http_ver);
1286 }
1287 }
1288 }
1289 }
1290 break;
1291 }
1292
1293 /* XXX PIPELINE: This is inaccurate during pipelining */
1294
1295 if (http->getConn() != NULL && Comm::IsConnOpen(http->getConn()->clientConnection))
1296 fd_note(http->getConn()->clientConnection->fd, http->uri);
1297
1298 assert(http->uri);
1299
1300 http->doCallouts();
1301 }
1302
1303 /**
1304 * This method handles the different replies from StoreID helper.
1305 */
1306 void
1307 ClientRequestContext::clientStoreIdDone(const Helper::Reply &reply)
1308 {
1309 HttpRequest *old_request = http->request;
1310 debugs(85, 5, "'" << http->uri << "' result=" << reply);
1311 assert(store_id_state == REDIRECT_PENDING);
1312 store_id_state = REDIRECT_DONE;
1313
1314 // Put helper response Notes into the transaction state record (ALE) eventually
1315 // do it early to ensure that no matter what the outcome the notes are present.
1316 if (http->al)
1317 http->al->syncNotes(old_request);
1318
1319 UpdateRequestNotes(http->getConn(), *old_request, reply.notes);
1320
1321 switch (reply.result) {
1322 case Helper::Unknown:
1323 case Helper::TT:
1324 // Handler in redirect.cc should have already mapped Unknown
1325 // IF it contained valid entry for the old helper protocol
1326 debugs(85, DBG_IMPORTANT, "ERROR: storeID helper returned invalid result code. Wrong helper? " << reply);
1327 break;
1328
1329 case Helper::TimedOut:
1330 // Timeouts for storeID are not implemented
1331 case Helper::BrokenHelper:
1332 debugs(85, DBG_IMPORTANT, "ERROR: storeID helper: " << reply);
1333 break;
1334
1335 case Helper::Error:
1336 // no change to be done.
1337 break;
1338
1339 case Helper::Okay: {
1340 const char *urlNote = reply.notes.findFirst("store-id");
1341
1342 // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
1343 if (urlNote != NULL && strcmp(urlNote, http->uri) ) {
1344 // Debug section required for some very specific cases.
1345 debugs(85, 9, "Setting storeID with: " << urlNote );
1346 http->request->store_id = urlNote;
1347 http->store_id = urlNote;
1348 }
1349 }
1350 break;
1351 }
1352
1353 http->doCallouts();
1354 }
1355
1356 /** Test cache allow/deny configuration
1357 * Sets flags.cachable=1 if caching is not denied.
1358 */
1359 void
1360 ClientRequestContext::checkNoCache()
1361 {
1362 if (Config.accessList.noCache) {
1363 acl_checklist = clientAclChecklistCreate(Config.accessList.noCache, http);
1364 acl_checklist->nonBlockingCheck(checkNoCacheDoneWrapper, this);
1365 } else {
1366 /* unless otherwise specified, we try to cache. */
1367 checkNoCacheDone(ACCESS_ALLOWED);
1368 }
1369 }
1370
1371 static void
1372 checkNoCacheDoneWrapper(Acl::Answer answer, void *data)
1373 {
1374 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
1375
1376 if (!calloutContext->httpStateIsValid())
1377 return;
1378
1379 calloutContext->checkNoCacheDone(answer);
1380 }
1381
1382 void
1383 ClientRequestContext::checkNoCacheDone(const Acl::Answer &answer)
1384 {
1385 acl_checklist = NULL;
1386 if (answer.denied()) {
1387 http->request->flags.noCache = true; // do not read reply from cache
1388 http->request->flags.cachable = false; // do not store reply into cache
1389 }
1390 http->doCallouts();
1391 }
1392
1393 #if USE_OPENSSL
1394 bool
1395 ClientRequestContext::sslBumpAccessCheck()
1396 {
1397 if (!http->getConn()) {
1398 http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
1399 return false;
1400 }
1401
1402 const Ssl::BumpMode bumpMode = http->getConn()->sslBumpMode;
1403 if (http->request->flags.forceTunnel) {
1404 debugs(85, 5, "not needed; already decided to tunnel " << http->getConn());
1405 if (bumpMode != Ssl::bumpEnd)
1406 http->al->ssl.bumpMode = bumpMode; // inherited from bumped connection
1407 return false;
1408 }
1409
1410 // If SSL connection tunneling or bumping decision has been made, obey it.
1411 if (bumpMode != Ssl::bumpEnd) {
1412 debugs(85, 5, HERE << "SslBump already decided (" << bumpMode <<
1413 "), " << "ignoring ssl_bump for " << http->getConn());
1414
1415 // We need the following "if" for transparently bumped TLS connection,
1416 // because in this case we are running ssl_bump access list before
1417 // the doCallouts runs. It can be removed after the bug #4340 fixed.
1418 // We do not want to proceed to bumping steps:
1419 // - if the TLS connection with the client is already established
1420 // because we are accepting normal HTTP requests on TLS port,
1421 // or because of the client-first bumping mode
1422 // - When the bumping is already started
1423 if (!http->getConn()->switchedToHttps() &&
1424 !http->getConn()->serverBump())
1425 http->sslBumpNeed(bumpMode); // for processRequest() to bump if needed and not already bumped
1426 http->al->ssl.bumpMode = bumpMode; // inherited from bumped connection
1427 return false;
1428 }
1429
1430 // If we have not decided yet, decide whether to bump now.
1431
1432 // Bumping here can only start with a CONNECT request on a bumping port
1433 // (bumping of intercepted SSL conns is decided before we get 1st request).
1434 // We also do not bump redirected CONNECT requests.
1435 if (http->request->method != Http::METHOD_CONNECT || http->redirect.status ||
1436 !Config.accessList.ssl_bump ||
1437 !http->getConn()->port->flags.tunnelSslBumping) {
1438 http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
1439 debugs(85, 5, HERE << "cannot SslBump this request");
1440 return false;
1441 }
1442
1443 // Do not bump during authentication: clients would not proxy-authenticate
1444 // if we delay a 407 response and respond with 200 OK to CONNECT.
1445 if (error && error->httpStatus == Http::scProxyAuthenticationRequired) {
1446 http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
1447 debugs(85, 5, HERE << "no SslBump during proxy authentication");
1448 return false;
1449 }
1450
1451 if (error) {
1452 debugs(85, 5, "SslBump applies. Force bump action on error " << errorTypeName(error->type));
1453 http->sslBumpNeed(Ssl::bumpBump);
1454 http->al->ssl.bumpMode = Ssl::bumpBump;
1455 return false;
1456 }
1457
1458 debugs(85, 5, HERE << "SslBump possible, checking ACL");
1459
1460 ACLFilledChecklist *aclChecklist = clientAclChecklistCreate(Config.accessList.ssl_bump, http);
1461 aclChecklist->nonBlockingCheck(sslBumpAccessCheckDoneWrapper, this);
1462 return true;
1463 }
1464
1465 /**
1466 * A wrapper function to use the ClientRequestContext::sslBumpAccessCheckDone method
1467 * as ACLFilledChecklist callback
1468 */
1469 static void
1470 sslBumpAccessCheckDoneWrapper(Acl::Answer answer, void *data)
1471 {
1472 ClientRequestContext *calloutContext = static_cast<ClientRequestContext *>(data);
1473
1474 if (!calloutContext->httpStateIsValid())
1475 return;
1476 calloutContext->sslBumpAccessCheckDone(answer);
1477 }
1478
1479 void
1480 ClientRequestContext::sslBumpAccessCheckDone(const Acl::Answer &answer)
1481 {
1482 if (!httpStateIsValid())
1483 return;
1484
1485 const Ssl::BumpMode bumpMode = answer.allowed() ?
1486 static_cast<Ssl::BumpMode>(answer.kind) : Ssl::bumpSplice;
1487 http->sslBumpNeed(bumpMode); // for processRequest() to bump if needed
1488 http->al->ssl.bumpMode = bumpMode; // for logging
1489
1490 if (bumpMode == Ssl::bumpTerminate) {
1491 const Comm::ConnectionPointer clientConn = http->getConn() ? http->getConn()->clientConnection : nullptr;
1492 if (Comm::IsConnOpen(clientConn)) {
1493 debugs(85, 3, "closing after Ssl::bumpTerminate ");
1494 clientConn->close();
1495 }
1496 return;
1497 }
1498
1499 http->doCallouts();
1500 }
1501 #endif
1502
1503 /*
1504 * Identify requests that do not go through the store and client side stream
1505 * and forward them to the appropriate location. All other requests, request
1506 * them.
1507 */
1508 void
1509 ClientHttpRequest::processRequest()
1510 {
1511 debugs(85, 4, request->method << ' ' << uri);
1512
1513 const bool untouchedConnect = request->method == Http::METHOD_CONNECT && !redirect.status;
1514
1515 #if USE_OPENSSL
1516 if (untouchedConnect && sslBumpNeeded()) {
1517 assert(!request->flags.forceTunnel);
1518 sslBumpStart();
1519 return;
1520 }
1521 #endif
1522
1523 if (untouchedConnect || request->flags.forceTunnel) {
1524 getConn()->stopReading(); // tunnels read for themselves
1525 tunnelStart(this);
1526 return;
1527 }
1528
1529 httpStart();
1530 }
1531
1532 void
1533 ClientHttpRequest::httpStart()
1534 {
1535 PROF_start(httpStart);
1536 // XXX: Re-initializes rather than updates. Should not be needed at all.
1537 logType.update(LOG_TAG_NONE);
1538 debugs(85, 4, logType.c_str() << " for '" << uri << "'");
1539
1540 /* no one should have touched this */
1541 assert(out.offset == 0);
1542 /* Use the Stream Luke */
1543 clientStreamNode *node = (clientStreamNode *)client_stream.tail->data;
1544 clientStreamRead(node, this, node->readBuffer);
1545 PROF_stop(httpStart);
1546 }
1547
1548 #if USE_OPENSSL
1549
1550 void
1551 ClientHttpRequest::sslBumpNeed(Ssl::BumpMode mode)
1552 {
1553 debugs(83, 3, HERE << "sslBump required: "<< Ssl::bumpMode(mode));
1554 sslBumpNeed_ = mode;
1555 }
1556
1557 // called when comm_write has completed
1558 static void
1559 SslBumpEstablish(const Comm::ConnectionPointer &, char *, size_t, Comm::Flag errflag, int, void *data)
1560 {
1561 ClientHttpRequest *r = static_cast<ClientHttpRequest*>(data);
1562 debugs(85, 5, HERE << "responded to CONNECT: " << r << " ? " << errflag);
1563
1564 assert(r && cbdataReferenceValid(r));
1565 r->sslBumpEstablish(errflag);
1566 }
1567
1568 void
1569 ClientHttpRequest::sslBumpEstablish(Comm::Flag errflag)
1570 {
1571 // Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up
1572 if (errflag == Comm::ERR_CLOSING)
1573 return;
1574
1575 if (errflag) {
1576 debugs(85, 3, HERE << "CONNECT response failure in SslBump: " << errflag);
1577 getConn()->clientConnection->close();
1578 return;
1579 }
1580
1581 #if USE_AUTH
1582 // Preserve authentication info for the ssl-bumped request
1583 if (request->auth_user_request != NULL)
1584 getConn()->setAuth(request->auth_user_request, "SSL-bumped CONNECT");
1585 #endif
1586
1587 assert(sslBumpNeeded());
1588 getConn()->switchToHttps(this, sslBumpNeed_);
1589 }
1590
1591 void
1592 ClientHttpRequest::sslBumpStart()
1593 {
1594 debugs(85, 5, HERE << "Confirming " << Ssl::bumpMode(sslBumpNeed_) <<
1595 "-bumped CONNECT tunnel on FD " << getConn()->clientConnection);
1596 getConn()->sslBumpMode = sslBumpNeed_;
1597
1598 AsyncCall::Pointer bumpCall = commCbCall(85, 5, "ClientSocketContext::sslBumpEstablish",
1599 CommIoCbPtrFun(&SslBumpEstablish, this));
1600
1601 if (request->flags.interceptTproxy || request->flags.intercepted) {
1602 CommIoCbParams &params = GetCommParams<CommIoCbParams>(bumpCall);
1603 params.flag = Comm::OK;
1604 params.conn = getConn()->clientConnection;
1605 ScheduleCallHere(bumpCall);
1606 return;
1607 }
1608
1609 al->reply = HttpReply::MakeConnectionEstablished();
1610
1611 const auto mb = al->reply->pack();
1612 // send an HTTP 200 response to kick client SSL negotiation
1613 // TODO: Unify with tunnel.cc and add a Server(?) header
1614 Comm::Write(getConn()->clientConnection, mb, bumpCall);
1615 delete mb;
1616 }
1617
1618 #endif
1619
1620 void
1621 ClientHttpRequest::updateError(const Error &error)
1622 {
1623 if (request)
1624 request->error.update(error);
1625 else
1626 al->updateError(error);
1627 }
1628
1629 bool
1630 ClientHttpRequest::gotEnough() const
1631 {
1632 // TODO: See also (and unify with) clientReplyContext::storeNotOKTransferDone()
1633 int64_t contentLength =
1634 memObject()->baseReply().bodySize(request->method);
1635 assert(contentLength >= 0);
1636
1637 if (out.offset < contentLength)
1638 return false;
1639
1640 return true;
1641 }
1642
1643 void
1644 ClientHttpRequest::storeEntry(StoreEntry *newEntry)
1645 {
1646 entry_ = newEntry;
1647 }
1648
1649 void
1650 ClientHttpRequest::loggingEntry(StoreEntry *newEntry)
1651 {
1652 if (loggingEntry_)
1653 loggingEntry_->unlock("ClientHttpRequest::loggingEntry");
1654
1655 loggingEntry_ = newEntry;
1656
1657 if (loggingEntry_)
1658 loggingEntry_->lock("ClientHttpRequest::loggingEntry");
1659 }
1660
1661 void
1662 ClientHttpRequest::initRequest(HttpRequest *aRequest)
1663 {
1664 assignRequest(aRequest);
1665 if (const auto csd = getConn()) {
1666 if (!csd->notes()->empty())
1667 request->notes()->appendNewOnly(csd->notes().getRaw());
1668 }
1669 // al is created in the constructor
1670 assert(al);
1671 if (!al->request) {
1672 al->request = request;
1673 HTTPMSGLOCK(al->request);
1674 al->syncNotes(request);
1675 }
1676 }
1677
1678 void
1679 ClientHttpRequest::resetRequest(HttpRequest *newRequest)
1680 {
1681 assert(request != newRequest);
1682 clearRequest();
1683 assignRequest(newRequest);
1684 xfree(uri);
1685 uri = SBufToCstring(request->effectiveRequestUri());
1686 }
1687
1688 void
1689 ClientHttpRequest::assignRequest(HttpRequest *newRequest)
1690 {
1691 assert(newRequest);
1692 assert(!request);
1693 const_cast<HttpRequest *&>(request) = newRequest;
1694 HTTPMSGLOCK(request);
1695 setLogUriToRequestUri();
1696 }
1697
1698 void
1699 ClientHttpRequest::clearRequest()
1700 {
1701 HttpRequest *oldRequest = request;
1702 HTTPMSGUNLOCK(oldRequest);
1703 const_cast<HttpRequest *&>(request) = nullptr;
1704 absorbLogUri(nullptr);
1705 }
1706
1707 /*
1708 * doCallouts() - This function controls the order of "callout"
1709 * executions, including non-blocking access control checks, the
1710 * redirector, and ICAP. Previously, these callouts were chained
1711 * together such that "clientAccessCheckDone()" would call
1712 * "clientRedirectStart()" and so on.
1713 *
1714 * The ClientRequestContext (aka calloutContext) class holds certain
1715 * state data for the callout/callback operations. Previously
1716 * ClientHttpRequest would sort of hand off control to ClientRequestContext
1717 * for a short time. ClientRequestContext would then delete itself
1718 * and pass control back to ClientHttpRequest when all callouts
1719 * were finished.
1720 *
1721 * This caused some problems for ICAP because we want to make the
1722 * ICAP callout after checking ACLs, but before checking the no_cache
1723 * list. We can't stuff the ICAP state into the ClientRequestContext
1724 * class because we still need the ICAP state after ClientRequestContext
1725 * goes away.
1726 *
1727 * Note that ClientRequestContext is created before the first call
1728 * to doCallouts().
1729 *
1730 * If one of the callouts notices that ClientHttpRequest is no
1731 * longer valid, it should call cbdataReferenceDone() so that
1732 * ClientHttpRequest's reference count goes to zero and it will get
1733 * deleted. ClientHttpRequest will then delete ClientRequestContext.
1734 *
1735 * Note that we set the _done flags here before actually starting
1736 * the callout. This is strictly for convenience.
1737 */
1738
1739 tos_t aclMapTOS (acl_tos * head, ACLChecklist * ch);
1740 Ip::NfMarkConfig aclFindNfMarkConfig (acl_nfmark * head, ACLChecklist * ch);
1741
1742 void
1743 ClientHttpRequest::doCallouts()
1744 {
1745 assert(calloutContext);
1746
1747 if (!calloutContext->error) {
1748 // CVE-2009-0801: verify the Host: header is consistent with other known details.
1749 if (!calloutContext->host_header_verify_done) {
1750 debugs(83, 3, HERE << "Doing calloutContext->hostHeaderVerify()");
1751 calloutContext->host_header_verify_done = true;
1752 calloutContext->hostHeaderVerify();
1753 return;
1754 }
1755
1756 if (!calloutContext->http_access_done) {
1757 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck()");
1758 calloutContext->http_access_done = true;
1759 calloutContext->clientAccessCheck();
1760 return;
1761 }
1762
1763 #if USE_ADAPTATION
1764 if (!calloutContext->adaptation_acl_check_done) {
1765 calloutContext->adaptation_acl_check_done = true;
1766 if (Adaptation::AccessCheck::Start(
1767 Adaptation::methodReqmod, Adaptation::pointPreCache,
1768 request, NULL, calloutContext->http->al, this))
1769 return; // will call callback
1770 }
1771 #endif
1772
1773 if (!calloutContext->redirect_done) {
1774 calloutContext->redirect_done = true;
1775
1776 if (Config.Program.redirect) {
1777 debugs(83, 3, HERE << "Doing calloutContext->clientRedirectStart()");
1778 calloutContext->redirect_state = REDIRECT_PENDING;
1779 calloutContext->clientRedirectStart();
1780 return;
1781 }
1782 }
1783
1784 if (!calloutContext->adapted_http_access_done) {
1785 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck2()");
1786 calloutContext->adapted_http_access_done = true;
1787 calloutContext->clientAccessCheck2();
1788 return;
1789 }
1790
1791 if (!calloutContext->store_id_done) {
1792 calloutContext->store_id_done = true;
1793
1794 if (Config.Program.store_id) {
1795 debugs(83, 3,"Doing calloutContext->clientStoreIdStart()");
1796 calloutContext->store_id_state = REDIRECT_PENDING;
1797 calloutContext->clientStoreIdStart();
1798 return;
1799 }
1800 }
1801
1802 if (!calloutContext->interpreted_req_hdrs) {
1803 debugs(83, 3, HERE << "Doing clientInterpretRequestHeaders()");
1804 calloutContext->interpreted_req_hdrs = 1;
1805 clientInterpretRequestHeaders(this);
1806 }
1807
1808 if (!calloutContext->no_cache_done) {
1809 calloutContext->no_cache_done = true;
1810
1811 if (Config.accessList.noCache && request->flags.cachable) {
1812 debugs(83, 3, HERE << "Doing calloutContext->checkNoCache()");
1813 calloutContext->checkNoCache();
1814 return;
1815 }
1816 }
1817 } // if !calloutContext->error
1818
1819 // Set appropriate MARKs and CONNMARKs if needed.
1820 if (getConn() && Comm::IsConnOpen(getConn()->clientConnection)) {
1821 ACLFilledChecklist ch(nullptr, request, nullptr);
1822 ch.al = calloutContext->http->al;
1823 ch.src_addr = request->client_addr;
1824 ch.my_addr = request->my_addr;
1825 ch.syncAle(request, log_uri);
1826
1827 if (!calloutContext->toClientMarkingDone) {
1828 calloutContext->toClientMarkingDone = true;
1829 tos_t tos = aclMapTOS(Ip::Qos::TheConfig.tosToClient, &ch);
1830 if (tos)
1831 Ip::Qos::setSockTos(getConn()->clientConnection, tos);
1832
1833 const auto packetMark = aclFindNfMarkConfig(Ip::Qos::TheConfig.nfmarkToClient, &ch);
1834 if (!packetMark.isEmpty())
1835 Ip::Qos::setSockNfmark(getConn()->clientConnection, packetMark.mark);
1836
1837 const auto connmark = aclFindNfMarkConfig(Ip::Qos::TheConfig.nfConnmarkToClient, &ch);
1838 if (!connmark.isEmpty())
1839 Ip::Qos::setNfConnmark(getConn()->clientConnection, Ip::Qos::dirAccepted, connmark);
1840 }
1841 }
1842
1843 #if USE_OPENSSL
1844 // Even with calloutContext->error, we call sslBumpAccessCheck() to decide
1845 // whether SslBump applies to this transaction. If it applies, we will
1846 // attempt to bump the client to serve the error.
1847 if (!calloutContext->sslBumpCheckDone) {
1848 calloutContext->sslBumpCheckDone = true;
1849 if (calloutContext->sslBumpAccessCheck())
1850 return;
1851 /* else no ssl bump required*/
1852 }
1853 #endif
1854
1855 if (calloutContext->error) {
1856 // XXX: prformance regression. c_str() reallocates
1857 SBuf storeUriBuf(request->storeId());
1858 const char *storeUri = storeUriBuf.c_str();
1859 StoreEntry *e = storeCreateEntry(storeUri, storeUri, request->flags, request->method);
1860 #if USE_OPENSSL
1861 if (sslBumpNeeded()) {
1862 // We have to serve an error, so bump the client first.
1863 sslBumpNeed(Ssl::bumpClientFirst);
1864 // set final error but delay sending until we bump
1865 Ssl::ServerBump *srvBump = new Ssl::ServerBump(this, e, Ssl::bumpClientFirst);
1866 errorAppendEntry(e, calloutContext->error);
1867 calloutContext->error = NULL;
1868 getConn()->setServerBump(srvBump);
1869 e->unlock("ClientHttpRequest::doCallouts+sslBumpNeeded");
1870 } else
1871 #endif
1872 {
1873 // send the error to the client now
1874 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1875 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1876 assert (repContext);
1877 repContext->setReplyToStoreEntry(e, "immediate SslBump error");
1878 errorAppendEntry(e, calloutContext->error);
1879 calloutContext->error = NULL;
1880 if (calloutContext->readNextRequest && getConn())
1881 getConn()->flags.readMore = true; // resume any pipeline reads.
1882 node = (clientStreamNode *)client_stream.tail->data;
1883 clientStreamRead(node, this, node->readBuffer);
1884 e->unlock("ClientHttpRequest::doCallouts-sslBumpNeeded");
1885 return;
1886 }
1887 }
1888
1889 cbdataReferenceDone(calloutContext->http);
1890 delete calloutContext;
1891 calloutContext = NULL;
1892 #if HEADERS_LOG
1893
1894 headersLog(0, 1, request->method, request);
1895 #endif
1896
1897 debugs(83, 3, HERE << "calling processRequest()");
1898 processRequest();
1899
1900 #if ICAP_CLIENT
1901 Adaptation::Icap::History::Pointer ih = request->icapHistory();
1902 if (ih != NULL)
1903 ih->logType = logType;
1904 #endif
1905 }
1906
1907 void
1908 ClientHttpRequest::setLogUriToRequestUri()
1909 {
1910 assert(request);
1911 const auto canonicalUri = request->canonicalCleanUrl();
1912 absorbLogUri(xstrndup(canonicalUri, MAX_URL));
1913 }
1914
1915 void
1916 ClientHttpRequest::setLogUriToRawUri(const char *rawUri, const HttpRequestMethod &method)
1917 {
1918 assert(rawUri);
1919 // Should(!request);
1920
1921 // TODO: SBuf() performance regression, fix by converting rawUri to SBuf
1922 char *canonicalUri = urlCanonicalCleanWithoutRequest(SBuf(rawUri), method, AnyP::UriScheme());
1923
1924 absorbLogUri(AnyP::Uri::cleanup(canonicalUri));
1925
1926 char *cleanedRawUri = AnyP::Uri::cleanup(rawUri);
1927 al->setVirginUrlForMissingRequest(SBuf(cleanedRawUri));
1928 xfree(cleanedRawUri);
1929 }
1930
1931 void
1932 ClientHttpRequest::absorbLogUri(char *aUri)
1933 {
1934 xfree(log_uri);
1935 const_cast<char *&>(log_uri) = aUri;
1936 }
1937
1938 void
1939 ClientHttpRequest::setErrorUri(const char *aUri)
1940 {
1941 assert(!uri);
1942 assert(aUri);
1943 // Should(!request);
1944
1945 uri = xstrdup(aUri);
1946 // TODO: SBuf() performance regression, fix by converting setErrorUri() parameter to SBuf
1947 const SBuf errorUri(aUri);
1948 const auto canonicalUri = urlCanonicalCleanWithoutRequest(errorUri, HttpRequestMethod(), AnyP::UriScheme());
1949 absorbLogUri(xstrndup(canonicalUri, MAX_URL));
1950
1951 al->setVirginUrlForMissingRequest(errorUri);
1952 }
1953
1954 #if USE_ADAPTATION
1955 /// Initiate an asynchronous adaptation transaction which will call us back.
1956 void
1957 ClientHttpRequest::startAdaptation(const Adaptation::ServiceGroupPointer &g)
1958 {
1959 debugs(85, 3, HERE << "adaptation needed for " << this);
1960 assert(!virginHeadSource);
1961 assert(!adaptedBodySource);
1962 virginHeadSource = initiateAdaptation(
1963 new Adaptation::Iterator(request, NULL, al, g));
1964
1965 // we could try to guess whether we can bypass this adaptation
1966 // initiation failure, but it should not really happen
1967 Must(initiated(virginHeadSource));
1968 }
1969
1970 void
1971 ClientHttpRequest::noteAdaptationAnswer(const Adaptation::Answer &answer)
1972 {
1973 assert(cbdataReferenceValid(this)); // indicates bug
1974 clearAdaptation(virginHeadSource);
1975 assert(!adaptedBodySource);
1976
1977 switch (answer.kind) {
1978 case Adaptation::Answer::akForward:
1979 handleAdaptedHeader(const_cast<Http::Message*>(answer.message.getRaw()));
1980 break;
1981
1982 case Adaptation::Answer::akBlock:
1983 handleAdaptationBlock(answer);
1984 break;
1985
1986 case Adaptation::Answer::akError: {
1987 static const auto d = MakeNamedErrorDetail("CLT_REQMOD_ABORT");
1988 handleAdaptationFailure(d, !answer.final);
1989 break;
1990 }
1991 }
1992 }
1993
1994 void
1995 ClientHttpRequest::handleAdaptedHeader(Http::Message *msg)
1996 {
1997 assert(msg);
1998
1999 if (HttpRequest *new_req = dynamic_cast<HttpRequest*>(msg)) {
2000 // update the new message to flag whether URL re-writing was done on it
2001 if (request->effectiveRequestUri() != new_req->effectiveRequestUri())
2002 new_req->flags.redirected = true;
2003 resetRequest(new_req);
2004 assert(request->method.id());
2005 } else if (HttpReply *new_rep = dynamic_cast<HttpReply*>(msg)) {
2006 debugs(85,3,HERE << "REQMOD reply is HTTP reply");
2007
2008 // subscribe to receive reply body
2009 if (new_rep->body_pipe != NULL) {
2010 adaptedBodySource = new_rep->body_pipe;
2011 int consumer_ok = adaptedBodySource->setConsumerIfNotLate(this);
2012 assert(consumer_ok);
2013 }
2014
2015 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
2016 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2017 assert(repContext);
2018 repContext->createStoreEntry(request->method, request->flags);
2019
2020 request_satisfaction_mode = true;
2021 request_satisfaction_offset = 0;
2022 storeEntry()->replaceHttpReply(new_rep);
2023 storeEntry()->timestampsSet();
2024
2025 al->reply = new_rep;
2026
2027 if (!adaptedBodySource) // no body
2028 storeEntry()->complete();
2029 clientGetMoreData(node, this);
2030 }
2031
2032 // we are done with getting headers (but may be receiving body)
2033 clearAdaptation(virginHeadSource);
2034
2035 if (!request_satisfaction_mode)
2036 doCallouts();
2037 }
2038
2039 void
2040 ClientHttpRequest::handleAdaptationBlock(const Adaptation::Answer &answer)
2041 {
2042 static const auto d = MakeNamedErrorDetail("REQMOD_BLOCK");
2043 request->detailError(ERR_ACCESS_DENIED, d);
2044 AclMatchedName = answer.ruleId.termedBuf();
2045 assert(calloutContext);
2046 calloutContext->clientAccessCheckDone(ACCESS_DENIED);
2047 AclMatchedName = NULL;
2048 }
2049
2050 void
2051 ClientHttpRequest::resumeBodyStorage()
2052 {
2053 if (!adaptedBodySource)
2054 return;
2055
2056 noteMoreBodyDataAvailable(adaptedBodySource);
2057 }
2058
2059 void
2060 ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer)
2061 {
2062 assert(request_satisfaction_mode);
2063 assert(adaptedBodySource != NULL);
2064
2065 if (size_t contentSize = adaptedBodySource->buf().contentSize()) {
2066 const size_t spaceAvailable = storeEntry()->bytesWanted(Range<size_t>(0,contentSize));
2067
2068 if (spaceAvailable < contentSize ) {
2069 // No or partial body data consuming
2070 typedef NullaryMemFunT<ClientHttpRequest> Dialer;
2071 AsyncCall::Pointer call = asyncCall(93, 5, "ClientHttpRequest::resumeBodyStorage",
2072 Dialer(this, &ClientHttpRequest::resumeBodyStorage));
2073 storeEntry()->deferProducer(call);
2074 }
2075
2076 if (!spaceAvailable)
2077 return;
2078
2079 if (spaceAvailable < contentSize )
2080 contentSize = spaceAvailable;
2081
2082 BodyPipeCheckout bpc(*adaptedBodySource);
2083 const StoreIOBuffer ioBuf(&bpc.buf, request_satisfaction_offset, contentSize);
2084 storeEntry()->write(ioBuf);
2085 // assume StoreEntry::write() writes the entire ioBuf
2086 request_satisfaction_offset += ioBuf.length;
2087 bpc.buf.consume(contentSize);
2088 bpc.checkIn();
2089 }
2090
2091 if (adaptedBodySource->exhausted())
2092 endRequestSatisfaction();
2093 // else wait for more body data
2094 }
2095
2096 void
2097 ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer)
2098 {
2099 assert(!virginHeadSource);
2100 // should we end request satisfaction now?
2101 if (adaptedBodySource != NULL && adaptedBodySource->exhausted())
2102 endRequestSatisfaction();
2103 }
2104
2105 void
2106 ClientHttpRequest::endRequestSatisfaction()
2107 {
2108 debugs(85,4, HERE << this << " ends request satisfaction");
2109 assert(request_satisfaction_mode);
2110 stopConsumingFrom(adaptedBodySource);
2111
2112 // TODO: anything else needed to end store entry formation correctly?
2113 storeEntry()->complete();
2114 }
2115
2116 void
2117 ClientHttpRequest::noteBodyProducerAborted(BodyPipe::Pointer)
2118 {
2119 assert(!virginHeadSource);
2120 stopConsumingFrom(adaptedBodySource);
2121
2122 debugs(85,3, HERE << "REQMOD body production failed");
2123 if (request_satisfaction_mode) { // too late to recover or serve an error
2124 static const auto d = MakeNamedErrorDetail("CLT_REQMOD_RESP_BODY");
2125 request->detailError(ERR_ICAP_FAILURE, d);
2126 const Comm::ConnectionPointer c = getConn()->clientConnection;
2127 Must(Comm::IsConnOpen(c));
2128 c->close(); // drastic, but we may be writing a response already
2129 } else {
2130 static const auto d = MakeNamedErrorDetail("CLT_REQMOD_REQ_BODY");
2131 handleAdaptationFailure(d);
2132 }
2133 }
2134
2135 void
2136 ClientHttpRequest::handleAdaptationFailure(const ErrorDetail::Pointer &errDetail, bool bypassable)
2137 {
2138 debugs(85,3, HERE << "handleAdaptationFailure(" << bypassable << ")");
2139
2140 const bool usedStore = storeEntry() && !storeEntry()->isEmpty();
2141 const bool usedPipe = request->body_pipe != NULL &&
2142 request->body_pipe->consumedSize() > 0;
2143
2144 if (bypassable && !usedStore && !usedPipe) {
2145 debugs(85,3, HERE << "ICAP REQMOD callout failed, bypassing: " << calloutContext);
2146 if (calloutContext)
2147 doCallouts();
2148 return;
2149 }
2150
2151 debugs(85,3, HERE << "ICAP REQMOD callout failed, responding with error");
2152
2153 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
2154 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2155 assert(repContext);
2156
2157 calloutsError(ERR_ICAP_FAILURE, errDetail);
2158
2159 if (calloutContext)
2160 doCallouts();
2161 }
2162
2163 void
2164 ClientHttpRequest::callException(const std::exception &ex)
2165 {
2166 if (const auto clientConn = getConn() ? getConn()->clientConnection : nullptr) {
2167 if (Comm::IsConnOpen(clientConn)) {
2168 debugs(85, 3, "closing after exception: " << ex.what());
2169 clientConn->close(); // initiate orderly top-to-bottom cleanup
2170 return;
2171 }
2172 }
2173 debugs(85, DBG_IMPORTANT, "ClientHttpRequest exception without connection. Ignoring " << ex.what());
2174 // XXX: Normally, we mustStop() but we cannot do that here because it is
2175 // likely to leave Http::Stream and ConnStateData with a dangling http
2176 // pointer. See r13480 or XXX in Http::Stream class description.
2177 }
2178 #endif
2179
2180 // XXX: modify and use with ClientRequestContext::clientAccessCheckDone too.
2181 void
2182 ClientHttpRequest::calloutsError(const err_type error, const ErrorDetail::Pointer &errDetail)
2183 {
2184 // The original author of the code also wanted to pass an errno to
2185 // setReplyToError, but it seems unlikely that the errno reflects the
2186 // true cause of the error at this point, so I did not pass it.
2187 if (calloutContext) {
2188 ConnStateData * c = getConn();
2189 calloutContext->error = clientBuildError(error, Http::scInternalServerError,
2190 nullptr, c, request, al);
2191 #if USE_AUTH
2192 calloutContext->error->auth_user_request =
2193 c != NULL && c->getAuth() != NULL ? c->getAuth() : request->auth_user_request;
2194 #endif
2195 calloutContext->error->detailError(errDetail);
2196 calloutContext->readNextRequest = true;
2197 if (c != NULL)
2198 c->expectNoForwarding();
2199 }
2200 //else if(calloutContext == NULL) is it possible?
2201 }
2202