Switch.hpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. * @param packet Packet to send
  87. * @param encrypt Encrypt packet payload? (always true except for HELLO)
  88. */
  89. void send(const Packet &packet,bool encrypt);
  90. /**
  91. * Send RENDEZVOUS to two peers to permit them to directly connect
  92. *
  93. * This only works if both peers are known, with known working direct
  94. * links to this peer. The best link for each peer is sent to the other.
  95. *
  96. * @param p1 One of two peers (order doesn't matter)
  97. * @param p2 Second of pair
  98. */
  99. bool unite(const Address &p1,const Address &p2);
  100. /**
  101. * Request WHOIS on a given address
  102. *
  103. * @param addr Address to look up
  104. */
  105. void requestWhois(const Address &addr);
  106. /**
  107. * Run any processes that are waiting for this peer's identity
  108. *
  109. * Called when we learn of a peer's identity from HELLO, OK(WHOIS), etc.
  110. *
  111. * @param peer New peer
  112. */
  113. void doAnythingWaitingForPeer(const SharedPtr<Peer> &peer);
  114. /**
  115. * Perform retries and other periodic timer tasks
  116. *
  117. * This can return a very long delay if there are no pending timer
  118. * tasks. The caller should cap this comparatively vs. other values.
  119. *
  120. * @param now Current time
  121. * @return Number of milliseconds until doTimerTasks() should be run again
  122. */
  123. unsigned long doTimerTasks(uint64_t now);
  124. private:
  125. Address _sendWhoisRequest(const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted);
  126. bool _trySend(const Packet &packet,bool encrypt);
  127. const RuntimeEnvironment *const RR;
  128. uint64_t _lastBeaconResponse;
  129. // Outstanding WHOIS requests and how many retries they've undergone
  130. struct WhoisRequest
  131. {
  132. WhoisRequest() : lastSent(0),retries(0) {}
  133. uint64_t lastSent;
  134. Address peersConsulted[ZT_MAX_WHOIS_RETRIES]; // by retry
  135. unsigned int retries; // 0..ZT_MAX_WHOIS_RETRIES
  136. };
  137. Hashtable< Address,WhoisRequest > _outstandingWhoisRequests;
  138. Mutex _outstandingWhoisRequests_m;
  139. // Packets waiting for WHOIS replies or other decode info or missing fragments
  140. struct RXQueueEntry
  141. {
  142. RXQueueEntry() : timestamp(0) {}
  143. uint64_t timestamp; // 0 if entry is not in use
  144. uint64_t packetId;
  145. IncomingPacket frag0; // head of packet
  146. Packet::Fragment frags[ZT_MAX_PACKET_FRAGMENTS - 1]; // later fragments (if any)
  147. unsigned int totalFragments; // 0 if only frag0 received, waiting for frags
  148. uint32_t haveFragments; // bit mask, LSB to MSB
  149. bool complete; // if true, packet is complete
  150. };
  151. RXQueueEntry _rxQueue[ZT_RX_QUEUE_SIZE];
  152. Mutex _rxQueue_m;
  153. /* Returns the matching or oldest entry. Caller must check timestamp and
  154. * packet ID to determine which. */
  155. inline RXQueueEntry *_findRXQueueEntry(uint64_t now,uint64_t packetId)
  156. {
  157. RXQueueEntry *rq;
  158. RXQueueEntry *oldest = &(_rxQueue[ZT_RX_QUEUE_SIZE - 1]);
  159. unsigned long i = ZT_RX_QUEUE_SIZE;
  160. while (i) {
  161. rq = &(_rxQueue[--i]);
  162. if ((rq->packetId == packetId)&&(rq->timestamp))
  163. return rq;
  164. if ((now - rq->timestamp) >= ZT_RX_QUEUE_EXPIRE)
  165. rq->timestamp = 0;
  166. if (rq->timestamp < oldest->timestamp)
  167. oldest = rq;
  168. }
  169. return oldest;
  170. }
  171. // ZeroTier-layer TX queue entry
  172. struct TXQueueEntry
  173. {
  174. TXQueueEntry() {}
  175. TXQueueEntry(Address d,uint64_t ct,const Packet &p,bool enc) :
  176. dest(d),
  177. creationTime(ct),
  178. packet(p),
  179. encrypt(enc) {}
  180. Address dest;
  181. uint64_t creationTime;
  182. Packet packet; // unencrypted/unMAC'd packet -- this is done at send time
  183. bool encrypt;
  184. };
  185. std::list< TXQueueEntry > _txQueue;
  186. Mutex _txQueue_m;
  187. // Tracks sending of VERB_RENDEZVOUS to relaying peers
  188. struct _LastUniteKey
  189. {
  190. _LastUniteKey() : x(0),y(0) {}
  191. _LastUniteKey(const Address &a1,const Address &a2)
  192. {
  193. if (a1 > a2) {
  194. x = a2.toInt();
  195. y = a1.toInt();
  196. } else {
  197. x = a1.toInt();
  198. y = a2.toInt();
  199. }
  200. }
  201. inline unsigned long hashCode() const throw() { return ((unsigned long)x ^ (unsigned long)y); }
  202. inline bool operator==(const _LastUniteKey &k) const throw() { return ((x == k.x)&&(y == k.y)); }
  203. uint64_t x,y;
  204. };
  205. Hashtable< _LastUniteKey,uint64_t > _lastUniteAttempt; // key is always sorted in ascending order, for set-like behavior
  206. Mutex _lastUniteAttempt_m;
  207. };
  208. } // namespace ZeroTier
  209. #endif