OneService.cpp 67 KB

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