OneService.cpp 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938
  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. // Default network permission settings: allow management of IPs and routes but only for private and "pseudo-private" IP spaces
  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. // Begin private implementation methods
  893. // Checks if a managed IP or route target is allowed
  894. bool checkIfManagedIsAllowed(const NetworkState &n,const InetAddress &addr)
  895. {
  896. if (!n.settings.allowManaged)
  897. return false;
  898. if (addr.isDefaultRoute())
  899. return n.settings.allowDefault;
  900. switch(addr.ipScope()) {
  901. case InetAddress::IP_SCOPE_NONE:
  902. case InetAddress::IP_SCOPE_MULTICAST:
  903. case InetAddress::IP_SCOPE_LOOPBACK:
  904. case InetAddress::IP_SCOPE_LINK_LOCAL:
  905. return false;
  906. case InetAddress::IP_SCOPE_GLOBAL:
  907. return n.settings.allowGlobal;
  908. default:
  909. return true;
  910. }
  911. }
  912. // Apply or update managed IPs for a configured network (be sure n.tap exists)
  913. void syncManagedStuff(NetworkState &n,bool syncIps,bool syncRoutes)
  914. {
  915. if (syncIps) {
  916. std::vector<InetAddress> newManagedIps;
  917. newManagedIps.reserve(n.config.assignedAddressCount);
  918. for(unsigned int i=0;i<n.config.assignedAddressCount;++i) {
  919. const InetAddress *ii = reinterpret_cast<const InetAddress *>(&(n.config.assignedAddresses[i]));
  920. if (checkIfManagedIsAllowed(n,*ii))
  921. newManagedIps.push_back(*ii);
  922. }
  923. std::sort(newManagedIps.begin(),newManagedIps.end());
  924. newManagedIps.erase(std::unique(newManagedIps.begin(),newManagedIps.end()),newManagedIps.end());
  925. for(std::vector<InetAddress>::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) {
  926. if (std::find(n.managedIps.begin(),n.managedIps.end(),*ip) == n.managedIps.end()) {
  927. if (!n.tap->addIp(*ip))
  928. fprintf(stderr,"ERROR: unable to add ip address %s"ZT_EOL_S, ip->toString().c_str());
  929. }
  930. }
  931. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  932. if (std::find(newManagedIps.begin(),newManagedIps.end(),*ip) == newManagedIps.end()) {
  933. if (!n.tap->removeIp(*ip))
  934. fprintf(stderr,"ERROR: unable to remove ip address %s"ZT_EOL_S, ip->toString().c_str());
  935. }
  936. }
  937. n.managedIps.swap(newManagedIps);
  938. }
  939. if (syncRoutes) {
  940. char tapdev[64];
  941. #ifdef __WINDOWS__
  942. Utils::snprintf(tapdev,sizeof(tapdev),"%.16llx",(unsigned long long)n.tap->luid().Value);
  943. #else
  944. Utils::scopy(tapdev,sizeof(tapdev),n.tap->deviceName().c_str());
  945. #endif
  946. // Nuke applied routes that are no longer in n.config.routes[] and/or are not allowed
  947. for(std::list<ManagedRoute>::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();) {
  948. bool haveRoute = false;
  949. if (checkIfManagedIsAllowed(n,mr->target())) {
  950. for(unsigned int i=0;i<n.config.routeCount;++i) {
  951. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  952. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  953. if ( (mr->target() == *target) && ( ((via->ss_family == target->ss_family)&&(mr->via() == *via)) || (tapdev == mr->device()) ) ) {
  954. haveRoute = true;
  955. break;
  956. }
  957. }
  958. }
  959. if (haveRoute) {
  960. ++mr;
  961. } else {
  962. n.managedRoutes.erase(mr++);
  963. }
  964. }
  965. // Apply routes in n.config.routes[] that we haven't applied yet, and sync those we have in case shadow routes need to change
  966. for(unsigned int i=0;i<n.config.routeCount;++i) {
  967. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  968. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  969. if (!checkIfManagedIsAllowed(n,*target))
  970. continue;
  971. bool haveRoute = false;
  972. // Ignore routes implied by local managed IPs since adding the IP adds the route
  973. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  974. if ((target->netmaskBits() == ip->netmaskBits())&&(target->containsAddress(*ip))) {
  975. haveRoute = true;
  976. break;
  977. }
  978. }
  979. if (haveRoute)
  980. continue;
  981. // If we've already applied this route, just sync it and continue
  982. for(std::list<ManagedRoute>::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();++mr) {
  983. if ( (mr->target() == *target) && ( ((via->ss_family == target->ss_family)&&(mr->via() == *via)) || (tapdev == mr->device()) ) ) {
  984. haveRoute = true;
  985. mr->sync();
  986. break;
  987. }
  988. }
  989. if (haveRoute)
  990. continue;
  991. // Add and apply new routes
  992. n.managedRoutes.push_back(ManagedRoute());
  993. if (!n.managedRoutes.back().set(*target,*via,tapdev))
  994. n.managedRoutes.pop_back();
  995. }
  996. }
  997. }
  998. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  999. {
  1000. #ifdef ZT_ENABLE_CLUSTER
  1001. if (sock == _clusterMessageSocket) {
  1002. _lastDirectReceiveFromGlobal = OSUtils::now();
  1003. _node->clusterHandleIncomingMessage(data,len);
  1004. return;
  1005. }
  1006. #endif
  1007. #ifdef ZT_BREAK_UDP
  1008. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  1009. return;
  1010. #endif
  1011. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  1012. _lastDirectReceiveFromGlobal = OSUtils::now();
  1013. const ZT_ResultCode rc = _node->processWirePacket(
  1014. OSUtils::now(),
  1015. reinterpret_cast<const struct sockaddr_storage *>(localAddr),
  1016. (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
  1017. data,
  1018. len,
  1019. &_nextBackgroundTaskDeadline);
  1020. if (ZT_ResultCode_isFatal(rc)) {
  1021. char tmp[256];
  1022. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1023. Mutex::Lock _l(_termReason_m);
  1024. _termReason = ONE_UNRECOVERABLE_ERROR;
  1025. _fatalErrorMessage = tmp;
  1026. this->terminate();
  1027. }
  1028. }
  1029. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  1030. {
  1031. if (!success)
  1032. return;
  1033. // Outgoing TCP connections are always TCP fallback tunnel connections.
  1034. TcpConnection *tc = new TcpConnection();
  1035. _tcpConnections.insert(tc);
  1036. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  1037. tc->shouldKeepAlive = true;
  1038. tc->parent = this;
  1039. tc->sock = sock;
  1040. // from and parser are not used
  1041. tc->messageSize = 0; // unused
  1042. tc->lastActivity = OSUtils::now();
  1043. // HTTP stuff is not used
  1044. tc->writeBuf = "";
  1045. *uptr = (void *)tc;
  1046. // Send "hello" message
  1047. tc->writeBuf.push_back((char)0x17);
  1048. tc->writeBuf.push_back((char)0x03);
  1049. tc->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1050. tc->writeBuf.push_back((char)0x00);
  1051. tc->writeBuf.push_back((char)0x04); // mlen == 4
  1052. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MAJOR);
  1053. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MINOR);
  1054. tc->writeBuf.push_back((char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff));
  1055. tc->writeBuf.push_back((char)(ZEROTIER_ONE_VERSION_REVISION & 0xff));
  1056. _phy.setNotifyWritable(sock,true);
  1057. _tcpFallbackTunnel = tc;
  1058. }
  1059. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  1060. {
  1061. if ((!from)||(reinterpret_cast<const InetAddress *>(from)->ipScope() != InetAddress::IP_SCOPE_LOOPBACK)) {
  1062. // Non-Loopback: deny (for now)
  1063. _phy.close(sockN,false);
  1064. return;
  1065. } else {
  1066. // Loopback == HTTP JSON API request
  1067. TcpConnection *tc = new TcpConnection();
  1068. _tcpConnections.insert(tc);
  1069. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  1070. tc->shouldKeepAlive = true;
  1071. tc->parent = this;
  1072. tc->sock = sockN;
  1073. tc->from = from;
  1074. http_parser_init(&(tc->parser),HTTP_REQUEST);
  1075. tc->parser.data = (void *)tc;
  1076. tc->messageSize = 0;
  1077. tc->lastActivity = OSUtils::now();
  1078. tc->currentHeaderField = "";
  1079. tc->currentHeaderValue = "";
  1080. tc->url = "";
  1081. tc->status = "";
  1082. tc->headers.clear();
  1083. tc->body = "";
  1084. tc->writeBuf = "";
  1085. *uptrN = (void *)tc;
  1086. }
  1087. }
  1088. inline void phyOnTcpClose(PhySocket *sock,void **uptr)
  1089. {
  1090. TcpConnection *tc = (TcpConnection *)*uptr;
  1091. if (tc) {
  1092. if (tc == _tcpFallbackTunnel)
  1093. _tcpFallbackTunnel = (TcpConnection *)0;
  1094. _tcpConnections.erase(tc);
  1095. delete tc;
  1096. }
  1097. }
  1098. inline void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  1099. {
  1100. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1101. switch(tc->type) {
  1102. case TcpConnection::TCP_HTTP_INCOMING:
  1103. case TcpConnection::TCP_HTTP_OUTGOING:
  1104. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  1105. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK)) {
  1106. _phy.close(sock);
  1107. return;
  1108. }
  1109. break;
  1110. case TcpConnection::TCP_TUNNEL_OUTGOING:
  1111. tc->body.append((const char *)data,len);
  1112. while (tc->body.length() >= 5) {
  1113. const char *data = tc->body.data();
  1114. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  1115. if (tc->body.length() >= (mlen + 5)) {
  1116. InetAddress from;
  1117. unsigned long plen = mlen; // payload length, modified if there's an IP header
  1118. data += 5; // skip forward past pseudo-TLS junk and mlen
  1119. if (plen == 4) {
  1120. // Hello message, which isn't sent by proxy and would be ignored by client
  1121. } else if (plen) {
  1122. // Messages should contain IPv4 or IPv6 source IP address data
  1123. switch(data[0]) {
  1124. case 4: // IPv4
  1125. if (plen >= 7) {
  1126. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  1127. data += 7; // type + 4 byte IP + 2 byte port
  1128. plen -= 7;
  1129. } else {
  1130. _phy.close(sock);
  1131. return;
  1132. }
  1133. break;
  1134. case 6: // IPv6
  1135. if (plen >= 19) {
  1136. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  1137. data += 19; // type + 16 byte IP + 2 byte port
  1138. plen -= 19;
  1139. } else {
  1140. _phy.close(sock);
  1141. return;
  1142. }
  1143. break;
  1144. case 0: // none/omitted
  1145. ++data;
  1146. --plen;
  1147. break;
  1148. default: // invalid address type
  1149. _phy.close(sock);
  1150. return;
  1151. }
  1152. if (from) {
  1153. InetAddress fakeTcpLocalInterfaceAddress((uint32_t)0xffffffff,0xffff);
  1154. const ZT_ResultCode rc = _node->processWirePacket(
  1155. OSUtils::now(),
  1156. reinterpret_cast<struct sockaddr_storage *>(&fakeTcpLocalInterfaceAddress),
  1157. reinterpret_cast<struct sockaddr_storage *>(&from),
  1158. data,
  1159. plen,
  1160. &_nextBackgroundTaskDeadline);
  1161. if (ZT_ResultCode_isFatal(rc)) {
  1162. char tmp[256];
  1163. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1164. Mutex::Lock _l(_termReason_m);
  1165. _termReason = ONE_UNRECOVERABLE_ERROR;
  1166. _fatalErrorMessage = tmp;
  1167. this->terminate();
  1168. _phy.close(sock);
  1169. return;
  1170. }
  1171. }
  1172. }
  1173. if (tc->body.length() > (mlen + 5))
  1174. tc->body = tc->body.substr(mlen + 5);
  1175. else tc->body = "";
  1176. } else break;
  1177. }
  1178. break;
  1179. }
  1180. }
  1181. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  1182. {
  1183. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1184. Mutex::Lock _l(tc->writeBuf_m);
  1185. if (tc->writeBuf.length() > 0) {
  1186. long sent = (long)_phy.streamSend(sock,tc->writeBuf.data(),(unsigned long)tc->writeBuf.length(),true);
  1187. if (sent > 0) {
  1188. tc->lastActivity = OSUtils::now();
  1189. if ((unsigned long)sent >= (unsigned long)tc->writeBuf.length()) {
  1190. tc->writeBuf = "";
  1191. _phy.setNotifyWritable(sock,false);
  1192. if (!tc->shouldKeepAlive)
  1193. _phy.close(sock); // will call close handler to delete from _tcpConnections
  1194. } else {
  1195. tc->writeBuf = tc->writeBuf.substr(sent);
  1196. }
  1197. }
  1198. } else {
  1199. _phy.setNotifyWritable(sock,false);
  1200. }
  1201. }
  1202. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  1203. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  1204. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  1205. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  1206. inline void phyOnUnixWritable(PhySocket *sock,void **uptr,bool lwip_invoked) {}
  1207. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  1208. {
  1209. Mutex::Lock _l(_nets_m);
  1210. NetworkState &n = _nets[nwid];
  1211. switch(op) {
  1212. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  1213. if (!n.tap) {
  1214. try {
  1215. char friendlyName[128];
  1216. Utils::snprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  1217. n.tap = new EthernetTap(
  1218. _homePath.c_str(),
  1219. MAC(nwc->mac),
  1220. nwc->mtu,
  1221. (unsigned int)ZT_IF_METRIC,
  1222. nwid,
  1223. friendlyName,
  1224. StapFrameHandler,
  1225. (void *)this);
  1226. *nuptr = (void *)&n;
  1227. } catch (std::exception &exc) {
  1228. #ifdef __WINDOWS__
  1229. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1230. if (tapFailLog) {
  1231. fprintf(tapFailLog,"%.16llx: %s"ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1232. fclose(tapFailLog);
  1233. }
  1234. #else
  1235. fprintf(stderr,"ERROR: unable to configure virtual network port: %s"ZT_EOL_S,exc.what());
  1236. #endif
  1237. _nets.erase(nwid);
  1238. return -999;
  1239. } catch ( ... ) {
  1240. return -999; // tap init failed
  1241. }
  1242. }
  1243. // After setting up tap, fall through to CONFIG_UPDATE since we also want to do this...
  1244. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1245. memcpy(&(n.config),nwc,sizeof(ZT_VirtualNetworkConfig));
  1246. if (n.tap) { // sanity check
  1247. syncManagedStuff(n,true,true);
  1248. } else {
  1249. _nets.erase(nwid);
  1250. return -999; // tap init failed
  1251. }
  1252. break;
  1253. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1254. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1255. if (n.tap) { // sanity check
  1256. #ifdef __WINDOWS__
  1257. std::string winInstanceId(n.tap->instanceId());
  1258. #endif
  1259. *nuptr = (void *)0;
  1260. delete n.tap;
  1261. _nets.erase(nwid);
  1262. #ifdef __WINDOWS__
  1263. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1264. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1265. #endif
  1266. } else {
  1267. _nets.erase(nwid);
  1268. }
  1269. break;
  1270. }
  1271. return 0;
  1272. }
  1273. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1274. {
  1275. switch(event) {
  1276. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  1277. Mutex::Lock _l(_termReason_m);
  1278. _termReason = ONE_IDENTITY_COLLISION;
  1279. _fatalErrorMessage = "identity/address collision";
  1280. this->terminate();
  1281. } break;
  1282. case ZT_EVENT_TRACE: {
  1283. if (metaData) {
  1284. ::fprintf(stderr,"%s"ZT_EOL_S,(const char *)metaData);
  1285. ::fflush(stderr);
  1286. }
  1287. } break;
  1288. default:
  1289. break;
  1290. }
  1291. }
  1292. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1293. {
  1294. std::string p(_dataStorePrepPath(name));
  1295. if (!p.length())
  1296. return -2;
  1297. FILE *f = fopen(p.c_str(),"rb");
  1298. if (!f)
  1299. return -1;
  1300. if (fseek(f,0,SEEK_END) != 0) {
  1301. fclose(f);
  1302. return -2;
  1303. }
  1304. long ts = ftell(f);
  1305. if (ts < 0) {
  1306. fclose(f);
  1307. return -2;
  1308. }
  1309. *totalSize = (unsigned long)ts;
  1310. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  1311. fclose(f);
  1312. return -2;
  1313. }
  1314. long n = (long)fread(buf,1,bufSize,f);
  1315. fclose(f);
  1316. return n;
  1317. }
  1318. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  1319. {
  1320. std::string p(_dataStorePrepPath(name));
  1321. if (!p.length())
  1322. return -2;
  1323. if (!data) {
  1324. OSUtils::rm(p.c_str());
  1325. return 0;
  1326. }
  1327. FILE *f = fopen(p.c_str(),"wb");
  1328. if (!f)
  1329. return -1;
  1330. if (fwrite(data,len,1,f) == 1) {
  1331. fclose(f);
  1332. if (secure)
  1333. OSUtils::lockDownFile(p.c_str(),false);
  1334. return 0;
  1335. } else {
  1336. fclose(f);
  1337. OSUtils::rm(p.c_str());
  1338. return -1;
  1339. }
  1340. }
  1341. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1342. {
  1343. unsigned int fromBindingNo = 0;
  1344. if (addr->ss_family == AF_INET) {
  1345. if (reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port == 0) {
  1346. // If sender is sending from wildcard (null address), choose the secondary backup
  1347. // port 1/4 of the time. (but only for IPv4)
  1348. fromBindingNo = (++_udpPortPickerCounter & 0x4) >> 2;
  1349. if (!_ports[fromBindingNo])
  1350. fromBindingNo = 0;
  1351. } else {
  1352. const uint16_t lp = reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port;
  1353. if (lp == _portsBE[1])
  1354. fromBindingNo = 1;
  1355. else if (lp == _portsBE[2])
  1356. fromBindingNo = 2;
  1357. }
  1358. #ifdef ZT_TCP_FALLBACK_RELAY
  1359. // TCP fallback tunnel support, currently IPv4 only
  1360. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  1361. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  1362. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  1363. // valid direct traffic we'll stop using it and close the socket after a while.
  1364. const uint64_t now = OSUtils::now();
  1365. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  1366. if (_tcpFallbackTunnel) {
  1367. Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
  1368. if (!_tcpFallbackTunnel->writeBuf.length())
  1369. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  1370. unsigned long mlen = len + 7;
  1371. _tcpFallbackTunnel->writeBuf.push_back((char)0x17);
  1372. _tcpFallbackTunnel->writeBuf.push_back((char)0x03);
  1373. _tcpFallbackTunnel->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1374. _tcpFallbackTunnel->writeBuf.push_back((char)((mlen >> 8) & 0xff));
  1375. _tcpFallbackTunnel->writeBuf.push_back((char)(mlen & 0xff));
  1376. _tcpFallbackTunnel->writeBuf.push_back((char)4); // IPv4
  1377. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  1378. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  1379. _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
  1380. } else if (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INVERVAL / 2))) {
  1381. std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
  1382. if (tunnelIps.empty()) {
  1383. if (!_tcpFallbackResolver.running())
  1384. _tcpFallbackResolver.resolveNow();
  1385. } else {
  1386. bool connected = false;
  1387. InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
  1388. addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
  1389. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
  1390. }
  1391. }
  1392. }
  1393. _lastSendToGlobalV4 = now;
  1394. }
  1395. #endif // ZT_TCP_FALLBACK_RELAY
  1396. } else if (addr->ss_family == AF_INET6) {
  1397. if (reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port != 0) {
  1398. const uint16_t lp = reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port;
  1399. if (lp == _portsBE[1])
  1400. fromBindingNo = 1;
  1401. else if (lp == _portsBE[2])
  1402. fromBindingNo = 2;
  1403. }
  1404. } else {
  1405. return -1;
  1406. }
  1407. #ifdef ZT_BREAK_UDP
  1408. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  1409. return 0; // silently break UDP
  1410. #endif
  1411. return (_bindings[fromBindingNo].udpSend(_phy,*(reinterpret_cast<const InetAddress *>(localAddr)),*(reinterpret_cast<const InetAddress *>(addr)),data,len,ttl)) ? 0 : -1;
  1412. }
  1413. 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)
  1414. {
  1415. NetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);
  1416. if ((!n)||(!n->tap))
  1417. return;
  1418. n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1419. }
  1420. inline int nodePathCheckFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1421. {
  1422. Mutex::Lock _l(_nets_m);
  1423. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1424. if (n->second.tap) {
  1425. std::vector<InetAddress> ips(n->second.tap->ips());
  1426. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1427. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  1428. return 0;
  1429. }
  1430. }
  1431. }
  1432. }
  1433. /* Note: I do not think we need to scan for overlap with managed routes
  1434. * because of the "route forking" and interface binding that we do. This
  1435. * ensures (we hope) that ZeroTier traffic will still take the physical
  1436. * path even if its managed routes override this for other traffic. Will
  1437. * revisit if we see problems with this. */
  1438. return 1;
  1439. }
  1440. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1441. {
  1442. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1443. }
  1444. inline void onHttpRequestToServer(TcpConnection *tc)
  1445. {
  1446. char tmpn[256];
  1447. std::string data;
  1448. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1449. unsigned int scode = 404;
  1450. try {
  1451. if (_controlPlane)
  1452. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  1453. else scode = 500;
  1454. } catch ( ... ) {
  1455. scode = 500;
  1456. }
  1457. const char *scodestr;
  1458. switch(scode) {
  1459. case 200: scodestr = "OK"; break;
  1460. case 400: scodestr = "Bad Request"; break;
  1461. case 401: scodestr = "Unauthorized"; break;
  1462. case 403: scodestr = "Forbidden"; break;
  1463. case 404: scodestr = "Not Found"; break;
  1464. case 500: scodestr = "Internal Server Error"; break;
  1465. case 501: scodestr = "Not Implemented"; break;
  1466. case 503: scodestr = "Service Unavailable"; break;
  1467. default: scodestr = "Error"; break;
  1468. }
  1469. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  1470. {
  1471. Mutex::Lock _l(tc->writeBuf_m);
  1472. tc->writeBuf.assign(tmpn);
  1473. tc->writeBuf.append("Content-Type: ");
  1474. tc->writeBuf.append(contentType);
  1475. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  1476. tc->writeBuf.append(tmpn);
  1477. if (!tc->shouldKeepAlive)
  1478. tc->writeBuf.append("Connection: close\r\n");
  1479. tc->writeBuf.append("\r\n");
  1480. if (tc->parser.method != HTTP_HEAD)
  1481. tc->writeBuf.append(data);
  1482. }
  1483. _phy.setNotifyWritable(tc->sock,true);
  1484. }
  1485. inline void onHttpResponseFromClient(TcpConnection *tc)
  1486. {
  1487. if (!tc->shouldKeepAlive)
  1488. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConnections
  1489. }
  1490. bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
  1491. {
  1492. if (isBlacklistedLocalInterfaceForZeroTierTraffic(ifname))
  1493. return false;
  1494. Mutex::Lock _l(_nets_m);
  1495. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1496. if (n->second.tap) {
  1497. std::vector<InetAddress> ips(n->second.tap->ips());
  1498. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1499. if (i->ipsEqual(ifaddr))
  1500. return false;
  1501. }
  1502. }
  1503. }
  1504. return true;
  1505. }
  1506. std::string _dataStorePrepPath(const char *name) const
  1507. {
  1508. std::string p(_homePath);
  1509. p.push_back(ZT_PATH_SEPARATOR);
  1510. char lastc = (char)0;
  1511. for(const char *n=name;(*n);++n) {
  1512. if ((*n == '.')&&(lastc == '.'))
  1513. return std::string(); // don't allow ../../ stuff as a precaution
  1514. if (*n == '/') {
  1515. OSUtils::mkdir(p.c_str());
  1516. p.push_back(ZT_PATH_SEPARATOR);
  1517. } else p.push_back(*n);
  1518. lastc = *n;
  1519. }
  1520. return p;
  1521. }
  1522. bool _trialBind(unsigned int port)
  1523. {
  1524. struct sockaddr_in in4;
  1525. struct sockaddr_in6 in6;
  1526. PhySocket *tb;
  1527. memset(&in4,0,sizeof(in4));
  1528. in4.sin_family = AF_INET;
  1529. in4.sin_port = Utils::hton((uint16_t)port);
  1530. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
  1531. if (tb) {
  1532. _phy.close(tb,false);
  1533. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
  1534. if (tb) {
  1535. _phy.close(tb,false);
  1536. return true;
  1537. }
  1538. }
  1539. memset(&in6,0,sizeof(in6));
  1540. in6.sin6_family = AF_INET6;
  1541. in6.sin6_port = Utils::hton((uint16_t)port);
  1542. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
  1543. if (tb) {
  1544. _phy.close(tb,false);
  1545. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
  1546. if (tb) {
  1547. _phy.close(tb,false);
  1548. return true;
  1549. }
  1550. }
  1551. return false;
  1552. }
  1553. };
  1554. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  1555. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  1556. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData)
  1557. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1558. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1559. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  1560. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  1561. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  1562. 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)
  1563. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localAddr,addr,data,len,ttl); }
  1564. 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)
  1565. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  1566. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1567. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(localAddr,remoteAddr); }
  1568. #ifdef ZT_ENABLE_CLUSTER
  1569. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len)
  1570. {
  1571. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1572. const ClusterDefinition::MemberDefinition &md = (*(impl->_clusterDefinition))[toMemberId];
  1573. if (md.clusterEndpoint)
  1574. impl->_phy.udpSend(impl->_clusterMessageSocket,reinterpret_cast<const struct sockaddr *>(&(md.clusterEndpoint)),data,len);
  1575. }
  1576. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z)
  1577. {
  1578. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1579. return (int)(impl->_clusterDefinition->geo().locate(*(reinterpret_cast<const InetAddress *>(addr)),*x,*y,*z));
  1580. }
  1581. #endif
  1582. 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)
  1583. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1584. static int ShttpOnMessageBegin(http_parser *parser)
  1585. {
  1586. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1587. tc->currentHeaderField = "";
  1588. tc->currentHeaderValue = "";
  1589. tc->messageSize = 0;
  1590. tc->url = "";
  1591. tc->status = "";
  1592. tc->headers.clear();
  1593. tc->body = "";
  1594. return 0;
  1595. }
  1596. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  1597. {
  1598. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1599. tc->messageSize += (unsigned long)length;
  1600. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1601. return -1;
  1602. tc->url.append(ptr,length);
  1603. return 0;
  1604. }
  1605. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  1606. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1607. #else
  1608. static int ShttpOnStatus(http_parser *parser)
  1609. #endif
  1610. {
  1611. /*
  1612. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1613. tc->messageSize += (unsigned long)length;
  1614. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1615. return -1;
  1616. tc->status.append(ptr,length);
  1617. */
  1618. return 0;
  1619. }
  1620. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1621. {
  1622. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1623. tc->messageSize += (unsigned long)length;
  1624. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1625. return -1;
  1626. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1627. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1628. tc->currentHeaderField = "";
  1629. tc->currentHeaderValue = "";
  1630. }
  1631. for(size_t i=0;i<length;++i)
  1632. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1633. return 0;
  1634. }
  1635. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1636. {
  1637. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1638. tc->messageSize += (unsigned long)length;
  1639. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1640. return -1;
  1641. tc->currentHeaderValue.append(ptr,length);
  1642. return 0;
  1643. }
  1644. static int ShttpOnHeadersComplete(http_parser *parser)
  1645. {
  1646. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1647. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  1648. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1649. return 0;
  1650. }
  1651. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  1652. {
  1653. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1654. tc->messageSize += (unsigned long)length;
  1655. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1656. return -1;
  1657. tc->body.append(ptr,length);
  1658. return 0;
  1659. }
  1660. static int ShttpOnMessageComplete(http_parser *parser)
  1661. {
  1662. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1663. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  1664. tc->lastActivity = OSUtils::now();
  1665. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  1666. tc->parent->onHttpRequestToServer(tc);
  1667. } else {
  1668. tc->parent->onHttpResponseFromClient(tc);
  1669. }
  1670. return 0;
  1671. }
  1672. } // anonymous namespace
  1673. std::string OneService::platformDefaultHomePath()
  1674. {
  1675. #ifdef __UNIX_LIKE__
  1676. #ifdef __APPLE__
  1677. // /Library/... on Apple
  1678. return std::string("/Library/Application Support/ZeroTier/One");
  1679. #else
  1680. #ifdef __BSD__
  1681. // BSD likes /var/db instead of /var/lib
  1682. return std::string("/var/db/zerotier-one");
  1683. #else
  1684. // Use /var/lib for Linux and other *nix
  1685. return std::string("/var/lib/zerotier-one");
  1686. #endif
  1687. #endif
  1688. #else // not __UNIX_LIKE__
  1689. #ifdef __WINDOWS__
  1690. // Look up app data folder on Windows, e.g. C:\ProgramData\...
  1691. char buf[16384];
  1692. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_COMMON_APPDATA,NULL,0,buf)))
  1693. return (std::string(buf) + "\\ZeroTier\\One");
  1694. else return std::string("C:\\ZeroTier\\One");
  1695. #else
  1696. return std::string(); // UNKNOWN PLATFORM
  1697. #endif
  1698. #endif // __UNIX_LIKE__ or not...
  1699. }
  1700. std::string OneService::autoUpdateUrl()
  1701. {
  1702. #ifdef ZT_AUTO_UPDATE
  1703. /*
  1704. #if defined(__LINUX__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1705. if (sizeof(void *) == 8)
  1706. return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x64-LATEST.nfo";
  1707. else return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x86-LATEST.nfo";
  1708. #endif
  1709. */
  1710. #if defined(__APPLE__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1711. return "http://download.zerotier.com/update/mac_intel/";
  1712. #endif
  1713. #ifdef __WINDOWS__
  1714. return "http://download.zerotier.com/update/win_intel/";
  1715. #endif
  1716. #endif // ZT_AUTO_UPDATE
  1717. return std::string();
  1718. }
  1719. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  1720. OneService::~OneService() {}
  1721. } // namespace ZeroTier