Switch.hpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 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. #ifndef ZT_N_SWITCH_HPP
  19. #define ZT_N_SWITCH_HPP
  20. #include <map>
  21. #include <set>
  22. #include <vector>
  23. #include <list>
  24. #include "Constants.hpp"
  25. #include "Mutex.hpp"
  26. #include "MAC.hpp"
  27. #include "NonCopyable.hpp"
  28. #include "Packet.hpp"
  29. #include "Utils.hpp"
  30. #include "InetAddress.hpp"
  31. #include "Topology.hpp"
  32. #include "Array.hpp"
  33. #include "Network.hpp"
  34. #include "SharedPtr.hpp"
  35. #include "IncomingPacket.hpp"
  36. #include "Hashtable.hpp"
  37. namespace ZeroTier {
  38. class RuntimeEnvironment;
  39. class Peer;
  40. /**
  41. * Core of the distributed Ethernet switch and protocol implementation
  42. *
  43. * This class is perhaps a bit misnamed, but it's basically where everything
  44. * meets. Transport-layer ZT packets come in here, as do virtual network
  45. * packets from tap devices, and this sends them where they need to go and
  46. * wraps/unwraps accordingly. It also handles queues and timeouts and such.
  47. */
  48. class Switch : NonCopyable
  49. {
  50. public:
  51. Switch(const RuntimeEnvironment *renv);
  52. ~Switch();
  53. /**
  54. * Called when a packet is received from the real network
  55. *
  56. * @param localAddr Local interface address
  57. * @param fromAddr Internet IP address of origin
  58. * @param data Packet data
  59. * @param len Packet length
  60. */
  61. void onRemotePacket(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len);
  62. /**
  63. * Called when a packet comes from a local Ethernet tap
  64. *
  65. * @param network Which network's TAP did this packet come from?
  66. * @param from Originating MAC address
  67. * @param to Destination MAC address
  68. * @param etherType Ethernet packet type
  69. * @param vlanId VLAN ID or 0 if none
  70. * @param data Ethernet payload
  71. * @param len Frame length
  72. */
  73. void onLocalEthernet(const SharedPtr<Network> &network,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  74. /**
  75. * Send a packet to a ZeroTier address (destination in packet)
  76. *
  77. * The packet must be fully composed with source and destination but not
  78. * yet encrypted. If the destination peer is known the packet
  79. * is sent immediately. Otherwise it is queued and a WHOIS is dispatched.
  80. *
  81. * The packet may be compressed. Compression isn't done here.
  82. *
  83. * Needless to say, the packet's source must be this node. Otherwise it
  84. * won't be encrypted right. (This is not used for relaying.)
  85. *
  86. * The network ID should only be specified for frames and other actual
  87. * network traffic. Other traffic such as controller requests and regular
  88. * protocol messages should specify zero.
  89. *
  90. * @param packet Packet to send
  91. * @param encrypt Encrypt packet payload? (always true except for HELLO)
  92. * @param nwid Related network ID or 0 if message is not in-network traffic
  93. */
  94. void send(const Packet &packet,bool encrypt,uint64_t nwid);
  95. /**
  96. * Send RENDEZVOUS to two peers to permit them to directly connect
  97. *
  98. * This only works if both peers are known, with known working direct
  99. * links to this peer. The best link for each peer is sent to the other.
  100. *
  101. * @param p1 One of two peers (order doesn't matter)
  102. * @param p2 Second of pair
  103. */
  104. bool unite(const Address &p1,const Address &p2);
  105. /**
  106. * Attempt NAT traversal to peer at a given physical address
  107. *
  108. * @param peer Peer to contact
  109. * @param localAddr Local interface address
  110. * @param atAddr Address of peer
  111. */
  112. void rendezvous(const SharedPtr<Peer> &peer,const InetAddress &localAddr,const InetAddress &atAddr);
  113. /**
  114. * Request WHOIS on a given address
  115. *
  116. * @param addr Address to look up
  117. */
  118. void requestWhois(const Address &addr);
  119. /**
  120. * Run any processes that are waiting for this peer's identity
  121. *
  122. * Called when we learn of a peer's identity from HELLO, OK(WHOIS), etc.
  123. *
  124. * @param peer New peer
  125. */
  126. void doAnythingWaitingForPeer(const SharedPtr<Peer> &peer);
  127. /**
  128. * Perform retries and other periodic timer tasks
  129. *
  130. * This can return a very long delay if there are no pending timer
  131. * tasks. The caller should cap this comparatively vs. other values.
  132. *
  133. * @param now Current time
  134. * @return Number of milliseconds until doTimerTasks() should be run again
  135. */
  136. unsigned long doTimerTasks(uint64_t now);
  137. private:
  138. Address _sendWhoisRequest(const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted);
  139. bool _trySend(const Packet &packet,bool encrypt,uint64_t nwid);
  140. const RuntimeEnvironment *const RR;
  141. uint64_t _lastBeaconResponse;
  142. // Outstanding WHOIS requests and how many retries they've undergone
  143. struct WhoisRequest
  144. {
  145. WhoisRequest() : lastSent(0),retries(0) {}
  146. uint64_t lastSent;
  147. Address peersConsulted[ZT_MAX_WHOIS_RETRIES]; // by retry
  148. unsigned int retries; // 0..ZT_MAX_WHOIS_RETRIES
  149. };
  150. Hashtable< Address,WhoisRequest > _outstandingWhoisRequests;
  151. Mutex _outstandingWhoisRequests_m;
  152. // Packets waiting for WHOIS replies or other decode info or missing fragments
  153. struct RXQueueEntry
  154. {
  155. RXQueueEntry() : timestamp(0) {}
  156. uint64_t timestamp; // 0 if entry is not in use
  157. uint64_t packetId;
  158. IncomingPacket frag0; // head of packet
  159. Packet::Fragment frags[ZT_MAX_PACKET_FRAGMENTS - 1]; // later fragments (if any)
  160. unsigned int totalFragments; // 0 if only frag0 received, waiting for frags
  161. uint32_t haveFragments; // bit mask, LSB to MSB
  162. bool complete; // if true, packet is complete
  163. };
  164. RXQueueEntry _rxQueue[ZT_RX_QUEUE_SIZE];
  165. Mutex _rxQueue_m;
  166. /* Returns the matching or oldest entry. Caller must check timestamp and
  167. * packet ID to determine which. */
  168. inline RXQueueEntry *_findRXQueueEntry(uint64_t now,uint64_t packetId)
  169. {
  170. RXQueueEntry *rq;
  171. RXQueueEntry *oldest = &(_rxQueue[ZT_RX_QUEUE_SIZE - 1]);
  172. unsigned long i = ZT_RX_QUEUE_SIZE;
  173. while (i) {
  174. rq = &(_rxQueue[--i]);
  175. if ((rq->packetId == packetId)&&(rq->timestamp))
  176. return rq;
  177. if ((now - rq->timestamp) >= ZT_RX_QUEUE_EXPIRE)
  178. rq->timestamp = 0;
  179. if (rq->timestamp < oldest->timestamp)
  180. oldest = rq;
  181. }
  182. return oldest;
  183. }
  184. // ZeroTier-layer TX queue entry
  185. struct TXQueueEntry
  186. {
  187. TXQueueEntry() {}
  188. TXQueueEntry(Address d,uint64_t ct,const Packet &p,bool enc,uint64_t nw) :
  189. dest(d),
  190. creationTime(ct),
  191. nwid(nw),
  192. packet(p),
  193. encrypt(enc) {}
  194. Address dest;
  195. uint64_t creationTime;
  196. uint64_t nwid;
  197. Packet packet; // unencrypted/unMAC'd packet -- this is done at send time
  198. bool encrypt;
  199. };
  200. std::list< TXQueueEntry > _txQueue;
  201. Mutex _txQueue_m;
  202. // Tracks sending of VERB_RENDEZVOUS to relaying peers
  203. struct _LastUniteKey
  204. {
  205. _LastUniteKey() : x(0),y(0) {}
  206. _LastUniteKey(const Address &a1,const Address &a2)
  207. {
  208. if (a1 > a2) {
  209. x = a2.toInt();
  210. y = a1.toInt();
  211. } else {
  212. x = a1.toInt();
  213. y = a2.toInt();
  214. }
  215. }
  216. inline unsigned long hashCode() const throw() { return ((unsigned long)x ^ (unsigned long)y); }
  217. inline bool operator==(const _LastUniteKey &k) const throw() { return ((x == k.x)&&(y == k.y)); }
  218. uint64_t x,y;
  219. };
  220. Hashtable< _LastUniteKey,uint64_t > _lastUniteAttempt; // key is always sorted in ascending order, for set-like behavior
  221. Mutex _lastUniteAttempt_m;
  222. // Active attempts to contact remote peers, including state of multi-phase NAT traversal
  223. struct ContactQueueEntry
  224. {
  225. ContactQueueEntry() {}
  226. ContactQueueEntry(const SharedPtr<Peer> &p,uint64_t ft,const InetAddress &laddr,const InetAddress &a) :
  227. peer(p),
  228. fireAtTime(ft),
  229. inaddr(a),
  230. localAddr(laddr),
  231. strategyIteration(0) {}
  232. SharedPtr<Peer> peer;
  233. uint64_t fireAtTime;
  234. InetAddress inaddr;
  235. InetAddress localAddr;
  236. unsigned int strategyIteration;
  237. };
  238. std::list<ContactQueueEntry> _contactQueue;
  239. Mutex _contactQueue_m;
  240. };
  241. } // namespace ZeroTier
  242. #endif