OneService.cpp 51 KB

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