OneService.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918
  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() : tap((EthernetTap *)0),managedIps(),managedRoutes(),allowManaged(true),allowGlobal(true),allowDefault(true) {}
  469. EthernetTap *tap;
  470. ZT_VirtualNetworkConfig config; // memcpy() of raw config from core
  471. std::vector<InetAddress> managedIps;
  472. std::list<ManagedRoute> managedRoutes;
  473. bool allowManaged; // allow managed addresses and routes
  474. bool allowGlobal; // allow global (non-private) IP routes?
  475. bool allowDefault; // allow default route?
  476. };
  477. std::map<uint64_t,NetworkState> _nets;
  478. Mutex _nets_m;
  479. // Active TCP/IP connections
  480. std::set< TcpConnection * > _tcpConnections; // no mutex for this since it's done in the main loop thread only
  481. TcpConnection *_tcpFallbackTunnel;
  482. // Termination status information
  483. ReasonForTermination _termReason;
  484. std::string _fatalErrorMessage;
  485. Mutex _termReason_m;
  486. // uPnP/NAT-PMP port mapper if enabled
  487. #ifdef ZT_USE_MINIUPNPC
  488. PortMapper *_portMapper;
  489. #endif
  490. // Cluster management instance if enabled
  491. #ifdef ZT_ENABLE_CLUSTER
  492. PhySocket *_clusterMessageSocket;
  493. ClusterDefinition *_clusterDefinition;
  494. unsigned int _clusterMemberId;
  495. #endif
  496. // Set to false to force service to stop
  497. volatile bool _run;
  498. Mutex _run_m;
  499. // end member variables ----------------------------------------------------
  500. OneServiceImpl(const char *hp,unsigned int port) :
  501. _homePath((hp) ? hp : ".")
  502. ,_tcpFallbackResolver(ZT_TCP_FALLBACK_RELAY)
  503. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  504. ,_controller((SqliteNetworkController *)0)
  505. #endif
  506. ,_phy(this,false,true)
  507. ,_node((Node *)0)
  508. ,_controlPlane((ControlPlane *)0)
  509. ,_lastDirectReceiveFromGlobal(0)
  510. #ifdef ZT_TCP_FALLBACK_RELAY
  511. ,_lastSendToGlobalV4(0)
  512. #endif
  513. ,_lastRestart(0)
  514. ,_nextBackgroundTaskDeadline(0)
  515. ,_tcpFallbackTunnel((TcpConnection *)0)
  516. ,_termReason(ONE_STILL_RUNNING)
  517. #ifdef ZT_USE_MINIUPNPC
  518. ,_portMapper((PortMapper *)0)
  519. #endif
  520. #ifdef ZT_ENABLE_CLUSTER
  521. ,_clusterMessageSocket((PhySocket *)0)
  522. ,_clusterDefinition((ClusterDefinition *)0)
  523. ,_clusterMemberId(0)
  524. #endif
  525. ,_run(true)
  526. {
  527. _ports[0] = 0;
  528. _ports[1] = 0;
  529. _ports[2] = 0;
  530. // The control socket is bound to the default/static port on localhost. If we
  531. // can do this, we have successfully allocated a port. The binders will take
  532. // care of binding non-local addresses for ZeroTier traffic.
  533. const int portTrials = (port == 0) ? 256 : 1; // if port is 0, pick random
  534. for(int k=0;k<portTrials;++k) {
  535. if (port == 0) {
  536. unsigned int randp = 0;
  537. Utils::getSecureRandom(&randp,sizeof(randp));
  538. port = 20000 + (randp % 45500);
  539. }
  540. if (_trialBind(port)) {
  541. struct sockaddr_in in4;
  542. memset(&in4,0,sizeof(in4));
  543. in4.sin_family = AF_INET;
  544. in4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001); // right now we just listen for TCP @127.0.0.1
  545. in4.sin_port = Utils::hton((uint16_t)port);
  546. _v4TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
  547. struct sockaddr_in6 in6;
  548. memset((void *)&in6,0,sizeof(in6));
  549. in6.sin6_family = AF_INET6;
  550. in6.sin6_port = in4.sin_port;
  551. in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
  552. _v6TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
  553. // We must bind one of IPv4 or IPv6 -- support either failing to support hosts that
  554. // have only IPv4 or only IPv6 stacks.
  555. if ((_v4TcpControlSocket)||(_v6TcpControlSocket)) {
  556. _ports[0] = port;
  557. break;
  558. } else {
  559. if (_v4TcpControlSocket)
  560. _phy.close(_v4TcpControlSocket,false);
  561. if (_v6TcpControlSocket)
  562. _phy.close(_v6TcpControlSocket,false);
  563. port = 0;
  564. }
  565. } else {
  566. port = 0;
  567. }
  568. }
  569. if (_ports[0] == 0)
  570. throw std::runtime_error("cannot bind to local control interface port");
  571. char portstr[64];
  572. Utils::snprintf(portstr,sizeof(portstr),"%u",_ports[0]);
  573. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),std::string(portstr));
  574. }
  575. virtual ~OneServiceImpl()
  576. {
  577. for(int i=0;i<3;++i)
  578. _bindings[i].closeAll(_phy);
  579. _phy.close(_v4TcpControlSocket);
  580. _phy.close(_v6TcpControlSocket);
  581. #ifdef ZT_ENABLE_CLUSTER
  582. _phy.close(_clusterMessageSocket);
  583. #endif
  584. #ifdef ZT_USE_MINIUPNPC
  585. delete _portMapper;
  586. #endif
  587. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  588. delete _controller;
  589. #endif
  590. #ifdef ZT_ENABLE_CLUSTER
  591. delete _clusterDefinition;
  592. #endif
  593. }
  594. virtual ReasonForTermination run()
  595. {
  596. try {
  597. std::string authToken;
  598. {
  599. std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  600. if (!OSUtils::readFile(authTokenPath.c_str(),authToken)) {
  601. unsigned char foo[24];
  602. Utils::getSecureRandom(foo,sizeof(foo));
  603. authToken = "";
  604. for(unsigned int i=0;i<sizeof(foo);++i)
  605. authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  606. if (!OSUtils::writeFile(authTokenPath.c_str(),authToken)) {
  607. Mutex::Lock _l(_termReason_m);
  608. _termReason = ONE_UNRECOVERABLE_ERROR;
  609. _fatalErrorMessage = "authtoken.secret could not be written";
  610. return _termReason;
  611. } else {
  612. OSUtils::lockDownFile(authTokenPath.c_str(),false);
  613. }
  614. }
  615. }
  616. authToken = _trimString(authToken);
  617. _node = new Node(
  618. OSUtils::now(),
  619. this,
  620. SnodeDataStoreGetFunction,
  621. SnodeDataStorePutFunction,
  622. SnodeWirePacketSendFunction,
  623. SnodeVirtualNetworkFrameFunction,
  624. SnodeVirtualNetworkConfigFunction,
  625. SnodePathCheckFunction,
  626. SnodeEventCallback);
  627. // Attempt to bind to a secondary port chosen from our ZeroTier address.
  628. // This exists because there are buggy NATs out there that fail if more
  629. // than one device behind the same NAT tries to use the same internal
  630. // private address port number.
  631. _ports[1] = 20000 + ((unsigned int)_node->address() % 45500);
  632. for(int i=0;;++i) {
  633. if (i > 1000) {
  634. _ports[1] = 0;
  635. break;
  636. } else if (++_ports[1] >= 65536) {
  637. _ports[1] = 20000;
  638. }
  639. if (_trialBind(_ports[1]))
  640. break;
  641. }
  642. #ifdef ZT_USE_MINIUPNPC
  643. // If we're running uPnP/NAT-PMP, bind a *third* port for that. We can't
  644. // use the other two ports for that because some NATs do really funky
  645. // stuff with ports that are explicitly mapped that breaks things.
  646. if (_ports[1]) {
  647. _ports[2] = _ports[1];
  648. for(int i=0;;++i) {
  649. if (i > 1000) {
  650. _ports[2] = 0;
  651. break;
  652. } else if (++_ports[2] >= 65536) {
  653. _ports[2] = 20000;
  654. }
  655. if (_trialBind(_ports[2]))
  656. break;
  657. }
  658. if (_ports[2]) {
  659. char uniqueName[64];
  660. Utils::snprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]);
  661. _portMapper = new PortMapper(_ports[2],uniqueName);
  662. }
  663. }
  664. #endif
  665. for(int i=0;i<3;++i)
  666. _portsBE[i] = Utils::hton((uint16_t)_ports[i]);
  667. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  668. _controller = new SqliteNetworkController(_node,(_homePath + ZT_PATH_SEPARATOR_S + ZT_CONTROLLER_DB_PATH).c_str(),(_homePath + ZT_PATH_SEPARATOR_S + "circuitTestResults.d").c_str());
  669. _node->setNetconfMaster((void *)_controller);
  670. #endif
  671. #ifdef ZT_ENABLE_CLUSTER
  672. if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str())) {
  673. _clusterDefinition = new ClusterDefinition(_node->address(),(_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str());
  674. if (_clusterDefinition->size() > 0) {
  675. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  676. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  677. PhySocket *cs = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&(m->clusterEndpoint)));
  678. if (cs) {
  679. if (_clusterMessageSocket) {
  680. _phy.close(_clusterMessageSocket,false);
  681. _phy.close(cs,false);
  682. Mutex::Lock _l(_termReason_m);
  683. _termReason = ONE_UNRECOVERABLE_ERROR;
  684. _fatalErrorMessage = "Cluster: can't determine my cluster member ID: able to bind more than one cluster message socket IP/port!";
  685. return _termReason;
  686. }
  687. _clusterMessageSocket = cs;
  688. _clusterMemberId = m->id;
  689. }
  690. }
  691. if (!_clusterMessageSocket) {
  692. Mutex::Lock _l(_termReason_m);
  693. _termReason = ONE_UNRECOVERABLE_ERROR;
  694. _fatalErrorMessage = "Cluster: can't determine my cluster member ID: unable to bind to any cluster message socket IP/port.";
  695. return _termReason;
  696. }
  697. const ClusterDefinition::MemberDefinition &me = (*_clusterDefinition)[_clusterMemberId];
  698. InetAddress endpoints[255];
  699. unsigned int numEndpoints = 0;
  700. for(std::vector<InetAddress>::const_iterator i(me.zeroTierEndpoints.begin());i!=me.zeroTierEndpoints.end();++i)
  701. endpoints[numEndpoints++] = *i;
  702. 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) {
  703. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  704. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  705. if (m->id != _clusterMemberId)
  706. _node->clusterAddMember(m->id);
  707. }
  708. }
  709. } else {
  710. delete _clusterDefinition;
  711. _clusterDefinition = (ClusterDefinition *)0;
  712. }
  713. }
  714. #endif
  715. _controlPlane = new ControlPlane(this,_node,(_homePath + ZT_PATH_SEPARATOR_S + "ui").c_str());
  716. _controlPlane->addAuthToken(authToken.c_str());
  717. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  718. _controlPlane->setController(_controller);
  719. #endif
  720. { // Remember networks from previous session
  721. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S + "networks.d").c_str()));
  722. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  723. std::size_t dot = f->find_last_of('.');
  724. if ((dot == 16)&&(f->substr(16) == ".conf"))
  725. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()),(void *)0);
  726. }
  727. }
  728. // Start two background threads to handle expensive ops out of line
  729. Thread::start(_node);
  730. Thread::start(_node);
  731. _nextBackgroundTaskDeadline = 0;
  732. uint64_t clockShouldBe = OSUtils::now();
  733. _lastRestart = clockShouldBe;
  734. uint64_t lastTapMulticastGroupCheck = 0;
  735. uint64_t lastTcpFallbackResolve = 0;
  736. uint64_t lastBindRefresh = 0;
  737. 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
  738. #ifdef ZT_AUTO_UPDATE
  739. uint64_t lastSoftwareUpdateCheck = 0;
  740. #endif // ZT_AUTO_UPDATE
  741. for(;;) {
  742. _run_m.lock();
  743. if (!_run) {
  744. _run_m.unlock();
  745. _termReason_m.lock();
  746. _termReason = ONE_NORMAL_TERMINATION;
  747. _termReason_m.unlock();
  748. break;
  749. } else {
  750. _run_m.unlock();
  751. }
  752. const uint64_t now = OSUtils::now();
  753. // Attempt to detect sleep/wake events by detecting delay overruns
  754. bool restarted = false;
  755. if ((now > clockShouldBe)&&((now - clockShouldBe) > 10000)) {
  756. _lastRestart = now;
  757. restarted = true;
  758. }
  759. // Refresh bindings in case device's interfaces have changed, and also sync routes to update any shadow routes (e.g. shadow default)
  760. if (((now - lastBindRefresh) >= ZT_BINDER_REFRESH_PERIOD)||(restarted)) {
  761. lastBindRefresh = now;
  762. for(int i=0;i<3;++i) {
  763. if (_ports[i]) {
  764. _bindings[i].refresh(_phy,_ports[i],*this);
  765. }
  766. }
  767. {
  768. Mutex::Lock _l(_nets_m);
  769. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n) {
  770. if (n->second.tap)
  771. syncManagedStuff(n->second,false,true);
  772. }
  773. }
  774. }
  775. uint64_t dl = _nextBackgroundTaskDeadline;
  776. if (dl <= now) {
  777. _node->processBackgroundTasks(now,&_nextBackgroundTaskDeadline);
  778. dl = _nextBackgroundTaskDeadline;
  779. }
  780. #ifdef ZT_AUTO_UPDATE
  781. if ((now - lastSoftwareUpdateCheck) >= ZT_AUTO_UPDATE_CHECK_PERIOD) {
  782. lastSoftwareUpdateCheck = now;
  783. Thread::start(&backgroundSoftwareUpdateChecker);
  784. }
  785. #endif // ZT_AUTO_UPDATE
  786. if ((now - lastTcpFallbackResolve) >= ZT_TCP_FALLBACK_RERESOLVE_DELAY) {
  787. lastTcpFallbackResolve = now;
  788. _tcpFallbackResolver.resolveNow();
  789. }
  790. if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2)))
  791. _phy.close(_tcpFallbackTunnel->sock);
  792. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  793. lastTapMulticastGroupCheck = now;
  794. Mutex::Lock _l(_nets_m);
  795. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  796. if (n->second.tap) {
  797. std::vector<MulticastGroup> added,removed;
  798. n->second.tap->scanMulticastGroups(added,removed);
  799. for(std::vector<MulticastGroup>::iterator m(added.begin());m!=added.end();++m)
  800. _node->multicastSubscribe(n->first,m->mac().toInt(),m->adi());
  801. for(std::vector<MulticastGroup>::iterator m(removed.begin());m!=removed.end();++m)
  802. _node->multicastUnsubscribe(n->first,m->mac().toInt(),m->adi());
  803. }
  804. }
  805. }
  806. if ((now - lastLocalInterfaceAddressCheck) >= ZT_LOCAL_INTERFACE_CHECK_INTERVAL) {
  807. lastLocalInterfaceAddressCheck = now;
  808. _node->clearLocalInterfaceAddresses();
  809. #ifdef ZT_USE_MINIUPNPC
  810. if (_portMapper) {
  811. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  812. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  813. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  814. }
  815. #endif
  816. std::vector<InetAddress> boundAddrs(_bindings[0].allBoundLocalInterfaceAddresses());
  817. for(std::vector<InetAddress>::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i)
  818. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*i)));
  819. }
  820. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  821. clockShouldBe = now + (uint64_t)delay;
  822. _phy.poll(delay);
  823. }
  824. } catch (std::exception &exc) {
  825. Mutex::Lock _l(_termReason_m);
  826. _termReason = ONE_UNRECOVERABLE_ERROR;
  827. _fatalErrorMessage = exc.what();
  828. } catch ( ... ) {
  829. Mutex::Lock _l(_termReason_m);
  830. _termReason = ONE_UNRECOVERABLE_ERROR;
  831. _fatalErrorMessage = "unexpected exception in main thread";
  832. }
  833. try {
  834. while (!_tcpConnections.empty())
  835. _phy.close((*_tcpConnections.begin())->sock);
  836. } catch ( ... ) {}
  837. {
  838. Mutex::Lock _l(_nets_m);
  839. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n)
  840. delete n->second.tap;
  841. _nets.clear();
  842. }
  843. delete _controlPlane;
  844. _controlPlane = (ControlPlane *)0;
  845. delete _node;
  846. _node = (Node *)0;
  847. return _termReason;
  848. }
  849. virtual ReasonForTermination reasonForTermination() const
  850. {
  851. Mutex::Lock _l(_termReason_m);
  852. return _termReason;
  853. }
  854. virtual std::string fatalErrorMessage() const
  855. {
  856. Mutex::Lock _l(_termReason_m);
  857. return _fatalErrorMessage;
  858. }
  859. virtual std::string portDeviceName(uint64_t nwid) const
  860. {
  861. Mutex::Lock _l(_nets_m);
  862. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  863. if ((n != _nets.end())&&(n->second.tap))
  864. return n->second.tap->deviceName();
  865. else return std::string();
  866. }
  867. virtual bool tcpFallbackActive() const
  868. {
  869. return (_tcpFallbackTunnel != (TcpConnection *)0);
  870. }
  871. virtual void terminate()
  872. {
  873. _run_m.lock();
  874. _run = false;
  875. _run_m.unlock();
  876. _phy.whack();
  877. }
  878. // Begin private implementation methods
  879. // Checks if a managed IP or route target is allowed
  880. bool checkIfManagedIsAllowed(const NetworkState &n,const InetAddress &addr)
  881. {
  882. if (!n.allowManaged)
  883. return false;
  884. if (addr.isDefaultRoute())
  885. return n.allowDefault;
  886. switch(addr.ipScope()) {
  887. case InetAddress::IP_SCOPE_NONE:
  888. case InetAddress::IP_SCOPE_MULTICAST:
  889. case InetAddress::IP_SCOPE_LOOPBACK:
  890. case InetAddress::IP_SCOPE_LINK_LOCAL:
  891. return false;
  892. case InetAddress::IP_SCOPE_GLOBAL:
  893. return n.allowGlobal;
  894. default:
  895. return true;
  896. }
  897. }
  898. // Apply or update managed IPs for a configured network (be sure n.tap exists)
  899. void syncManagedStuff(NetworkState &n,bool syncIps,bool syncRoutes)
  900. {
  901. if (syncIps) {
  902. std::vector<InetAddress> newManagedIps;
  903. newManagedIps.reserve(n.config.assignedAddressCount);
  904. for(unsigned int i=0;i<n.config.assignedAddressCount;++i) {
  905. const InetAddress *ii = reinterpret_cast<const InetAddress *>(&(n.config.assignedAddresses[i]));
  906. if (checkIfManagedIsAllowed(n,*ii))
  907. newManagedIps.push_back(*ii);
  908. }
  909. std::sort(newManagedIps.begin(),newManagedIps.end());
  910. newManagedIps.erase(std::unique(newManagedIps.begin(),newManagedIps.end()),newManagedIps.end());
  911. for(std::vector<InetAddress>::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) {
  912. if (std::find(n.managedIps.begin(),n.managedIps.end(),*ip) == n.managedIps.end()) {
  913. if (!n.tap->addIp(*ip))
  914. fprintf(stderr,"ERROR: unable to add ip address %s"ZT_EOL_S, ip->toString().c_str());
  915. }
  916. }
  917. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  918. if (std::find(newManagedIps.begin(),newManagedIps.end(),*ip) == newManagedIps.end()) {
  919. if (!n.tap->removeIp(*ip))
  920. fprintf(stderr,"ERROR: unable to remove ip address %s"ZT_EOL_S, ip->toString().c_str());
  921. }
  922. }
  923. n.managedIps.swap(newManagedIps);
  924. }
  925. if (syncRoutes) {
  926. const std::string tapdev(n.tap->deviceName());
  927. // Nuke applied routes that are no longer in n.config.routes[] and/or are not allowed
  928. for(std::list<ManagedRoute>::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();) {
  929. bool haveRoute = false;
  930. if (checkIfManagedIsAllowed(n,mr->target())) {
  931. for(unsigned int i=0;i<n.config.routeCount;++i) {
  932. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  933. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  934. if ( (mr->target() == *target) && ( ((via->ss_family == target->ss_family)&&(mr->via() == *via)) || (tapdev == mr->device()) ) ) {
  935. haveRoute = true;
  936. break;
  937. }
  938. }
  939. }
  940. if (haveRoute) {
  941. ++mr;
  942. } else {
  943. n.managedRoutes.erase(mr++);
  944. }
  945. }
  946. // Apply routes in n.config.routes[] that we haven't applied yet, and sync those we have in case shadow routes need to change
  947. for(unsigned int i=0;i<n.config.routeCount;++i) {
  948. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  949. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  950. if (!checkIfManagedIsAllowed(n,*target))
  951. continue;
  952. bool haveRoute = false;
  953. // Ignore routes implied by local managed IPs since adding the IP adds the route
  954. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  955. if ((target->netmaskBits() == ip->netmaskBits())&&(target->containsAddress(*ip))) {
  956. haveRoute = true;
  957. break;
  958. }
  959. }
  960. if (haveRoute)
  961. continue;
  962. // If we've already applied this route, just sync it and continue
  963. for(std::list<ManagedRoute>::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();++mr) {
  964. if ( (mr->target() == *target) && ( ((via->ss_family == target->ss_family)&&(mr->via() == *via)) || (tapdev == mr->device()) ) ) {
  965. haveRoute = true;
  966. mr->sync();
  967. break;
  968. }
  969. }
  970. if (haveRoute)
  971. continue;
  972. // Add and apply new routes
  973. n.managedRoutes.push_back(ManagedRoute());
  974. if (!n.managedRoutes.back().set(*target,*via,tapdev.c_str()))
  975. n.managedRoutes.pop_back();
  976. }
  977. }
  978. }
  979. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  980. {
  981. #ifdef ZT_ENABLE_CLUSTER
  982. if (sock == _clusterMessageSocket) {
  983. _lastDirectReceiveFromGlobal = OSUtils::now();
  984. _node->clusterHandleIncomingMessage(data,len);
  985. return;
  986. }
  987. #endif
  988. #ifdef ZT_BREAK_UDP
  989. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  990. return;
  991. #endif
  992. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  993. _lastDirectReceiveFromGlobal = OSUtils::now();
  994. const ZT_ResultCode rc = _node->processWirePacket(
  995. OSUtils::now(),
  996. reinterpret_cast<const struct sockaddr_storage *>(localAddr),
  997. (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
  998. data,
  999. len,
  1000. &_nextBackgroundTaskDeadline);
  1001. if (ZT_ResultCode_isFatal(rc)) {
  1002. char tmp[256];
  1003. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1004. Mutex::Lock _l(_termReason_m);
  1005. _termReason = ONE_UNRECOVERABLE_ERROR;
  1006. _fatalErrorMessage = tmp;
  1007. this->terminate();
  1008. }
  1009. }
  1010. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  1011. {
  1012. if (!success)
  1013. return;
  1014. // Outgoing TCP connections are always TCP fallback tunnel connections.
  1015. TcpConnection *tc = new TcpConnection();
  1016. _tcpConnections.insert(tc);
  1017. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  1018. tc->shouldKeepAlive = true;
  1019. tc->parent = this;
  1020. tc->sock = sock;
  1021. // from and parser are not used
  1022. tc->messageSize = 0; // unused
  1023. tc->lastActivity = OSUtils::now();
  1024. // HTTP stuff is not used
  1025. tc->writeBuf = "";
  1026. *uptr = (void *)tc;
  1027. // Send "hello" message
  1028. tc->writeBuf.push_back((char)0x17);
  1029. tc->writeBuf.push_back((char)0x03);
  1030. tc->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1031. tc->writeBuf.push_back((char)0x00);
  1032. tc->writeBuf.push_back((char)0x04); // mlen == 4
  1033. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MAJOR);
  1034. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MINOR);
  1035. tc->writeBuf.push_back((char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff));
  1036. tc->writeBuf.push_back((char)(ZEROTIER_ONE_VERSION_REVISION & 0xff));
  1037. _phy.setNotifyWritable(sock,true);
  1038. _tcpFallbackTunnel = tc;
  1039. }
  1040. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  1041. {
  1042. if ((!from)||(reinterpret_cast<const InetAddress *>(from)->ipScope() != InetAddress::IP_SCOPE_LOOPBACK)) {
  1043. // Non-Loopback: deny (for now)
  1044. _phy.close(sockN,false);
  1045. return;
  1046. } else {
  1047. // Loopback == HTTP JSON API request
  1048. TcpConnection *tc = new TcpConnection();
  1049. _tcpConnections.insert(tc);
  1050. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  1051. tc->shouldKeepAlive = true;
  1052. tc->parent = this;
  1053. tc->sock = sockN;
  1054. tc->from = from;
  1055. http_parser_init(&(tc->parser),HTTP_REQUEST);
  1056. tc->parser.data = (void *)tc;
  1057. tc->messageSize = 0;
  1058. tc->lastActivity = OSUtils::now();
  1059. tc->currentHeaderField = "";
  1060. tc->currentHeaderValue = "";
  1061. tc->url = "";
  1062. tc->status = "";
  1063. tc->headers.clear();
  1064. tc->body = "";
  1065. tc->writeBuf = "";
  1066. *uptrN = (void *)tc;
  1067. }
  1068. }
  1069. inline void phyOnTcpClose(PhySocket *sock,void **uptr)
  1070. {
  1071. TcpConnection *tc = (TcpConnection *)*uptr;
  1072. if (tc) {
  1073. if (tc == _tcpFallbackTunnel)
  1074. _tcpFallbackTunnel = (TcpConnection *)0;
  1075. _tcpConnections.erase(tc);
  1076. delete tc;
  1077. }
  1078. }
  1079. inline void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  1080. {
  1081. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1082. switch(tc->type) {
  1083. case TcpConnection::TCP_HTTP_INCOMING:
  1084. case TcpConnection::TCP_HTTP_OUTGOING:
  1085. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  1086. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK)) {
  1087. _phy.close(sock);
  1088. return;
  1089. }
  1090. break;
  1091. case TcpConnection::TCP_TUNNEL_OUTGOING:
  1092. tc->body.append((const char *)data,len);
  1093. while (tc->body.length() >= 5) {
  1094. const char *data = tc->body.data();
  1095. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  1096. if (tc->body.length() >= (mlen + 5)) {
  1097. InetAddress from;
  1098. unsigned long plen = mlen; // payload length, modified if there's an IP header
  1099. data += 5; // skip forward past pseudo-TLS junk and mlen
  1100. if (plen == 4) {
  1101. // Hello message, which isn't sent by proxy and would be ignored by client
  1102. } else if (plen) {
  1103. // Messages should contain IPv4 or IPv6 source IP address data
  1104. switch(data[0]) {
  1105. case 4: // IPv4
  1106. if (plen >= 7) {
  1107. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  1108. data += 7; // type + 4 byte IP + 2 byte port
  1109. plen -= 7;
  1110. } else {
  1111. _phy.close(sock);
  1112. return;
  1113. }
  1114. break;
  1115. case 6: // IPv6
  1116. if (plen >= 19) {
  1117. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  1118. data += 19; // type + 16 byte IP + 2 byte port
  1119. plen -= 19;
  1120. } else {
  1121. _phy.close(sock);
  1122. return;
  1123. }
  1124. break;
  1125. case 0: // none/omitted
  1126. ++data;
  1127. --plen;
  1128. break;
  1129. default: // invalid address type
  1130. _phy.close(sock);
  1131. return;
  1132. }
  1133. if (from) {
  1134. InetAddress fakeTcpLocalInterfaceAddress((uint32_t)0xffffffff,0xffff);
  1135. const ZT_ResultCode rc = _node->processWirePacket(
  1136. OSUtils::now(),
  1137. reinterpret_cast<struct sockaddr_storage *>(&fakeTcpLocalInterfaceAddress),
  1138. reinterpret_cast<struct sockaddr_storage *>(&from),
  1139. data,
  1140. plen,
  1141. &_nextBackgroundTaskDeadline);
  1142. if (ZT_ResultCode_isFatal(rc)) {
  1143. char tmp[256];
  1144. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1145. Mutex::Lock _l(_termReason_m);
  1146. _termReason = ONE_UNRECOVERABLE_ERROR;
  1147. _fatalErrorMessage = tmp;
  1148. this->terminate();
  1149. _phy.close(sock);
  1150. return;
  1151. }
  1152. }
  1153. }
  1154. if (tc->body.length() > (mlen + 5))
  1155. tc->body = tc->body.substr(mlen + 5);
  1156. else tc->body = "";
  1157. } else break;
  1158. }
  1159. break;
  1160. }
  1161. }
  1162. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  1163. {
  1164. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1165. Mutex::Lock _l(tc->writeBuf_m);
  1166. if (tc->writeBuf.length() > 0) {
  1167. long sent = (long)_phy.streamSend(sock,tc->writeBuf.data(),(unsigned long)tc->writeBuf.length(),true);
  1168. if (sent > 0) {
  1169. tc->lastActivity = OSUtils::now();
  1170. if ((unsigned long)sent >= (unsigned long)tc->writeBuf.length()) {
  1171. tc->writeBuf = "";
  1172. _phy.setNotifyWritable(sock,false);
  1173. if (!tc->shouldKeepAlive)
  1174. _phy.close(sock); // will call close handler to delete from _tcpConnections
  1175. } else {
  1176. tc->writeBuf = tc->writeBuf.substr(sent);
  1177. }
  1178. }
  1179. } else {
  1180. _phy.setNotifyWritable(sock,false);
  1181. }
  1182. }
  1183. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  1184. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  1185. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  1186. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  1187. inline void phyOnUnixWritable(PhySocket *sock,void **uptr,bool lwip_invoked) {}
  1188. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  1189. {
  1190. Mutex::Lock _l(_nets_m);
  1191. NetworkState &n = _nets[nwid];
  1192. switch(op) {
  1193. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  1194. if (!n.tap) {
  1195. try {
  1196. char friendlyName[128];
  1197. Utils::snprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  1198. n.tap = new EthernetTap(
  1199. _homePath.c_str(),
  1200. MAC(nwc->mac),
  1201. nwc->mtu,
  1202. (unsigned int)ZT_IF_METRIC,
  1203. nwid,
  1204. friendlyName,
  1205. StapFrameHandler,
  1206. (void *)this);
  1207. *nuptr = (void *)&n;
  1208. } catch (std::exception &exc) {
  1209. #ifdef __WINDOWS__
  1210. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1211. if (tapFailLog) {
  1212. fprintf(tapFailLog,"%.16llx: %s"ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1213. fclose(tapFailLog);
  1214. }
  1215. #else
  1216. fprintf(stderr,"ERROR: unable to configure virtual network port: %s"ZT_EOL_S,exc.what());
  1217. #endif
  1218. _nets.erase(nwid);
  1219. return -999;
  1220. } catch ( ... ) {
  1221. return -999; // tap init failed
  1222. }
  1223. }
  1224. // After setting up tap, fall through to CONFIG_UPDATE since we also want to do this...
  1225. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1226. memcpy(&(n.config),nwc,sizeof(ZT_VirtualNetworkConfig));
  1227. if (n.tap) { // sanity check
  1228. syncManagedStuff(n,true,true);
  1229. } else {
  1230. _nets.erase(nwid);
  1231. return -999; // tap init failed
  1232. }
  1233. break;
  1234. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1235. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1236. if (n.tap) { // sanity check
  1237. #ifdef __WINDOWS__
  1238. std::string winInstanceId(n.tap->instanceId());
  1239. #endif
  1240. *nuptr = (void *)0;
  1241. delete n.tap;
  1242. _nets.erase(nwid);
  1243. #ifdef __WINDOWS__
  1244. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1245. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1246. #endif
  1247. } else {
  1248. _nets.erase(nwid);
  1249. }
  1250. break;
  1251. }
  1252. return 0;
  1253. }
  1254. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1255. {
  1256. switch(event) {
  1257. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  1258. Mutex::Lock _l(_termReason_m);
  1259. _termReason = ONE_IDENTITY_COLLISION;
  1260. _fatalErrorMessage = "identity/address collision";
  1261. this->terminate();
  1262. } break;
  1263. case ZT_EVENT_TRACE: {
  1264. if (metaData) {
  1265. ::fprintf(stderr,"%s"ZT_EOL_S,(const char *)metaData);
  1266. ::fflush(stderr);
  1267. }
  1268. } break;
  1269. default:
  1270. break;
  1271. }
  1272. }
  1273. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1274. {
  1275. std::string p(_dataStorePrepPath(name));
  1276. if (!p.length())
  1277. return -2;
  1278. FILE *f = fopen(p.c_str(),"rb");
  1279. if (!f)
  1280. return -1;
  1281. if (fseek(f,0,SEEK_END) != 0) {
  1282. fclose(f);
  1283. return -2;
  1284. }
  1285. long ts = ftell(f);
  1286. if (ts < 0) {
  1287. fclose(f);
  1288. return -2;
  1289. }
  1290. *totalSize = (unsigned long)ts;
  1291. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  1292. fclose(f);
  1293. return -2;
  1294. }
  1295. long n = (long)fread(buf,1,bufSize,f);
  1296. fclose(f);
  1297. return n;
  1298. }
  1299. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  1300. {
  1301. std::string p(_dataStorePrepPath(name));
  1302. if (!p.length())
  1303. return -2;
  1304. if (!data) {
  1305. OSUtils::rm(p.c_str());
  1306. return 0;
  1307. }
  1308. FILE *f = fopen(p.c_str(),"wb");
  1309. if (!f)
  1310. return -1;
  1311. if (fwrite(data,len,1,f) == 1) {
  1312. fclose(f);
  1313. if (secure)
  1314. OSUtils::lockDownFile(p.c_str(),false);
  1315. return 0;
  1316. } else {
  1317. fclose(f);
  1318. OSUtils::rm(p.c_str());
  1319. return -1;
  1320. }
  1321. }
  1322. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1323. {
  1324. unsigned int fromBindingNo = 0;
  1325. if (addr->ss_family == AF_INET) {
  1326. if (reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port == 0) {
  1327. // If sender is sending from wildcard (null address), choose the secondary backup
  1328. // port 1/4 of the time. (but only for IPv4)
  1329. fromBindingNo = (++_udpPortPickerCounter & 0x4) >> 2;
  1330. if (!_ports[fromBindingNo])
  1331. fromBindingNo = 0;
  1332. } else {
  1333. const uint16_t lp = reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port;
  1334. if (lp == _portsBE[1])
  1335. fromBindingNo = 1;
  1336. else if (lp == _portsBE[2])
  1337. fromBindingNo = 2;
  1338. }
  1339. #ifdef ZT_TCP_FALLBACK_RELAY
  1340. // TCP fallback tunnel support, currently IPv4 only
  1341. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  1342. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  1343. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  1344. // valid direct traffic we'll stop using it and close the socket after a while.
  1345. const uint64_t now = OSUtils::now();
  1346. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  1347. if (_tcpFallbackTunnel) {
  1348. Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
  1349. if (!_tcpFallbackTunnel->writeBuf.length())
  1350. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  1351. unsigned long mlen = len + 7;
  1352. _tcpFallbackTunnel->writeBuf.push_back((char)0x17);
  1353. _tcpFallbackTunnel->writeBuf.push_back((char)0x03);
  1354. _tcpFallbackTunnel->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1355. _tcpFallbackTunnel->writeBuf.push_back((char)((mlen >> 8) & 0xff));
  1356. _tcpFallbackTunnel->writeBuf.push_back((char)(mlen & 0xff));
  1357. _tcpFallbackTunnel->writeBuf.push_back((char)4); // IPv4
  1358. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  1359. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  1360. _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
  1361. } else if (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INVERVAL / 2))) {
  1362. std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
  1363. if (tunnelIps.empty()) {
  1364. if (!_tcpFallbackResolver.running())
  1365. _tcpFallbackResolver.resolveNow();
  1366. } else {
  1367. bool connected = false;
  1368. InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
  1369. addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
  1370. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
  1371. }
  1372. }
  1373. }
  1374. _lastSendToGlobalV4 = now;
  1375. }
  1376. #endif // ZT_TCP_FALLBACK_RELAY
  1377. } else if (addr->ss_family == AF_INET6) {
  1378. if (reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port != 0) {
  1379. const uint16_t lp = reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port;
  1380. if (lp == _portsBE[1])
  1381. fromBindingNo = 1;
  1382. else if (lp == _portsBE[2])
  1383. fromBindingNo = 2;
  1384. }
  1385. } else {
  1386. return -1;
  1387. }
  1388. #ifdef ZT_BREAK_UDP
  1389. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  1390. return 0; // silently break UDP
  1391. #endif
  1392. return (_bindings[fromBindingNo].udpSend(_phy,*(reinterpret_cast<const InetAddress *>(localAddr)),*(reinterpret_cast<const InetAddress *>(addr)),data,len,ttl)) ? 0 : -1;
  1393. }
  1394. 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)
  1395. {
  1396. NetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);
  1397. if ((!n)||(!n->tap))
  1398. return;
  1399. n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1400. }
  1401. inline int nodePathCheckFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1402. {
  1403. Mutex::Lock _l(_nets_m);
  1404. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1405. if (n->second.tap) {
  1406. std::vector<InetAddress> ips(n->second.tap->ips());
  1407. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1408. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  1409. return 0;
  1410. }
  1411. }
  1412. }
  1413. }
  1414. /* Note: I do not think we need to scan for overlap with managed routes
  1415. * because of the "route forking" and interface binding that we do. This
  1416. * ensures (we hope) that ZeroTier traffic will still take the physical
  1417. * path even if its managed routes override this for other traffic. Will
  1418. * revisit if we see problems with this. */
  1419. return 1;
  1420. }
  1421. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1422. {
  1423. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1424. }
  1425. inline void onHttpRequestToServer(TcpConnection *tc)
  1426. {
  1427. char tmpn[256];
  1428. std::string data;
  1429. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1430. unsigned int scode = 404;
  1431. try {
  1432. if (_controlPlane)
  1433. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  1434. else scode = 500;
  1435. } catch ( ... ) {
  1436. scode = 500;
  1437. }
  1438. const char *scodestr;
  1439. switch(scode) {
  1440. case 200: scodestr = "OK"; break;
  1441. case 400: scodestr = "Bad Request"; break;
  1442. case 401: scodestr = "Unauthorized"; break;
  1443. case 403: scodestr = "Forbidden"; break;
  1444. case 404: scodestr = "Not Found"; break;
  1445. case 500: scodestr = "Internal Server Error"; break;
  1446. case 501: scodestr = "Not Implemented"; break;
  1447. case 503: scodestr = "Service Unavailable"; break;
  1448. default: scodestr = "Error"; break;
  1449. }
  1450. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  1451. {
  1452. Mutex::Lock _l(tc->writeBuf_m);
  1453. tc->writeBuf.assign(tmpn);
  1454. tc->writeBuf.append("Content-Type: ");
  1455. tc->writeBuf.append(contentType);
  1456. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  1457. tc->writeBuf.append(tmpn);
  1458. if (!tc->shouldKeepAlive)
  1459. tc->writeBuf.append("Connection: close\r\n");
  1460. tc->writeBuf.append("\r\n");
  1461. if (tc->parser.method != HTTP_HEAD)
  1462. tc->writeBuf.append(data);
  1463. }
  1464. _phy.setNotifyWritable(tc->sock,true);
  1465. }
  1466. inline void onHttpResponseFromClient(TcpConnection *tc)
  1467. {
  1468. if (!tc->shouldKeepAlive)
  1469. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConnections
  1470. }
  1471. bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
  1472. {
  1473. if (isBlacklistedLocalInterfaceForZeroTierTraffic(ifname))
  1474. return false;
  1475. Mutex::Lock _l(_nets_m);
  1476. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1477. if (n->second.tap) {
  1478. std::vector<InetAddress> ips(n->second.tap->ips());
  1479. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1480. if (i->ipsEqual(ifaddr))
  1481. return false;
  1482. }
  1483. }
  1484. }
  1485. return true;
  1486. }
  1487. std::string _dataStorePrepPath(const char *name) const
  1488. {
  1489. std::string p(_homePath);
  1490. p.push_back(ZT_PATH_SEPARATOR);
  1491. char lastc = (char)0;
  1492. for(const char *n=name;(*n);++n) {
  1493. if ((*n == '.')&&(lastc == '.'))
  1494. return std::string(); // don't allow ../../ stuff as a precaution
  1495. if (*n == '/') {
  1496. OSUtils::mkdir(p.c_str());
  1497. p.push_back(ZT_PATH_SEPARATOR);
  1498. } else p.push_back(*n);
  1499. lastc = *n;
  1500. }
  1501. return p;
  1502. }
  1503. bool _trialBind(unsigned int port)
  1504. {
  1505. struct sockaddr_in in4;
  1506. struct sockaddr_in6 in6;
  1507. PhySocket *tb;
  1508. memset(&in4,0,sizeof(in4));
  1509. in4.sin_family = AF_INET;
  1510. in4.sin_port = Utils::hton((uint16_t)port);
  1511. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
  1512. if (tb) {
  1513. _phy.close(tb,false);
  1514. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
  1515. if (tb) {
  1516. _phy.close(tb,false);
  1517. return true;
  1518. }
  1519. }
  1520. memset(&in6,0,sizeof(in6));
  1521. in6.sin6_family = AF_INET6;
  1522. in6.sin6_port = Utils::hton((uint16_t)port);
  1523. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
  1524. if (tb) {
  1525. _phy.close(tb,false);
  1526. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
  1527. if (tb) {
  1528. _phy.close(tb,false);
  1529. return true;
  1530. }
  1531. }
  1532. return false;
  1533. }
  1534. };
  1535. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  1536. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  1537. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData)
  1538. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1539. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1540. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  1541. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  1542. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  1543. 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)
  1544. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localAddr,addr,data,len,ttl); }
  1545. 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)
  1546. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  1547. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1548. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(localAddr,remoteAddr); }
  1549. #ifdef ZT_ENABLE_CLUSTER
  1550. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len)
  1551. {
  1552. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1553. const ClusterDefinition::MemberDefinition &md = (*(impl->_clusterDefinition))[toMemberId];
  1554. if (md.clusterEndpoint)
  1555. impl->_phy.udpSend(impl->_clusterMessageSocket,reinterpret_cast<const struct sockaddr *>(&(md.clusterEndpoint)),data,len);
  1556. }
  1557. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z)
  1558. {
  1559. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1560. return (int)(impl->_clusterDefinition->geo().locate(*(reinterpret_cast<const InetAddress *>(addr)),*x,*y,*z));
  1561. }
  1562. #endif
  1563. 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)
  1564. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1565. static int ShttpOnMessageBegin(http_parser *parser)
  1566. {
  1567. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1568. tc->currentHeaderField = "";
  1569. tc->currentHeaderValue = "";
  1570. tc->messageSize = 0;
  1571. tc->url = "";
  1572. tc->status = "";
  1573. tc->headers.clear();
  1574. tc->body = "";
  1575. return 0;
  1576. }
  1577. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  1578. {
  1579. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1580. tc->messageSize += (unsigned long)length;
  1581. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1582. return -1;
  1583. tc->url.append(ptr,length);
  1584. return 0;
  1585. }
  1586. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  1587. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1588. #else
  1589. static int ShttpOnStatus(http_parser *parser)
  1590. #endif
  1591. {
  1592. /*
  1593. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1594. tc->messageSize += (unsigned long)length;
  1595. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1596. return -1;
  1597. tc->status.append(ptr,length);
  1598. */
  1599. return 0;
  1600. }
  1601. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1602. {
  1603. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1604. tc->messageSize += (unsigned long)length;
  1605. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1606. return -1;
  1607. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1608. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1609. tc->currentHeaderField = "";
  1610. tc->currentHeaderValue = "";
  1611. }
  1612. for(size_t i=0;i<length;++i)
  1613. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1614. return 0;
  1615. }
  1616. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1617. {
  1618. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1619. tc->messageSize += (unsigned long)length;
  1620. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1621. return -1;
  1622. tc->currentHeaderValue.append(ptr,length);
  1623. return 0;
  1624. }
  1625. static int ShttpOnHeadersComplete(http_parser *parser)
  1626. {
  1627. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1628. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  1629. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1630. return 0;
  1631. }
  1632. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  1633. {
  1634. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1635. tc->messageSize += (unsigned long)length;
  1636. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1637. return -1;
  1638. tc->body.append(ptr,length);
  1639. return 0;
  1640. }
  1641. static int ShttpOnMessageComplete(http_parser *parser)
  1642. {
  1643. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1644. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  1645. tc->lastActivity = OSUtils::now();
  1646. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  1647. tc->parent->onHttpRequestToServer(tc);
  1648. } else {
  1649. tc->parent->onHttpResponseFromClient(tc);
  1650. }
  1651. return 0;
  1652. }
  1653. } // anonymous namespace
  1654. std::string OneService::platformDefaultHomePath()
  1655. {
  1656. #ifdef __UNIX_LIKE__
  1657. #ifdef __APPLE__
  1658. // /Library/... on Apple
  1659. return std::string("/Library/Application Support/ZeroTier/One");
  1660. #else
  1661. #ifdef __BSD__
  1662. // BSD likes /var/db instead of /var/lib
  1663. return std::string("/var/db/zerotier-one");
  1664. #else
  1665. // Use /var/lib for Linux and other *nix
  1666. return std::string("/var/lib/zerotier-one");
  1667. #endif
  1668. #endif
  1669. #else // not __UNIX_LIKE__
  1670. #ifdef __WINDOWS__
  1671. // Look up app data folder on Windows, e.g. C:\ProgramData\...
  1672. char buf[16384];
  1673. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_COMMON_APPDATA,NULL,0,buf)))
  1674. return (std::string(buf) + "\\ZeroTier\\One");
  1675. else return std::string("C:\\ZeroTier\\One");
  1676. #else
  1677. return std::string(); // UNKNOWN PLATFORM
  1678. #endif
  1679. #endif // __UNIX_LIKE__ or not...
  1680. }
  1681. std::string OneService::autoUpdateUrl()
  1682. {
  1683. #ifdef ZT_AUTO_UPDATE
  1684. /*
  1685. #if defined(__LINUX__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1686. if (sizeof(void *) == 8)
  1687. return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x64-LATEST.nfo";
  1688. else return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x86-LATEST.nfo";
  1689. #endif
  1690. */
  1691. #if defined(__APPLE__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1692. return "http://download.zerotier.com/update/mac_intel/";
  1693. #endif
  1694. #ifdef __WINDOWS__
  1695. return "http://download.zerotier.com/update/win_intel/";
  1696. #endif
  1697. #endif // ZT_AUTO_UPDATE
  1698. return std::string();
  1699. }
  1700. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  1701. OneService::~OneService() {}
  1702. } // namespace ZeroTier