One.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include "../version.h"
  31. #include "../include/ZeroTierOne.h"
  32. #include "../node/Constants.hpp"
  33. #include "../node/Mutex.hpp"
  34. #include "../node/Node.hpp"
  35. #include "../node/Utils.hpp"
  36. #include "../node/InetAddress.hpp"
  37. #include "../osdep/Phy.hpp"
  38. #include "../osdep/OSUtils.hpp"
  39. #include "One.hpp"
  40. namespace ZeroTier {
  41. static void SphyOnDatagramFunction(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len);
  42. static void SphyOnTcpConnectFunction(PhySocket *sock,void **uptr,bool success);
  43. static void SphyOnTcpAcceptFunction(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from);
  44. static void SphyOnTcpCloseFunction(PhySocket *sock,void **uptr);
  45. static void SphyOnTcpDataFunction(PhySocket *sock,void **uptr,void *data,unsigned long len);
  46. static void SphyOnTcpWritableFunction(PhySocket *sock,void **uptr);
  47. static int SnodeVirtualNetworkConfigFunction(ZT1_Node *node,void *uptr,uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwconf);
  48. static void SnodeEventCallback(ZT1_Node *node,void *uptr,enum ZT1_Event event,const void *metaData);
  49. static long SnodeDataStoreGetFunction(ZT1_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize);
  50. static int SnodeDataStorePutFunction(ZT1_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure);
  51. static int SnodeWirePacketSendFunction(ZT1_Node *node,void *uptr,const struct sockaddr_storage *addr,unsigned int desperation,const void *data,unsigned int len);
  52. static void SnodeVirtualNetworkFrameFunction(ZT1_Node *node,void *uptr,uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  53. class OneImpl : public One
  54. {
  55. public:
  56. OneImpl(const char *hp,unsigned int port,NetworkConfigMaster *master,const char *overrideRootTopology) :
  57. _homePath((hp) ? hp : "."),
  58. _phy(SphyOnDatagramFunction,SphyOnTcpConnectFunction,SphyOnTcpAcceptFunction,SphyOnTcpCloseFunction,SphyOnTcpDataFunction,SphyOnTcpWritableFunction,true),
  59. _master(master),
  60. _overrideRootTopology((overrideRootTopology) ? overrideRootTopology : ""),
  61. _node((Node *)0),
  62. _nextBackgroundTaskDeadline(0),
  63. _termReason(ONE_STILL_RUNNING),
  64. _run(true)
  65. {
  66. struct sockaddr_in in4;
  67. struct sockaddr_in6 in6;
  68. if (*hp) {
  69. std::vector<std::string> hpsp(Utils::split(hp,ZT_PATH_SEPARATOR_S,"",""));
  70. std::string ptmp;
  71. if (*hp == '/')
  72. ptmp.push_back('/');
  73. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  74. if (ptmp.length() > 0)
  75. ptmp.push_back(ZT_PATH_SEPARATOR);
  76. ptmp.append(*pi);
  77. if ((*pi != ".")&&(*pi != "..")) {
  78. if (!OSUtils::mkdir(ptmp))
  79. throw std::runtime_error("home path does not exist, and could not create");
  80. }
  81. }
  82. }
  83. ::memset((void *)&in4,0,sizeof(in4));
  84. in4.sin_family = AF_INET;
  85. in4.sin_port = Utils::hton(port);
  86. _v4UdpSocket = _phy.udpBind((const struct sockaddr *)&in4,this,131072);
  87. if (!_v4UdpSocket)
  88. throw std::runtime_error("cannot bind to port (UDP/IPv4)");
  89. _v4TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
  90. if (!_v4TcpListenSocket) {
  91. _phy.close(_v4UdpSocket);
  92. throw std::runtime_error("cannot bind to port (TCP/IPv4)");
  93. }
  94. ::memset((void *)&in6,0,sizeof(in6));
  95. in6.sin6_family = AF_INET6;
  96. in6.sin6_port = in4.sin_port;
  97. _v6UdpSocket = _phy.udpBind((const struct sockaddr *)&in6,this,131072);
  98. _v6TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
  99. }
  100. virtual ~OneImpl()
  101. {
  102. _phy.close(_v4UdpSocket);
  103. _phy.close(_v6UdpSocket);
  104. _phy.close(_v4TcpListenSocket);
  105. _phy.close(_v6TcpListenSocket);
  106. }
  107. virtual ReasonForTermination run()
  108. {
  109. try {
  110. _node = new Node(
  111. OSUtils::now(),
  112. this,
  113. SnodeDataStoreGetFunction,
  114. SnodeDataStorePutFunction,
  115. SnodeWirePacketSendFunction,
  116. SnodeVirtualNetworkFrameFunction,
  117. SnodeVirtualNetworkConfigFunction,
  118. SnodeEventCallback,
  119. ((_overrideRootTopology.length() > 0) ? _overrideRootTopology.c_str() : (const char *)0));
  120. if (_master)
  121. _node->setNetconfMaster((void *)_master);
  122. _nextBackgroundTaskDeadline = 0;
  123. for(;;) {
  124. _run_m.lock();
  125. if (!_run) {
  126. _run_m.unlock();
  127. _termReason_m.lock();
  128. _termReason = ONE_NORMAL_TERMINATION;
  129. _termReason_m.unlock();
  130. break;
  131. } else _run_m.unlock();
  132. uint64_t dl = _nextBackgroundTaskDeadline;
  133. uint64_t now = OSUtils::now();
  134. if (dl <= now) {
  135. _node->processBackgroundTasks(now,const_cast<uint64_t *>(&_nextBackgroundTaskDeadline));
  136. dl = _nextBackgroundTaskDeadline;
  137. now = OSUtils::now();
  138. }
  139. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  140. printf("polling: %lums timeout\n",delay);
  141. _phy.poll(delay);
  142. }
  143. } catch (std::exception &exc) {
  144. Mutex::Lock _l(_termReason_m);
  145. _termReason = ONE_UNRECOVERABLE_ERROR;
  146. _fatalErrorMessage = exc.what();
  147. } catch ( ... ) {
  148. Mutex::Lock _l(_termReason_m);
  149. _termReason = ONE_UNRECOVERABLE_ERROR;
  150. _fatalErrorMessage = "unexpected exception in main thread";
  151. }
  152. delete _node;
  153. _node = (Node *)0;
  154. return _termReason;
  155. }
  156. virtual ReasonForTermination reasonForTermination() const
  157. {
  158. Mutex::Lock _l(_termReason_m);
  159. return _termReason;
  160. }
  161. virtual std::string fatalErrorMessage() const
  162. {
  163. Mutex::Lock _l(_termReason_m);
  164. return _fatalErrorMessage;
  165. }
  166. virtual void terminate()
  167. {
  168. _run_m.lock();
  169. _run = false;
  170. _run_m.unlock();
  171. _phy.whack();
  172. }
  173. // Begin private implementation methods
  174. inline void phyOnDatagramFunction(PhySocket *sock,const struct sockaddr *from,void *data,unsigned long len)
  175. {
  176. try {
  177. ZT1_ResultCode rc = _node->processWirePacket(
  178. OSUtils::now(),
  179. (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
  180. 0,
  181. data,
  182. len,
  183. const_cast<uint64_t *>(&_nextBackgroundTaskDeadline));
  184. if (ZT1_ResultCode_isFatal(rc)) {
  185. char tmp[256];
  186. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket(%d)",(int)rc);
  187. Mutex::Lock _l(_termReason_m);
  188. _termReason = ONE_UNRECOVERABLE_ERROR;
  189. _fatalErrorMessage = tmp;
  190. this->terminate();
  191. }
  192. } catch ( ... ) {}
  193. }
  194. inline void phyOnTcpConnectFunction(PhySocket *sock,bool success)
  195. {
  196. }
  197. inline void phyOnTcpAcceptFunction(PhySocket *sockN,const struct sockaddr *from)
  198. {
  199. }
  200. inline void phyOnTcpCloseFunction(PhySocket *sock)
  201. {
  202. }
  203. inline void phyOnTcpDataFunction(PhySocket *sock,void *data,unsigned long len)
  204. {
  205. }
  206. inline void phyOnTcpWritableFunction(PhySocket *sock)
  207. {
  208. }
  209. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwconf)
  210. {
  211. return 0;
  212. }
  213. inline void nodeEventCallback(enum ZT1_Event event,const void *metaData)
  214. {
  215. switch(event) {
  216. case ZT1_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  217. Mutex::Lock _l(_termReason_m);
  218. _termReason = ONE_IDENTITY_COLLISION;
  219. _fatalErrorMessage = "identity/address collision";
  220. this->terminate();
  221. } break;
  222. case ZT1_EVENT_SAW_MORE_RECENT_VERSION: {
  223. } break;
  224. case ZT1_EVENT_TRACE: {
  225. if (metaData) {
  226. ::fprintf(stderr,"%s"ZT_EOL_S,(const char *)metaData);
  227. ::fflush(stderr);
  228. }
  229. } break;
  230. default:
  231. break;
  232. }
  233. }
  234. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  235. {
  236. std::string p(_homePath);
  237. p.push_back(ZT_PATH_SEPARATOR);
  238. char lastc = (char)0;
  239. for(const char *n=name;(*n);++n) {
  240. if ((*n == '.')&&(lastc == '.'))
  241. return -2; // security sanity check-- don't allow ../ stuff even though there's really no way Node will ever do this
  242. p.push_back((*n == '/') ? ZT_PATH_SEPARATOR : *n);
  243. lastc = *n;
  244. }
  245. FILE *f = fopen(p.c_str(),"rb");
  246. if (!f)
  247. return -1;
  248. if (fseek(f,0,SEEK_END) != 0) {
  249. fclose(f);
  250. return -2;
  251. }
  252. long ts = ftell(f);
  253. if (ts < 0) {
  254. fclose(f);
  255. return -2;
  256. }
  257. *totalSize = (unsigned long)ts;
  258. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  259. fclose(f);
  260. return -2;
  261. }
  262. long n = (long)fread(buf,1,bufSize,f);
  263. fclose(f);
  264. return n;
  265. }
  266. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  267. {
  268. std::string p(_homePath);
  269. p.push_back(ZT_PATH_SEPARATOR);
  270. char lastc = (char)0;
  271. for(const char *n=name;(*n);++n) {
  272. if ((*n == '.')&&(lastc == '.'))
  273. return -2; // security sanity check-- don't allow ../ stuff even though there's really no way Node will ever do this
  274. p.push_back((*n == '/') ? ZT_PATH_SEPARATOR : *n);
  275. lastc = *n;
  276. }
  277. if (!data) {
  278. OSUtils::rm(p.c_str());
  279. return 0;
  280. }
  281. FILE *f = fopen(p.c_str(),"wb");
  282. if (!f)
  283. return -1;
  284. if (fwrite(data,len,1,f) == 1) {
  285. fclose(f);
  286. if (secure)
  287. OSUtils::lockDownFile(p.c_str(),false);
  288. return 0;
  289. } else {
  290. fclose(f);
  291. OSUtils::rm(p.c_str());
  292. return -1;
  293. }
  294. }
  295. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *addr,unsigned int desperation,const void *data,unsigned int len)
  296. {
  297. switch(addr->ss_family) {
  298. case AF_INET:
  299. if (_v4UdpSocket)
  300. return (_phy.udpSend(_v4UdpSocket,(const struct sockaddr *)addr,data,len) ? 0 : -1);
  301. break;
  302. case AF_INET6:
  303. if (_v6UdpSocket)
  304. return (_phy.udpSend(_v6UdpSocket,(const struct sockaddr *)addr,data,len) ? 0 : -1);
  305. break;
  306. }
  307. return -1;
  308. }
  309. inline void nodeVirtualNetworkFrameFunction(uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  310. {
  311. fprintf(stderr,"VIRTUAL NETWORK FRAME from %.16llx : %.12llx -> %.12llx %.4x %u bytes\n",nwid,sourceMac,destMac,etherType,len);
  312. fflush(stderr);
  313. }
  314. private:
  315. const std::string _homePath;
  316. SimpleFunctionPhy _phy;
  317. NetworkConfigMaster *_master;
  318. std::string _overrideRootTopology;
  319. Node *_node;
  320. PhySocket *_v4UdpSocket;
  321. PhySocket *_v6UdpSocket;
  322. PhySocket *_v4TcpListenSocket;
  323. PhySocket *_v6TcpListenSocket;
  324. volatile uint64_t _nextBackgroundTaskDeadline;
  325. ReasonForTermination _termReason;
  326. std::string _fatalErrorMessage;
  327. Mutex _termReason_m;
  328. bool _run;
  329. Mutex _run_m;
  330. };
  331. static void SphyOnDatagramFunction(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
  332. { reinterpret_cast<OneImpl *>(*uptr)->phyOnDatagramFunction(sock,from,data,len); }
  333. static void SphyOnTcpConnectFunction(PhySocket *sock,void **uptr,bool success)
  334. { reinterpret_cast<OneImpl *>(*uptr)->phyOnTcpConnectFunction(sock,success); }
  335. static void SphyOnTcpAcceptFunction(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  336. { *uptrN = *uptrL; reinterpret_cast<OneImpl *>(*uptrL)->phyOnTcpAcceptFunction(sockN,from); }
  337. static void SphyOnTcpCloseFunction(PhySocket *sock,void **uptr)
  338. { reinterpret_cast<OneImpl *>(*uptr)->phyOnTcpCloseFunction(sock); }
  339. static void SphyOnTcpDataFunction(PhySocket *sock,void **uptr,void *data,unsigned long len)
  340. { reinterpret_cast<OneImpl *>(*uptr)->phyOnTcpDataFunction(sock,data,len); }
  341. static void SphyOnTcpWritableFunction(PhySocket *sock,void **uptr)
  342. { reinterpret_cast<OneImpl *>(*uptr)->phyOnTcpWritableFunction(sock); }
  343. static int SnodeVirtualNetworkConfigFunction(ZT1_Node *node,void *uptr,uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwconf)
  344. { return reinterpret_cast<OneImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,op,nwconf); }
  345. static void SnodeEventCallback(ZT1_Node *node,void *uptr,enum ZT1_Event event,const void *metaData)
  346. { reinterpret_cast<OneImpl *>(uptr)->nodeEventCallback(event,metaData); }
  347. static long SnodeDataStoreGetFunction(ZT1_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  348. { return reinterpret_cast<OneImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  349. static int SnodeDataStorePutFunction(ZT1_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  350. { return reinterpret_cast<OneImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  351. static int SnodeWirePacketSendFunction(ZT1_Node *node,void *uptr,const struct sockaddr_storage *addr,unsigned int desperation,const void *data,unsigned int len)
  352. { return reinterpret_cast<OneImpl *>(uptr)->nodeWirePacketSendFunction(addr,desperation,data,len); }
  353. static void SnodeVirtualNetworkFrameFunction(ZT1_Node *node,void *uptr,uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  354. { reinterpret_cast<OneImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,sourceMac,destMac,etherType,vlanId,data,len); }
  355. std::string One::platformDefaultHomePath()
  356. {
  357. #ifdef __UNIX_LIKE__
  358. #ifdef __APPLE__
  359. // /Library/... on Apple
  360. return std::string("/Library/Application Support/ZeroTier/One");
  361. #else
  362. #ifdef __FreeBSD__
  363. // FreeBSD likes /var/db instead of /var/lib
  364. return std::string("/var/db/zerotier-one");
  365. #else
  366. // Use /var/lib for Linux and other *nix
  367. return std::string("/var/lib/zerotier-one");
  368. #endif
  369. #endif
  370. #else // not __UNIX_LIKE__
  371. #ifdef __WINDOWS__
  372. // Look up app data folder on Windows, e.g. C:\ProgramData\...
  373. char buf[16384];
  374. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_COMMON_APPDATA,NULL,0,buf)))
  375. return (std::string(buf) + "\\ZeroTier\\One");
  376. else return std::string("C:\\ZeroTier\\One");
  377. #else
  378. return std::string(); // UNKNOWN PLATFORM
  379. #endif
  380. #endif // __UNIX_LIKE__ or not...
  381. }
  382. One *One::newInstance(const char *hp,unsigned int port,NetworkConfigMaster *master,const char *overrideRootTopology) { return new OneImpl(hp,port,master,overrideRootTopology); }
  383. One::~One() {}
  384. } // namespace ZeroTier