Switch.hpp 6.7 KB

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