]> git.ipfire.org Git - thirdparty/squid.git/blame - src/peer_select.cc
SourceFormat Enforcement
[thirdparty/squid.git] / src / peer_select.cc
CommitLineData
062e2281 1/*
f6e9a3ee 2 * Copyright (C) 1996-2019 The Squid Software Foundation and contributors
e25c139f 3 *
bbc27441
AJ
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.
062e2281 7 */
8
bbc27441
AJ
9/* DEBUG: section 44 Peer Selection Algorithm */
10
582c2af2
FC
11#include "squid.h"
12#include "acl/FilledChecklist.h"
6043e368 13#include "base/InstanceId.h"
a011edee 14#include "CachePeer.h"
21c22f04 15#include "carp.h"
582c2af2 16#include "client_side.h"
4a3b98d7 17#include "dns/LookupDetails.h"
a37fdd8a 18#include "errorpage.h"
a553a5a3 19#include "event.h"
eb13c21e 20#include "FwdState.h"
af69c635 21#include "globals.h"
bbaf2685 22#include "hier_code.h"
924f73bc 23#include "htcp.h"
d3dddfb5 24#include "http/Stream.h"
582c2af2 25#include "HttpRequest.h"
9b5c4a9a 26#include "icmp/net_db.h"
582c2af2 27#include "ICP.h"
c7a52e6d 28#include "ip/tools.h"
602d9612 29#include "ipcache.h"
f0ba2534 30#include "neighbors.h"
f795b373 31#include "peer_sourcehash.h"
37236ba1 32#include "peer_userhash.h"
582c2af2 33#include "PeerSelectState.h"
4d5904f7 34#include "SquidConfig.h"
582c2af2
FC
35#include "SquidTime.h"
36#include "Store.h"
062e2281 37
6043e368
AR
38/**
39 * A CachePeer which has been selected as a possible destination.
40 * Listed as pointers here so as to prevent duplicates being added but will
41 * be converted to a set of IP address path options before handing back out
42 * to the caller.
43 *
44 * Certain connection flags and outgoing settings will also be looked up and
45 * set based on the received request and CachePeer settings before handing back.
46 */
47class FwdServer
48{
49 MEMPROXY_CLASS(FwdServer);
50
51public:
52 FwdServer(CachePeer *p, hier_code c) :
53 _peer(p),
54 code(c),
55 next(nullptr)
56 {}
57
58 CbcPointer<CachePeer> _peer; /* NULL --> origin server */
59 hier_code code;
60 FwdServer *next;
61};
62
26ac0430 63static struct {
75e88d56 64 int timeouts;
2fadd50d 65} PeerStats;
062e2281 66
26ac0430
AJ
67static const char *DirectStr[] = {
68 "DIRECT_UNKNOWN",
69 "DIRECT_NO",
70 "DIRECT_MAYBE",
71 "DIRECT_YES"
72};
75e88d56 73
e7b08eec
AR
74/// a helper class to report a selected destination (for debugging)
75class PeerSelectionDumper
76{
77public:
cb835136
AR
78 PeerSelectionDumper(const PeerSelector * const aSelector, const CachePeer * const aPeer, const hier_code aCode):
79 selector(aSelector), peer(aPeer), code(aCode) {}
e7b08eec 80
cb835136 81 const PeerSelector * const selector; ///< selection parameters
e7b08eec
AR
82 const CachePeer * const peer; ///< successful selection info
83 const hier_code code; ///< selection algorithm
84};
85
cb835136 86CBDATA_CLASS_INIT(PeerSelector);
aa839030 87
e7b08eec
AR
88/// prints PeerSelectionDumper (for debugging)
89static std::ostream &
90operator <<(std::ostream &os, const PeerSelectionDumper &fsd)
91{
92 os << hier_code_str[fsd.code];
93
94 if (fsd.peer)
95 os << '/' << fsd.peer->host;
cb835136
AR
96 else if (fsd.selector) // useful for DIRECT and gone PINNED destinations
97 os << '#' << fsd.selector->request->url.host();
e7b08eec
AR
98
99 return os;
100}
101
cb835136 102PeerSelector::~PeerSelector()
348b2031 103{
36339742
AJ
104 while (servers) {
105 FwdServer *next = servers->next;
3c670b50 106 delete servers;
36339742
AJ
107 servers = next;
108 }
109
029c8349
AJ
110 if (entry) {
111 debugs(44, 3, entry->url());
5ae21d99 112
029c8349 113 if (entry->ping_status == PING_WAITING)
cb835136 114 eventDelete(HandlePingTimeout, this);
5ae21d99 115
029c8349 116 entry->ping_status = PING_DONE;
5ae21d99
AJ
117 }
118
029c8349 119 if (acl_checklist) {
cb835136 120 debugs(44, DBG_IMPORTANT, "BUG: peer selector gone while waiting for a slow ACL");
029c8349 121 delete acl_checklist;
348b2031 122 }
62e76326 123
029c8349 124 HTTPMSGUNLOCK(request);
62e76326 125
029c8349
AJ
126 if (entry) {
127 assert(entry->ping_status != PING_WAITING);
1f90fd4a 128 entry->unlock("peerSelect");
029c8349 129 entry = NULL;
73a201f8 130 }
62e76326 131
029c8349 132 delete lastError;
348b2031 133}
062e2281 134
2d72d4fd 135static int
cb365059 136peerSelectIcpPing(PeerSelector *ps, int direct, StoreEntry * entry)
062e2281 137{
cb365059
EB
138 assert(ps);
139 HttpRequest *request = ps->request;
140
7b665aeb 141 int n;
db1cd23c 142 assert(entry);
143 assert(entry->ping_status == PING_NONE);
9bd6a36d 144 assert(direct != DIRECT_YES);
cb835136 145 debugs(44, 3, entry->url());
62e76326 146
45e5102d 147 if (!request->flags.hierarchical && direct != DIRECT_NO)
62e76326 148 return 0;
149
d46a87a8 150 if (EBIT_TEST(entry->flags, KEY_PRIVATE) && !neighbors_do_private_keys)
62e76326 151 if (direct != DIRECT_NO)
152 return 0;
153
cb365059 154 n = neighborsCount(ps);
62e76326 155
cb835136 156 debugs(44, 3, "counted " << n << " neighbors");
62e76326 157
7b665aeb 158 return n;
062e2281 159}
160
6043e368
AR
161static void
162peerSelect(PeerSelectionInitiator *initiator,
cfd66529 163 HttpRequest * request,
d4806c91 164 AccessLogEntry::Pointer const &al,
6043e368 165 StoreEntry * entry)
75e88d56 166{
86b389fc 167 if (entry)
7f06a3d8 168 debugs(44, 3, *entry << ' ' << entry->url());
86b389fc 169 else
7f06a3d8 170 debugs(44, 3, request->method);
62e76326 171
cb835136 172 const auto selector = new PeerSelector(initiator);
62e76326 173
cb835136
AR
174 selector->request = request;
175 HTTPMSGLOCK(selector->request);
176 selector->al = al;
62e76326 177
cb835136 178 selector->entry = entry;
62e76326 179
6cfa8966 180#if USE_CACHE_DIGESTS
62e76326 181
39edba21 182 request->hier.peer_select_start = current_time;
62e76326 183
39edba21 184#endif
62e76326 185
cb835136
AR
186 if (selector->entry)
187 selector->entry->lock("peerSelect");
62e76326 188
cb835136 189 selector->selectMore();
75e88d56 190}
191
6043e368
AR
192void
193PeerSelectionInitiator::startSelectingDestinations(HttpRequest *request, const AccessLogEntry::Pointer &ale, StoreEntry *entry)
194{
195 subscribed = true;
196 peerSelect(this, request, ale, entry);
197 // and wait for noteDestination() and/or noteDestinationsEnd() calls
198}
199
cb835136
AR
200void
201PeerSelector::checkNeverDirectDone(const allow_t answer)
75e88d56 202{
cb835136
AR
203 acl_checklist = nullptr;
204 debugs(44, 3, answer);
205 never_direct = answer;
3985b3f8 206 switch (answer) {
ae026ec6 207 case ACCESS_ALLOWED:
f365d297 208 /** if never_direct says YES, do that. */
cb835136
AR
209 direct = DIRECT_NO;
210 debugs(44, 3, "direct = " << DirectStr[direct] << " (never_direct allow)");
ae026ec6
AJ
211 break;
212 case ACCESS_DENIED: // not relevant.
1f585949 213 case ACCESS_DUNNO: // not relevant.
ae026ec6 214 break;
1f585949 215 case ACCESS_AUTH_REQUIRED:
ae026ec6 216 debugs(44, DBG_IMPORTANT, "WARNING: never_direct resulted in " << answer << ". Username ACLs are not reliable here.");
1f585949 217 break;
ae026ec6 218 }
cb835136 219 selectMore();
75e88d56 220}
221
cb835136
AR
222void
223PeerSelector::CheckNeverDirectDone(allow_t answer, void *data)
75e88d56 224{
cb835136
AR
225 static_cast<PeerSelector*>(data)->checkNeverDirectDone(answer);
226}
227
228void
229PeerSelector::checkAlwaysDirectDone(const allow_t answer)
230{
231 acl_checklist = nullptr;
232 debugs(44, 3, answer);
233 always_direct = answer;
3985b3f8 234 switch (answer) {
ae026ec6
AJ
235 case ACCESS_ALLOWED:
236 /** if always_direct says YES, do that. */
cb835136
AR
237 direct = DIRECT_YES;
238 debugs(44, 3, "direct = " << DirectStr[direct] << " (always_direct allow)");
ae026ec6
AJ
239 break;
240 case ACCESS_DENIED: // not relevant.
1f585949 241 case ACCESS_DUNNO: // not relevant.
ae026ec6 242 break;
1f585949 243 case ACCESS_AUTH_REQUIRED:
ae026ec6 244 debugs(44, DBG_IMPORTANT, "WARNING: always_direct resulted in " << answer << ". Username ACLs are not reliable here.");
1f585949 245 break;
ae026ec6 246 }
cb835136
AR
247 selectMore();
248}
249
250void
251PeerSelector::CheckAlwaysDirectDone(allow_t answer, void *data)
252{
253 static_cast<PeerSelector*>(data)->checkAlwaysDirectDone(answer);
75e88d56 254}
255
cb835136 256/// \returns true (after destroying "this") if the peer initiator is gone
6043e368 257/// \returns false (without side effects) otherwise
cb835136
AR
258bool
259PeerSelector::selectionAborted()
6043e368 260{
cb835136 261 if (interestedInitiator())
6043e368
AR
262 return false;
263
264 debugs(44, 3, "Aborting peer selection: Initiator gone or lost interest.");
cb835136 265 delete this;
6043e368
AR
266 return true;
267}
268
cb835136 269/// A single DNS resolution loop iteration: Converts selected FwdServer to IPs.
cfd66529 270void
cb835136 271PeerSelector::resolveSelected()
cfd66529 272{
cb835136 273 if (selectionAborted())
36339742 274 return;
6043e368 275
cb835136 276 FwdServer *fs = servers;
36339742 277
7177edfb
AJ
278 // Bug 3243: CVE 2009-0801
279 // Bypass of browser same-origin access control in intercepted communication
280 // To resolve this we must use only the original client destination when going DIRECT
281 // on intercepted traffic which failed Host verification
cb835136 282 const HttpRequest *req = request;
45e5102d 283 const bool isIntercepted = !req->flags.redirected &&
0d901ef4 284 (req->flags.intercepted || req->flags.interceptTproxy);
45e5102d 285 const bool useOriginalDst = Config.onoff.client_dst_passthru || !req->flags.hostVerified;
7177edfb
AJ
286 const bool choseDirect = fs && fs->code == HIER_DIRECT;
287 if (isIntercepted && useOriginalDst && choseDirect) {
d9371d7b
AJ
288 // check the client is still around before using any of its details
289 if (req->clientConnectionManager.valid()) {
290 // construct a "result" adding the ORIGINAL_DST to the set instead of DIRECT
291 Comm::ConnectionPointer p = new Comm::Connection();
292 p->remote = req->clientConnectionManager->clientConnection->local;
6043e368 293 fs->code = ORIGINAL_DST; // fs->code is DIRECT. This fixes the display.
cb835136 294 handlePath(p, *fs);
d9371d7b 295 }
7177edfb
AJ
296
297 // clear the used fs and continue
cb835136 298 servers = fs->next;
3c670b50 299 delete fs;
cb835136 300 resolveSelected();
7177edfb
AJ
301 return;
302 }
303
cfd66529 304 // convert the list of FwdServer destinations into destinations IP addresses
cb835136 305 if (fs && wantsMoreDestinations()) {
cfd66529 306 // send the next one off for DNS lookup.
cb835136
AR
307 const char *host = fs->_peer.valid() ? fs->_peer->host : request->url.host();
308 debugs(44, 2, "Find IP destination for: " << url() << "' via " << host);
309 Dns::nbgethostbyname(host, this);
cfd66529
AJ
310 return;
311 }
312
c2f4e9cc
AJ
313 // Bug 3605: clear any extra listed FwdServer destinations, when the options exceeds max_foward_tries.
314 // due to the allocation method of fs, we must deallocate each manually.
315 // TODO: use a std::list so we can get the size and abort adding whenever the selection loops reach Config.forward_max_tries
6043e368 316 if (fs) {
cb835136 317 assert(fs == servers);
9bc68187 318 while (fs) {
cb835136 319 servers = fs->next;
3c670b50 320 delete fs;
cb835136 321 fs = servers;
c2f4e9cc
AJ
322 }
323 }
324
cfd66529 325 // done with DNS lookups. pass back to caller
62e76326 326
cb835136
AR
327 debugs(44, 2, id << " found all " << foundPaths << " destinations for " << url());
328 debugs(44, 2, " always_direct = " << always_direct);
329 debugs(44, 2, " never_direct = " << never_direct);
330 debugs(44, 2, " timedout = " << ping.timedout);
5ae21d99 331
cb835136
AR
332 ping.stop = current_time;
333 request->hier.ping = ping; // final result
3dfe8371 334
cb835136 335 if (lastError && foundPaths) {
6043e368
AR
336 // nobody cares about errors if we found destinations despite them
337 debugs(44, 3, "forgetting the last error");
cb835136
AR
338 delete lastError;
339 lastError = nullptr;
db1cd23c 340 }
62e76326 341
cb835136
AR
342 if (const auto initiator = interestedInitiator())
343 initiator->noteDestinationsEnd(lastError);
344 lastError = nullptr; // initiator owns the ErrorState object now
345 delete this;
93775f90 346}
347
fd9c47d1 348void
cb835136 349PeerSelector::noteLookup(const Dns::LookupDetails &details)
cfd66529 350{
fd9c47d1 351 /* ignore lookup delays that occurred after the initiator moved on */
cfd66529 352
cb835136 353 if (selectionAborted())
fd9c47d1 354 return;
cfd66529 355
fd9c47d1
AR
356 if (!wantsMoreDestinations())
357 return;
cfd66529 358
fd9c47d1
AR
359 request->recordLookup(details);
360}
5229395c 361
fd9c47d1 362void
cb835136 363PeerSelector::noteIp(const Ip::Address &ip)
fd9c47d1 364{
cb835136 365 if (selectionAborted())
fd9c47d1 366 return;
cfd66529 367
fd9c47d1
AR
368 if (!wantsMoreDestinations())
369 return;
27d1f0a0 370
fd9c47d1 371 const auto peer = servers->_peer.valid();
cfd66529 372
fd9c47d1
AR
373 // for TPROXY spoofing, we must skip unusable addresses
374 if (request->flags.spoofClientIp && !(peer && peer->options.no_tproxy) ) {
375 if (ip.isIPv4() != request->client_addr.isIPv4())
376 return; // cannot spoof the client address on this link
377 }
c7a52e6d 378
fd9c47d1
AR
379 Comm::ConnectionPointer p = new Comm::Connection();
380 p->remote = ip;
381 p->remote.port(peer ? peer->http_port : request->url.port());
382 handlePath(p, *servers);
383}
c7a52e6d 384
fd9c47d1 385void
cb835136 386PeerSelector::noteIps(const Dns::CachedIps *ia, const Dns::LookupDetails &details)
fd9c47d1 387{
cb835136 388 if (selectionAborted())
fd9c47d1 389 return;
cfd66529 390
fd9c47d1
AR
391 FwdServer *fs = servers;
392 if (!ia) {
393 debugs(44, 3, "Unknown host: " << (fs->_peer.valid() ? fs->_peer->host : request->url.host()));
a37fdd8a 394 // discard any previous error.
fd9c47d1
AR
395 delete lastError;
396 lastError = NULL;
a37fdd8a 397 if (fs->code == HIER_DIRECT) {
fd9c47d1
AR
398 lastError = new ErrorState(ERR_DNS_FAIL, Http::scServiceUnavailable, request);
399 lastError->dnsError = details.error;
a37fdd8a 400 }
cfd66529 401 }
fd9c47d1 402 // else noteIp() calls have already processed all IPs in *ia
cfd66529 403
fd9c47d1 404 servers = fs->next;
3c670b50 405 delete fs;
cfd66529 406
cb835136
AR
407 // continue resolving selected peers
408 resolveSelected();
cfd66529
AJ
409}
410
cb835136
AR
411int
412PeerSelector::checkNetdbDirect()
b3264694 413{
9b5c4a9a 414#if USE_ICMP
a3c6762c 415 CachePeer *p;
b3264694 416 int myrtt;
417 int myhops;
62e76326 418
cb835136 419 if (direct == DIRECT_NO)
62e76326 420 return 0;
421
9b5c4a9a
AJ
422 /* base lookup on RTT and Hops if ICMP NetDB is enabled. */
423
cb835136 424 myrtt = netdbHostRtt(request->url.host());
5c51bffb
AJ
425 debugs(44, 3, "MY RTT = " << myrtt << " msec");
426 debugs(44, 3, "minimum_direct_rtt = " << Config.minDirectRtt << " msec");
62e76326 427
5f84d830 428 if (myrtt && myrtt <= Config.minDirectRtt)
62e76326 429 return 1;
430
cb835136 431 myhops = netdbHostHops(request->url.host());
62e76326 432
cb835136
AR
433 debugs(44, 3, "MY hops = " << myhops);
434 debugs(44, 3, "minimum_direct_hops = " << Config.minDirectHops);
62e76326 435
b3264694 436 if (myhops && myhops <= Config.minDirectHops)
62e76326 437 return 1;
438
cb835136 439 p = whichPeer(closest_parent_miss);
62e76326 440
5f84d830 441 if (p == NULL)
62e76326 442 return 0;
443
cb835136 444 debugs(44, 3, "closest_parent_miss RTT = " << ping.p_rtt << " msec");
62e76326 445
cb835136 446 if (myrtt && myrtt <= ping.p_rtt)
62e76326 447 return 1;
448
9b5c4a9a
AJ
449#endif /* USE_ICMP */
450
b3264694 451 return 0;
452}
453
cb835136
AR
454void
455PeerSelector::selectMore()
062e2281 456{
cb835136 457 if (selectionAborted())
36339742 458 return;
36339742 459
5c51bffb 460 debugs(44, 3, request->method << ' ' << request->url.host());
62e76326 461
45e5102d 462 /** If we don't know whether DIRECT is permitted ... */
cb835136
AR
463 if (direct == DIRECT_UNKNOWN) {
464 if (always_direct == ACCESS_DUNNO) {
465 debugs(44, 3, "direct = " << DirectStr[direct] << " (always_direct to be checked)");
45e5102d 466 /** check always_direct; */
d4806c91 467 ACLFilledChecklist *ch = new ACLFilledChecklist(Config.accessList.AlwaysDirect, request, NULL);
cb835136
AR
468 ch->al = al;
469 acl_checklist = ch;
cb365059 470 acl_checklist->syncAle(request, nullptr);
cb835136 471 acl_checklist->nonBlockingCheck(CheckAlwaysDirectDone, this);
62e76326 472 return;
cb835136
AR
473 } else if (never_direct == ACCESS_DUNNO) {
474 debugs(44, 3, "direct = " << DirectStr[direct] << " (never_direct to be checked)");
45e5102d 475 /** check never_direct; */
d4806c91 476 ACLFilledChecklist *ch = new ACLFilledChecklist(Config.accessList.NeverDirect, request, NULL);
cb835136
AR
477 ch->al = al;
478 acl_checklist = ch;
cb365059 479 acl_checklist->syncAle(request, nullptr);
cb835136 480 acl_checklist->nonBlockingCheck(CheckNeverDirectDone, this);
62e76326 481 return;
450fe1cb 482 } else if (request->flags.noDirect) {
45e5102d 483 /** if we are accelerating, direct is not an option. */
cb835136
AR
484 direct = DIRECT_NO;
485 debugs(44, 3, "direct = " << DirectStr[direct] << " (forced non-direct)");
450fe1cb 486 } else if (request->flags.loopDetected) {
45e5102d 487 /** if we are in a forwarding-loop, direct is not an option. */
cb835136
AR
488 direct = DIRECT_YES;
489 debugs(44, 3, "direct = " << DirectStr[direct] << " (forwarding loop detected)");
490 } else if (checkNetdbDirect()) {
491 direct = DIRECT_YES;
492 debugs(44, 3, "direct = " << DirectStr[direct] << " (checkNetdbDirect)");
62e76326 493 } else {
cb835136
AR
494 direct = DIRECT_MAYBE;
495 debugs(44, 3, "direct = " << DirectStr[direct] << " (default)");
62e76326 496 }
497
cb835136 498 debugs(44, 3, "direct = " << DirectStr[direct]);
db1cd23c 499 }
62e76326 500
d67acb4e 501 if (!entry || entry->ping_status == PING_NONE)
cb835136 502 selectPinned();
df503d6c 503 if (entry == NULL) {
62e76326 504 (void) 0;
df503d6c 505 } else if (entry->ping_status == PING_NONE) {
cb835136 506 selectSomeNeighbor();
62e76326 507
508 if (entry->ping_status == PING_WAITING)
509 return;
db1cd23c 510 } else if (entry->ping_status == PING_WAITING) {
cb835136 511 selectSomeNeighborReplies();
62e76326 512 entry->ping_status = PING_DONE;
db1cd23c 513 }
62e76326 514
cb835136 515 switch (direct) {
62e76326 516
168dfda9 517 case DIRECT_YES:
cb835136 518 selectSomeDirect();
62e76326 519 break;
520
168dfda9 521 case DIRECT_NO:
cb835136
AR
522 selectSomeParent();
523 selectAllParents();
62e76326 524 break;
525
168dfda9 526 default:
62e76326 527
528 if (Config.onoff.prefer_direct)
cb835136 529 selectSomeDirect();
62e76326 530
45e5102d 531 if (request->flags.hierarchical || !Config.onoff.nonhierarchical_direct) {
cb835136
AR
532 selectSomeParent();
533 selectAllParents();
8b9a89c9 534 }
62e76326 535
536 if (!Config.onoff.prefer_direct)
cb835136 537 selectSomeDirect();
62e76326 538
539 break;
168dfda9 540 }
62e76326 541
cb835136
AR
542 // end peer selection; start resolving selected peers
543 resolveSelected();
db1cd23c 544}
545
cb365059 546bool peerAllowedToUse(const CachePeer *, PeerSelector*);
cfd66529 547
cb835136
AR
548/// Selects a pinned connection if it exists, is valid, and is allowed.
549void
550PeerSelector::selectPinned()
d67acb4e 551{
cb835136 552 // TODO: Avoid all repeated calls. Relying on PING_DONE is not enough.
d67acb4e
AJ
553 if (!request->pinnedConnection())
554 return;
a3c6762c 555 CachePeer *pear = request->pinnedConnection()->pinnedPeer();
e3a4aecc 556 if (Comm::IsConnOpen(request->pinnedConnection()->validatePinnedConnection(request, pear))) {
cb365059 557 const bool usePinned = pear ? peerAllowedToUse(pear, this) : (direct != DIRECT_NO);
cb835136
AR
558 if (usePinned) {
559 addSelection(pear, PINNED);
560 if (entry)
561 entry->ping_status = PING_DONE; // skip ICP
d67acb4e
AJ
562 }
563 }
cb835136
AR
564 // If the pinned connection is prohibited (for this request) or gone, then
565 // the initiator must decide whether it is OK to open a new one instead.
d67acb4e
AJ
566}
567
27774cee 568/**
db1cd23c 569 * Selects a neighbor (parent or sibling) based on one of the
570 * following methods:
571 * Cache Digests
572 * CARP
9b5c4a9a 573 * ICMP Netdb RTT estimates
db1cd23c 574 * ICP/HTCP queries
575 */
cb835136
AR
576void
577PeerSelector::selectSomeNeighbor()
db1cd23c 578{
a3c6762c 579 CachePeer *p;
db1cd23c 580 hier_code code = HIER_NONE;
581 assert(entry->ping_status == PING_NONE);
62e76326 582
cb835136 583 if (direct == DIRECT_YES) {
62e76326 584 entry->ping_status = PING_DONE;
585 return;
124511e5 586 }
62e76326 587
6cfa8966 588#if USE_CACHE_DIGESTS
cb365059 589 if ((p = neighborsDigestSelect(this))) {
5c51bffb 590 if (neighborType(p, request->url) == PEER_PARENT)
62e76326 591 code = CD_PARENT_HIT;
592 else
593 code = CD_SIBLING_HIT;
db1cd23c 594 } else
c127134a 595#endif
cb365059 596 if ((p = netdbClosestParent(this))) {
62e76326 597 code = CLOSEST_PARENT;
cb365059 598 } else if (peerSelectIcpPing(this, direct, entry)) {
cb835136
AR
599 debugs(44, 3, "Doing ICP pings");
600 ping.start = current_time;
601 ping.n_sent = neighborsUdpPing(request,
602 entry,
603 HandlePingReply,
604 this,
605 &ping.n_replies_expected,
606 &ping.timeout);
607
608 if (ping.n_sent == 0)
fa84c01d 609 debugs(44, DBG_CRITICAL, "WARNING: neighborsUdpPing returned 0");
cb835136
AR
610 debugs(44, 3, ping.n_replies_expected <<
611 " ICP replies expected, RTT " << ping.timeout <<
26ac0430 612 " msec");
62e76326 613
cb835136 614 if (ping.n_replies_expected > 0) {
62e76326 615 entry->ping_status = PING_WAITING;
cb835136
AR
616 eventAdd("PeerSelector::HandlePingTimeout",
617 HandlePingTimeout,
618 this,
619 0.001 * ping.timeout,
62e76326 620 0);
621 return;
622 }
623 }
624
db1cd23c 625 if (code != HIER_NONE) {
62e76326 626 assert(p);
cb835136 627 addSelection(p, code);
db1cd23c 628 }
62e76326 629
db1cd23c 630 entry->ping_status = PING_DONE;
631}
632
cb835136
AR
633/// Selects a neighbor (parent or sibling) based on ICP/HTCP replies.
634void
635PeerSelector::selectSomeNeighborReplies()
db1cd23c 636{
a3c6762c 637 CachePeer *p = NULL;
db1cd23c 638 hier_code code = HIER_NONE;
cb835136
AR
639 assert(entry->ping_status == PING_WAITING);
640 assert(direct != DIRECT_YES);
62e76326 641
cb835136 642 if (checkNetdbDirect()) {
62e76326 643 code = CLOSEST_DIRECT;
cb835136 644 addSelection(nullptr, code);
62e76326 645 return;
db1cd23c 646 }
62e76326 647
cb835136
AR
648 if ((p = hit)) {
649 code = hit_type == PEER_PARENT ? PARENT_HIT : SIBLING_HIT;
26ac0430 650 } else {
cb835136
AR
651 if (!closest_parent_miss.isAnyAddr()) {
652 p = whichPeer(closest_parent_miss);
cc192b50 653 code = CLOSEST_PARENT_MISS;
cb835136
AR
654 } else if (!first_parent_miss.isAnyAddr()) {
655 p = whichPeer(first_parent_miss);
cc192b50 656 code = FIRST_PARENT_MISS;
657 }
658 }
db1cd23c 659 if (p && code != HIER_NONE) {
cb835136 660 addSelection(p, code);
db1cd23c 661 }
662}
663
cb835136
AR
664/// Adds a "direct" entry if the request can be forwarded to the origin server.
665void
666PeerSelector::selectSomeDirect()
db1cd23c 667{
cb835136 668 if (direct == DIRECT_NO)
62e76326 669 return;
670
db80e881 671 /* WAIS is not implemented natively */
cb835136 672 if (request->url.getScheme() == AnyP::PROTO_WAIS)
26ac0430 673 return;
db80e881 674
cb835136 675 addSelection(nullptr, HIER_DIRECT);
db1cd23c 676}
677
cb835136
AR
678void
679PeerSelector::selectSomeParent()
db1cd23c 680{
a3c6762c 681 CachePeer *p;
db1cd23c 682 hier_code code = HIER_NONE;
5c51bffb 683 debugs(44, 3, request->method << ' ' << request->url.host());
62e76326 684
cb835136 685 if (direct == DIRECT_YES)
62e76326 686 return;
687
cb365059 688 if ((p = peerSourceHashSelectParent(this))) {
b4ab8666 689 code = SOURCEHASH_PARENT;
2f1431ea 690#if USE_AUTH
cb365059 691 } else if ((p = peerUserHashSelectParent(this))) {
f7e1d9ce 692 code = USERHASH_PARENT;
2f1431ea 693#endif
cb365059 694 } else if ((p = carpSelectParent(this))) {
62e76326 695 code = CARP;
cb365059 696 } else if ((p = getRoundRobinParent(this))) {
62e76326 697 code = ROUNDROBIN_PARENT;
cb365059 698 } else if ((p = getWeightedRoundRobinParent(this))) {
62e76326 699 code = ROUNDROBIN_PARENT;
cb365059 700 } else if ((p = getFirstUpParent(this))) {
62e76326 701 code = FIRSTUP_PARENT;
cb365059 702 } else if ((p = getDefaultParent(this))) {
b4ab8666 703 code = DEFAULT_PARENT;
db1cd23c 704 }
62e76326 705
db1cd23c 706 if (code != HIER_NONE) {
cb835136 707 addSelection(p, code);
062e2281 708 }
709}
710
cb835136
AR
711/// Adds alive parents. Used as a last resort for never_direct.
712void
713PeerSelector::selectAllParents()
168dfda9 714{
a3c6762c 715 CachePeer *p;
168dfda9 716 /* Add all alive parents */
62e76326 717
168dfda9 718 for (p = Config.peers; p; p = p->next) {
62e76326 719 /* XXX: neighbors.c lacks a public interface for enumerating
720 * parents to a request so we have to dig some here..
721 */
722
5c51bffb 723 if (neighborType(p, request->url) != PEER_PARENT)
62e76326 724 continue;
725
cb365059 726 if (!peerHTTPOkay(p, this))
62e76326 727 continue;
728
cb835136 729 addSelection(p, ANY_OLD_PARENT);
168dfda9 730 }
62e76326 731
168dfda9 732 /* XXX: should add dead parents here, but it is currently
733 * not possible to find out which parents are dead or which
734 * simply are not configured to handle the request.
735 */
736 /* Add default parent as a last resort */
cb365059 737 if ((p = getDefaultParent(this))) {
cb835136 738 addSelection(p, DEFAULT_PARENT);
168dfda9 739 }
740}
741
cb835136
AR
742void
743PeerSelector::handlePingTimeout()
062e2281 744{
cb835136 745 debugs(44, 3, url());
62e76326 746
cb835136 747 if (entry)
6043e368
AR
748 entry->ping_status = PING_DONE;
749
cb835136 750 if (selectionAborted())
62e76326 751 return;
62e76326 752
5db6bf73 753 ++PeerStats.timeouts;
cb835136
AR
754 ping.timedout = 1;
755 selectMore();
756}
757
758void
759PeerSelector::HandlePingTimeout(void *data)
760{
761 static_cast<PeerSelector*>(data)->handlePingTimeout();
85034133 762}
763
764void
765peerSelectInit(void)
766{
75e88d56 767 memset(&PeerStats, '\0', sizeof(PeerStats));
062e2281 768}
93775f90 769
cb835136
AR
770void
771PeerSelector::handleIcpParentMiss(CachePeer *p, icp_common_t *header)
b3264694 772{
773 int rtt;
62e76326 774
9b5c4a9a 775#if USE_ICMP
b3264694 776 if (Config.onoff.query_icmp) {
62e76326 777 if (header->flags & ICP_FLAG_SRC_RTT) {
778 rtt = header->pad & 0xFFFF;
9b5c4a9a 779 int hops = (header->pad >> 16) & 0xFFFF;
62e76326 780
781 if (rtt > 0 && rtt < 0xFFFF)
cb835136 782 netdbUpdatePeer(request->url, p, rtt, hops);
62e76326 783
cb835136
AR
784 if (rtt && (ping.p_rtt == 0 || rtt < ping.p_rtt)) {
785 closest_parent_miss = p->in_addr;
786 ping.p_rtt = rtt;
62e76326 787 }
788 }
b3264694 789 }
9b5c4a9a 790#endif /* USE_ICMP */
62e76326 791
18ec72b2 792 /* if closest-only is set, then don't allow FIRST_PARENT_MISS */
cd196bc8 793 if (p->options.closest_only)
62e76326 794 return;
795
85223cd7 796 /* set FIRST_MISS if there is no CLOSEST parent */
cb835136 797 if (!closest_parent_miss.isAnyAddr())
62e76326 798 return;
799
cb835136 800 rtt = (tvSubMsec(ping.start, current_time) - p->basetime) / p->weight;
62e76326 801
d1b63fc8 802 if (rtt < 1)
62e76326 803 rtt = 1;
804
cb835136
AR
805 if (first_parent_miss.isAnyAddr() || rtt < ping.w_rtt) {
806 first_parent_miss = p->in_addr;
807 ping.w_rtt = rtt;
b3264694 808 }
809}
93775f90 810
cb835136
AR
811void
812PeerSelector::handleIcpReply(CachePeer *p, const peer_t type, icp_common_t *header)
93775f90 813{
e6ccf245 814 icp_opcode op = header->getOpCode();
cb835136 815 debugs(44, 3, icp_opcode_str[op] << ' ' << url());
69c95dd3 816#if USE_CACHE_DIGESTS && 0
26b164ac 817 /* do cd lookup to count false misses */
62e76326 818
3ab66981 819 if (p && request)
62e76326 820 peerNoteDigestLookup(request, p,
cb365059 821 peerDigestLookup(p, this));
62e76326 822
26b164ac 823#endif
62e76326 824
cb835136 825 ++ping.n_recv;
62e76326 826
27cd7235 827 if (op == ICP_MISS || op == ICP_DECHO) {
62e76326 828 if (type == PEER_PARENT)
cb835136 829 handleIcpParentMiss(p, header);
a7c05555 830 } else if (op == ICP_HIT) {
cb835136
AR
831 hit = p;
832 hit_type = type;
833 selectMore();
62e76326 834 return;
db1cd23c 835 }
62e76326 836
cb835136 837 if (ping.n_recv < ping.n_replies_expected)
62e76326 838 return;
839
cb835136 840 selectMore();
93775f90 841}
86aebcda 842
843#if USE_HTCP
cb835136
AR
844void
845PeerSelector::handleHtcpReply(CachePeer *p, const peer_t type, HtcpReplyData *htcp)
86aebcda 846{
cb835136
AR
847 debugs(44, 3, (htcp->hit ? "HIT" : "MISS") << ' ' << url());
848 ++ping.n_recv;
62e76326 849
44e237d0 850 if (htcp->hit) {
cb835136
AR
851 hit = p;
852 hit_type = type;
853 selectMore();
62e76326 854 return;
44e237d0 855 }
62e76326 856
44e237d0 857 if (type == PEER_PARENT)
cb835136 858 handleHtcpParentMiss(p, htcp);
62e76326 859
cb835136 860 if (ping.n_recv < ping.n_replies_expected)
62e76326 861 return;
862
cb835136 863 selectMore();
44e237d0 864}
865
cb835136
AR
866void
867PeerSelector::handleHtcpParentMiss(CachePeer *p, HtcpReplyData *htcp)
44e237d0 868{
869 int rtt;
62e76326 870
9b5c4a9a 871#if USE_ICMP
44e237d0 872 if (Config.onoff.query_icmp) {
62e76326 873 if (htcp->cto.rtt > 0) {
874 rtt = (int) htcp->cto.rtt * 1000;
9b5c4a9a 875 int hops = (int) htcp->cto.hops * 1000;
cb835136 876 netdbUpdatePeer(request->url, p, rtt, hops);
62e76326 877
cb835136
AR
878 if (rtt && (ping.p_rtt == 0 || rtt < ping.p_rtt)) {
879 closest_parent_miss = p->in_addr;
880 ping.p_rtt = rtt;
62e76326 881 }
882 }
44e237d0 883 }
9b5c4a9a 884#endif /* USE_ICMP */
62e76326 885
44e237d0 886 /* if closest-only is set, then don't allow FIRST_PARENT_MISS */
cd196bc8 887 if (p->options.closest_only)
62e76326 888 return;
889
44e237d0 890 /* set FIRST_MISS if there is no CLOSEST parent */
cb835136 891 if (!closest_parent_miss.isAnyAddr())
62e76326 892 return;
893
cb835136 894 rtt = (tvSubMsec(ping.start, current_time) - p->basetime) / p->weight;
62e76326 895
d1b63fc8 896 if (rtt < 1)
62e76326 897 rtt = 1;
898
cb835136
AR
899 if (first_parent_miss.isAnyAddr() || rtt < ping.w_rtt) {
900 first_parent_miss = p->in_addr;
901 ping.w_rtt = rtt;
44e237d0 902 }
86aebcda 903}
62e76326 904
86aebcda 905#endif
906
cb835136
AR
907void
908PeerSelector::HandlePingReply(CachePeer * p, peer_t type, AnyP::ProtocolType proto, void *pingdata, void *data)
86aebcda 909{
0c3d3f65 910 if (proto == AnyP::PROTO_ICP)
cb835136 911 static_cast<PeerSelector*>(data)->handleIcpReply(p, type, static_cast<icp_common_t*>(pingdata));
62e76326 912
86aebcda 913#if USE_HTCP
62e76326 914
0c3d3f65 915 else if (proto == AnyP::PROTO_HTCP)
cb835136 916 static_cast<PeerSelector*>(data)->handleHtcpReply(p, type, static_cast<HtcpReplyData*>(pingdata));
62e76326 917
86aebcda 918#endif
62e76326 919
86aebcda 920 else
cb835136 921 debugs(44, DBG_IMPORTANT, "ERROR: ignoring an ICP reply with unknown protocol " << proto);
86aebcda 922}
db1cd23c 923
cb835136
AR
924void
925PeerSelector::addSelection(CachePeer *peer, const hier_code code)
db1cd23c 926{
e7b08eec 927 // Find the end of the servers list. Bail on a duplicate destination.
cb835136
AR
928 auto **serversTail = &servers;
929 while (const auto server = *serversTail) {
e7b08eec
AR
930 // There can be at most one PINNED destination.
931 // Non-PINNED destinations are uniquely identified by their CachePeer
932 // (even though a DIRECT destination might match a cache_peer address).
933 const bool duplicate = (server->code == PINNED) ?
cb835136 934 (code == PINNED) : (server->_peer == peer);
e7b08eec 935 if (duplicate) {
cb835136
AR
936 debugs(44, 3, "skipping " << PeerSelectionDumper(this, peer, code) <<
937 "; have " << PeerSelectionDumper(this, server->_peer.get(), server->code));
e7b08eec
AR
938 return;
939 }
cb835136 940 serversTail = &server->next;
e7b08eec 941 }
62e76326 942
cb835136
AR
943 debugs(44, 3, "adding " << PeerSelectionDumper(this, peer, code));
944 *serversTail = new FwdServer(peer, code);
db1cd23c 945}
b24880fe 946
cb835136 947PeerSelector::PeerSelector(PeerSelectionInitiator *initiator):
6043e368 948 request(nullptr),
f53969cc
SM
949 entry (NULL),
950 always_direct(Config.accessList.AlwaysDirect?ACCESS_DUNNO:ACCESS_DENIED),
951 never_direct(Config.accessList.NeverDirect?ACCESS_DUNNO:ACCESS_DENIED),
952 direct(DIRECT_UNKNOWN),
f53969cc
SM
953 lastError(NULL),
954 servers (NULL),
955 first_parent_miss(),
956 closest_parent_miss(),
957 hit(NULL),
958 hit_type(PEER_NONE),
6043e368
AR
959 acl_checklist (NULL),
960 initiator_(initiator)
b24880fe 961{
cc192b50 962 ; // no local defaults.
b24880fe 963}
964
851feda6 965const SBuf
cb835136 966PeerSelector::url() const
769c64cc
AJ
967{
968 if (entry)
851feda6 969 return SBuf(entry->url());
769c64cc
AJ
970
971 if (request)
851feda6 972 return request->effectiveRequestUri();
769c64cc 973
851feda6
AJ
974 static const SBuf noUrl("[no URL]");
975 return noUrl;
769c64cc
AJ
976}
977
6043e368
AR
978/// \returns valid/interested peer initiator or nil
979PeerSelectionInitiator *
cb835136 980PeerSelector::interestedInitiator()
6043e368
AR
981{
982 const auto initiator = initiator_.valid();
983
984 if (!initiator) {
985 debugs(44, 3, id << " initiator gone");
986 return nullptr;
987 }
988
989 if (!initiator->subscribed) {
990 debugs(44, 3, id << " initiator lost interest");
991 return nullptr;
992 }
993
fd9c47d1 994 debugs(44, 7, id);
6043e368
AR
995 return initiator;
996}
997
998bool
cb835136 999PeerSelector::wantsMoreDestinations() const {
6043e368
AR
1000 const auto maxCount = Config.forward_max_tries;
1001 return maxCount >= 0 && foundPaths <
d22511f9 1002 static_cast<std::make_unsigned<decltype(maxCount)>::type>(maxCount);
6043e368
AR
1003}
1004
1005void
cb835136 1006PeerSelector::handlePath(Comm::ConnectionPointer &path, FwdServer &fs)
6043e368
AR
1007{
1008 ++foundPaths;
1009
1010 path->peerType = fs.code;
1011 path->setPeer(fs._peer.get());
1012
1013 // check for a configured outgoing address for this destination...
1014 getOutgoingAddress(request, path);
1015
1016 request->hier.ping = ping; // may be updated later
1017
1018 debugs(44, 2, id << " found " << path << ", destination #" << foundPaths << " for " << url());
1019 debugs(44, 2, " always_direct = " << always_direct);
1020 debugs(44, 2, " never_direct = " << never_direct);
1021 debugs(44, 2, " timedout = " << ping.timedout);
1022
1023 if (const auto initiator = interestedInitiator())
1024 initiator->noteDestination(path);
1025}
1026
cb835136 1027InstanceIdDefinitions(PeerSelector, "PeerSelector");
6043e368 1028
b24880fe 1029ping_data::ping_data() :
f53969cc
SM
1030 n_sent(0),
1031 n_recv(0),
1032 n_replies_expected(0),
1033 timeout(0),
1034 timedout(0),
1035 w_rtt(0),
1036 p_rtt(0)
b24880fe 1037{
1038 start.tv_sec = 0;
1039 start.tv_usec = 0;
1040 stop.tv_sec = 0;
1041 stop.tv_usec = 0;
1042}
f53969cc 1043