OneService.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  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 <stdint.h>
  31. #include <string>
  32. #include <map>
  33. #include <set>
  34. #include <vector>
  35. #include <algorithm>
  36. #include "../version.h"
  37. #include "../include/ZeroTierOne.h"
  38. #include "../ext/http-parser/http_parser.h"
  39. #include "../node/Constants.hpp"
  40. #include "../node/Mutex.hpp"
  41. #include "../node/Node.hpp"
  42. #include "../node/Utils.hpp"
  43. #include "../node/InetAddress.hpp"
  44. #include "../node/MAC.hpp"
  45. #include "../node/Identity.hpp"
  46. #include "../osdep/Phy.hpp"
  47. #include "../osdep/Thread.hpp"
  48. #include "../osdep/OSUtils.hpp"
  49. #include "../osdep/Http.hpp"
  50. #include "../osdep/BackgroundResolver.hpp"
  51. #include "../osdep/UPNPClient.hpp"
  52. #include "OneService.hpp"
  53. #include "ControlPlane.hpp"
  54. /**
  55. * Uncomment to enable UDP breakage switch
  56. *
  57. * If this is defined, the presence of a file called /tmp/ZT_BREAK_UDP
  58. * will cause direct UDP TX/RX to stop working. This can be used to
  59. * test TCP tunneling fallback and other robustness features. Deleting
  60. * this file will cause it to start working again.
  61. */
  62. //#define ZT_BREAK_UDP
  63. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  64. #include "../controller/SqliteNetworkController.hpp"
  65. #else
  66. class SqliteNetworkController;
  67. #endif // ZT_ENABLE_NETWORK_CONTROLLER
  68. #ifdef __WINDOWS__
  69. #include <WinSock2.h>
  70. #include <Windows.h>
  71. #include <ShlObj.h>
  72. #include <netioapi.h>
  73. #include <iphlpapi.h>
  74. #else
  75. #include <sys/types.h>
  76. #include <sys/socket.h>
  77. #include <sys/wait.h>
  78. #include <unistd.h>
  79. #include <ifaddrs.h>
  80. #endif
  81. // Include the right tap device driver for this platform -- add new platforms here
  82. #ifdef __APPLE__
  83. #include "../osdep/OSXEthernetTap.hpp"
  84. namespace ZeroTier { typedef OSXEthernetTap EthernetTap; }
  85. #endif
  86. #ifdef __LINUX__
  87. #include "../osdep/LinuxEthernetTap.hpp"
  88. namespace ZeroTier { typedef LinuxEthernetTap EthernetTap; }
  89. #endif
  90. #ifdef __WINDOWS__
  91. #include "../osdep/WindowsEthernetTap.hpp"
  92. namespace ZeroTier { typedef WindowsEthernetTap EthernetTap; }
  93. #endif
  94. #ifdef __FreeBSD__
  95. #include "../osdep/BSDEthernetTap.hpp"
  96. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  97. #endif
  98. // Sanity limits for HTTP
  99. #define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 64)
  100. #define ZT_MAX_HTTP_CONNECTIONS 64
  101. // Interface metric for ZeroTier taps
  102. #define ZT_IF_METRIC 32768
  103. // How often to check for new multicast subscriptions on a tap device
  104. #define ZT_TAP_CHECK_MULTICAST_INTERVAL 30000
  105. // Path under ZT1 home for controller database if controller is enabled
  106. #define ZT_CONTROLLER_DB_PATH "controller.db"
  107. // TCP fallback relay host -- geo-distributed using Amazon Route53 geo-aware DNS
  108. #define ZT_TCP_FALLBACK_RELAY "tcp-fallback.zerotier.com"
  109. #define ZT_TCP_FALLBACK_RELAY_PORT 443
  110. // Frequency at which we re-resolve the TCP fallback relay
  111. #define ZT_TCP_FALLBACK_RERESOLVE_DELAY 86400000
  112. // Attempt to engage TCP fallback after this many ms of no reply to packets sent to global-scope IPs
  113. #define ZT_TCP_FALLBACK_AFTER 60000
  114. // How often to check for local interface addresses
  115. #define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 300000
  116. namespace ZeroTier {
  117. namespace {
  118. #ifdef ZT_AUTO_UPDATE
  119. #define ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE (1024 * 1024 * 64)
  120. #define ZT_AUTO_UPDATE_CHECK_PERIOD 21600000
  121. class BackgroundSoftwareUpdateChecker
  122. {
  123. public:
  124. bool isValidSigningIdentity(const Identity &id)
  125. {
  126. return (
  127. /* 0005 */ (id == Identity("ba57ea350e:0:9d4be6d7f86c5660d5ee1951a3d759aa6e12a84fc0c0b74639500f1dbc1a8c566622e7d1c531967ebceb1e9d1761342f88324a8ba520c93c35f92f35080fa23f"))
  128. /* 0006 */ ||(id == Identity("5067b21b83:0:8af477730f5055c48135b84bed6720a35bca4c0e34be4060a4c636288b1ec22217eb22709d610c66ed464c643130c51411bbb0294eef12fbe8ecc1a1e2c63a7a"))
  129. /* 0007 */ ||(id == Identity("4f5e97a8f1:0:57880d056d7baeb04bbc057d6f16e6cb41388570e87f01492fce882485f65a798648595610a3ad49885604e7fb1db2dd3c2c534b75e42c3c0b110ad07b4bb138"))
  130. /* 0008 */ ||(id == Identity("580bbb8e15:0:ad5ef31155bebc6bc413991992387e083fed26d699997ef76e7c947781edd47d1997161fa56ba337b1a2b44b129fd7c7197ce5185382f06011bc88d1363b4ddd"))
  131. );
  132. }
  133. void doUpdateCheck()
  134. {
  135. std::string url(OneService::autoUpdateUrl());
  136. if ((url.length() <= 7)||(url.substr(0,7) != "http://"))
  137. return;
  138. std::string httpHost;
  139. std::string httpPath;
  140. {
  141. std::size_t slashIdx = url.substr(7).find_first_of('/');
  142. if (slashIdx == std::string::npos) {
  143. httpHost = url.substr(7);
  144. httpPath = "/";
  145. } else {
  146. httpHost = url.substr(7,slashIdx);
  147. httpPath = url.substr(slashIdx + 7);
  148. }
  149. }
  150. if (httpHost.length() == 0)
  151. return;
  152. std::vector<InetAddress> ips(OSUtils::resolve(httpHost.c_str()));
  153. for(std::vector<InetAddress>::iterator ip(ips.begin());ip!=ips.end();++ip) {
  154. if (!ip->port())
  155. ip->setPort(80);
  156. std::string nfoPath = httpPath + "LATEST.nfo";
  157. std::map<std::string,std::string> requestHeaders,responseHeaders;
  158. std::string body;
  159. requestHeaders["Host"] = httpHost;
  160. unsigned int scode = Http::GET(ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE,60000,reinterpret_cast<const struct sockaddr *>(&(*ip)),nfoPath.c_str(),requestHeaders,responseHeaders,body);
  161. //fprintf(stderr,"UPDATE %s %s %u %lu\n",ip->toString().c_str(),nfoPath.c_str(),scode,body.length());
  162. if ((scode == 200)&&(body.length() > 0)) {
  163. /* NFO fields:
  164. *
  165. * file=<filename>
  166. * signedBy=<signing identity>
  167. * ed25519=<ed25519 ECC signature of archive>
  168. * vMajor=<major version>
  169. * vMinor=<minor version>
  170. * vRevision=<revision> */
  171. Dictionary nfo(body);
  172. unsigned int vMajor = Utils::strToUInt(nfo.get("vMajor","0").c_str());
  173. unsigned int vMinor = Utils::strToUInt(nfo.get("vMinor","0").c_str());
  174. unsigned int vRevision = Utils::strToUInt(nfo.get("vRevision","0").c_str());
  175. if (Utils::compareVersion(vMajor,vMinor,vRevision,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION) <= 0) {
  176. //fprintf(stderr,"UPDATE %u.%u.%u is not newer than our version\n",vMajor,vMinor,vRevision);
  177. return;
  178. }
  179. Identity signedBy;
  180. if ((!signedBy.fromString(nfo.get("signedBy","")))||(!isValidSigningIdentity(signedBy))) {
  181. //fprintf(stderr,"UPDATE invalid signedBy or not authorized signing identity.\n");
  182. return;
  183. }
  184. std::string filePath(nfo.get("file",""));
  185. if ((!filePath.length())||(filePath.find("..") != std::string::npos))
  186. return;
  187. filePath = httpPath + filePath;
  188. std::string fileData;
  189. if (Http::GET(ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE,60000,reinterpret_cast<const struct sockaddr *>(&(*ip)),filePath.c_str(),requestHeaders,responseHeaders,fileData) != 200) {
  190. //fprintf(stderr,"UPDATE GET %s failed\n",filePath.c_str());
  191. return;
  192. }
  193. std::string ed25519(Utils::unhex(nfo.get("ed25519","")));
  194. if ((ed25519.length() == 0)||(!signedBy.verify(fileData.data(),(unsigned int)fileData.length(),ed25519.data(),(unsigned int)ed25519.length()))) {
  195. //fprintf(stderr,"UPDATE %s failed signature check!\n",filePath.c_str());
  196. return;
  197. }
  198. /* --------------------------------------------------------------- */
  199. /* We made it! Begin OS-specific installation code. */
  200. #ifdef __APPLE__
  201. /* OSX version is in the form of a MacOSX .pkg file, so we will
  202. * launch installer (normally in /usr/sbin) to install it. It will
  203. * then turn around and shut down the service, update files, and
  204. * relaunch. */
  205. {
  206. char bashp[128],pkgp[128];
  207. Utils::snprintf(bashp,sizeof(bashp),"/tmp/ZeroTierOne-update-%u.%u.%u.sh",vMajor,vMinor,vRevision);
  208. Utils::snprintf(pkgp,sizeof(pkgp),"/tmp/ZeroTierOne-update-%u.%u.%u.pkg",vMajor,vMinor,vRevision);
  209. FILE *pkg = fopen(pkgp,"w");
  210. if ((!pkg)||(fwrite(fileData.data(),fileData.length(),1,pkg) != 1)) {
  211. fclose(pkg);
  212. unlink(bashp);
  213. unlink(pkgp);
  214. fprintf(stderr,"UPDATE error writing %s\n",pkgp);
  215. return;
  216. }
  217. fclose(pkg);
  218. FILE *bash = fopen(bashp,"w");
  219. if (!bash) {
  220. fclose(pkg);
  221. unlink(bashp);
  222. unlink(pkgp);
  223. fprintf(stderr,"UPDATE error writing %s\n",bashp);
  224. return;
  225. }
  226. fprintf(bash,
  227. "#!/bin/bash\n"
  228. "export PATH=/bin:/usr/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/sbin\n"
  229. "sleep 1\n"
  230. "installer -pkg \"%s\" -target /\n"
  231. "sleep 1\n"
  232. "rm -f \"%s\" \"%s\"\n"
  233. "exit 0\n",
  234. pkgp,
  235. pkgp,
  236. bashp);
  237. fclose(bash);
  238. long pid = (long)vfork();
  239. if (pid == 0) {
  240. setsid(); // detach from parent so that shell isn't killed when parent is killed
  241. signal(SIGHUP,SIG_IGN);
  242. signal(SIGTERM,SIG_IGN);
  243. signal(SIGQUIT,SIG_IGN);
  244. execl("/bin/bash","/bin/bash",bashp,(char *)0);
  245. exit(0);
  246. }
  247. }
  248. #endif // __APPLE__
  249. #ifdef __WINDOWS__
  250. /* Windows version comes in the form of .MSI package that
  251. * takes care of everything. */
  252. {
  253. char tempp[512],batp[512],msip[512],cmdline[512];
  254. if (GetTempPathA(sizeof(tempp),tempp) <= 0)
  255. return;
  256. CreateDirectoryA(tempp,(LPSECURITY_ATTRIBUTES)0);
  257. Utils::snprintf(batp,sizeof(batp),"%s\\ZeroTierOne-update-%u.%u.%u.bat",tempp,vMajor,vMinor,vRevision);
  258. Utils::snprintf(msip,sizeof(msip),"%s\\ZeroTierOne-update-%u.%u.%u.msi",tempp,vMajor,vMinor,vRevision);
  259. FILE *msi = fopen(msip,"wb");
  260. if ((!msi)||(fwrite(fileData.data(),(size_t)fileData.length(),1,msi) != 1)) {
  261. fclose(msi);
  262. return;
  263. }
  264. fclose(msi);
  265. FILE *bat = fopen(batp,"wb");
  266. if (!bat)
  267. return;
  268. fprintf(bat,
  269. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  270. "NET.EXE STOP \"ZeroTierOneService\"\r\n"
  271. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  272. "MSIEXEC.EXE /i \"%s\" /qn\r\n"
  273. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  274. "NET.EXE START \"ZeroTierOneService\"\r\n"
  275. "DEL \"%s\"\r\n"
  276. "DEL \"%s\"\r\n",
  277. msip,
  278. msip,
  279. batp);
  280. fclose(bat);
  281. STARTUPINFOA si;
  282. PROCESS_INFORMATION pi;
  283. memset(&si,0,sizeof(si));
  284. memset(&pi,0,sizeof(pi));
  285. Utils::snprintf(cmdline,sizeof(cmdline),"CMD.EXE /c \"%s\"",batp);
  286. CreateProcessA(NULL,cmdline,NULL,NULL,FALSE,CREATE_NO_WINDOW|CREATE_NEW_PROCESS_GROUP,NULL,NULL,&si,&pi);
  287. }
  288. #endif // __WINDOWS__
  289. /* --------------------------------------------------------------- */
  290. return;
  291. } // else try to fetch from next IP address
  292. }
  293. }
  294. void threadMain()
  295. throw()
  296. {
  297. try {
  298. this->doUpdateCheck();
  299. } catch ( ... ) {}
  300. }
  301. };
  302. static BackgroundSoftwareUpdateChecker backgroundSoftwareUpdateChecker;
  303. #endif // ZT_AUTO_UPDATE
  304. class OneServiceImpl;
  305. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
  306. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData);
  307. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize);
  308. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure);
  309. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len);
  310. static void SnodeVirtualNetworkFrameFunction(ZT_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);
  311. static void StapFrameHandler(void *uptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  312. static int ShttpOnMessageBegin(http_parser *parser);
  313. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  314. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  315. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  316. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  317. static int ShttpOnHeadersComplete(http_parser *parser);
  318. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  319. static int ShttpOnMessageComplete(http_parser *parser);
  320. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  321. ShttpOnMessageBegin,
  322. ShttpOnUrl,
  323. ShttpOnStatus,
  324. ShttpOnHeaderField,
  325. ShttpOnValue,
  326. ShttpOnHeadersComplete,
  327. ShttpOnBody,
  328. ShttpOnMessageComplete
  329. };
  330. struct TcpConnection
  331. {
  332. enum {
  333. TCP_HTTP_INCOMING,
  334. TCP_HTTP_OUTGOING, // not currently used
  335. TCP_TUNNEL_OUTGOING // fale-SSL outgoing tunnel -- HTTP-related fields are not used
  336. } type;
  337. bool shouldKeepAlive;
  338. OneServiceImpl *parent;
  339. PhySocket *sock;
  340. InetAddress from;
  341. http_parser parser;
  342. unsigned long messageSize;
  343. uint64_t lastActivity;
  344. std::string currentHeaderField;
  345. std::string currentHeaderValue;
  346. std::string url;
  347. std::string status;
  348. std::map< std::string,std::string > headers;
  349. std::string body;
  350. std::string writeBuf;
  351. Mutex writeBuf_m;
  352. };
  353. class OneServiceImpl : public OneService
  354. {
  355. public:
  356. OneServiceImpl(const char *hp,unsigned int port,const char *overrideRootTopology) :
  357. _homePath((hp) ? hp : "."),
  358. _tcpFallbackResolver(ZT_TCP_FALLBACK_RELAY),
  359. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  360. _controller((_homePath + ZT_PATH_SEPARATOR_S + ZT_CONTROLLER_DB_PATH).c_str()),
  361. #endif
  362. _phy(this,false,true),
  363. _overrideRootTopology((overrideRootTopology) ? overrideRootTopology : ""),
  364. _node((Node *)0),
  365. _controlPlane((ControlPlane *)0),
  366. _lastDirectReceiveFromGlobal(0),
  367. _lastSendToGlobal(0),
  368. _lastRestart(0),
  369. _nextBackgroundTaskDeadline(0),
  370. _tcpFallbackTunnel((TcpConnection *)0),
  371. _termReason(ONE_STILL_RUNNING),
  372. _port(0),
  373. #ifdef ZT_USE_MINIUPNPC
  374. _v4UpnpUdpSocket((PhySocket *)0),
  375. _upnpClient((UPNPClient *)0),
  376. #endif
  377. _run(true)
  378. {
  379. const int portTrials = (port == 0) ? 256 : 1; // if port is 0, pick random
  380. for(int k=0;k<portTrials;++k) {
  381. if (port == 0) {
  382. unsigned int randp = 0;
  383. Utils::getSecureRandom(&randp,sizeof(randp));
  384. port = 40000 + (randp % 25500);
  385. }
  386. _v4LocalAddress = InetAddress((uint32_t)0,port);
  387. _v4UdpSocket = _phy.udpBind((const struct sockaddr *)&_v4LocalAddress,reinterpret_cast<void *>(&_v4LocalAddress),131072);
  388. if (_v4UdpSocket) {
  389. struct sockaddr_in in4;
  390. memset(&in4,0,sizeof(in4));
  391. in4.sin_family = AF_INET;
  392. in4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001); // right now we just listen for TCP @localhost
  393. in4.sin_port = Utils::hton((uint16_t)port);
  394. _v4TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
  395. if (_v4TcpListenSocket) {
  396. _v6LocalAddress = InetAddress("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",16,port);
  397. _v6UdpSocket = _phy.udpBind((const struct sockaddr *)&_v6LocalAddress,reinterpret_cast<void *>(&_v6LocalAddress),131072);
  398. struct sockaddr_in6 in6;
  399. memset((void *)&in6,0,sizeof(in6));
  400. in6.sin6_family = AF_INET6;
  401. in6.sin6_port = in4.sin_port;
  402. in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
  403. _v6TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
  404. _port = port;
  405. break; // success!
  406. } else {
  407. _phy.close(_v4UdpSocket,false);
  408. }
  409. }
  410. port = 0;
  411. }
  412. if (_port == 0)
  413. throw std::runtime_error("cannot bind to port");
  414. char portstr[64];
  415. Utils::snprintf(portstr,sizeof(portstr),"%u",_port);
  416. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),std::string(portstr));
  417. #ifdef ZT_USE_MINIUPNPC
  418. // Bind a random secondary port for use with uPnP, since some NAT routers
  419. // (cough Ubiquity Edge cough) barf up a lung if you do both conventional
  420. // NAT-t and uPnP from behind the same port. I think this is a bug, but
  421. // everyone else's router bugs are our problem. :P
  422. for(int k=0;k<256;++k) {
  423. unsigned int randp = 0;
  424. Utils::getSecureRandom(&randp,sizeof(randp));
  425. unsigned int upnport = 40000 + (randp % 25500);
  426. _v4UpnpLocalAddress = InetAddress(0,upnport);
  427. _v4UpnpUdpSocket = _phy.udpBind((const struct sockaddr *)&_v4UpnpLocalAddress,reinterpret_cast<void *>(&_v4UpnpLocalAddress),131072);
  428. if (_v4UpnpUdpSocket) {
  429. _upnpClient = new UPNPClient(upnport);
  430. break;
  431. }
  432. }
  433. #endif
  434. }
  435. virtual ~OneServiceImpl()
  436. {
  437. _phy.close(_v4UdpSocket);
  438. _phy.close(_v6UdpSocket);
  439. _phy.close(_v4TcpListenSocket);
  440. _phy.close(_v6TcpListenSocket);
  441. #ifdef ZT_USE_MINIUPNPC
  442. _phy.close(_v4UpnpUdpSocket);
  443. delete _upnpClient;
  444. #endif
  445. }
  446. virtual ReasonForTermination run()
  447. {
  448. try {
  449. std::string authToken;
  450. {
  451. std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  452. if (!OSUtils::readFile(authTokenPath.c_str(),authToken)) {
  453. unsigned char foo[24];
  454. Utils::getSecureRandom(foo,sizeof(foo));
  455. authToken = "";
  456. for(unsigned int i=0;i<sizeof(foo);++i)
  457. authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  458. if (!OSUtils::writeFile(authTokenPath.c_str(),authToken)) {
  459. Mutex::Lock _l(_termReason_m);
  460. _termReason = ONE_UNRECOVERABLE_ERROR;
  461. _fatalErrorMessage = "authtoken.secret could not be written";
  462. return _termReason;
  463. } else OSUtils::lockDownFile(authTokenPath.c_str(),false);
  464. }
  465. }
  466. authToken = Utils::trim(authToken);
  467. _node = new Node(
  468. OSUtils::now(),
  469. this,
  470. SnodeDataStoreGetFunction,
  471. SnodeDataStorePutFunction,
  472. SnodeWirePacketSendFunction,
  473. SnodeVirtualNetworkFrameFunction,
  474. SnodeVirtualNetworkConfigFunction,
  475. SnodeEventCallback,
  476. ((_overrideRootTopology.length() > 0) ? _overrideRootTopology.c_str() : (const char *)0));
  477. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  478. _node->setNetconfMaster((void *)&_controller);
  479. #endif
  480. _controlPlane = new ControlPlane(this,_node,(_homePath + ZT_PATH_SEPARATOR_S + "ui").c_str());
  481. _controlPlane->addAuthToken(authToken.c_str());
  482. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  483. _controlPlane->setController(&_controller);
  484. #endif
  485. { // Remember networks from previous session
  486. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S + "networks.d").c_str()));
  487. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  488. std::size_t dot = f->find_last_of('.');
  489. if ((dot == 16)&&(f->substr(16) == ".conf"))
  490. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()));
  491. }
  492. }
  493. _nextBackgroundTaskDeadline = 0;
  494. uint64_t clockShouldBe = OSUtils::now();
  495. _lastRestart = clockShouldBe;
  496. uint64_t lastTapMulticastGroupCheck = 0;
  497. uint64_t lastTcpFallbackResolve = 0;
  498. uint64_t lastLocalInterfaceAddressCheck = (OSUtils::now() - ZT_LOCAL_INTERFACE_CHECK_INTERVAL) + 15000; // do this in 15s to give UPnP time to configure and other things time to settle
  499. #ifdef ZT_AUTO_UPDATE
  500. uint64_t lastSoftwareUpdateCheck = 0;
  501. #endif // ZT_AUTO_UPDATE
  502. for(;;) {
  503. _run_m.lock();
  504. if (!_run) {
  505. _run_m.unlock();
  506. _termReason_m.lock();
  507. _termReason = ONE_NORMAL_TERMINATION;
  508. _termReason_m.unlock();
  509. break;
  510. } else _run_m.unlock();
  511. uint64_t now = OSUtils::now();
  512. uint64_t dl = _nextBackgroundTaskDeadline;
  513. if (dl <= now) {
  514. _node->processBackgroundTasks(now,&_nextBackgroundTaskDeadline);
  515. dl = _nextBackgroundTaskDeadline;
  516. }
  517. // Attempt to detect sleep/wake events by detecting delay overruns
  518. if ((now > clockShouldBe)&&((now - clockShouldBe) > 2000))
  519. _lastRestart = now;
  520. #ifdef ZT_AUTO_UPDATE
  521. if ((now - lastSoftwareUpdateCheck) >= ZT_AUTO_UPDATE_CHECK_PERIOD) {
  522. lastSoftwareUpdateCheck = now;
  523. Thread::start(&backgroundSoftwareUpdateChecker);
  524. }
  525. #endif // ZT_AUTO_UPDATE
  526. if ((now - lastTcpFallbackResolve) >= ZT_TCP_FALLBACK_RERESOLVE_DELAY) {
  527. lastTcpFallbackResolve = now;
  528. _tcpFallbackResolver.resolveNow();
  529. }
  530. if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2)))
  531. _phy.close(_tcpFallbackTunnel->sock);
  532. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  533. lastTapMulticastGroupCheck = now;
  534. Mutex::Lock _l(_taps_m);
  535. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t) {
  536. std::vector<MulticastGroup> added,removed;
  537. t->second->scanMulticastGroups(added,removed);
  538. for(std::vector<MulticastGroup>::iterator m(added.begin());m!=added.end();++m)
  539. _node->multicastSubscribe(t->first,m->mac().toInt(),m->adi());
  540. for(std::vector<MulticastGroup>::iterator m(removed.begin());m!=removed.end();++m)
  541. _node->multicastUnsubscribe(t->first,m->mac().toInt(),m->adi());
  542. }
  543. }
  544. if ((now - lastLocalInterfaceAddressCheck) >= ZT_LOCAL_INTERFACE_CHECK_INTERVAL) {
  545. lastLocalInterfaceAddressCheck = now;
  546. #ifdef __UNIX_LIKE__
  547. std::vector<std::string> ztDevices;
  548. {
  549. Mutex::Lock _l(_taps_m);
  550. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t)
  551. ztDevices.push_back(t->second->deviceName());
  552. }
  553. _node->clearLocalInterfaceAddresses();
  554. #ifdef ZT_USE_MINIUPNPC
  555. std::vector<InetAddress> upnpAddresses(_upnpClient->get());
  556. for(std::vector<InetAddress>::const_iterator ext(upnpAddresses.begin());ext!=upnpAddresses.end();++ext)
  557. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)),0,ZT_LOCAL_INTERFACE_ADDRESS_TRUST_NORMAL);
  558. #endif
  559. struct ifaddrs *ifatbl = (struct ifaddrs *)0;
  560. if ((getifaddrs(&ifatbl) == 0)&&(ifatbl)) {
  561. struct ifaddrs *ifa = ifatbl;
  562. while (ifa) {
  563. if ((ifa->ifa_name)&&(ifa->ifa_addr)) {
  564. bool isZT = false;
  565. for(std::vector<std::string>::const_iterator d(ztDevices.begin());d!=ztDevices.end();++d) {
  566. if (*d == ifa->ifa_name) {
  567. isZT = true;
  568. break;
  569. }
  570. }
  571. if (!isZT) {
  572. InetAddress ip(ifa->ifa_addr);
  573. ip.setPort(_port);
  574. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip),0,ZT_LOCAL_INTERFACE_ADDRESS_TRUST_NORMAL);
  575. }
  576. }
  577. ifa = ifa->ifa_next;
  578. }
  579. freeifaddrs(ifatbl);
  580. }
  581. #endif // __UNIX_LIKE__
  582. #ifdef __WINDOWS__
  583. std::vector<NET_LUID> ztDevices;
  584. {
  585. Mutex::Lock _l(_taps_m);
  586. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t)
  587. ztDevices.push_back(t->second->luid());
  588. }
  589. char aabuf[16384];
  590. ULONG aalen = sizeof(aabuf);
  591. if (GetAdaptersAddresses(AF_UNSPEC,GAA_FLAG_SKIP_ANYCAST|GAA_FLAG_SKIP_MULTICAST|GAA_FLAG_SKIP_DNS_SERVER,(void *)0,reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf),&aalen) == NO_ERROR) {
  592. PIP_ADAPTER_ADDRESSES a = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf);
  593. while (a) {
  594. bool isZT = false;
  595. for(std::vector<NET_LUID>::const_iterator d(ztDevices.begin());d!=ztDevices.end();++d) {
  596. if (a->Luid.Value == d->Value) {
  597. isZT = true;
  598. break;
  599. }
  600. }
  601. if (!isZT) {
  602. PIP_ADAPTER_UNICAST_ADDRESS ua = a->FirstUnicastAddress;
  603. while (ua) {
  604. InetAddress ip(ua->Address.lpSockaddr);
  605. ip.setPort(_port);
  606. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip),0,ZT_LOCAL_INTERFACE_ADDRESS_TRUST_NORMAL);
  607. ua = ua->Next;
  608. }
  609. }
  610. a = a->Next;
  611. }
  612. }
  613. #endif // __WINDOWS__
  614. }
  615. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  616. clockShouldBe = now + (uint64_t)delay;
  617. _phy.poll(delay);
  618. }
  619. } catch (std::exception &exc) {
  620. Mutex::Lock _l(_termReason_m);
  621. _termReason = ONE_UNRECOVERABLE_ERROR;
  622. _fatalErrorMessage = exc.what();
  623. } catch ( ... ) {
  624. Mutex::Lock _l(_termReason_m);
  625. _termReason = ONE_UNRECOVERABLE_ERROR;
  626. _fatalErrorMessage = "unexpected exception in main thread";
  627. }
  628. try {
  629. while (!_tcpConnections.empty())
  630. _phy.close((*_tcpConnections.begin())->sock);
  631. } catch ( ... ) {}
  632. {
  633. Mutex::Lock _l(_taps_m);
  634. for(std::map< uint64_t,EthernetTap * >::iterator t(_taps.begin());t!=_taps.end();++t)
  635. delete t->second;
  636. _taps.clear();
  637. }
  638. delete _controlPlane;
  639. _controlPlane = (ControlPlane *)0;
  640. delete _node;
  641. _node = (Node *)0;
  642. return _termReason;
  643. }
  644. virtual ReasonForTermination reasonForTermination() const
  645. {
  646. Mutex::Lock _l(_termReason_m);
  647. return _termReason;
  648. }
  649. virtual std::string fatalErrorMessage() const
  650. {
  651. Mutex::Lock _l(_termReason_m);
  652. return _fatalErrorMessage;
  653. }
  654. virtual std::string portDeviceName(uint64_t nwid) const
  655. {
  656. Mutex::Lock _l(_taps_m);
  657. std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.find(nwid));
  658. if (t != _taps.end())
  659. return t->second->deviceName();
  660. return std::string();
  661. }
  662. virtual bool tcpFallbackActive() const
  663. {
  664. return (_tcpFallbackTunnel != (TcpConnection *)0);
  665. }
  666. virtual void terminate()
  667. {
  668. _run_m.lock();
  669. _run = false;
  670. _run_m.unlock();
  671. _phy.whack();
  672. }
  673. // Begin private implementation methods
  674. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
  675. {
  676. #ifdef ZT_BREAK_UDP
  677. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  678. return;
  679. #endif
  680. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  681. _lastDirectReceiveFromGlobal = OSUtils::now();
  682. ZT_ResultCode rc = _node->processWirePacket(
  683. OSUtils::now(),
  684. reinterpret_cast<const struct sockaddr_storage *>(*uptr),
  685. (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
  686. data,
  687. len,
  688. &_nextBackgroundTaskDeadline);
  689. if (ZT_ResultCode_isFatal(rc)) {
  690. char tmp[256];
  691. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  692. Mutex::Lock _l(_termReason_m);
  693. _termReason = ONE_UNRECOVERABLE_ERROR;
  694. _fatalErrorMessage = tmp;
  695. this->terminate();
  696. }
  697. }
  698. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  699. {
  700. if (!success)
  701. return;
  702. // Outgoing TCP connections are always TCP fallback tunnel connections.
  703. TcpConnection *tc = new TcpConnection();
  704. _tcpConnections.insert(tc);
  705. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  706. tc->shouldKeepAlive = true;
  707. tc->parent = this;
  708. tc->sock = sock;
  709. // from and parser are not used
  710. tc->messageSize = 0; // unused
  711. tc->lastActivity = OSUtils::now();
  712. // HTTP stuff is not used
  713. tc->writeBuf = "";
  714. *uptr = (void *)tc;
  715. // Send "hello" message
  716. tc->writeBuf.push_back((char)0x17);
  717. tc->writeBuf.push_back((char)0x03);
  718. tc->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  719. tc->writeBuf.push_back((char)0x00);
  720. tc->writeBuf.push_back((char)0x04); // mlen == 4
  721. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MAJOR);
  722. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MINOR);
  723. tc->writeBuf.push_back((char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff));
  724. tc->writeBuf.push_back((char)(ZEROTIER_ONE_VERSION_REVISION & 0xff));
  725. _phy.setNotifyWritable(sock,true);
  726. _tcpFallbackTunnel = tc;
  727. }
  728. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  729. {
  730. // Incoming TCP connections are HTTP JSON API requests.
  731. TcpConnection *tc = new TcpConnection();
  732. _tcpConnections.insert(tc);
  733. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  734. tc->shouldKeepAlive = true;
  735. tc->parent = this;
  736. tc->sock = sockN;
  737. tc->from = from;
  738. http_parser_init(&(tc->parser),HTTP_REQUEST);
  739. tc->parser.data = (void *)tc;
  740. tc->messageSize = 0;
  741. tc->lastActivity = OSUtils::now();
  742. tc->currentHeaderField = "";
  743. tc->currentHeaderValue = "";
  744. tc->url = "";
  745. tc->status = "";
  746. tc->headers.clear();
  747. tc->body = "";
  748. tc->writeBuf = "";
  749. *uptrN = (void *)tc;
  750. }
  751. inline void phyOnTcpClose(PhySocket *sock,void **uptr)
  752. {
  753. TcpConnection *tc = (TcpConnection *)*uptr;
  754. if (tc) {
  755. if (tc == _tcpFallbackTunnel)
  756. _tcpFallbackTunnel = (TcpConnection *)0;
  757. _tcpConnections.erase(tc);
  758. delete tc;
  759. }
  760. }
  761. inline void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  762. {
  763. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  764. switch(tc->type) {
  765. case TcpConnection::TCP_HTTP_INCOMING:
  766. case TcpConnection::TCP_HTTP_OUTGOING:
  767. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  768. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK)) {
  769. _phy.close(sock);
  770. return;
  771. }
  772. break;
  773. case TcpConnection::TCP_TUNNEL_OUTGOING:
  774. tc->body.append((const char *)data,len);
  775. while (tc->body.length() >= 5) {
  776. const char *data = tc->body.data();
  777. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  778. if (tc->body.length() >= (mlen + 5)) {
  779. InetAddress from;
  780. unsigned long plen = mlen; // payload length, modified if there's an IP header
  781. data += 5; // skip forward past pseudo-TLS junk and mlen
  782. if (plen == 4) {
  783. // Hello message, which isn't sent by proxy and would be ignored by client
  784. } else if (plen) {
  785. // Messages should contain IPv4 or IPv6 source IP address data
  786. switch(data[0]) {
  787. case 4: // IPv4
  788. if (plen >= 7) {
  789. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  790. data += 7; // type + 4 byte IP + 2 byte port
  791. plen -= 7;
  792. } else {
  793. _phy.close(sock);
  794. return;
  795. }
  796. break;
  797. case 6: // IPv6
  798. if (plen >= 19) {
  799. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  800. data += 19; // type + 16 byte IP + 2 byte port
  801. plen -= 19;
  802. } else {
  803. _phy.close(sock);
  804. return;
  805. }
  806. break;
  807. case 0: // none/omitted
  808. ++data;
  809. --plen;
  810. break;
  811. default: // invalid address type
  812. _phy.close(sock);
  813. return;
  814. }
  815. if (from) {
  816. ZT_ResultCode rc = _node->processWirePacket(
  817. OSUtils::now(),
  818. 0,
  819. reinterpret_cast<struct sockaddr_storage *>(&from),
  820. data,
  821. plen,
  822. &_nextBackgroundTaskDeadline);
  823. if (ZT_ResultCode_isFatal(rc)) {
  824. char tmp[256];
  825. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  826. Mutex::Lock _l(_termReason_m);
  827. _termReason = ONE_UNRECOVERABLE_ERROR;
  828. _fatalErrorMessage = tmp;
  829. this->terminate();
  830. _phy.close(sock);
  831. return;
  832. }
  833. }
  834. }
  835. if (tc->body.length() > (mlen + 5))
  836. tc->body = tc->body.substr(mlen + 5);
  837. else tc->body = "";
  838. } else break;
  839. }
  840. break;
  841. }
  842. }
  843. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  844. {
  845. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  846. Mutex::Lock _l(tc->writeBuf_m);
  847. if (tc->writeBuf.length() > 0) {
  848. long sent = (long)_phy.streamSend(sock,tc->writeBuf.data(),(unsigned long)tc->writeBuf.length(),true);
  849. if (sent > 0) {
  850. tc->lastActivity = OSUtils::now();
  851. if ((unsigned long)sent >= (unsigned long)tc->writeBuf.length()) {
  852. tc->writeBuf = "";
  853. _phy.setNotifyWritable(sock,false);
  854. if (!tc->shouldKeepAlive)
  855. _phy.close(sock); // will call close handler to delete from _tcpConnections
  856. } else {
  857. tc->writeBuf = tc->writeBuf.substr(sent);
  858. }
  859. }
  860. } else {
  861. _phy.setNotifyWritable(sock,false);
  862. }
  863. }
  864. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  865. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  866. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  867. inline void phyOnUnixWritable(PhySocket *sock,void **uptr) {}
  868. inline void phyOnSocketPairEndpointClose(PhySocket *sock,void **uptr) {}
  869. inline void phyOnSocketPairEndpointData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  870. inline void phyOnSocketPairEndpointWritable(PhySocket *sock,void **uptr) {}
  871. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  872. {
  873. Mutex::Lock _l(_taps_m);
  874. std::map< uint64_t,EthernetTap * >::iterator t(_taps.find(nwid));
  875. switch(op) {
  876. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  877. if (t == _taps.end()) {
  878. try {
  879. char friendlyName[1024];
  880. Utils::snprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  881. t = _taps.insert(std::pair< uint64_t,EthernetTap *>(nwid,new EthernetTap(
  882. _homePath.c_str(),
  883. MAC(nwc->mac),
  884. nwc->mtu,
  885. (unsigned int)ZT_IF_METRIC,
  886. nwid,
  887. friendlyName,
  888. StapFrameHandler,
  889. (void *)this))).first;
  890. } catch (std::exception &exc) {
  891. #ifdef __WINDOWS__
  892. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  893. if (tapFailLog) {
  894. fprintf(tapFailLog,"%.16llx: %s"ZT_EOL_S,(unsigned long long)nwid,exc.what());
  895. fclose(tapFailLog);
  896. }
  897. #else
  898. fprintf(stderr,"ERROR: unable to configure virtual network port: %s"ZT_EOL_S,exc.what());
  899. #endif
  900. return -999;
  901. } catch ( ... ) {
  902. return -999; // tap init failed
  903. }
  904. }
  905. // fall through...
  906. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  907. if (t != _taps.end()) {
  908. t->second->setEnabled(nwc->enabled != 0);
  909. std::vector<InetAddress> &assignedIps = _tapAssignedIps[nwid];
  910. std::vector<InetAddress> newAssignedIps;
  911. for(unsigned int i=0;i<nwc->assignedAddressCount;++i)
  912. newAssignedIps.push_back(InetAddress(nwc->assignedAddresses[i]));
  913. std::sort(newAssignedIps.begin(),newAssignedIps.end());
  914. newAssignedIps.erase(std::unique(newAssignedIps.begin(),newAssignedIps.end()),newAssignedIps.end());
  915. for(std::vector<InetAddress>::iterator ip(newAssignedIps.begin());ip!=newAssignedIps.end();++ip) {
  916. if (!std::binary_search(assignedIps.begin(),assignedIps.end(),*ip))
  917. t->second->addIp(*ip);
  918. }
  919. for(std::vector<InetAddress>::iterator ip(assignedIps.begin());ip!=assignedIps.end();++ip) {
  920. if (!std::binary_search(newAssignedIps.begin(),newAssignedIps.end(),*ip))
  921. t->second->removeIp(*ip);
  922. }
  923. assignedIps.swap(newAssignedIps);
  924. } else {
  925. return -999; // tap init failed
  926. }
  927. break;
  928. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  929. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  930. if (t != _taps.end()) {
  931. #ifdef __WINDOWS__
  932. std::string winInstanceId(t->second->instanceId());
  933. #endif
  934. delete t->second;
  935. _taps.erase(t);
  936. _tapAssignedIps.erase(nwid);
  937. #ifdef __WINDOWS__
  938. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  939. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  940. #endif
  941. }
  942. break;
  943. }
  944. return 0;
  945. }
  946. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  947. {
  948. switch(event) {
  949. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  950. Mutex::Lock _l(_termReason_m);
  951. _termReason = ONE_IDENTITY_COLLISION;
  952. _fatalErrorMessage = "identity/address collision";
  953. this->terminate();
  954. } break;
  955. case ZT_EVENT_TRACE: {
  956. if (metaData) {
  957. ::fprintf(stderr,"%s"ZT_EOL_S,(const char *)metaData);
  958. ::fflush(stderr);
  959. }
  960. } break;
  961. default:
  962. break;
  963. }
  964. }
  965. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  966. {
  967. std::string p(_dataStorePrepPath(name));
  968. if (!p.length())
  969. return -2;
  970. FILE *f = fopen(p.c_str(),"rb");
  971. if (!f)
  972. return -1;
  973. if (fseek(f,0,SEEK_END) != 0) {
  974. fclose(f);
  975. return -2;
  976. }
  977. long ts = ftell(f);
  978. if (ts < 0) {
  979. fclose(f);
  980. return -2;
  981. }
  982. *totalSize = (unsigned long)ts;
  983. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  984. fclose(f);
  985. return -2;
  986. }
  987. long n = (long)fread(buf,1,bufSize,f);
  988. fclose(f);
  989. return n;
  990. }
  991. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  992. {
  993. std::string p(_dataStorePrepPath(name));
  994. if (!p.length())
  995. return -2;
  996. if (!data) {
  997. OSUtils::rm(p.c_str());
  998. return 0;
  999. }
  1000. FILE *f = fopen(p.c_str(),"wb");
  1001. if (!f)
  1002. return -1;
  1003. if (fwrite(data,len,1,f) == 1) {
  1004. fclose(f);
  1005. if (secure)
  1006. OSUtils::lockDownFile(p.c_str(),false);
  1007. return 0;
  1008. } else {
  1009. fclose(f);
  1010. OSUtils::rm(p.c_str());
  1011. return -1;
  1012. }
  1013. }
  1014. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len)
  1015. {
  1016. #ifdef ZT_USE_MINIUPNPC
  1017. if ((localAddr->ss_family == AF_INET)&&(reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port == reinterpret_cast<const struct sockaddr_in *>(&_v4UpnpLocalAddress)->sin_port)) {
  1018. #ifdef ZT_BREAK_UDP
  1019. if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
  1020. #endif
  1021. if (addr->ss_family == AF_INET)
  1022. return ((_phy.udpSend(_v4UpnpUdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
  1023. else return -1;
  1024. #ifdef ZT_BREAK_UDP
  1025. }
  1026. #endif
  1027. }
  1028. #endif // ZT_USE_MINIUPNPC
  1029. int result = -1;
  1030. switch(addr->ss_family) {
  1031. case AF_INET:
  1032. #ifdef ZT_BREAK_UDP
  1033. if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
  1034. #endif
  1035. if (_v4UdpSocket)
  1036. result = ((_phy.udpSend(_v4UdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
  1037. #ifdef ZT_BREAK_UDP
  1038. }
  1039. #endif
  1040. #ifdef ZT_TCP_FALLBACK_RELAY
  1041. // TCP fallback tunnel support
  1042. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  1043. uint64_t now = OSUtils::now();
  1044. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  1045. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  1046. // valid direct traffic we'll stop using it and close the socket after a while.
  1047. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  1048. if (_tcpFallbackTunnel) {
  1049. Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
  1050. if (!_tcpFallbackTunnel->writeBuf.length())
  1051. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  1052. unsigned long mlen = len + 7;
  1053. _tcpFallbackTunnel->writeBuf.push_back((char)0x17);
  1054. _tcpFallbackTunnel->writeBuf.push_back((char)0x03);
  1055. _tcpFallbackTunnel->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1056. _tcpFallbackTunnel->writeBuf.push_back((char)((mlen >> 8) & 0xff));
  1057. _tcpFallbackTunnel->writeBuf.push_back((char)(mlen & 0xff));
  1058. _tcpFallbackTunnel->writeBuf.push_back((char)4); // IPv4
  1059. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  1060. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  1061. _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
  1062. result = 0;
  1063. } else if (((now - _lastSendToGlobal) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobal) > (ZT_PING_CHECK_INVERVAL / 2))) {
  1064. std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
  1065. if (tunnelIps.empty()) {
  1066. if (!_tcpFallbackResolver.running())
  1067. _tcpFallbackResolver.resolveNow();
  1068. } else {
  1069. bool connected = false;
  1070. InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
  1071. addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
  1072. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
  1073. }
  1074. }
  1075. }
  1076. _lastSendToGlobal = now;
  1077. }
  1078. #endif // ZT_TCP_FALLBACK_RELAY
  1079. break;
  1080. case AF_INET6:
  1081. #ifdef ZT_BREAK_UDP
  1082. if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
  1083. #endif
  1084. if (_v6UdpSocket)
  1085. result = ((_phy.udpSend(_v6UdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
  1086. #ifdef ZT_BREAK_UDP
  1087. }
  1088. #endif
  1089. break;
  1090. default:
  1091. return -1;
  1092. }
  1093. return result;
  1094. }
  1095. inline void nodeVirtualNetworkFrameFunction(uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1096. {
  1097. Mutex::Lock _l(_taps_m);
  1098. std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.find(nwid));
  1099. if (t != _taps.end())
  1100. t->second->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1101. }
  1102. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1103. {
  1104. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1105. }
  1106. inline void onHttpRequestToServer(TcpConnection *tc)
  1107. {
  1108. char tmpn[256];
  1109. std::string data;
  1110. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1111. unsigned int scode = 404;
  1112. try {
  1113. if (_controlPlane)
  1114. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  1115. else scode = 500;
  1116. } catch ( ... ) {
  1117. scode = 500;
  1118. }
  1119. const char *scodestr;
  1120. switch(scode) {
  1121. case 200: scodestr = "OK"; break;
  1122. case 400: scodestr = "Bad Request"; break;
  1123. case 401: scodestr = "Unauthorized"; break;
  1124. case 403: scodestr = "Forbidden"; break;
  1125. case 404: scodestr = "Not Found"; break;
  1126. case 500: scodestr = "Internal Server Error"; break;
  1127. case 501: scodestr = "Not Implemented"; break;
  1128. case 503: scodestr = "Service Unavailable"; break;
  1129. default: scodestr = "Error"; break;
  1130. }
  1131. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  1132. {
  1133. Mutex::Lock _l(tc->writeBuf_m);
  1134. tc->writeBuf.assign(tmpn);
  1135. tc->writeBuf.append("Content-Type: ");
  1136. tc->writeBuf.append(contentType);
  1137. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  1138. tc->writeBuf.append(tmpn);
  1139. if (!tc->shouldKeepAlive)
  1140. tc->writeBuf.append("Connection: close\r\n");
  1141. tc->writeBuf.append("\r\n");
  1142. if (tc->parser.method != HTTP_HEAD)
  1143. tc->writeBuf.append(data);
  1144. }
  1145. _phy.setNotifyWritable(tc->sock,true);
  1146. }
  1147. inline void onHttpResponseFromClient(TcpConnection *tc)
  1148. {
  1149. if (!tc->shouldKeepAlive)
  1150. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConnections
  1151. }
  1152. private:
  1153. std::string _dataStorePrepPath(const char *name) const
  1154. {
  1155. std::string p(_homePath);
  1156. p.push_back(ZT_PATH_SEPARATOR);
  1157. char lastc = (char)0;
  1158. for(const char *n=name;(*n);++n) {
  1159. if ((*n == '.')&&(lastc == '.'))
  1160. return std::string(); // don't allow ../../ stuff as a precaution
  1161. if (*n == '/') {
  1162. OSUtils::mkdir(p.c_str());
  1163. p.push_back(ZT_PATH_SEPARATOR);
  1164. } else p.push_back(*n);
  1165. lastc = *n;
  1166. }
  1167. return p;
  1168. }
  1169. const std::string _homePath;
  1170. BackgroundResolver _tcpFallbackResolver;
  1171. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  1172. SqliteNetworkController _controller;
  1173. #endif
  1174. Phy<OneServiceImpl *> _phy;
  1175. std::string _overrideRootTopology;
  1176. Node *_node;
  1177. InetAddress _v4LocalAddress,_v6LocalAddress;
  1178. PhySocket *_v4UdpSocket;
  1179. PhySocket *_v6UdpSocket;
  1180. PhySocket *_v4TcpListenSocket;
  1181. PhySocket *_v6TcpListenSocket;
  1182. ControlPlane *_controlPlane;
  1183. uint64_t _lastDirectReceiveFromGlobal;
  1184. uint64_t _lastSendToGlobal;
  1185. uint64_t _lastRestart;
  1186. volatile uint64_t _nextBackgroundTaskDeadline;
  1187. std::map< uint64_t,EthernetTap * > _taps;
  1188. std::map< uint64_t,std::vector<InetAddress> > _tapAssignedIps; // ZeroTier assigned IPs, not user or dhcp assigned
  1189. Mutex _taps_m;
  1190. std::set< TcpConnection * > _tcpConnections; // no mutex for this since it's done in the main loop thread only
  1191. TcpConnection *_tcpFallbackTunnel;
  1192. ReasonForTermination _termReason;
  1193. std::string _fatalErrorMessage;
  1194. Mutex _termReason_m;
  1195. unsigned int _port;
  1196. #ifdef ZT_USE_MINIUPNPC
  1197. InetAddress _v4UpnpLocalAddress;
  1198. PhySocket *_v4UpnpUdpSocket;
  1199. UPNPClient *_upnpClient;
  1200. #endif
  1201. bool _run;
  1202. Mutex _run_m;
  1203. };
  1204. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  1205. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,op,nwconf); }
  1206. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData)
  1207. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1208. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1209. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  1210. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  1211. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  1212. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len)
  1213. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localAddr,addr,data,len); }
  1214. static void SnodeVirtualNetworkFrameFunction(ZT_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)
  1215. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,sourceMac,destMac,etherType,vlanId,data,len); }
  1216. static void StapFrameHandler(void *uptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1217. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1218. static int ShttpOnMessageBegin(http_parser *parser)
  1219. {
  1220. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1221. tc->currentHeaderField = "";
  1222. tc->currentHeaderValue = "";
  1223. tc->messageSize = 0;
  1224. tc->url = "";
  1225. tc->status = "";
  1226. tc->headers.clear();
  1227. tc->body = "";
  1228. return 0;
  1229. }
  1230. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  1231. {
  1232. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1233. tc->messageSize += (unsigned long)length;
  1234. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1235. return -1;
  1236. tc->url.append(ptr,length);
  1237. return 0;
  1238. }
  1239. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1240. {
  1241. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1242. tc->messageSize += (unsigned long)length;
  1243. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1244. return -1;
  1245. tc->status.append(ptr,length);
  1246. return 0;
  1247. }
  1248. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1249. {
  1250. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1251. tc->messageSize += (unsigned long)length;
  1252. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1253. return -1;
  1254. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1255. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1256. tc->currentHeaderField = "";
  1257. tc->currentHeaderValue = "";
  1258. }
  1259. for(size_t i=0;i<length;++i)
  1260. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1261. return 0;
  1262. }
  1263. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1264. {
  1265. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1266. tc->messageSize += (unsigned long)length;
  1267. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1268. return -1;
  1269. tc->currentHeaderValue.append(ptr,length);
  1270. return 0;
  1271. }
  1272. static int ShttpOnHeadersComplete(http_parser *parser)
  1273. {
  1274. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1275. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  1276. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1277. return 0;
  1278. }
  1279. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  1280. {
  1281. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1282. tc->messageSize += (unsigned long)length;
  1283. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1284. return -1;
  1285. tc->body.append(ptr,length);
  1286. return 0;
  1287. }
  1288. static int ShttpOnMessageComplete(http_parser *parser)
  1289. {
  1290. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1291. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  1292. tc->lastActivity = OSUtils::now();
  1293. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  1294. tc->parent->onHttpRequestToServer(tc);
  1295. } else {
  1296. tc->parent->onHttpResponseFromClient(tc);
  1297. }
  1298. return 0;
  1299. }
  1300. } // anonymous namespace
  1301. std::string OneService::platformDefaultHomePath()
  1302. {
  1303. #ifdef __UNIX_LIKE__
  1304. #ifdef __APPLE__
  1305. // /Library/... on Apple
  1306. return std::string("/Library/Application Support/ZeroTier/One");
  1307. #else
  1308. #ifdef __BSD__
  1309. // BSD likes /var/db instead of /var/lib
  1310. return std::string("/var/db/zerotier-one");
  1311. #else
  1312. // Use /var/lib for Linux and other *nix
  1313. return std::string("/var/lib/zerotier-one");
  1314. #endif
  1315. #endif
  1316. #else // not __UNIX_LIKE__
  1317. #ifdef __WINDOWS__
  1318. // Look up app data folder on Windows, e.g. C:\ProgramData\...
  1319. char buf[16384];
  1320. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_COMMON_APPDATA,NULL,0,buf)))
  1321. return (std::string(buf) + "\\ZeroTier\\One");
  1322. else return std::string("C:\\ZeroTier\\One");
  1323. #else
  1324. return std::string(); // UNKNOWN PLATFORM
  1325. #endif
  1326. #endif // __UNIX_LIKE__ or not...
  1327. }
  1328. std::string OneService::autoUpdateUrl()
  1329. {
  1330. #ifdef ZT_AUTO_UPDATE
  1331. /*
  1332. #if defined(__LINUX__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1333. if (sizeof(void *) == 8)
  1334. return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x64-LATEST.nfo";
  1335. else return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x86-LATEST.nfo";
  1336. #endif
  1337. */
  1338. #if defined(__APPLE__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1339. return "http://download.zerotier.com/update/mac_intel/";
  1340. #endif
  1341. #ifdef __WINDOWS__
  1342. return "http://download.zerotier.com/update/win_intel/";
  1343. #endif
  1344. #endif // ZT_AUTO_UPDATE
  1345. return std::string();
  1346. }
  1347. OneService *OneService::newInstance(const char *hp,unsigned int port,const char *overrideRootTopology) { return new OneServiceImpl(hp,port,overrideRootTopology); }
  1348. OneService::~OneService() {}
  1349. } // namespace ZeroTier