OneService.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <stdint.h>
  22. #include <string>
  23. #include <map>
  24. #include <set>
  25. #include <vector>
  26. #include <algorithm>
  27. #include <list>
  28. #include "../version.h"
  29. #include "../include/ZeroTierOne.h"
  30. #ifdef ZT_USE_SYSTEM_HTTP_PARSER
  31. #include <http_parser.h>
  32. #else
  33. #include "../ext/http-parser/http_parser.h"
  34. #endif
  35. #include "../node/Constants.hpp"
  36. #include "../node/Mutex.hpp"
  37. #include "../node/Node.hpp"
  38. #include "../node/Utils.hpp"
  39. #include "../node/InetAddress.hpp"
  40. #include "../node/MAC.hpp"
  41. #include "../node/Identity.hpp"
  42. #include "../osdep/Phy.hpp"
  43. #include "../osdep/Thread.hpp"
  44. #include "../osdep/OSUtils.hpp"
  45. #include "../osdep/Http.hpp"
  46. #include "../osdep/BackgroundResolver.hpp"
  47. #include "../osdep/PortMapper.hpp"
  48. #include "../osdep/Binder.hpp"
  49. #include "../osdep/ManagedRoute.hpp"
  50. #include "OneService.hpp"
  51. #include "ControlPlane.hpp"
  52. #include "ClusterGeoIpService.hpp"
  53. #include "ClusterDefinition.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_SERVICE_NETCON
  83. // In network containers builds, use the virtual netcon endpoint instead of a tun/tap port driver
  84. #include "../netcon/NetconEthernetTap.hpp"
  85. namespace ZeroTier { typedef NetconEthernetTap EthernetTap; }
  86. #else // not ZT_SERVICE_NETCON so pick a tap driver
  87. #ifdef __APPLE__
  88. #include "../osdep/OSXEthernetTap.hpp"
  89. namespace ZeroTier { typedef OSXEthernetTap EthernetTap; }
  90. #endif // __APPLE__
  91. #ifdef __LINUX__
  92. #include "../osdep/LinuxEthernetTap.hpp"
  93. namespace ZeroTier { typedef LinuxEthernetTap EthernetTap; }
  94. #endif // __LINUX__
  95. #ifdef __WINDOWS__
  96. #include "../osdep/WindowsEthernetTap.hpp"
  97. namespace ZeroTier { typedef WindowsEthernetTap EthernetTap; }
  98. #endif // __WINDOWS__
  99. #ifdef __FreeBSD__
  100. #include "../osdep/BSDEthernetTap.hpp"
  101. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  102. #endif // __FreeBSD__
  103. #endif // ZT_SERVICE_NETCON
  104. // Sanity limits for HTTP
  105. #define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 64)
  106. #define ZT_MAX_HTTP_CONNECTIONS 64
  107. // Interface metric for ZeroTier taps -- this ensures that if we are on WiFi and also
  108. // bridged via ZeroTier to the same LAN traffic will (if the OS is sane) prefer WiFi.
  109. #define ZT_IF_METRIC 5000
  110. // How often to check for new multicast subscriptions on a tap device
  111. #define ZT_TAP_CHECK_MULTICAST_INTERVAL 5000
  112. // Path under ZT1 home for controller database if controller is enabled
  113. #define ZT_CONTROLLER_DB_PATH "controller.db"
  114. // TCP fallback relay host -- geo-distributed using Amazon Route53 geo-aware DNS
  115. #define ZT_TCP_FALLBACK_RELAY "tcp-fallback.zerotier.com"
  116. #define ZT_TCP_FALLBACK_RELAY_PORT 443
  117. // Frequency at which we re-resolve the TCP fallback relay
  118. #define ZT_TCP_FALLBACK_RERESOLVE_DELAY 86400000
  119. // Attempt to engage TCP fallback after this many ms of no reply to packets sent to global-scope IPs
  120. #define ZT_TCP_FALLBACK_AFTER 60000
  121. // How often to check for local interface addresses
  122. #define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 60000
  123. namespace ZeroTier {
  124. namespace {
  125. #ifdef ZT_AUTO_UPDATE
  126. #define ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE (1024 * 1024 * 64)
  127. #define ZT_AUTO_UPDATE_CHECK_PERIOD 21600000
  128. class BackgroundSoftwareUpdateChecker
  129. {
  130. public:
  131. bool isValidSigningIdentity(const Identity &id)
  132. {
  133. return (
  134. /* 0001 - 0004 : obsolete, used in old versions */
  135. /* 0005 */ (id == Identity("ba57ea350e:0:9d4be6d7f86c5660d5ee1951a3d759aa6e12a84fc0c0b74639500f1dbc1a8c566622e7d1c531967ebceb1e9d1761342f88324a8ba520c93c35f92f35080fa23f"))
  136. /* 0006 */ ||(id == Identity("5067b21b83:0:8af477730f5055c48135b84bed6720a35bca4c0e34be4060a4c636288b1ec22217eb22709d610c66ed464c643130c51411bbb0294eef12fbe8ecc1a1e2c63a7a"))
  137. /* 0007 */ ||(id == Identity("4f5e97a8f1:0:57880d056d7baeb04bbc057d6f16e6cb41388570e87f01492fce882485f65a798648595610a3ad49885604e7fb1db2dd3c2c534b75e42c3c0b110ad07b4bb138"))
  138. /* 0008 */ ||(id == Identity("580bbb8e15:0:ad5ef31155bebc6bc413991992387e083fed26d699997ef76e7c947781edd47d1997161fa56ba337b1a2b44b129fd7c7197ce5185382f06011bc88d1363b4ddd"))
  139. );
  140. }
  141. void doUpdateCheck()
  142. {
  143. std::string url(OneService::autoUpdateUrl());
  144. if ((url.length() <= 7)||(url.substr(0,7) != "http://"))
  145. return;
  146. std::string httpHost;
  147. std::string httpPath;
  148. {
  149. std::size_t slashIdx = url.substr(7).find_first_of('/');
  150. if (slashIdx == std::string::npos) {
  151. httpHost = url.substr(7);
  152. httpPath = "/";
  153. } else {
  154. httpHost = url.substr(7,slashIdx);
  155. httpPath = url.substr(slashIdx + 7);
  156. }
  157. }
  158. if (httpHost.length() == 0)
  159. return;
  160. std::vector<InetAddress> ips(OSUtils::resolve(httpHost.c_str()));
  161. for(std::vector<InetAddress>::iterator ip(ips.begin());ip!=ips.end();++ip) {
  162. if (!ip->port())
  163. ip->setPort(80);
  164. std::string nfoPath = httpPath + "LATEST.nfo";
  165. std::map<std::string,std::string> requestHeaders,responseHeaders;
  166. std::string body;
  167. requestHeaders["Host"] = httpHost;
  168. 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);
  169. //fprintf(stderr,"UPDATE %s %s %u %lu\n",ip->toString().c_str(),nfoPath.c_str(),scode,body.length());
  170. if ((scode == 200)&&(body.length() > 0)) {
  171. /* NFO fields:
  172. *
  173. * file=<filename>
  174. * signedBy=<signing identity>
  175. * ed25519=<ed25519 ECC signature of archive in hex>
  176. * vMajor=<major version>
  177. * vMinor=<minor version>
  178. * vRevision=<revision> */
  179. Dictionary<4096> nfo(body.c_str());
  180. char tmp[2048];
  181. if (nfo.get("vMajor",tmp,sizeof(tmp)) <= 0) return;
  182. const unsigned int vMajor = Utils::strToUInt(tmp);
  183. if (nfo.get("vMinor",tmp,sizeof(tmp)) <= 0) return;
  184. const unsigned int vMinor = Utils::strToUInt(tmp);
  185. if (nfo.get("vRevision",tmp,sizeof(tmp)) <= 0) return;
  186. const unsigned int vRevision = Utils::strToUInt(tmp);
  187. if (Utils::compareVersion(vMajor,vMinor,vRevision,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION) <= 0) {
  188. //fprintf(stderr,"UPDATE %u.%u.%u is not newer than our version\n",vMajor,vMinor,vRevision);
  189. return;
  190. }
  191. if (nfo.get("signedBy",tmp,sizeof(tmp)) <= 0) return;
  192. Identity signedBy;
  193. if ((!signedBy.fromString(tmp))||(!isValidSigningIdentity(signedBy))) {
  194. //fprintf(stderr,"UPDATE invalid signedBy or not authorized signing identity.\n");
  195. return;
  196. }
  197. if (nfo.get("file",tmp,sizeof(tmp)) <= 0) return;
  198. std::string filePath(tmp);
  199. if ((!filePath.length())||(filePath.find("..") != std::string::npos))
  200. return;
  201. filePath = httpPath + filePath;
  202. std::string fileData;
  203. if (Http::GET(ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE,60000,reinterpret_cast<const struct sockaddr *>(&(*ip)),filePath.c_str(),requestHeaders,responseHeaders,fileData) != 200) {
  204. //fprintf(stderr,"UPDATE GET %s failed\n",filePath.c_str());
  205. return;
  206. }
  207. if (nfo.get("ed25519",tmp,sizeof(tmp)) <= 0) return;
  208. std::string ed25519(Utils::unhex(tmp));
  209. if ((ed25519.length() == 0)||(!signedBy.verify(fileData.data(),(unsigned int)fileData.length(),ed25519.data(),(unsigned int)ed25519.length()))) {
  210. //fprintf(stderr,"UPDATE %s failed signature check!\n",filePath.c_str());
  211. return;
  212. }
  213. /* --------------------------------------------------------------- */
  214. /* We made it! Begin OS-specific installation code. */
  215. #ifdef __APPLE__
  216. /* OSX version is in the form of a MacOSX .pkg file, so we will
  217. * launch installer (normally in /usr/sbin) to install it. It will
  218. * then turn around and shut down the service, update files, and
  219. * relaunch. */
  220. {
  221. char bashp[128],pkgp[128];
  222. Utils::snprintf(bashp,sizeof(bashp),"/tmp/ZeroTierOne-update-%u.%u.%u.sh",vMajor,vMinor,vRevision);
  223. Utils::snprintf(pkgp,sizeof(pkgp),"/tmp/ZeroTierOne-update-%u.%u.%u.pkg",vMajor,vMinor,vRevision);
  224. FILE *pkg = fopen(pkgp,"w");
  225. if ((!pkg)||(fwrite(fileData.data(),fileData.length(),1,pkg) != 1)) {
  226. fclose(pkg);
  227. unlink(bashp);
  228. unlink(pkgp);
  229. fprintf(stderr,"UPDATE error writing %s\n",pkgp);
  230. return;
  231. }
  232. fclose(pkg);
  233. FILE *bash = fopen(bashp,"w");
  234. if (!bash) {
  235. fclose(pkg);
  236. unlink(bashp);
  237. unlink(pkgp);
  238. fprintf(stderr,"UPDATE error writing %s\n",bashp);
  239. return;
  240. }
  241. fprintf(bash,
  242. "#!/bin/bash\n"
  243. "export PATH=/bin:/usr/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/sbin\n"
  244. "sleep 1\n"
  245. "installer -pkg \"%s\" -target /\n"
  246. "sleep 1\n"
  247. "rm -f \"%s\" \"%s\"\n"
  248. "exit 0\n",
  249. pkgp,
  250. pkgp,
  251. bashp);
  252. fclose(bash);
  253. long pid = (long)vfork();
  254. if (pid == 0) {
  255. setsid(); // detach from parent so that shell isn't killed when parent is killed
  256. signal(SIGHUP,SIG_IGN);
  257. signal(SIGTERM,SIG_IGN);
  258. signal(SIGQUIT,SIG_IGN);
  259. execl("/bin/bash","/bin/bash",bashp,(char *)0);
  260. exit(0);
  261. }
  262. }
  263. #endif // __APPLE__
  264. #ifdef __WINDOWS__
  265. /* Windows version comes in the form of .MSI package that
  266. * takes care of everything. */
  267. {
  268. char tempp[512],batp[512],msip[512],cmdline[512];
  269. if (GetTempPathA(sizeof(tempp),tempp) <= 0)
  270. return;
  271. CreateDirectoryA(tempp,(LPSECURITY_ATTRIBUTES)0);
  272. Utils::snprintf(batp,sizeof(batp),"%s\\ZeroTierOne-update-%u.%u.%u.bat",tempp,vMajor,vMinor,vRevision);
  273. Utils::snprintf(msip,sizeof(msip),"%s\\ZeroTierOne-update-%u.%u.%u.msi",tempp,vMajor,vMinor,vRevision);
  274. FILE *msi = fopen(msip,"wb");
  275. if ((!msi)||(fwrite(fileData.data(),(size_t)fileData.length(),1,msi) != 1)) {
  276. fclose(msi);
  277. return;
  278. }
  279. fclose(msi);
  280. FILE *bat = fopen(batp,"wb");
  281. if (!bat)
  282. return;
  283. fprintf(bat,
  284. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  285. "NET.EXE STOP \"ZeroTierOneService\"\r\n"
  286. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  287. "MSIEXEC.EXE /i \"%s\" /qn\r\n"
  288. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  289. "NET.EXE START \"ZeroTierOneService\"\r\n"
  290. "DEL \"%s\"\r\n"
  291. "DEL \"%s\"\r\n",
  292. msip,
  293. msip,
  294. batp);
  295. fclose(bat);
  296. STARTUPINFOA si;
  297. PROCESS_INFORMATION pi;
  298. memset(&si,0,sizeof(si));
  299. memset(&pi,0,sizeof(pi));
  300. Utils::snprintf(cmdline,sizeof(cmdline),"CMD.EXE /c \"%s\"",batp);
  301. CreateProcessA(NULL,cmdline,NULL,NULL,FALSE,CREATE_NO_WINDOW|CREATE_NEW_PROCESS_GROUP,NULL,NULL,&si,&pi);
  302. }
  303. #endif // __WINDOWS__
  304. /* --------------------------------------------------------------- */
  305. return;
  306. } // else try to fetch from next IP address
  307. }
  308. }
  309. void threadMain()
  310. throw()
  311. {
  312. try {
  313. this->doUpdateCheck();
  314. } catch ( ... ) {}
  315. }
  316. };
  317. static BackgroundSoftwareUpdateChecker backgroundSoftwareUpdateChecker;
  318. #endif // ZT_AUTO_UPDATE
  319. static bool isBlacklistedLocalInterfaceForZeroTierTraffic(const char *ifn)
  320. {
  321. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  322. if ((ifn[0] == 'l')&&(ifn[1] == 'o')) return true; // loopback
  323. if ((ifn[0] == 'z')&&(ifn[1] == 't')) return true; // sanity check: zt#
  324. if ((ifn[0] == 't')&&(ifn[1] == 'u')&&(ifn[2] == 'n')) return true; // tun# is probably an OpenVPN tunnel or similar
  325. if ((ifn[0] == 't')&&(ifn[1] == 'a')&&(ifn[2] == 'p')) return true; // tap# is probably an OpenVPN tunnel or similar
  326. #endif
  327. #ifdef __APPLE__
  328. if ((ifn[0] == 'l')&&(ifn[1] == 'o')) return true; // loopback
  329. if ((ifn[0] == 'z')&&(ifn[1] == 't')) return true; // sanity check: zt#
  330. if ((ifn[0] == 't')&&(ifn[1] == 'u')&&(ifn[2] == 'n')) return true; // tun# is probably an OpenVPN tunnel or similar
  331. if ((ifn[0] == 't')&&(ifn[1] == 'a')&&(ifn[2] == 'p')) return true; // tap# is probably an OpenVPN tunnel or similar
  332. if ((ifn[0] == 'u')&&(ifn[1] == 't')&&(ifn[2] == 'u')&&(ifn[3] == 'n')) return true; // ... as is utun#
  333. #endif
  334. return false;
  335. }
  336. static std::string _trimString(const std::string &s)
  337. {
  338. unsigned long end = (unsigned long)s.length();
  339. while (end) {
  340. char c = s[end - 1];
  341. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  342. --end;
  343. else break;
  344. }
  345. unsigned long start = 0;
  346. while (start < end) {
  347. char c = s[start];
  348. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  349. ++start;
  350. else break;
  351. }
  352. return s.substr(start,end - start);
  353. }
  354. class OneServiceImpl;
  355. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
  356. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData);
  357. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize);
  358. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure);
  359. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl);
  360. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  361. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr);
  362. #ifdef ZT_ENABLE_CLUSTER
  363. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len);
  364. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z);
  365. #endif
  366. 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);
  367. static int ShttpOnMessageBegin(http_parser *parser);
  368. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  369. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  370. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  371. #else
  372. static int ShttpOnStatus(http_parser *parser);
  373. #endif
  374. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  375. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  376. static int ShttpOnHeadersComplete(http_parser *parser);
  377. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  378. static int ShttpOnMessageComplete(http_parser *parser);
  379. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 1)
  380. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  381. ShttpOnMessageBegin,
  382. ShttpOnUrl,
  383. ShttpOnStatus,
  384. ShttpOnHeaderField,
  385. ShttpOnValue,
  386. ShttpOnHeadersComplete,
  387. ShttpOnBody,
  388. ShttpOnMessageComplete
  389. };
  390. #else
  391. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  392. ShttpOnMessageBegin,
  393. ShttpOnUrl,
  394. ShttpOnHeaderField,
  395. ShttpOnValue,
  396. ShttpOnHeadersComplete,
  397. ShttpOnBody,
  398. ShttpOnMessageComplete
  399. };
  400. #endif
  401. struct TcpConnection
  402. {
  403. enum {
  404. TCP_HTTP_INCOMING,
  405. TCP_HTTP_OUTGOING, // not currently used
  406. TCP_TUNNEL_OUTGOING // fale-SSL outgoing tunnel -- HTTP-related fields are not used
  407. } type;
  408. bool shouldKeepAlive;
  409. OneServiceImpl *parent;
  410. PhySocket *sock;
  411. InetAddress from;
  412. http_parser parser;
  413. unsigned long messageSize;
  414. uint64_t lastActivity;
  415. std::string currentHeaderField;
  416. std::string currentHeaderValue;
  417. std::string url;
  418. std::string status;
  419. std::map< std::string,std::string > headers;
  420. std::string body;
  421. std::string writeBuf;
  422. Mutex writeBuf_m;
  423. };
  424. // Used to pseudo-randomize local source port picking
  425. static volatile unsigned int _udpPortPickerCounter = 0;
  426. class OneServiceImpl : public OneService
  427. {
  428. public:
  429. // begin member variables --------------------------------------------------
  430. const std::string _homePath;
  431. BackgroundResolver _tcpFallbackResolver;
  432. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  433. SqliteNetworkController *_controller;
  434. #endif
  435. Phy<OneServiceImpl *> _phy;
  436. Node *_node;
  437. /*
  438. * To attempt to handle NAT/gateway craziness we use three local UDP ports:
  439. *
  440. * [0] is the normal/default port, usually 9993
  441. * [1] is a port dervied from our ZeroTier address
  442. * [2] is a port computed from the normal/default for use with uPnP/NAT-PMP mappings
  443. *
  444. * [2] exists because on some gateways trying to do regular NAT-t interferes
  445. * destructively with uPnP port mapping behavior in very weird buggy ways.
  446. * It's only used if uPnP/NAT-PMP is enabled in this build.
  447. */
  448. Binder _bindings[3];
  449. unsigned int _ports[3];
  450. uint16_t _portsBE[3]; // ports in big-endian network byte order as in sockaddr
  451. // Sockets for JSON API -- bound only to V4 and V6 localhost
  452. PhySocket *_v4TcpControlSocket;
  453. PhySocket *_v6TcpControlSocket;
  454. // JSON API handler
  455. ControlPlane *_controlPlane;
  456. // Time we last received a packet from a global address
  457. uint64_t _lastDirectReceiveFromGlobal;
  458. #ifdef ZT_TCP_FALLBACK_RELAY
  459. uint64_t _lastSendToGlobalV4;
  460. #endif
  461. // Last potential sleep/wake event
  462. uint64_t _lastRestart;
  463. // Deadline for the next background task service function
  464. volatile uint64_t _nextBackgroundTaskDeadline;
  465. // Configured networks
  466. struct NetworkState
  467. {
  468. NetworkState() :
  469. tap((EthernetTap *)0)
  470. {
  471. // Real defaults are in network 'up' code in network event handler
  472. settings.allowManaged = true;
  473. settings.allowGlobal = false;
  474. settings.allowDefault = false;
  475. }
  476. EthernetTap *tap;
  477. ZT_VirtualNetworkConfig config; // memcpy() of raw config from core
  478. std::vector<InetAddress> managedIps;
  479. std::list<ManagedRoute> managedRoutes;
  480. NetworkSettings settings;
  481. };
  482. std::map<uint64_t,NetworkState> _nets;
  483. Mutex _nets_m;
  484. // Active TCP/IP connections
  485. std::set< TcpConnection * > _tcpConnections; // no mutex for this since it's done in the main loop thread only
  486. TcpConnection *_tcpFallbackTunnel;
  487. // Termination status information
  488. ReasonForTermination _termReason;
  489. std::string _fatalErrorMessage;
  490. Mutex _termReason_m;
  491. // uPnP/NAT-PMP port mapper if enabled
  492. #ifdef ZT_USE_MINIUPNPC
  493. PortMapper *_portMapper;
  494. #endif
  495. // Cluster management instance if enabled
  496. #ifdef ZT_ENABLE_CLUSTER
  497. PhySocket *_clusterMessageSocket;
  498. ClusterDefinition *_clusterDefinition;
  499. unsigned int _clusterMemberId;
  500. #endif
  501. // Set to false to force service to stop
  502. volatile bool _run;
  503. Mutex _run_m;
  504. // end member variables ----------------------------------------------------
  505. OneServiceImpl(const char *hp,unsigned int port) :
  506. _homePath((hp) ? hp : ".")
  507. ,_tcpFallbackResolver(ZT_TCP_FALLBACK_RELAY)
  508. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  509. ,_controller((SqliteNetworkController *)0)
  510. #endif
  511. ,_phy(this,false,true)
  512. ,_node((Node *)0)
  513. ,_controlPlane((ControlPlane *)0)
  514. ,_lastDirectReceiveFromGlobal(0)
  515. #ifdef ZT_TCP_FALLBACK_RELAY
  516. ,_lastSendToGlobalV4(0)
  517. #endif
  518. ,_lastRestart(0)
  519. ,_nextBackgroundTaskDeadline(0)
  520. ,_tcpFallbackTunnel((TcpConnection *)0)
  521. ,_termReason(ONE_STILL_RUNNING)
  522. #ifdef ZT_USE_MINIUPNPC
  523. ,_portMapper((PortMapper *)0)
  524. #endif
  525. #ifdef ZT_ENABLE_CLUSTER
  526. ,_clusterMessageSocket((PhySocket *)0)
  527. ,_clusterDefinition((ClusterDefinition *)0)
  528. ,_clusterMemberId(0)
  529. #endif
  530. ,_run(true)
  531. {
  532. _ports[0] = 0;
  533. _ports[1] = 0;
  534. _ports[2] = 0;
  535. // The control socket is bound to the default/static port on localhost. If we
  536. // can do this, we have successfully allocated a port. The binders will take
  537. // care of binding non-local addresses for ZeroTier traffic.
  538. const int portTrials = (port == 0) ? 256 : 1; // if port is 0, pick random
  539. for(int k=0;k<portTrials;++k) {
  540. if (port == 0) {
  541. unsigned int randp = 0;
  542. Utils::getSecureRandom(&randp,sizeof(randp));
  543. port = 20000 + (randp % 45500);
  544. }
  545. if (_trialBind(port)) {
  546. struct sockaddr_in in4;
  547. memset(&in4,0,sizeof(in4));
  548. in4.sin_family = AF_INET;
  549. in4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001); // right now we just listen for TCP @127.0.0.1
  550. in4.sin_port = Utils::hton((uint16_t)port);
  551. _v4TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
  552. struct sockaddr_in6 in6;
  553. memset((void *)&in6,0,sizeof(in6));
  554. in6.sin6_family = AF_INET6;
  555. in6.sin6_port = in4.sin_port;
  556. in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
  557. _v6TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
  558. // We must bind one of IPv4 or IPv6 -- support either failing to support hosts that
  559. // have only IPv4 or only IPv6 stacks.
  560. if ((_v4TcpControlSocket)||(_v6TcpControlSocket)) {
  561. _ports[0] = port;
  562. break;
  563. } else {
  564. if (_v4TcpControlSocket)
  565. _phy.close(_v4TcpControlSocket,false);
  566. if (_v6TcpControlSocket)
  567. _phy.close(_v6TcpControlSocket,false);
  568. port = 0;
  569. }
  570. } else {
  571. port = 0;
  572. }
  573. }
  574. if (_ports[0] == 0)
  575. throw std::runtime_error("cannot bind to local control interface port");
  576. char portstr[64];
  577. Utils::snprintf(portstr,sizeof(portstr),"%u",_ports[0]);
  578. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),std::string(portstr));
  579. }
  580. virtual ~OneServiceImpl()
  581. {
  582. for(int i=0;i<3;++i)
  583. _bindings[i].closeAll(_phy);
  584. _phy.close(_v4TcpControlSocket);
  585. _phy.close(_v6TcpControlSocket);
  586. #ifdef ZT_ENABLE_CLUSTER
  587. _phy.close(_clusterMessageSocket);
  588. #endif
  589. #ifdef ZT_USE_MINIUPNPC
  590. delete _portMapper;
  591. #endif
  592. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  593. delete _controller;
  594. #endif
  595. #ifdef ZT_ENABLE_CLUSTER
  596. delete _clusterDefinition;
  597. #endif
  598. }
  599. virtual ReasonForTermination run()
  600. {
  601. try {
  602. std::string authToken;
  603. {
  604. std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  605. if (!OSUtils::readFile(authTokenPath.c_str(),authToken)) {
  606. unsigned char foo[24];
  607. Utils::getSecureRandom(foo,sizeof(foo));
  608. authToken = "";
  609. for(unsigned int i=0;i<sizeof(foo);++i)
  610. authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  611. if (!OSUtils::writeFile(authTokenPath.c_str(),authToken)) {
  612. Mutex::Lock _l(_termReason_m);
  613. _termReason = ONE_UNRECOVERABLE_ERROR;
  614. _fatalErrorMessage = "authtoken.secret could not be written";
  615. return _termReason;
  616. } else {
  617. OSUtils::lockDownFile(authTokenPath.c_str(),false);
  618. }
  619. }
  620. }
  621. authToken = _trimString(authToken);
  622. _node = new Node(
  623. OSUtils::now(),
  624. this,
  625. SnodeDataStoreGetFunction,
  626. SnodeDataStorePutFunction,
  627. SnodeWirePacketSendFunction,
  628. SnodeVirtualNetworkFrameFunction,
  629. SnodeVirtualNetworkConfigFunction,
  630. SnodePathCheckFunction,
  631. SnodeEventCallback);
  632. // Attempt to bind to a secondary port chosen from our ZeroTier address.
  633. // This exists because there are buggy NATs out there that fail if more
  634. // than one device behind the same NAT tries to use the same internal
  635. // private address port number.
  636. _ports[1] = 20000 + ((unsigned int)_node->address() % 45500);
  637. for(int i=0;;++i) {
  638. if (i > 1000) {
  639. _ports[1] = 0;
  640. break;
  641. } else if (++_ports[1] >= 65536) {
  642. _ports[1] = 20000;
  643. }
  644. if (_trialBind(_ports[1]))
  645. break;
  646. }
  647. #ifdef ZT_USE_MINIUPNPC
  648. // If we're running uPnP/NAT-PMP, bind a *third* port for that. We can't
  649. // use the other two ports for that because some NATs do really funky
  650. // stuff with ports that are explicitly mapped that breaks things.
  651. if (_ports[1]) {
  652. _ports[2] = _ports[1];
  653. for(int i=0;;++i) {
  654. if (i > 1000) {
  655. _ports[2] = 0;
  656. break;
  657. } else if (++_ports[2] >= 65536) {
  658. _ports[2] = 20000;
  659. }
  660. if (_trialBind(_ports[2]))
  661. break;
  662. }
  663. if (_ports[2]) {
  664. char uniqueName[64];
  665. Utils::snprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]);
  666. _portMapper = new PortMapper(_ports[2],uniqueName);
  667. }
  668. }
  669. #endif
  670. for(int i=0;i<3;++i)
  671. _portsBE[i] = Utils::hton((uint16_t)_ports[i]);
  672. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  673. _controller = new SqliteNetworkController(_node,(_homePath + ZT_PATH_SEPARATOR_S + ZT_CONTROLLER_DB_PATH).c_str(),(_homePath + ZT_PATH_SEPARATOR_S + "circuitTestResults.d").c_str());
  674. _node->setNetconfMaster((void *)_controller);
  675. #endif
  676. #ifdef ZT_ENABLE_CLUSTER
  677. if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str())) {
  678. _clusterDefinition = new ClusterDefinition(_node->address(),(_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str());
  679. if (_clusterDefinition->size() > 0) {
  680. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  681. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  682. PhySocket *cs = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&(m->clusterEndpoint)));
  683. if (cs) {
  684. if (_clusterMessageSocket) {
  685. _phy.close(_clusterMessageSocket,false);
  686. _phy.close(cs,false);
  687. Mutex::Lock _l(_termReason_m);
  688. _termReason = ONE_UNRECOVERABLE_ERROR;
  689. _fatalErrorMessage = "Cluster: can't determine my cluster member ID: able to bind more than one cluster message socket IP/port!";
  690. return _termReason;
  691. }
  692. _clusterMessageSocket = cs;
  693. _clusterMemberId = m->id;
  694. }
  695. }
  696. if (!_clusterMessageSocket) {
  697. Mutex::Lock _l(_termReason_m);
  698. _termReason = ONE_UNRECOVERABLE_ERROR;
  699. _fatalErrorMessage = "Cluster: can't determine my cluster member ID: unable to bind to any cluster message socket IP/port.";
  700. return _termReason;
  701. }
  702. const ClusterDefinition::MemberDefinition &me = (*_clusterDefinition)[_clusterMemberId];
  703. InetAddress endpoints[255];
  704. unsigned int numEndpoints = 0;
  705. for(std::vector<InetAddress>::const_iterator i(me.zeroTierEndpoints.begin());i!=me.zeroTierEndpoints.end();++i)
  706. endpoints[numEndpoints++] = *i;
  707. if (_node->clusterInit(_clusterMemberId,reinterpret_cast<const struct sockaddr_storage *>(endpoints),numEndpoints,me.x,me.y,me.z,&SclusterSendFunction,this,_clusterDefinition->geo().available() ? &SclusterGeoIpFunction : 0,this) == ZT_RESULT_OK) {
  708. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  709. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  710. if (m->id != _clusterMemberId)
  711. _node->clusterAddMember(m->id);
  712. }
  713. }
  714. } else {
  715. delete _clusterDefinition;
  716. _clusterDefinition = (ClusterDefinition *)0;
  717. }
  718. }
  719. #endif
  720. _controlPlane = new ControlPlane(this,_node,(_homePath + ZT_PATH_SEPARATOR_S + "ui").c_str());
  721. _controlPlane->addAuthToken(authToken.c_str());
  722. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  723. _controlPlane->setController(_controller);
  724. #endif
  725. { // Remember networks from previous session
  726. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S + "networks.d").c_str()));
  727. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  728. std::size_t dot = f->find_last_of('.');
  729. if ((dot == 16)&&(f->substr(16) == ".conf"))
  730. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()),(void *)0);
  731. }
  732. }
  733. // Start two background threads to handle expensive ops out of line
  734. Thread::start(_node);
  735. Thread::start(_node);
  736. _nextBackgroundTaskDeadline = 0;
  737. uint64_t clockShouldBe = OSUtils::now();
  738. _lastRestart = clockShouldBe;
  739. uint64_t lastTapMulticastGroupCheck = 0;
  740. uint64_t lastTcpFallbackResolve = 0;
  741. uint64_t lastBindRefresh = 0;
  742. uint64_t lastLocalInterfaceAddressCheck = (OSUtils::now() - ZT_LOCAL_INTERFACE_CHECK_INTERVAL) + 15000; // do this in 15s to give portmapper time to configure and other things time to settle
  743. #ifdef ZT_AUTO_UPDATE
  744. uint64_t lastSoftwareUpdateCheck = 0;
  745. #endif // ZT_AUTO_UPDATE
  746. for(;;) {
  747. _run_m.lock();
  748. if (!_run) {
  749. _run_m.unlock();
  750. _termReason_m.lock();
  751. _termReason = ONE_NORMAL_TERMINATION;
  752. _termReason_m.unlock();
  753. break;
  754. } else {
  755. _run_m.unlock();
  756. }
  757. const uint64_t now = OSUtils::now();
  758. // Attempt to detect sleep/wake events by detecting delay overruns
  759. bool restarted = false;
  760. if ((now > clockShouldBe)&&((now - clockShouldBe) > 10000)) {
  761. _lastRestart = now;
  762. restarted = true;
  763. }
  764. // Refresh bindings in case device's interfaces have changed, and also sync routes to update any shadow routes (e.g. shadow default)
  765. if (((now - lastBindRefresh) >= ZT_BINDER_REFRESH_PERIOD)||(restarted)) {
  766. lastBindRefresh = now;
  767. for(int i=0;i<3;++i) {
  768. if (_ports[i]) {
  769. _bindings[i].refresh(_phy,_ports[i],*this);
  770. }
  771. }
  772. {
  773. Mutex::Lock _l(_nets_m);
  774. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n) {
  775. if (n->second.tap)
  776. syncManagedStuff(n->second,false,true);
  777. }
  778. }
  779. }
  780. uint64_t dl = _nextBackgroundTaskDeadline;
  781. if (dl <= now) {
  782. _node->processBackgroundTasks(now,&_nextBackgroundTaskDeadline);
  783. dl = _nextBackgroundTaskDeadline;
  784. }
  785. #ifdef ZT_AUTO_UPDATE
  786. if ((now - lastSoftwareUpdateCheck) >= ZT_AUTO_UPDATE_CHECK_PERIOD) {
  787. lastSoftwareUpdateCheck = now;
  788. Thread::start(&backgroundSoftwareUpdateChecker);
  789. }
  790. #endif // ZT_AUTO_UPDATE
  791. if ((now - lastTcpFallbackResolve) >= ZT_TCP_FALLBACK_RERESOLVE_DELAY) {
  792. lastTcpFallbackResolve = now;
  793. _tcpFallbackResolver.resolveNow();
  794. }
  795. if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2)))
  796. _phy.close(_tcpFallbackTunnel->sock);
  797. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  798. lastTapMulticastGroupCheck = now;
  799. Mutex::Lock _l(_nets_m);
  800. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  801. if (n->second.tap) {
  802. std::vector<MulticastGroup> added,removed;
  803. n->second.tap->scanMulticastGroups(added,removed);
  804. for(std::vector<MulticastGroup>::iterator m(added.begin());m!=added.end();++m)
  805. _node->multicastSubscribe(n->first,m->mac().toInt(),m->adi());
  806. for(std::vector<MulticastGroup>::iterator m(removed.begin());m!=removed.end();++m)
  807. _node->multicastUnsubscribe(n->first,m->mac().toInt(),m->adi());
  808. }
  809. }
  810. }
  811. if ((now - lastLocalInterfaceAddressCheck) >= ZT_LOCAL_INTERFACE_CHECK_INTERVAL) {
  812. lastLocalInterfaceAddressCheck = now;
  813. _node->clearLocalInterfaceAddresses();
  814. #ifdef ZT_USE_MINIUPNPC
  815. if (_portMapper) {
  816. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  817. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  818. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  819. }
  820. #endif
  821. std::vector<InetAddress> boundAddrs(_bindings[0].allBoundLocalInterfaceAddresses());
  822. for(std::vector<InetAddress>::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i)
  823. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*i)));
  824. }
  825. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  826. clockShouldBe = now + (uint64_t)delay;
  827. _phy.poll(delay);
  828. }
  829. } catch (std::exception &exc) {
  830. Mutex::Lock _l(_termReason_m);
  831. _termReason = ONE_UNRECOVERABLE_ERROR;
  832. _fatalErrorMessage = exc.what();
  833. } catch ( ... ) {
  834. Mutex::Lock _l(_termReason_m);
  835. _termReason = ONE_UNRECOVERABLE_ERROR;
  836. _fatalErrorMessage = "unexpected exception in main thread";
  837. }
  838. try {
  839. while (!_tcpConnections.empty())
  840. _phy.close((*_tcpConnections.begin())->sock);
  841. } catch ( ... ) {}
  842. {
  843. Mutex::Lock _l(_nets_m);
  844. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n)
  845. delete n->second.tap;
  846. _nets.clear();
  847. }
  848. delete _controlPlane;
  849. _controlPlane = (ControlPlane *)0;
  850. delete _node;
  851. _node = (Node *)0;
  852. return _termReason;
  853. }
  854. virtual ReasonForTermination reasonForTermination() const
  855. {
  856. Mutex::Lock _l(_termReason_m);
  857. return _termReason;
  858. }
  859. virtual std::string fatalErrorMessage() const
  860. {
  861. Mutex::Lock _l(_termReason_m);
  862. return _fatalErrorMessage;
  863. }
  864. virtual std::string portDeviceName(uint64_t nwid) const
  865. {
  866. Mutex::Lock _l(_nets_m);
  867. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  868. if ((n != _nets.end())&&(n->second.tap))
  869. return n->second.tap->deviceName();
  870. else return std::string();
  871. }
  872. virtual bool tcpFallbackActive() const
  873. {
  874. return (_tcpFallbackTunnel != (TcpConnection *)0);
  875. }
  876. virtual void terminate()
  877. {
  878. _run_m.lock();
  879. _run = false;
  880. _run_m.unlock();
  881. _phy.whack();
  882. }
  883. virtual bool getNetworkSettings(const uint64_t nwid,NetworkSettings &settings) const
  884. {
  885. Mutex::Lock _l(_nets_m);
  886. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  887. if (n == _nets.end())
  888. return false;
  889. memcpy(&settings,&(n->second.settings),sizeof(NetworkSettings));
  890. return true;
  891. }
  892. virtual bool setNetworkSettings(const uint64_t nwid,const NetworkSettings &settings)
  893. {
  894. Mutex::Lock _l(_nets_m);
  895. std::map<uint64_t,NetworkState>::iterator n(_nets.find(nwid));
  896. if (n == _nets.end())
  897. return false;
  898. memcpy(&(n->second.settings),&settings,sizeof(NetworkSettings));
  899. char nlcpath[256];
  900. Utils::snprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  901. FILE *out = fopen(nlcpath,"w");
  902. if (out) {
  903. fprintf(out,"allowManaged=%d\n",(int)n->second.settings.allowManaged);
  904. fprintf(out,"allowGlobal=%d\n",(int)n->second.settings.allowGlobal);
  905. fprintf(out,"allowDefault=%d\n",(int)n->second.settings.allowDefault);
  906. fclose(out);
  907. }
  908. if (n->second.tap)
  909. syncManagedStuff(n->second,true,true);
  910. return true;
  911. }
  912. // Begin private implementation methods
  913. // Checks if a managed IP or route target is allowed
  914. bool checkIfManagedIsAllowed(const NetworkState &n,const InetAddress &target)
  915. {
  916. if (!n.settings.allowManaged)
  917. return false;
  918. if (target.isDefaultRoute())
  919. return n.settings.allowDefault;
  920. switch(target.ipScope()) {
  921. case InetAddress::IP_SCOPE_NONE:
  922. case InetAddress::IP_SCOPE_MULTICAST:
  923. case InetAddress::IP_SCOPE_LOOPBACK:
  924. case InetAddress::IP_SCOPE_LINK_LOCAL:
  925. return false;
  926. case InetAddress::IP_SCOPE_GLOBAL:
  927. return n.settings.allowGlobal;
  928. default:
  929. return true;
  930. }
  931. }
  932. // Apply or update managed IPs for a configured network (be sure n.tap exists)
  933. void syncManagedStuff(NetworkState &n,bool syncIps,bool syncRoutes)
  934. {
  935. // assumes _nets_m is locked
  936. if (syncIps) {
  937. std::vector<InetAddress> newManagedIps;
  938. newManagedIps.reserve(n.config.assignedAddressCount);
  939. for(unsigned int i=0;i<n.config.assignedAddressCount;++i) {
  940. const InetAddress *ii = reinterpret_cast<const InetAddress *>(&(n.config.assignedAddresses[i]));
  941. if (checkIfManagedIsAllowed(n,*ii))
  942. newManagedIps.push_back(*ii);
  943. }
  944. std::sort(newManagedIps.begin(),newManagedIps.end());
  945. newManagedIps.erase(std::unique(newManagedIps.begin(),newManagedIps.end()),newManagedIps.end());
  946. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  947. if (std::find(newManagedIps.begin(),newManagedIps.end(),*ip) == newManagedIps.end()) {
  948. if (!n.tap->removeIp(*ip))
  949. fprintf(stderr,"ERROR: unable to remove ip address %s"ZT_EOL_S, ip->toString().c_str());
  950. }
  951. }
  952. for(std::vector<InetAddress>::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) {
  953. if (std::find(n.managedIps.begin(),n.managedIps.end(),*ip) == n.managedIps.end()) {
  954. if (!n.tap->addIp(*ip))
  955. fprintf(stderr,"ERROR: unable to add ip address %s"ZT_EOL_S, ip->toString().c_str());
  956. }
  957. }
  958. n.managedIps.swap(newManagedIps);
  959. }
  960. if (syncRoutes) {
  961. char tapdev[64];
  962. #ifdef __WINDOWS__
  963. Utils::snprintf(tapdev,sizeof(tapdev),"%.16llx",(unsigned long long)n.tap->luid().Value);
  964. #else
  965. Utils::scopy(tapdev,sizeof(tapdev),n.tap->deviceName().c_str());
  966. #endif
  967. std::vector<InetAddress> myIps(n.tap->ips());
  968. // Nuke applied routes that are no longer in n.config.routes[] and/or are not allowed
  969. for(std::list<ManagedRoute>::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();) {
  970. bool haveRoute = false;
  971. if ( (checkIfManagedIsAllowed(n,mr->target())) && ((!mr->via())||(std::find(myIps.begin(),myIps.end(),mr->via()) == myIps.end())) ) {
  972. for(unsigned int i=0;i<n.config.routeCount;++i) {
  973. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  974. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  975. if ( (mr->target() == *target) && ( ((via->ss_family == target->ss_family)&&(mr->via() == *via)) || (tapdev == mr->device()) ) ) {
  976. haveRoute = true;
  977. break;
  978. }
  979. }
  980. }
  981. if (haveRoute) {
  982. ++mr;
  983. } else {
  984. n.managedRoutes.erase(mr++);
  985. }
  986. }
  987. // Apply routes in n.config.routes[] that we haven't applied yet, and sync those we have in case shadow routes need to change
  988. for(unsigned int i=0;i<n.config.routeCount;++i) {
  989. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  990. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  991. if ( (!checkIfManagedIsAllowed(n,*target)) || ((via->ss_family == target->ss_family)&&(std::find(myIps.begin(),myIps.end(),*via) != myIps.end())) )
  992. continue;
  993. bool haveRoute = false;
  994. // Ignore routes implied by local managed IPs since adding the IP adds the route
  995. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  996. if ((target->netmaskBits() == ip->netmaskBits())&&(target->containsAddress(*ip))) {
  997. haveRoute = true;
  998. break;
  999. }
  1000. }
  1001. if (haveRoute)
  1002. continue;
  1003. // If we've already applied this route, just sync it and continue
  1004. for(std::list<ManagedRoute>::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();++mr) {
  1005. if ( (mr->target() == *target) && ( ((via->ss_family == target->ss_family)&&(mr->via() == *via)) || (tapdev == mr->device()) ) ) {
  1006. haveRoute = true;
  1007. mr->sync();
  1008. break;
  1009. }
  1010. }
  1011. if (haveRoute)
  1012. continue;
  1013. // Add and apply new routes
  1014. n.managedRoutes.push_back(ManagedRoute());
  1015. if (!n.managedRoutes.back().set(*target,*via,tapdev))
  1016. n.managedRoutes.pop_back();
  1017. }
  1018. }
  1019. }
  1020. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  1021. {
  1022. #ifdef ZT_ENABLE_CLUSTER
  1023. if (sock == _clusterMessageSocket) {
  1024. _lastDirectReceiveFromGlobal = OSUtils::now();
  1025. _node->clusterHandleIncomingMessage(data,len);
  1026. return;
  1027. }
  1028. #endif
  1029. #ifdef ZT_BREAK_UDP
  1030. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  1031. return;
  1032. #endif
  1033. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  1034. _lastDirectReceiveFromGlobal = OSUtils::now();
  1035. const ZT_ResultCode rc = _node->processWirePacket(
  1036. OSUtils::now(),
  1037. reinterpret_cast<const struct sockaddr_storage *>(localAddr),
  1038. (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
  1039. data,
  1040. len,
  1041. &_nextBackgroundTaskDeadline);
  1042. if (ZT_ResultCode_isFatal(rc)) {
  1043. char tmp[256];
  1044. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1045. Mutex::Lock _l(_termReason_m);
  1046. _termReason = ONE_UNRECOVERABLE_ERROR;
  1047. _fatalErrorMessage = tmp;
  1048. this->terminate();
  1049. }
  1050. }
  1051. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  1052. {
  1053. if (!success)
  1054. return;
  1055. // Outgoing TCP connections are always TCP fallback tunnel connections.
  1056. TcpConnection *tc = new TcpConnection();
  1057. _tcpConnections.insert(tc);
  1058. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  1059. tc->shouldKeepAlive = true;
  1060. tc->parent = this;
  1061. tc->sock = sock;
  1062. // from and parser are not used
  1063. tc->messageSize = 0; // unused
  1064. tc->lastActivity = OSUtils::now();
  1065. // HTTP stuff is not used
  1066. tc->writeBuf = "";
  1067. *uptr = (void *)tc;
  1068. // Send "hello" message
  1069. tc->writeBuf.push_back((char)0x17);
  1070. tc->writeBuf.push_back((char)0x03);
  1071. tc->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1072. tc->writeBuf.push_back((char)0x00);
  1073. tc->writeBuf.push_back((char)0x04); // mlen == 4
  1074. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MAJOR);
  1075. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MINOR);
  1076. tc->writeBuf.push_back((char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff));
  1077. tc->writeBuf.push_back((char)(ZEROTIER_ONE_VERSION_REVISION & 0xff));
  1078. _phy.setNotifyWritable(sock,true);
  1079. _tcpFallbackTunnel = tc;
  1080. }
  1081. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  1082. {
  1083. if ((!from)||(reinterpret_cast<const InetAddress *>(from)->ipScope() != InetAddress::IP_SCOPE_LOOPBACK)) {
  1084. // Non-Loopback: deny (for now)
  1085. _phy.close(sockN,false);
  1086. return;
  1087. } else {
  1088. // Loopback == HTTP JSON API request
  1089. TcpConnection *tc = new TcpConnection();
  1090. _tcpConnections.insert(tc);
  1091. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  1092. tc->shouldKeepAlive = true;
  1093. tc->parent = this;
  1094. tc->sock = sockN;
  1095. tc->from = from;
  1096. http_parser_init(&(tc->parser),HTTP_REQUEST);
  1097. tc->parser.data = (void *)tc;
  1098. tc->messageSize = 0;
  1099. tc->lastActivity = OSUtils::now();
  1100. tc->currentHeaderField = "";
  1101. tc->currentHeaderValue = "";
  1102. tc->url = "";
  1103. tc->status = "";
  1104. tc->headers.clear();
  1105. tc->body = "";
  1106. tc->writeBuf = "";
  1107. *uptrN = (void *)tc;
  1108. }
  1109. }
  1110. inline void phyOnTcpClose(PhySocket *sock,void **uptr)
  1111. {
  1112. TcpConnection *tc = (TcpConnection *)*uptr;
  1113. if (tc) {
  1114. if (tc == _tcpFallbackTunnel)
  1115. _tcpFallbackTunnel = (TcpConnection *)0;
  1116. _tcpConnections.erase(tc);
  1117. delete tc;
  1118. }
  1119. }
  1120. inline void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  1121. {
  1122. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1123. switch(tc->type) {
  1124. case TcpConnection::TCP_HTTP_INCOMING:
  1125. case TcpConnection::TCP_HTTP_OUTGOING:
  1126. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  1127. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK)) {
  1128. _phy.close(sock);
  1129. return;
  1130. }
  1131. break;
  1132. case TcpConnection::TCP_TUNNEL_OUTGOING:
  1133. tc->body.append((const char *)data,len);
  1134. while (tc->body.length() >= 5) {
  1135. const char *data = tc->body.data();
  1136. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  1137. if (tc->body.length() >= (mlen + 5)) {
  1138. InetAddress from;
  1139. unsigned long plen = mlen; // payload length, modified if there's an IP header
  1140. data += 5; // skip forward past pseudo-TLS junk and mlen
  1141. if (plen == 4) {
  1142. // Hello message, which isn't sent by proxy and would be ignored by client
  1143. } else if (plen) {
  1144. // Messages should contain IPv4 or IPv6 source IP address data
  1145. switch(data[0]) {
  1146. case 4: // IPv4
  1147. if (plen >= 7) {
  1148. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  1149. data += 7; // type + 4 byte IP + 2 byte port
  1150. plen -= 7;
  1151. } else {
  1152. _phy.close(sock);
  1153. return;
  1154. }
  1155. break;
  1156. case 6: // IPv6
  1157. if (plen >= 19) {
  1158. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  1159. data += 19; // type + 16 byte IP + 2 byte port
  1160. plen -= 19;
  1161. } else {
  1162. _phy.close(sock);
  1163. return;
  1164. }
  1165. break;
  1166. case 0: // none/omitted
  1167. ++data;
  1168. --plen;
  1169. break;
  1170. default: // invalid address type
  1171. _phy.close(sock);
  1172. return;
  1173. }
  1174. if (from) {
  1175. InetAddress fakeTcpLocalInterfaceAddress((uint32_t)0xffffffff,0xffff);
  1176. const ZT_ResultCode rc = _node->processWirePacket(
  1177. OSUtils::now(),
  1178. reinterpret_cast<struct sockaddr_storage *>(&fakeTcpLocalInterfaceAddress),
  1179. reinterpret_cast<struct sockaddr_storage *>(&from),
  1180. data,
  1181. plen,
  1182. &_nextBackgroundTaskDeadline);
  1183. if (ZT_ResultCode_isFatal(rc)) {
  1184. char tmp[256];
  1185. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1186. Mutex::Lock _l(_termReason_m);
  1187. _termReason = ONE_UNRECOVERABLE_ERROR;
  1188. _fatalErrorMessage = tmp;
  1189. this->terminate();
  1190. _phy.close(sock);
  1191. return;
  1192. }
  1193. }
  1194. }
  1195. if (tc->body.length() > (mlen + 5))
  1196. tc->body = tc->body.substr(mlen + 5);
  1197. else tc->body = "";
  1198. } else break;
  1199. }
  1200. break;
  1201. }
  1202. }
  1203. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  1204. {
  1205. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1206. Mutex::Lock _l(tc->writeBuf_m);
  1207. if (tc->writeBuf.length() > 0) {
  1208. long sent = (long)_phy.streamSend(sock,tc->writeBuf.data(),(unsigned long)tc->writeBuf.length(),true);
  1209. if (sent > 0) {
  1210. tc->lastActivity = OSUtils::now();
  1211. if ((unsigned long)sent >= (unsigned long)tc->writeBuf.length()) {
  1212. tc->writeBuf = "";
  1213. _phy.setNotifyWritable(sock,false);
  1214. if (!tc->shouldKeepAlive)
  1215. _phy.close(sock); // will call close handler to delete from _tcpConnections
  1216. } else {
  1217. tc->writeBuf = tc->writeBuf.substr(sent);
  1218. }
  1219. }
  1220. } else {
  1221. _phy.setNotifyWritable(sock,false);
  1222. }
  1223. }
  1224. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  1225. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  1226. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  1227. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  1228. inline void phyOnUnixWritable(PhySocket *sock,void **uptr,bool lwip_invoked) {}
  1229. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  1230. {
  1231. Mutex::Lock _l(_nets_m);
  1232. NetworkState &n = _nets[nwid];
  1233. switch(op) {
  1234. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  1235. if (!n.tap) {
  1236. try {
  1237. char friendlyName[128];
  1238. Utils::snprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  1239. n.tap = new EthernetTap(
  1240. _homePath.c_str(),
  1241. MAC(nwc->mac),
  1242. nwc->mtu,
  1243. (unsigned int)ZT_IF_METRIC,
  1244. nwid,
  1245. friendlyName,
  1246. StapFrameHandler,
  1247. (void *)this);
  1248. *nuptr = (void *)&n;
  1249. char nlcpath[256];
  1250. Utils::snprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1251. std::string nlcbuf;
  1252. if (OSUtils::readFile(nlcpath,nlcbuf)) {
  1253. Dictionary<4096> nc;
  1254. nc.load(nlcbuf.c_str());
  1255. n.settings.allowManaged = nc.getB("allowManaged",true);
  1256. n.settings.allowGlobal = nc.getB("allowGlobal",false);
  1257. n.settings.allowDefault = nc.getB("allowDefault",false);
  1258. }
  1259. } catch (std::exception &exc) {
  1260. #ifdef __WINDOWS__
  1261. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1262. if (tapFailLog) {
  1263. fprintf(tapFailLog,"%.16llx: %s"ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1264. fclose(tapFailLog);
  1265. }
  1266. #else
  1267. fprintf(stderr,"ERROR: unable to configure virtual network port: %s"ZT_EOL_S,exc.what());
  1268. #endif
  1269. _nets.erase(nwid);
  1270. return -999;
  1271. } catch ( ... ) {
  1272. return -999; // tap init failed
  1273. }
  1274. }
  1275. // After setting up tap, fall through to CONFIG_UPDATE since we also want to do this...
  1276. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1277. memcpy(&(n.config),nwc,sizeof(ZT_VirtualNetworkConfig));
  1278. if (n.tap) { // sanity check
  1279. syncManagedStuff(n,true,true);
  1280. } else {
  1281. _nets.erase(nwid);
  1282. return -999; // tap init failed
  1283. }
  1284. break;
  1285. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1286. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1287. if (n.tap) { // sanity check
  1288. #ifdef __WINDOWS__
  1289. std::string winInstanceId(n.tap->instanceId());
  1290. #endif
  1291. *nuptr = (void *)0;
  1292. delete n.tap;
  1293. _nets.erase(nwid);
  1294. #ifdef __WINDOWS__
  1295. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1296. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1297. #endif
  1298. if (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY) {
  1299. char nlcpath[256];
  1300. Utils::snprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1301. OSUtils::rm(nlcpath);
  1302. }
  1303. } else {
  1304. _nets.erase(nwid);
  1305. }
  1306. break;
  1307. }
  1308. return 0;
  1309. }
  1310. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1311. {
  1312. switch(event) {
  1313. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  1314. Mutex::Lock _l(_termReason_m);
  1315. _termReason = ONE_IDENTITY_COLLISION;
  1316. _fatalErrorMessage = "identity/address collision";
  1317. this->terminate();
  1318. } break;
  1319. case ZT_EVENT_TRACE: {
  1320. if (metaData) {
  1321. ::fprintf(stderr,"%s"ZT_EOL_S,(const char *)metaData);
  1322. ::fflush(stderr);
  1323. }
  1324. } break;
  1325. default:
  1326. break;
  1327. }
  1328. }
  1329. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1330. {
  1331. std::string p(_dataStorePrepPath(name));
  1332. if (!p.length())
  1333. return -2;
  1334. FILE *f = fopen(p.c_str(),"rb");
  1335. if (!f)
  1336. return -1;
  1337. if (fseek(f,0,SEEK_END) != 0) {
  1338. fclose(f);
  1339. return -2;
  1340. }
  1341. long ts = ftell(f);
  1342. if (ts < 0) {
  1343. fclose(f);
  1344. return -2;
  1345. }
  1346. *totalSize = (unsigned long)ts;
  1347. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  1348. fclose(f);
  1349. return -2;
  1350. }
  1351. long n = (long)fread(buf,1,bufSize,f);
  1352. fclose(f);
  1353. return n;
  1354. }
  1355. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  1356. {
  1357. std::string p(_dataStorePrepPath(name));
  1358. if (!p.length())
  1359. return -2;
  1360. if (!data) {
  1361. OSUtils::rm(p.c_str());
  1362. return 0;
  1363. }
  1364. FILE *f = fopen(p.c_str(),"wb");
  1365. if (!f)
  1366. return -1;
  1367. if (fwrite(data,len,1,f) == 1) {
  1368. fclose(f);
  1369. if (secure)
  1370. OSUtils::lockDownFile(p.c_str(),false);
  1371. return 0;
  1372. } else {
  1373. fclose(f);
  1374. OSUtils::rm(p.c_str());
  1375. return -1;
  1376. }
  1377. }
  1378. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1379. {
  1380. unsigned int fromBindingNo = 0;
  1381. if (addr->ss_family == AF_INET) {
  1382. if (reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port == 0) {
  1383. // If sender is sending from wildcard (null address), choose the secondary backup
  1384. // port 1/4 of the time. (but only for IPv4)
  1385. fromBindingNo = (++_udpPortPickerCounter & 0x4) >> 2;
  1386. if (!_ports[fromBindingNo])
  1387. fromBindingNo = 0;
  1388. } else {
  1389. const uint16_t lp = reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port;
  1390. if (lp == _portsBE[1])
  1391. fromBindingNo = 1;
  1392. else if (lp == _portsBE[2])
  1393. fromBindingNo = 2;
  1394. }
  1395. #ifdef ZT_TCP_FALLBACK_RELAY
  1396. // TCP fallback tunnel support, currently IPv4 only
  1397. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  1398. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  1399. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  1400. // valid direct traffic we'll stop using it and close the socket after a while.
  1401. const uint64_t now = OSUtils::now();
  1402. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  1403. if (_tcpFallbackTunnel) {
  1404. Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
  1405. if (!_tcpFallbackTunnel->writeBuf.length())
  1406. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  1407. unsigned long mlen = len + 7;
  1408. _tcpFallbackTunnel->writeBuf.push_back((char)0x17);
  1409. _tcpFallbackTunnel->writeBuf.push_back((char)0x03);
  1410. _tcpFallbackTunnel->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1411. _tcpFallbackTunnel->writeBuf.push_back((char)((mlen >> 8) & 0xff));
  1412. _tcpFallbackTunnel->writeBuf.push_back((char)(mlen & 0xff));
  1413. _tcpFallbackTunnel->writeBuf.push_back((char)4); // IPv4
  1414. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  1415. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  1416. _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
  1417. } else if (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INVERVAL / 2))) {
  1418. std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
  1419. if (tunnelIps.empty()) {
  1420. if (!_tcpFallbackResolver.running())
  1421. _tcpFallbackResolver.resolveNow();
  1422. } else {
  1423. bool connected = false;
  1424. InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
  1425. addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
  1426. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
  1427. }
  1428. }
  1429. }
  1430. _lastSendToGlobalV4 = now;
  1431. }
  1432. #endif // ZT_TCP_FALLBACK_RELAY
  1433. } else if (addr->ss_family == AF_INET6) {
  1434. if (reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port != 0) {
  1435. const uint16_t lp = reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port;
  1436. if (lp == _portsBE[1])
  1437. fromBindingNo = 1;
  1438. else if (lp == _portsBE[2])
  1439. fromBindingNo = 2;
  1440. }
  1441. } else {
  1442. return -1;
  1443. }
  1444. #ifdef ZT_BREAK_UDP
  1445. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  1446. return 0; // silently break UDP
  1447. #endif
  1448. return (_bindings[fromBindingNo].udpSend(_phy,*(reinterpret_cast<const InetAddress *>(localAddr)),*(reinterpret_cast<const InetAddress *>(addr)),data,len,ttl)) ? 0 : -1;
  1449. }
  1450. inline void nodeVirtualNetworkFrameFunction(uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1451. {
  1452. NetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);
  1453. if ((!n)||(!n->tap))
  1454. return;
  1455. n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1456. }
  1457. inline int nodePathCheckFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1458. {
  1459. Mutex::Lock _l(_nets_m);
  1460. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1461. if (n->second.tap) {
  1462. std::vector<InetAddress> ips(n->second.tap->ips());
  1463. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1464. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  1465. return 0;
  1466. }
  1467. }
  1468. }
  1469. }
  1470. /* Note: I do not think we need to scan for overlap with managed routes
  1471. * because of the "route forking" and interface binding that we do. This
  1472. * ensures (we hope) that ZeroTier traffic will still take the physical
  1473. * path even if its managed routes override this for other traffic. Will
  1474. * revisit if we see problems with this. */
  1475. return 1;
  1476. }
  1477. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1478. {
  1479. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1480. }
  1481. inline void onHttpRequestToServer(TcpConnection *tc)
  1482. {
  1483. char tmpn[256];
  1484. std::string data;
  1485. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1486. unsigned int scode = 404;
  1487. try {
  1488. if (_controlPlane)
  1489. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  1490. else scode = 500;
  1491. } catch ( ... ) {
  1492. scode = 500;
  1493. }
  1494. const char *scodestr;
  1495. switch(scode) {
  1496. case 200: scodestr = "OK"; break;
  1497. case 400: scodestr = "Bad Request"; break;
  1498. case 401: scodestr = "Unauthorized"; break;
  1499. case 403: scodestr = "Forbidden"; break;
  1500. case 404: scodestr = "Not Found"; break;
  1501. case 500: scodestr = "Internal Server Error"; break;
  1502. case 501: scodestr = "Not Implemented"; break;
  1503. case 503: scodestr = "Service Unavailable"; break;
  1504. default: scodestr = "Error"; break;
  1505. }
  1506. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  1507. {
  1508. Mutex::Lock _l(tc->writeBuf_m);
  1509. tc->writeBuf.assign(tmpn);
  1510. tc->writeBuf.append("Content-Type: ");
  1511. tc->writeBuf.append(contentType);
  1512. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  1513. tc->writeBuf.append(tmpn);
  1514. if (!tc->shouldKeepAlive)
  1515. tc->writeBuf.append("Connection: close\r\n");
  1516. tc->writeBuf.append("\r\n");
  1517. if (tc->parser.method != HTTP_HEAD)
  1518. tc->writeBuf.append(data);
  1519. }
  1520. _phy.setNotifyWritable(tc->sock,true);
  1521. }
  1522. inline void onHttpResponseFromClient(TcpConnection *tc)
  1523. {
  1524. if (!tc->shouldKeepAlive)
  1525. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConnections
  1526. }
  1527. bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
  1528. {
  1529. if (isBlacklistedLocalInterfaceForZeroTierTraffic(ifname))
  1530. return false;
  1531. Mutex::Lock _l(_nets_m);
  1532. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1533. if (n->second.tap) {
  1534. std::vector<InetAddress> ips(n->second.tap->ips());
  1535. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1536. if (i->ipsEqual(ifaddr))
  1537. return false;
  1538. }
  1539. }
  1540. }
  1541. return true;
  1542. }
  1543. std::string _dataStorePrepPath(const char *name) const
  1544. {
  1545. std::string p(_homePath);
  1546. p.push_back(ZT_PATH_SEPARATOR);
  1547. char lastc = (char)0;
  1548. for(const char *n=name;(*n);++n) {
  1549. if ((*n == '.')&&(lastc == '.'))
  1550. return std::string(); // don't allow ../../ stuff as a precaution
  1551. if (*n == '/') {
  1552. OSUtils::mkdir(p.c_str());
  1553. p.push_back(ZT_PATH_SEPARATOR);
  1554. } else p.push_back(*n);
  1555. lastc = *n;
  1556. }
  1557. return p;
  1558. }
  1559. bool _trialBind(unsigned int port)
  1560. {
  1561. struct sockaddr_in in4;
  1562. struct sockaddr_in6 in6;
  1563. PhySocket *tb;
  1564. memset(&in4,0,sizeof(in4));
  1565. in4.sin_family = AF_INET;
  1566. in4.sin_port = Utils::hton((uint16_t)port);
  1567. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
  1568. if (tb) {
  1569. _phy.close(tb,false);
  1570. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
  1571. if (tb) {
  1572. _phy.close(tb,false);
  1573. return true;
  1574. }
  1575. }
  1576. memset(&in6,0,sizeof(in6));
  1577. in6.sin6_family = AF_INET6;
  1578. in6.sin6_port = Utils::hton((uint16_t)port);
  1579. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
  1580. if (tb) {
  1581. _phy.close(tb,false);
  1582. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
  1583. if (tb) {
  1584. _phy.close(tb,false);
  1585. return true;
  1586. }
  1587. }
  1588. return false;
  1589. }
  1590. };
  1591. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  1592. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  1593. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData)
  1594. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1595. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1596. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  1597. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  1598. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  1599. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1600. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localAddr,addr,data,len,ttl); }
  1601. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1602. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  1603. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1604. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(localAddr,remoteAddr); }
  1605. #ifdef ZT_ENABLE_CLUSTER
  1606. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len)
  1607. {
  1608. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1609. const ClusterDefinition::MemberDefinition &md = (*(impl->_clusterDefinition))[toMemberId];
  1610. if (md.clusterEndpoint)
  1611. impl->_phy.udpSend(impl->_clusterMessageSocket,reinterpret_cast<const struct sockaddr *>(&(md.clusterEndpoint)),data,len);
  1612. }
  1613. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z)
  1614. {
  1615. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1616. return (int)(impl->_clusterDefinition->geo().locate(*(reinterpret_cast<const InetAddress *>(addr)),*x,*y,*z));
  1617. }
  1618. #endif
  1619. 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)
  1620. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1621. static int ShttpOnMessageBegin(http_parser *parser)
  1622. {
  1623. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1624. tc->currentHeaderField = "";
  1625. tc->currentHeaderValue = "";
  1626. tc->messageSize = 0;
  1627. tc->url = "";
  1628. tc->status = "";
  1629. tc->headers.clear();
  1630. tc->body = "";
  1631. return 0;
  1632. }
  1633. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  1634. {
  1635. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1636. tc->messageSize += (unsigned long)length;
  1637. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1638. return -1;
  1639. tc->url.append(ptr,length);
  1640. return 0;
  1641. }
  1642. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  1643. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1644. #else
  1645. static int ShttpOnStatus(http_parser *parser)
  1646. #endif
  1647. {
  1648. /*
  1649. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1650. tc->messageSize += (unsigned long)length;
  1651. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1652. return -1;
  1653. tc->status.append(ptr,length);
  1654. */
  1655. return 0;
  1656. }
  1657. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1658. {
  1659. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1660. tc->messageSize += (unsigned long)length;
  1661. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1662. return -1;
  1663. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1664. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1665. tc->currentHeaderField = "";
  1666. tc->currentHeaderValue = "";
  1667. }
  1668. for(size_t i=0;i<length;++i)
  1669. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1670. return 0;
  1671. }
  1672. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1673. {
  1674. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1675. tc->messageSize += (unsigned long)length;
  1676. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1677. return -1;
  1678. tc->currentHeaderValue.append(ptr,length);
  1679. return 0;
  1680. }
  1681. static int ShttpOnHeadersComplete(http_parser *parser)
  1682. {
  1683. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1684. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  1685. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1686. return 0;
  1687. }
  1688. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  1689. {
  1690. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1691. tc->messageSize += (unsigned long)length;
  1692. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1693. return -1;
  1694. tc->body.append(ptr,length);
  1695. return 0;
  1696. }
  1697. static int ShttpOnMessageComplete(http_parser *parser)
  1698. {
  1699. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1700. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  1701. tc->lastActivity = OSUtils::now();
  1702. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  1703. tc->parent->onHttpRequestToServer(tc);
  1704. } else {
  1705. tc->parent->onHttpResponseFromClient(tc);
  1706. }
  1707. return 0;
  1708. }
  1709. } // anonymous namespace
  1710. std::string OneService::platformDefaultHomePath()
  1711. {
  1712. return OSUtils::platformDefaultHomePath();
  1713. }
  1714. std::string OneService::autoUpdateUrl()
  1715. {
  1716. #ifdef ZT_AUTO_UPDATE
  1717. /*
  1718. #if defined(__LINUX__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1719. if (sizeof(void *) == 8)
  1720. return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x64-LATEST.nfo";
  1721. else return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x86-LATEST.nfo";
  1722. #endif
  1723. */
  1724. #if defined(__APPLE__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1725. return "http://download.zerotier.com/update/mac_intel/";
  1726. #endif
  1727. #ifdef __WINDOWS__
  1728. return "http://download.zerotier.com/update/win_intel/";
  1729. #endif
  1730. #endif // ZT_AUTO_UPDATE
  1731. return std::string();
  1732. }
  1733. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  1734. OneService::~OneService() {}
  1735. } // namespace ZeroTier