Path.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifndef ZT_PATH_HPP
  27. #define ZT_PATH_HPP
  28. #include <stdint.h>
  29. #include <string.h>
  30. #include <stdlib.h>
  31. #include <stdexcept>
  32. #include <algorithm>
  33. #include "Constants.hpp"
  34. #include "InetAddress.hpp"
  35. #include "SharedPtr.hpp"
  36. #include "AtomicCounter.hpp"
  37. #include "Utils.hpp"
  38. #include "RingBuffer.hpp"
  39. #include "../osdep/Phy.hpp"
  40. /**
  41. * Maximum return value of preferenceRank()
  42. */
  43. #define ZT_PATH_MAX_PREFERENCE_RANK ((ZT_INETADDRESS_MAX_SCOPE << 1) | 1)
  44. namespace ZeroTier {
  45. class RuntimeEnvironment;
  46. /**
  47. * A path across the physical network
  48. */
  49. class Path
  50. {
  51. friend class SharedPtr<Path>;
  52. Phy<Path *> *_phy;
  53. public:
  54. /**
  55. * Efficient unique key for paths in a Hashtable
  56. */
  57. class HashKey
  58. {
  59. public:
  60. HashKey() {}
  61. HashKey(const int64_t l,const InetAddress &r)
  62. {
  63. if (r.ss_family == AF_INET) {
  64. _k[0] = (uint64_t)reinterpret_cast<const struct sockaddr_in *>(&r)->sin_addr.s_addr;
  65. _k[1] = (uint64_t)reinterpret_cast<const struct sockaddr_in *>(&r)->sin_port;
  66. _k[2] = (uint64_t)l;
  67. } else if (r.ss_family == AF_INET6) {
  68. ZT_FAST_MEMCPY(_k,reinterpret_cast<const struct sockaddr_in6 *>(&r)->sin6_addr.s6_addr,16);
  69. _k[2] = ((uint64_t)reinterpret_cast<const struct sockaddr_in6 *>(&r)->sin6_port << 32) ^ (uint64_t)l;
  70. } else {
  71. ZT_FAST_MEMCPY(_k,&r,std::min(sizeof(_k),sizeof(InetAddress)));
  72. _k[2] += (uint64_t)l;
  73. }
  74. }
  75. inline unsigned long hashCode() const { return (unsigned long)(_k[0] + _k[1] + _k[2]); }
  76. inline bool operator==(const HashKey &k) const { return ( (_k[0] == k._k[0]) && (_k[1] == k._k[1]) && (_k[2] == k._k[2]) ); }
  77. inline bool operator!=(const HashKey &k) const { return (!(*this == k)); }
  78. private:
  79. uint64_t _k[3];
  80. };
  81. Path() :
  82. _lastOut(0),
  83. _lastIn(0),
  84. _lastTrustEstablishedPacketReceived(0),
  85. _lastPathQualityComputeTime(0),
  86. _localSocket(-1),
  87. _latency(0xffff),
  88. _addr(),
  89. _ipScope(InetAddress::IP_SCOPE_NONE),
  90. _currentPacketSampleCounter(0),
  91. _meanPacketErrorRatio(0.0),
  92. _meanLatency(0.0),
  93. _lastLatencyUpdate(0),
  94. _jitter(0.0),
  95. _lastPathQualitySampleTime(0),
  96. _lastComputedQuality(0.0),
  97. _lastPathQualityEstimate(0),
  98. _meanAge(0.0),
  99. _meanThroughput(0.0),
  100. _packetLossRatio(0)
  101. {
  102. memset(_ifname, 0, sizeof(_ifname));
  103. memset(_addrString, 0, sizeof(_addrString));
  104. _throughputSamples = new RingBuffer<uint64_t>(ZT_PATH_QUALITY_METRIC_WIN_SZ);
  105. _ageSamples = new RingBuffer<uint64_t>(ZT_PATH_QUALITY_METRIC_WIN_SZ);
  106. _latencySamples = new RingBuffer<uint32_t>(ZT_PATH_QUALITY_METRIC_WIN_SZ);
  107. _errSamples = new RingBuffer<float>(ZT_PATH_QUALITY_METRIC_WIN_SZ);
  108. }
  109. Path(const int64_t localSocket,const InetAddress &addr) :
  110. _lastOut(0),
  111. _lastIn(0),
  112. _lastTrustEstablishedPacketReceived(0),
  113. _lastPathQualityComputeTime(0),
  114. _localSocket(localSocket),
  115. _latency(0xffff),
  116. _addr(addr),
  117. _ipScope(addr.ipScope()),
  118. _currentPacketSampleCounter(0),
  119. _meanPacketErrorRatio(0.0),
  120. _meanLatency(0.0),
  121. _lastLatencyUpdate(0),
  122. _jitter(0.0),
  123. _lastPathQualitySampleTime(0),
  124. _lastComputedQuality(0.0),
  125. _lastPathQualityEstimate(0),
  126. _meanAge(0.0),
  127. _meanThroughput(0.0),
  128. _packetLossRatio(0)
  129. {
  130. memset(_ifname, 0, sizeof(_ifname));
  131. memset(_addrString, 0, sizeof(_addrString));
  132. _throughputSamples = new RingBuffer<uint64_t>(ZT_PATH_QUALITY_METRIC_WIN_SZ);
  133. _ageSamples = new RingBuffer<uint64_t>(ZT_PATH_QUALITY_METRIC_WIN_SZ);
  134. _latencySamples = new RingBuffer<uint32_t>(ZT_PATH_QUALITY_METRIC_WIN_SZ);
  135. _errSamples = new RingBuffer<float>(ZT_PATH_QUALITY_METRIC_WIN_SZ);
  136. }
  137. ~Path()
  138. {
  139. delete _throughputSamples;
  140. delete _ageSamples;
  141. delete _latencySamples;
  142. delete _errSamples;
  143. _throughputSamples = NULL;
  144. _ageSamples = NULL;
  145. _latencySamples = NULL;
  146. _errSamples = NULL;
  147. }
  148. /**
  149. * Called when a packet is received from this remote path, regardless of content
  150. *
  151. * @param t Time of receive
  152. */
  153. inline void received(const uint64_t t) { _lastIn = t; }
  154. /**
  155. * Set time last trusted packet was received (done in Peer::received())
  156. */
  157. inline void trustedPacketReceived(const uint64_t t) { _lastTrustEstablishedPacketReceived = t; }
  158. /**
  159. * Send a packet via this path (last out time is also updated)
  160. *
  161. * @param RR Runtime environment
  162. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  163. * @param data Packet data
  164. * @param len Packet length
  165. * @param now Current time
  166. * @return True if transport reported success
  167. */
  168. bool send(const RuntimeEnvironment *RR,void *tPtr,const void *data,unsigned int len,int64_t now);
  169. /**
  170. * Manually update last sent time
  171. *
  172. * @param t Time of send
  173. */
  174. inline void sent(const int64_t t) { _lastOut = t; }
  175. /**
  176. * Update path latency with a new measurement
  177. *
  178. * @param l Measured latency
  179. */
  180. inline void updateLatency(const unsigned int l, int64_t now)
  181. {
  182. unsigned int pl = _latency;
  183. if (pl < 0xffff) {
  184. _latency = (pl + l) / 2;
  185. }
  186. else {
  187. _latency = l;
  188. }
  189. _lastLatencyUpdate = now;
  190. _latencySamples->push(l);
  191. }
  192. /**
  193. * @return Local socket as specified by external code
  194. */
  195. inline int64_t localSocket() const { return _localSocket; }
  196. /**
  197. * @return Physical address
  198. */
  199. inline const InetAddress &address() const { return _addr; }
  200. /**
  201. * @return IP scope -- faster shortcut for address().ipScope()
  202. */
  203. inline InetAddress::IpScope ipScope() const { return _ipScope; }
  204. /**
  205. * @return True if path has received a trust established packet (e.g. common network membership) in the past ZT_TRUST_EXPIRATION ms
  206. */
  207. inline bool trustEstablished(const int64_t now) const { return ((now - _lastTrustEstablishedPacketReceived) < ZT_TRUST_EXPIRATION); }
  208. /**
  209. * @return Preference rank, higher == better
  210. */
  211. inline unsigned int preferenceRank() const
  212. {
  213. // This causes us to rank paths in order of IP scope rank (see InetAdddress.hpp) but
  214. // within each IP scope class to prefer IPv6 over IPv4.
  215. return ( ((unsigned int)_ipScope << 1) | (unsigned int)(_addr.ss_family == AF_INET6) );
  216. }
  217. /**
  218. * Check whether this address is valid for a ZeroTier path
  219. *
  220. * This checks the address type and scope against address types and scopes
  221. * that we currently support for ZeroTier communication.
  222. *
  223. * @param a Address to check
  224. * @return True if address is good for ZeroTier path use
  225. */
  226. static inline bool isAddressValidForPath(const InetAddress &a)
  227. {
  228. if ((a.ss_family == AF_INET)||(a.ss_family == AF_INET6)) {
  229. switch(a.ipScope()) {
  230. /* Note: we don't do link-local at the moment. Unfortunately these
  231. * cause several issues. The first is that they usually require a
  232. * device qualifier, which we don't handle yet and can't portably
  233. * push in PUSH_DIRECT_PATHS. The second is that some OSes assign
  234. * these very ephemerally or otherwise strangely. So we'll use
  235. * private, pseudo-private, shared (e.g. carrier grade NAT), or
  236. * global IP addresses. */
  237. case InetAddress::IP_SCOPE_PRIVATE:
  238. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  239. case InetAddress::IP_SCOPE_SHARED:
  240. case InetAddress::IP_SCOPE_GLOBAL:
  241. if (a.ss_family == AF_INET6) {
  242. // TEMPORARY HACK: for now, we are going to blacklist he.net IPv6
  243. // tunnels due to very spotty performance and low MTU issues over
  244. // these IPv6 tunnel links.
  245. const uint8_t *ipd = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_addr.s6_addr);
  246. if ((ipd[0] == 0x20)&&(ipd[1] == 0x01)&&(ipd[2] == 0x04)&&(ipd[3] == 0x70))
  247. return false;
  248. }
  249. return true;
  250. default:
  251. return false;
  252. }
  253. }
  254. return false;
  255. }
  256. /**
  257. * @return Latency or 0xffff if unknown
  258. */
  259. inline unsigned int latency() const { return _latency; }
  260. /**
  261. * @return Path quality -- lower is better
  262. */
  263. inline long quality(const int64_t now) const
  264. {
  265. const int l = (long)_latency;
  266. const int age = (long)std::min((now - _lastIn),(int64_t)(ZT_PATH_HEARTBEAT_PERIOD * 10)); // set an upper sanity limit to avoid overflow
  267. return (((age < (ZT_PATH_HEARTBEAT_PERIOD + 5000)) ? l : (l + 0xffff + age)) * (long)((ZT_INETADDRESS_MAX_SCOPE - _ipScope) + 1));
  268. }
  269. /**
  270. * @return An estimate of path quality -- higher is better.
  271. */
  272. inline float computeQuality(const int64_t now)
  273. {
  274. float latency_contrib = _meanLatency ? (float)1.0 / _meanLatency : 0;
  275. float jitter_contrib = _jitter ? (float)1.0 / _jitter : 0;
  276. float throughput_contrib = _meanThroughput ? _meanThroughput / 1000000 : 0; // in Mbps
  277. float age_contrib = _meanAge > 0 ? (float)sqrt(_meanAge) : 1;
  278. float error_contrib = (float)1.0 - _meanPacketErrorRatio;
  279. float sum = (latency_contrib + jitter_contrib + throughput_contrib + error_contrib) / age_contrib;
  280. _lastComputedQuality = sum * (long)((_ipScope) + 1);
  281. return _lastComputedQuality;
  282. }
  283. /**
  284. * Since quality estimates can become expensive we should cache the most recent result for traffic allocation
  285. * algorithms which may need to reference this value multiple times through the course of their execution.
  286. */
  287. inline float lastComputedQuality() {
  288. return _lastComputedQuality;
  289. }
  290. /**
  291. * @return A pointer to a cached copy of the human-readable name of the interface this Path's localSocket is bound to
  292. */
  293. inline char *getName() { return _ifname; }
  294. /**
  295. * @return Estimated throughput in bps of this link
  296. */
  297. inline uint64_t getThroughput() { return _phy->getThroughput((PhySocket *)((uintptr_t)_localSocket)); }
  298. /**
  299. * @return Packet delay varience
  300. */
  301. inline float jitter() { return _jitter; }
  302. /**
  303. * @return Previously-computed mean latency
  304. */
  305. inline float meanLatency() { return _meanLatency; }
  306. /**
  307. * @return Packet loss rate
  308. */
  309. inline float packetLossRatio() { return _packetLossRatio; }
  310. /**
  311. * @return Mean packet error ratio
  312. */
  313. inline float meanPacketErrorRatio() { return _meanPacketErrorRatio; }
  314. /**
  315. * @return Current packet error ratio (possibly incomplete sample set)
  316. */
  317. inline float currentPacketErrorRatio() {
  318. int errorsPerSample = 0;
  319. for (int i=0; i<_currentPacketSampleCounter; i++) {
  320. if (_packetValidity[i] == false) {
  321. errorsPerSample++;
  322. }
  323. }
  324. return (float)errorsPerSample / (float)ZT_PATH_ERROR_SAMPLE_WIN_SZ;
  325. }
  326. /**
  327. * @return Whether the Path's local socket is in a CLOSED state
  328. */
  329. inline bool isClosed() { return _phy->isClosed((PhySocket *)((uintptr_t)_localSocket)); }
  330. /**
  331. * @return The state of a Path's local socket
  332. */
  333. inline int getState() { return _phy->getState((PhySocket *)((uintptr_t)_localSocket)); }
  334. /**
  335. * @return Whether this socket may have been erased by the virtual physical link layer
  336. */
  337. inline bool isValidState() { return _phy->isValidState((PhySocket *)((uintptr_t)_localSocket)); }
  338. /**
  339. * @return Whether the path quality monitors have collected enough data to provide a quality value
  340. * TODO: expand this
  341. */
  342. inline bool monitorsReady() {
  343. return _latencySamples->count() && _ageSamples->count() && _throughputSamples->count();
  344. }
  345. /**
  346. * @return A pointer to a cached copy of the address string for this Path (For debugging only)
  347. */
  348. inline char *getAddressString() { return _addrString; }
  349. /**
  350. * Handle path sampling, computation of quality estimates, and other periodic tasks
  351. * @param now Current time
  352. */
  353. inline void measureLink(int64_t now) {
  354. // Sample path properties and store them in a continuously-revolving buffer
  355. if (now - _lastPathQualitySampleTime > ZT_PATH_QUALITY_SAMPLE_INTERVAL) {
  356. _lastPathQualitySampleTime = now;
  357. _throughputSamples->push(getThroughput()); // Thoughtput in bits/s
  358. _ageSamples->push(now - _lastIn); // Age (time since last received packet)
  359. if (now - _lastLatencyUpdate > ZT_PATH_LATENCY_SAMPLE_INTERVAL) {
  360. _lastLatencyUpdate = now;
  361. // Record 0 bp/s. Since we're using this to detect possible packet loss
  362. updateLatency(0, now);
  363. }
  364. }
  365. // Compute statistical values for use in link quality estimates
  366. if (now - _lastPathQualityComputeTime > ZT_PATH_QUALITY_COMPUTE_INTERVAL) {
  367. _lastPathQualityComputeTime = now;
  368. // Cache Path address string
  369. address().toString(_addrString);
  370. _phy->getIfName((PhySocket *)((uintptr_t)_localSocket), _ifname, ZT_PATH_INTERFACE_NAME_SZ); // Cache Interface name
  371. // Derived values
  372. if (_throughputSamples->count()) {
  373. _packetLossRatio = (float)_throughputSamples->zeroCount() / (float)_throughputSamples->count();
  374. }
  375. _meanThroughput = _throughputSamples->mean();
  376. _meanAge = _ageSamples->mean();
  377. _meanLatency = _latencySamples->mean();
  378. // Jitter
  379. // SEE: RFC 3393, RFC 4689
  380. _jitter = _latencySamples->stddev();
  381. _meanPacketErrorRatio = _errSamples->mean(); // Packet Error Ratio (PER)
  382. }
  383. // Periodically compute a path quality estimate
  384. if (now - _lastPathQualityEstimate > ZT_PATH_QUALITY_ESTIMATE_INTERVAL) {
  385. computeQuality(now);
  386. }
  387. }
  388. /**
  389. * @param buf Buffer to store resultant string
  390. * @return Description of path, in ASCII string format
  391. */
  392. inline char *toString(char *buf) {
  393. sprintf(buf,"%6s, q=%8.3f, %5.3f Mb/s, j=%8.2f, ml=%8.2f, meanAge=%8.2f, addr=%45s",
  394. getName(),
  395. lastComputedQuality(),
  396. (float)meanThroughput() / (float)1000000,
  397. jitter(),
  398. meanLatency(),
  399. meanAge(),
  400. getAddressString());
  401. return buf;
  402. }
  403. /**
  404. * Record whether a packet is considered invalid by MAC/compression/cipher checks. This
  405. * could be an indication of a bit error. This function will keep a running counter of
  406. * up to a given window size and with each counter overflow it will compute a mean error rate
  407. * and store that in a continuously shifting sample window.
  408. *
  409. * @param isValid Whether the packet in question is considered invalid
  410. */
  411. inline void recordPacket(bool isValid) {
  412. if (_currentPacketSampleCounter < ZT_PATH_ERROR_SAMPLE_WIN_SZ) {
  413. _packetValidity[_currentPacketSampleCounter] = isValid;
  414. _currentPacketSampleCounter++;
  415. }
  416. else {
  417. // Sample array is full, compute an mean and stick it in the ring buffer for trend analysis
  418. _errSamples->push(currentPacketErrorRatio());
  419. _currentPacketSampleCounter=0;
  420. }
  421. }
  422. /**
  423. * @return The mean age (in ms) of this link
  424. */
  425. inline float meanAge() { return _meanAge; }
  426. /**
  427. * @return The mean throughput (in bits/s) of this link
  428. */
  429. inline float meanThroughput() { return _meanThroughput; }
  430. /**
  431. * @return True if this path is alive (receiving heartbeats)
  432. */
  433. inline bool alive(const int64_t now) const { return ((now - _lastIn) < (ZT_PATH_HEARTBEAT_PERIOD + 5000)); }
  434. /**
  435. * @return True if this path hasn't received a packet in a "significant" amount of time
  436. */
  437. inline bool stale(const int64_t now) const { return ((now - _lastIn) > ZT_LINK_SPEED_TEST_INTERVAL * 10); }
  438. /**
  439. * @return True if this path needs a heartbeat
  440. */
  441. inline bool needsHeartbeat(const int64_t now) const { return ((now - _lastOut) >= ZT_PATH_HEARTBEAT_PERIOD); }
  442. /**
  443. * @return Last time we sent something
  444. */
  445. inline int64_t lastOut() const { return _lastOut; }
  446. /**
  447. * @return Last time we received anything
  448. */
  449. inline int64_t lastIn() const { return _lastIn; }
  450. /**
  451. * @return Time last trust-established packet was received
  452. */
  453. inline int64_t lastTrustEstablishedPacketReceived() const { return _lastTrustEstablishedPacketReceived; }
  454. private:
  455. volatile int64_t _lastOut;
  456. volatile int64_t _lastIn;
  457. volatile int64_t _lastTrustEstablishedPacketReceived;
  458. volatile int64_t _lastPathQualityComputeTime;
  459. int64_t _localSocket;
  460. volatile unsigned int _latency;
  461. InetAddress _addr;
  462. InetAddress::IpScope _ipScope; // memoize this since it's a computed value checked often
  463. AtomicCounter __refCount;
  464. // Packet Error Ratio (PER)
  465. int _packetValidity[ZT_PATH_ERROR_SAMPLE_WIN_SZ];
  466. int _currentPacketSampleCounter;
  467. volatile float _meanPacketErrorRatio;
  468. // Latency and Jitter
  469. volatile float _meanLatency;
  470. int64_t _lastLatencyUpdate;
  471. volatile float _jitter;
  472. int64_t _lastPathQualitySampleTime;
  473. float _lastComputedQuality;
  474. int64_t _lastPathQualityEstimate;
  475. float _meanAge;
  476. float _meanThroughput;
  477. // Circular buffers used to efficiently store large time series
  478. RingBuffer<uint64_t> *_throughputSamples;
  479. RingBuffer<uint32_t> *_latencySamples;
  480. RingBuffer<uint64_t> *_ageSamples;
  481. RingBuffer<float> *_errSamples;
  482. float _packetLossRatio;
  483. char _ifname[ZT_PATH_INTERFACE_NAME_SZ];
  484. char _addrString[256];
  485. };
  486. } // namespace ZeroTier
  487. #endif