1 /*
2  * Copyright (c)2013-2020 ZeroTier, Inc.
3  *
4  * Use of this software is governed by the Business Source License included
5  * in the LICENSE.TXT file in the project's root directory.
6  *
7  * Change Date: 2025-01-01
8  *
9  * On the date above, in accordance with the Business Source License, use
10  * of this software will be governed by version 2.0 of the Apache License.
11  */
12 /****/
13 
14 #ifndef ZT_NODE_HPP
15 #define ZT_NODE_HPP
16 
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 
21 #include <map>
22 #include <vector>
23 
24 #include "Constants.hpp"
25 
26 #include "../include/ZeroTierOne.h"
27 
28 #include "RuntimeEnvironment.hpp"
29 #include "InetAddress.hpp"
30 #include "Mutex.hpp"
31 #include "MAC.hpp"
32 #include "Network.hpp"
33 #include "Path.hpp"
34 #include "Salsa20.hpp"
35 #include "NetworkController.hpp"
36 #include "Hashtable.hpp"
37 #include "Bond.hpp"
38 
39 // Bit mask for "expecting reply" hash
40 #define ZT_EXPECTING_REPLIES_BUCKET_MASK1 255
41 #define ZT_EXPECTING_REPLIES_BUCKET_MASK2 31
42 
43 namespace ZeroTier {
44 
45 class World;
46 
47 /**
48  * Implementation of Node object as defined in CAPI
49  *
50  * The pointer returned by ZT_Node_new() is an instance of this class.
51  */
52 class Node : public NetworkController::Sender
53 {
54 public:
55 	Node(void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now);
56 	virtual ~Node();
57 
58 	// Get rid of alignment warnings on 32-bit Windows and possibly improve performance
59 #ifdef __WINDOWS__
operator new(size_t i)60 	void * operator new(size_t i) { return _mm_malloc(i,16); }
operator delete(void * p)61 	void operator delete(void* p) { _mm_free(p); }
62 #endif
63 
64 	// Public API Functions ----------------------------------------------------
65 
66 	ZT_ResultCode processWirePacket(
67 		void *tptr,
68 		int64_t now,
69 		int64_t localSocket,
70 		const struct sockaddr_storage *remoteAddress,
71 		const void *packetData,
72 		unsigned int packetLength,
73 		volatile int64_t *nextBackgroundTaskDeadline);
74 	ZT_ResultCode processVirtualNetworkFrame(
75 		void *tptr,
76 		int64_t now,
77 		uint64_t nwid,
78 		uint64_t sourceMac,
79 		uint64_t destMac,
80 		unsigned int etherType,
81 		unsigned int vlanId,
82 		const void *frameData,
83 		unsigned int frameLength,
84 		volatile int64_t *nextBackgroundTaskDeadline);
85 	ZT_ResultCode processBackgroundTasks(void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline);
86 	ZT_ResultCode join(uint64_t nwid,void *uptr,void *tptr);
87 	ZT_ResultCode leave(uint64_t nwid,void **uptr,void *tptr);
88 	ZT_ResultCode multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
89 	ZT_ResultCode multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
90 	ZT_ResultCode orbit(void *tptr,uint64_t moonWorldId,uint64_t moonSeed);
91 	ZT_ResultCode deorbit(void *tptr,uint64_t moonWorldId);
92 	uint64_t address() const;
93 	void status(ZT_NodeStatus *status) const;
94 	ZT_PeerList *peers() const;
95 	ZT_VirtualNetworkConfig *networkConfig(uint64_t nwid) const;
96 	ZT_VirtualNetworkList *networks() const;
97 	void freeQueryResult(void *qr);
98 	int addLocalInterfaceAddress(const struct sockaddr_storage *addr);
99 	void clearLocalInterfaceAddresses();
100 	int sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len);
101 	void setNetconfMaster(void *networkControllerInstance);
102 
103 	// Internal functions ------------------------------------------------------
104 
now() const105 	inline int64_t now() const { return _now; }
106 
putPacket(void * tPtr,const int64_t localSocket,const InetAddress & addr,const void * data,unsigned int len,unsigned int ttl=0)107 	inline bool putPacket(void *tPtr,const int64_t localSocket,const InetAddress &addr,const void *data,unsigned int len,unsigned int ttl = 0)
108 	{
109 		return (_cb.wirePacketSendFunction(
110 			reinterpret_cast<ZT_Node *>(this),
111 			_uPtr,
112 			tPtr,
113 			localSocket,
114 			reinterpret_cast<const struct sockaddr_storage *>(&addr),
115 			data,
116 			len,
117 			ttl) == 0);
118 	}
119 
putFrame(void * tPtr,uint64_t nwid,void ** nuptr,const MAC & source,const MAC & dest,unsigned int etherType,unsigned int vlanId,const void * data,unsigned int len)120 	inline void putFrame(void *tPtr,uint64_t nwid,void **nuptr,const MAC &source,const MAC &dest,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
121 	{
122 		_cb.virtualNetworkFrameFunction(
123 			reinterpret_cast<ZT_Node *>(this),
124 			_uPtr,
125 			tPtr,
126 			nwid,
127 			nuptr,
128 			source.toInt(),
129 			dest.toInt(),
130 			etherType,
131 			vlanId,
132 			data,
133 			len);
134 	}
135 
network(uint64_t nwid) const136 	inline SharedPtr<Network> network(uint64_t nwid) const
137 	{
138 		Mutex::Lock _l(_networks_m);
139 		const SharedPtr<Network> *n = _networks.get(nwid);
140 		if (n)
141 			return *n;
142 		return SharedPtr<Network>();
143 	}
144 
belongsToNetwork(uint64_t nwid) const145 	inline bool belongsToNetwork(uint64_t nwid) const
146 	{
147 		Mutex::Lock _l(_networks_m);
148 		return _networks.contains(nwid);
149 	}
150 
allNetworks() const151 	inline std::vector< SharedPtr<Network> > allNetworks() const
152 	{
153 		std::vector< SharedPtr<Network> > nw;
154 		Mutex::Lock _l(_networks_m);
155 		Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(*const_cast< Hashtable< uint64_t,SharedPtr<Network> > * >(&_networks));
156 		uint64_t *k = (uint64_t *)0;
157 		SharedPtr<Network> *v = (SharedPtr<Network> *)0;
158 		while (i.next(k,v))
159 			nw.push_back(*v);
160 		return nw;
161 	}
162 
directPaths() const163 	inline std::vector<InetAddress> directPaths() const
164 	{
165 		Mutex::Lock _l(_directPaths_m);
166 		return _directPaths;
167 	}
168 
postEvent(void * tPtr,ZT_Event ev,const void * md=(const void *)0)169 	inline void postEvent(void *tPtr,ZT_Event ev,const void *md = (const void *)0) { _cb.eventCallback(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ev,md); }
170 
configureVirtualNetworkPort(void * tPtr,uint64_t nwid,void ** nuptr,ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig * nc)171 	inline int configureVirtualNetworkPort(void *tPtr,uint64_t nwid,void **nuptr,ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nc) { return _cb.virtualNetworkConfigFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,nwid,nuptr,op,nc); }
172 
online() const173 	inline bool online() const { return _online; }
174 
stateObjectGet(void * const tPtr,ZT_StateObjectType type,const uint64_t id[2],void * const data,const unsigned int maxlen)175 	inline int stateObjectGet(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2],void *const data,const unsigned int maxlen) { return _cb.stateGetFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,type,id,data,maxlen); }
stateObjectPut(void * const tPtr,ZT_StateObjectType type,const uint64_t id[2],const void * const data,const unsigned int len)176 	inline void stateObjectPut(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2],const void *const data,const unsigned int len) { _cb.statePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,type,id,data,(int)len); }
stateObjectDelete(void * const tPtr,ZT_StateObjectType type,const uint64_t id[2])177 	inline void stateObjectDelete(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2]) { _cb.statePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,type,id,(const void *)0,-1); }
178 
179 	bool shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const int64_t localSocket,const InetAddress &remoteAddress);
externalPathLookup(void * tPtr,const Address & ztaddr,int family,InetAddress & addr)180 	inline bool externalPathLookup(void *tPtr,const Address &ztaddr,int family,InetAddress &addr) { return ( (_cb.pathLookupFunction) ? (_cb.pathLookupFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ztaddr.toInt(),family,reinterpret_cast<struct sockaddr_storage *>(&addr)) != 0) : false ); }
181 
182 	uint64_t prng();
183 	ZT_ResultCode setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig);
184 
185 	World planet() const;
186 	std::vector<World> moons() const;
187 
identity() const188 	inline const Identity &identity() const { return _RR.identity; }
189 
bondController() const190 	inline Bond *bondController() const { return _RR.bc; }
191 
192 	/**
193 	 * Register that we are expecting a reply to a packet ID
194 	 *
195 	 * This only uses the most significant bits of the packet ID, both to save space
196 	 * and to avoid using the higher bits that can be modified during armor() to
197 	 * mask against the packet send counter used for QoS detection.
198 	 *
199 	 * @param packetId Packet ID to expect reply to
200 	 */
expectReplyTo(const uint64_t packetId)201 	inline void expectReplyTo(const uint64_t packetId)
202 	{
203 		const unsigned long pid2 = (unsigned long)(packetId >> 32);
204 		const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
205 		_expectingRepliesTo[bucket][_expectingRepliesToBucketPtr[bucket]++ & ZT_EXPECTING_REPLIES_BUCKET_MASK2] = (uint32_t)pid2;
206 	}
207 
208 	/**
209 	 * Check whether a given packet ID is something we are expecting a reply to
210 	 *
211 	 * This only uses the most significant bits of the packet ID, both to save space
212 	 * and to avoid using the higher bits that can be modified during armor() to
213 	 * mask against the packet send counter used for QoS detection.
214 	 *
215 	 * @param packetId Packet ID to check
216 	 * @return True if we're expecting a reply
217 	 */
expectingReplyTo(const uint64_t packetId) const218 	inline bool expectingReplyTo(const uint64_t packetId) const
219 	{
220 		const uint32_t pid2 = (uint32_t)(packetId >> 32);
221 		const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
222 		for(unsigned long i=0;i<=ZT_EXPECTING_REPLIES_BUCKET_MASK2;++i) {
223 			if (_expectingRepliesTo[bucket][i] == pid2)
224 				return true;
225 		}
226 		return false;
227 	}
228 
229 	/**
230 	 * Check whether we should do potentially expensive identity verification (rate limit)
231 	 *
232 	 * @param now Current time
233 	 * @param from Source address of packet
234 	 * @return True if within rate limits
235 	 */
rateGateIdentityVerification(const int64_t now,const InetAddress & from)236 	inline bool rateGateIdentityVerification(const int64_t now,const InetAddress &from)
237 	{
238 		unsigned long iph = from.rateGateHash();
239 		if ((now - _lastIdentityVerification[iph]) >= ZT_IDENTITY_VALIDATION_SOURCE_RATE_LIMIT) {
240 			_lastIdentityVerification[iph] = now;
241 			return true;
242 		}
243 		return false;
244 	}
245 
246 	virtual void ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig);
247 	virtual void ncSendRevocation(const Address &destination,const Revocation &rev);
248 	virtual void ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode, const void *errorData, unsigned int errorDataSize);
249 
remoteTraceTarget() const250 	inline const Address &remoteTraceTarget() const { return _remoteTraceTarget; }
remoteTraceLevel() const251 	inline Trace::Level remoteTraceLevel() const { return _remoteTraceLevel; }
252 
localControllerHasAuthorized(const int64_t now,const uint64_t nwid,const Address & addr) const253 	inline bool localControllerHasAuthorized(const int64_t now,const uint64_t nwid,const Address &addr) const
254 	{
255 		_localControllerAuthorizations_m.lock();
256 		const int64_t *const at = _localControllerAuthorizations.get(_LocalControllerAuth(nwid,addr));
257 		_localControllerAuthorizations_m.unlock();
258 		if (at)
259 			return ((now - *at) < (ZT_NETWORK_AUTOCONF_DELAY * 3));
260 		return false;
261 	}
262 
statsLogVerb(const unsigned int v,const unsigned int bytes)263 	inline void statsLogVerb(const unsigned int v,const unsigned int bytes)
264 	{
265 		++_stats.inVerbCounts[v];
266 		_stats.inVerbBytes[v] += (uint64_t)bytes;
267 	}
268 
269 private:
270 	RuntimeEnvironment _RR;
271 	RuntimeEnvironment *RR;
272 	void *_uPtr; // _uptr (lower case) is reserved in Visual Studio :P
273 	ZT_Node_Callbacks _cb;
274 
275 	// For tracking packet IDs to filter out OK/ERROR replies to packets we did not send
276 	uint8_t _expectingRepliesToBucketPtr[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1];
277 	uint32_t _expectingRepliesTo[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1][ZT_EXPECTING_REPLIES_BUCKET_MASK2 + 1];
278 
279 	// Time of last identity verification indexed by InetAddress.rateGateHash() -- used in IncomingPacket::_doHELLO() via rateGateIdentityVerification()
280 	int64_t _lastIdentityVerification[16384];
281 
282 	// Statistics about stuff happening
283 	volatile ZT_NodeStatistics _stats;
284 
285 	// Map that remembers if we have recently sent a network config to someone
286 	// querying us as a controller.
287 	struct _LocalControllerAuth
288 	{
289 		uint64_t nwid,address;
_LocalControllerAuthZeroTier::Node::_LocalControllerAuth290 		_LocalControllerAuth(const uint64_t nwid_,const Address &address_) : nwid(nwid_),address(address_.toInt()) {}
hashCodeZeroTier::Node::_LocalControllerAuth291 		inline unsigned long hashCode() const { return (unsigned long)(nwid ^ address); }
operator ==ZeroTier::Node::_LocalControllerAuth292 		inline bool operator==(const _LocalControllerAuth &a) const { return ((a.nwid == nwid)&&(a.address == address)); }
operator !=ZeroTier::Node::_LocalControllerAuth293 		inline bool operator!=(const _LocalControllerAuth &a) const { return ((a.nwid != nwid)||(a.address != address)); }
294 	};
295 	Hashtable< _LocalControllerAuth,int64_t > _localControllerAuthorizations;
296 	Mutex _localControllerAuthorizations_m;
297 
298 	Hashtable< uint64_t,SharedPtr<Network> > _networks;
299 	Mutex _networks_m;
300 
301 	std::vector<InetAddress> _directPaths;
302 	Mutex _directPaths_m;
303 
304 	Mutex _backgroundTasksLock;
305 
306 	Address _remoteTraceTarget;
307 	enum Trace::Level _remoteTraceLevel;
308 
309 	volatile int64_t _now;
310 	int64_t _lastPingCheck;
311 	int64_t _lastGratuitousPingCheck;
312 	int64_t _lastHousekeepingRun;
313 	int64_t _lastMemoizedTraceSettings;
314 	volatile int64_t _prngState[2];
315 	bool _online;
316 };
317 
318 } // namespace ZeroTier
319 
320 #endif
321