OneService.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <stdint.h>
  31. #include <string>
  32. #include <map>
  33. #include <set>
  34. #include <vector>
  35. #include <algorithm>
  36. #include "../version.h"
  37. #include "../include/ZeroTierOne.h"
  38. #include "../ext/http-parser/http_parser.h"
  39. #include "../node/Constants.hpp"
  40. #include "../node/Mutex.hpp"
  41. #include "../node/Node.hpp"
  42. #include "../node/Utils.hpp"
  43. #include "../node/InetAddress.hpp"
  44. #include "../node/MAC.hpp"
  45. #include "../node/Identity.hpp"
  46. #include "../osdep/Phy.hpp"
  47. #include "../osdep/Thread.hpp"
  48. #include "../osdep/OSUtils.hpp"
  49. #include "../osdep/Http.hpp"
  50. #include "../osdep/BackgroundResolver.hpp"
  51. #include "../osdep/PortMapper.hpp"
  52. #include "OneService.hpp"
  53. #include "ControlPlane.hpp"
  54. #include "ClusterGeoIpService.hpp"
  55. #include "ClusterDefinition.hpp"
  56. /**
  57. * Uncomment to enable UDP breakage switch
  58. *
  59. * If this is defined, the presence of a file called /tmp/ZT_BREAK_UDP
  60. * will cause direct UDP TX/RX to stop working. This can be used to
  61. * test TCP tunneling fallback and other robustness features. Deleting
  62. * this file will cause it to start working again.
  63. */
  64. //#define ZT_BREAK_UDP
  65. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  66. #include "../controller/SqliteNetworkController.hpp"
  67. #else
  68. class SqliteNetworkController;
  69. #endif // ZT_ENABLE_NETWORK_CONTROLLER
  70. #ifdef __WINDOWS__
  71. #include <WinSock2.h>
  72. #include <Windows.h>
  73. #include <ShlObj.h>
  74. #include <netioapi.h>
  75. #include <iphlpapi.h>
  76. #else
  77. #include <sys/types.h>
  78. #include <sys/socket.h>
  79. #include <sys/wait.h>
  80. #include <unistd.h>
  81. #include <ifaddrs.h>
  82. #endif
  83. // Include the right tap device driver for this platform -- add new platforms here
  84. #ifdef ZT_ENABLE_NETCON
  85. #include "../netcon/NetconEthernetTap.hpp"
  86. namespace ZeroTier { typedef NetconEthernetTap EthernetTap; }
  87. #else
  88. #ifdef __APPLE__
  89. #include "../osdep/OSXEthernetTap.hpp"
  90. namespace ZeroTier { typedef OSXEthernetTap EthernetTap; }
  91. #endif
  92. #ifdef __LINUX__
  93. #include "../osdep/LinuxEthernetTap.hpp"
  94. namespace ZeroTier { typedef LinuxEthernetTap EthernetTap; }
  95. #endif
  96. #ifdef __WINDOWS__
  97. #include "../osdep/WindowsEthernetTap.hpp"
  98. namespace ZeroTier { typedef WindowsEthernetTap EthernetTap; }
  99. #endif
  100. #ifdef __FreeBSD__
  101. #include "../osdep/BSDEthernetTap.hpp"
  102. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  103. #endif
  104. #endif // ZT_ENABLE_NETCON
  105. // Sanity limits for HTTP
  106. #define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 64)
  107. #define ZT_MAX_HTTP_CONNECTIONS 64
  108. // Interface metric for ZeroTier taps
  109. #define ZT_IF_METRIC 32768
  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 300000
  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. /* 0005 */ (id == Identity("ba57ea350e:0:9d4be6d7f86c5660d5ee1951a3d759aa6e12a84fc0c0b74639500f1dbc1a8c566622e7d1c531967ebceb1e9d1761342f88324a8ba520c93c35f92f35080fa23f"))
  135. /* 0006 */ ||(id == Identity("5067b21b83:0:8af477730f5055c48135b84bed6720a35bca4c0e34be4060a4c636288b1ec22217eb22709d610c66ed464c643130c51411bbb0294eef12fbe8ecc1a1e2c63a7a"))
  136. /* 0007 */ ||(id == Identity("4f5e97a8f1:0:57880d056d7baeb04bbc057d6f16e6cb41388570e87f01492fce882485f65a798648595610a3ad49885604e7fb1db2dd3c2c534b75e42c3c0b110ad07b4bb138"))
  137. /* 0008 */ ||(id == Identity("580bbb8e15:0:ad5ef31155bebc6bc413991992387e083fed26d699997ef76e7c947781edd47d1997161fa56ba337b1a2b44b129fd7c7197ce5185382f06011bc88d1363b4ddd"))
  138. );
  139. }
  140. void doUpdateCheck()
  141. {
  142. std::string url(OneService::autoUpdateUrl());
  143. if ((url.length() <= 7)||(url.substr(0,7) != "http://"))
  144. return;
  145. std::string httpHost;
  146. std::string httpPath;
  147. {
  148. std::size_t slashIdx = url.substr(7).find_first_of('/');
  149. if (slashIdx == std::string::npos) {
  150. httpHost = url.substr(7);
  151. httpPath = "/";
  152. } else {
  153. httpHost = url.substr(7,slashIdx);
  154. httpPath = url.substr(slashIdx + 7);
  155. }
  156. }
  157. if (httpHost.length() == 0)
  158. return;
  159. std::vector<InetAddress> ips(OSUtils::resolve(httpHost.c_str()));
  160. for(std::vector<InetAddress>::iterator ip(ips.begin());ip!=ips.end();++ip) {
  161. if (!ip->port())
  162. ip->setPort(80);
  163. std::string nfoPath = httpPath + "LATEST.nfo";
  164. std::map<std::string,std::string> requestHeaders,responseHeaders;
  165. std::string body;
  166. requestHeaders["Host"] = httpHost;
  167. 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);
  168. //fprintf(stderr,"UPDATE %s %s %u %lu\n",ip->toString().c_str(),nfoPath.c_str(),scode,body.length());
  169. if ((scode == 200)&&(body.length() > 0)) {
  170. /* NFO fields:
  171. *
  172. * file=<filename>
  173. * signedBy=<signing identity>
  174. * ed25519=<ed25519 ECC signature of archive>
  175. * vMajor=<major version>
  176. * vMinor=<minor version>
  177. * vRevision=<revision> */
  178. Dictionary nfo(body);
  179. unsigned int vMajor = Utils::strToUInt(nfo.get("vMajor","0").c_str());
  180. unsigned int vMinor = Utils::strToUInt(nfo.get("vMinor","0").c_str());
  181. unsigned int vRevision = Utils::strToUInt(nfo.get("vRevision","0").c_str());
  182. if (Utils::compareVersion(vMajor,vMinor,vRevision,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION) <= 0) {
  183. //fprintf(stderr,"UPDATE %u.%u.%u is not newer than our version\n",vMajor,vMinor,vRevision);
  184. return;
  185. }
  186. Identity signedBy;
  187. if ((!signedBy.fromString(nfo.get("signedBy","")))||(!isValidSigningIdentity(signedBy))) {
  188. //fprintf(stderr,"UPDATE invalid signedBy or not authorized signing identity.\n");
  189. return;
  190. }
  191. std::string filePath(nfo.get("file",""));
  192. if ((!filePath.length())||(filePath.find("..") != std::string::npos))
  193. return;
  194. filePath = httpPath + filePath;
  195. std::string fileData;
  196. if (Http::GET(ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE,60000,reinterpret_cast<const struct sockaddr *>(&(*ip)),filePath.c_str(),requestHeaders,responseHeaders,fileData) != 200) {
  197. //fprintf(stderr,"UPDATE GET %s failed\n",filePath.c_str());
  198. return;
  199. }
  200. std::string ed25519(Utils::unhex(nfo.get("ed25519","")));
  201. if ((ed25519.length() == 0)||(!signedBy.verify(fileData.data(),(unsigned int)fileData.length(),ed25519.data(),(unsigned int)ed25519.length()))) {
  202. //fprintf(stderr,"UPDATE %s failed signature check!\n",filePath.c_str());
  203. return;
  204. }
  205. /* --------------------------------------------------------------- */
  206. /* We made it! Begin OS-specific installation code. */
  207. #ifdef __APPLE__
  208. /* OSX version is in the form of a MacOSX .pkg file, so we will
  209. * launch installer (normally in /usr/sbin) to install it. It will
  210. * then turn around and shut down the service, update files, and
  211. * relaunch. */
  212. {
  213. char bashp[128],pkgp[128];
  214. Utils::snprintf(bashp,sizeof(bashp),"/tmp/ZeroTierOne-update-%u.%u.%u.sh",vMajor,vMinor,vRevision);
  215. Utils::snprintf(pkgp,sizeof(pkgp),"/tmp/ZeroTierOne-update-%u.%u.%u.pkg",vMajor,vMinor,vRevision);
  216. FILE *pkg = fopen(pkgp,"w");
  217. if ((!pkg)||(fwrite(fileData.data(),fileData.length(),1,pkg) != 1)) {
  218. fclose(pkg);
  219. unlink(bashp);
  220. unlink(pkgp);
  221. fprintf(stderr,"UPDATE error writing %s\n",pkgp);
  222. return;
  223. }
  224. fclose(pkg);
  225. FILE *bash = fopen(bashp,"w");
  226. if (!bash) {
  227. fclose(pkg);
  228. unlink(bashp);
  229. unlink(pkgp);
  230. fprintf(stderr,"UPDATE error writing %s\n",bashp);
  231. return;
  232. }
  233. fprintf(bash,
  234. "#!/bin/bash\n"
  235. "export PATH=/bin:/usr/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/sbin\n"
  236. "sleep 1\n"
  237. "installer -pkg \"%s\" -target /\n"
  238. "sleep 1\n"
  239. "rm -f \"%s\" \"%s\"\n"
  240. "exit 0\n",
  241. pkgp,
  242. pkgp,
  243. bashp);
  244. fclose(bash);
  245. long pid = (long)vfork();
  246. if (pid == 0) {
  247. setsid(); // detach from parent so that shell isn't killed when parent is killed
  248. signal(SIGHUP,SIG_IGN);
  249. signal(SIGTERM,SIG_IGN);
  250. signal(SIGQUIT,SIG_IGN);
  251. execl("/bin/bash","/bin/bash",bashp,(char *)0);
  252. exit(0);
  253. }
  254. }
  255. #endif // __APPLE__
  256. #ifdef __WINDOWS__
  257. /* Windows version comes in the form of .MSI package that
  258. * takes care of everything. */
  259. {
  260. char tempp[512],batp[512],msip[512],cmdline[512];
  261. if (GetTempPathA(sizeof(tempp),tempp) <= 0)
  262. return;
  263. CreateDirectoryA(tempp,(LPSECURITY_ATTRIBUTES)0);
  264. Utils::snprintf(batp,sizeof(batp),"%s\\ZeroTierOne-update-%u.%u.%u.bat",tempp,vMajor,vMinor,vRevision);
  265. Utils::snprintf(msip,sizeof(msip),"%s\\ZeroTierOne-update-%u.%u.%u.msi",tempp,vMajor,vMinor,vRevision);
  266. FILE *msi = fopen(msip,"wb");
  267. if ((!msi)||(fwrite(fileData.data(),(size_t)fileData.length(),1,msi) != 1)) {
  268. fclose(msi);
  269. return;
  270. }
  271. fclose(msi);
  272. FILE *bat = fopen(batp,"wb");
  273. if (!bat)
  274. return;
  275. fprintf(bat,
  276. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  277. "NET.EXE STOP \"ZeroTierOneService\"\r\n"
  278. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  279. "MSIEXEC.EXE /i \"%s\" /qn\r\n"
  280. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  281. "NET.EXE START \"ZeroTierOneService\"\r\n"
  282. "DEL \"%s\"\r\n"
  283. "DEL \"%s\"\r\n",
  284. msip,
  285. msip,
  286. batp);
  287. fclose(bat);
  288. STARTUPINFOA si;
  289. PROCESS_INFORMATION pi;
  290. memset(&si,0,sizeof(si));
  291. memset(&pi,0,sizeof(pi));
  292. Utils::snprintf(cmdline,sizeof(cmdline),"CMD.EXE /c \"%s\"",batp);
  293. CreateProcessA(NULL,cmdline,NULL,NULL,FALSE,CREATE_NO_WINDOW|CREATE_NEW_PROCESS_GROUP,NULL,NULL,&si,&pi);
  294. }
  295. #endif // __WINDOWS__
  296. /* --------------------------------------------------------------- */
  297. return;
  298. } // else try to fetch from next IP address
  299. }
  300. }
  301. void threadMain()
  302. throw()
  303. {
  304. try {
  305. this->doUpdateCheck();
  306. } catch ( ... ) {}
  307. }
  308. };
  309. static BackgroundSoftwareUpdateChecker backgroundSoftwareUpdateChecker;
  310. #endif // ZT_AUTO_UPDATE
  311. static bool isBlacklistedLocalInterfaceForZeroTierTraffic(const char *ifn)
  312. {
  313. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  314. if ((ifn[0] == 'l')&&(ifn[1] == 'o')) return true; // loopback
  315. if ((ifn[0] == 'z')&&(ifn[1] == 't')) return true; // sanity check: zt#
  316. if ((ifn[0] == 't')&&(ifn[1] == 'u')&&(ifn[2] == 'n')) return true; // tun# is probably an OpenVPN tunnel or similar
  317. if ((ifn[0] == 't')&&(ifn[1] == 'a')&&(ifn[2] == 'p')) return true; // tap# is probably an OpenVPN tunnel or similar
  318. #endif
  319. #ifdef __APPLE__
  320. if ((ifn[0] == 'l')&&(ifn[1] == 'o')) return true; // loopback
  321. if ((ifn[0] == 'z')&&(ifn[1] == 't')) return true; // sanity check: zt#
  322. if ((ifn[0] == 't')&&(ifn[1] == 'u')&&(ifn[2] == 'n')) return true; // tun# is probably an OpenVPN tunnel or similar
  323. if ((ifn[0] == 't')&&(ifn[1] == 'a')&&(ifn[2] == 'p')) return true; // tap# is probably an OpenVPN tunnel or similar
  324. if ((ifn[0] == 'u')&&(ifn[1] == 't')&&(ifn[2] == 'u')&&(ifn[3] == 'n')) return true; // ... as is utun#
  325. #endif
  326. return false;
  327. }
  328. static std::string _trimString(const std::string &s)
  329. {
  330. unsigned long end = (unsigned long)s.length();
  331. while (end) {
  332. char c = s[end - 1];
  333. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  334. --end;
  335. else break;
  336. }
  337. unsigned long start = 0;
  338. while (start < end) {
  339. char c = s[start];
  340. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  341. ++start;
  342. else break;
  343. }
  344. return s.substr(start,end - start);
  345. }
  346. class OneServiceImpl;
  347. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
  348. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData);
  349. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize);
  350. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure);
  351. 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);
  352. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  353. #ifdef ZT_ENABLE_CLUSTER
  354. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len);
  355. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z);
  356. #endif
  357. 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);
  358. static int ShttpOnMessageBegin(http_parser *parser);
  359. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  360. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  361. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  362. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  363. static int ShttpOnHeadersComplete(http_parser *parser);
  364. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  365. static int ShttpOnMessageComplete(http_parser *parser);
  366. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  367. ShttpOnMessageBegin,
  368. ShttpOnUrl,
  369. ShttpOnStatus,
  370. ShttpOnHeaderField,
  371. ShttpOnValue,
  372. ShttpOnHeadersComplete,
  373. ShttpOnBody,
  374. ShttpOnMessageComplete
  375. };
  376. struct TcpConnection
  377. {
  378. enum {
  379. TCP_HTTP_INCOMING,
  380. TCP_HTTP_OUTGOING, // not currently used
  381. TCP_TUNNEL_OUTGOING // fale-SSL outgoing tunnel -- HTTP-related fields are not used
  382. } type;
  383. bool shouldKeepAlive;
  384. OneServiceImpl *parent;
  385. PhySocket *sock;
  386. InetAddress from;
  387. http_parser parser;
  388. unsigned long messageSize;
  389. uint64_t lastActivity;
  390. std::string currentHeaderField;
  391. std::string currentHeaderValue;
  392. std::string url;
  393. std::string status;
  394. std::map< std::string,std::string > headers;
  395. std::string body;
  396. std::string writeBuf;
  397. Mutex writeBuf_m;
  398. };
  399. // Use a bigger buffer on AMD64 since these are likely to be bigger and
  400. // servers. Otherwise use a smaller buffer. This makes no difference
  401. // except under very high load.
  402. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__))
  403. #define ZT_UDP_DESIRED_BUF_SIZE 1048576
  404. #else
  405. #define ZT_UDP_DESIRED_BUF_SIZE 131072
  406. #endif
  407. class OneServiceImpl : public OneService
  408. {
  409. public:
  410. OneServiceImpl(const char *hp,unsigned int port) :
  411. _homePath((hp) ? hp : ".")
  412. ,_tcpFallbackResolver(ZT_TCP_FALLBACK_RELAY)
  413. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  414. ,_controller((SqliteNetworkController *)0)
  415. #endif
  416. ,_phy(this,false,true)
  417. ,_node((Node *)0)
  418. ,_controlPlane((ControlPlane *)0)
  419. ,_lastDirectReceiveFromGlobal(0)
  420. ,_lastSendToGlobal(0)
  421. ,_lastRestart(0)
  422. ,_nextBackgroundTaskDeadline(0)
  423. ,_tcpFallbackTunnel((TcpConnection *)0)
  424. ,_termReason(ONE_STILL_RUNNING)
  425. ,_port(0)
  426. #ifdef ZT_USE_MINIUPNPC
  427. ,_v4UpnpUdpSocket((PhySocket *)0)
  428. ,_portMapper((PortMapper *)0)
  429. #endif
  430. #ifdef ZT_ENABLE_CLUSTER
  431. ,_clusterMessageSocket((PhySocket *)0)
  432. ,_clusterGeoIpService((ClusterGeoIpService *)0)
  433. ,_clusterDefinition((ClusterDefinition *)0)
  434. ,_clusterMemberId(0)
  435. #endif
  436. ,_run(true)
  437. {
  438. const int portTrials = (port == 0) ? 256 : 1; // if port is 0, pick random
  439. for(int k=0;k<portTrials;++k) {
  440. if (port == 0) {
  441. unsigned int randp = 0;
  442. Utils::getSecureRandom(&randp,sizeof(randp));
  443. port = 40000 + (randp % 25500);
  444. }
  445. _v4LocalAddress = InetAddress((uint32_t)0,port);
  446. _v4UdpSocket = _phy.udpBind((const struct sockaddr *)&_v4LocalAddress,reinterpret_cast<void *>(&_v4LocalAddress),ZT_UDP_DESIRED_BUF_SIZE);
  447. if (_v4UdpSocket) {
  448. struct sockaddr_in in4;
  449. memset(&in4,0,sizeof(in4));
  450. in4.sin_family = AF_INET;
  451. in4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001); // right now we just listen for TCP @localhost
  452. in4.sin_port = Utils::hton((uint16_t)port);
  453. _v4TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
  454. if (_v4TcpListenSocket) {
  455. _v6LocalAddress = InetAddress("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",16,port);
  456. _v6UdpSocket = _phy.udpBind((const struct sockaddr *)&_v6LocalAddress,reinterpret_cast<void *>(&_v6LocalAddress),ZT_UDP_DESIRED_BUF_SIZE);
  457. struct sockaddr_in6 in6;
  458. memset((void *)&in6,0,sizeof(in6));
  459. in6.sin6_family = AF_INET6;
  460. in6.sin6_port = in4.sin_port;
  461. in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
  462. _v6TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
  463. _port = port;
  464. break; // success!
  465. } else {
  466. _phy.close(_v4UdpSocket,false);
  467. }
  468. }
  469. port = 0;
  470. }
  471. if (_port == 0)
  472. throw std::runtime_error("cannot bind to port");
  473. char portstr[64];
  474. Utils::snprintf(portstr,sizeof(portstr),"%u",_port);
  475. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),std::string(portstr));
  476. }
  477. virtual ~OneServiceImpl()
  478. {
  479. _phy.close(_v4UdpSocket);
  480. _phy.close(_v6UdpSocket);
  481. _phy.close(_v4TcpListenSocket);
  482. _phy.close(_v6TcpListenSocket);
  483. #ifdef ZT_ENABLE_CLUSTER
  484. _phy.close(_clusterMessageSocket);
  485. #endif
  486. #ifdef ZT_USE_MINIUPNPC
  487. _phy.close(_v4UpnpUdpSocket);
  488. delete _portMapper;
  489. #endif
  490. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  491. delete _controller;
  492. #endif
  493. #ifdef ZT_ENABLE_CLUSTER
  494. delete _clusterGeoIpService;
  495. delete _clusterDefinition;
  496. #endif
  497. }
  498. virtual ReasonForTermination run()
  499. {
  500. try {
  501. std::string authToken;
  502. {
  503. std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  504. if (!OSUtils::readFile(authTokenPath.c_str(),authToken)) {
  505. unsigned char foo[24];
  506. Utils::getSecureRandom(foo,sizeof(foo));
  507. authToken = "";
  508. for(unsigned int i=0;i<sizeof(foo);++i)
  509. authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  510. if (!OSUtils::writeFile(authTokenPath.c_str(),authToken)) {
  511. Mutex::Lock _l(_termReason_m);
  512. _termReason = ONE_UNRECOVERABLE_ERROR;
  513. _fatalErrorMessage = "authtoken.secret could not be written";
  514. return _termReason;
  515. } else OSUtils::lockDownFile(authTokenPath.c_str(),false);
  516. }
  517. }
  518. authToken = _trimString(authToken);
  519. _node = new Node(
  520. OSUtils::now(),
  521. this,
  522. SnodeDataStoreGetFunction,
  523. SnodeDataStorePutFunction,
  524. SnodeWirePacketSendFunction,
  525. SnodeVirtualNetworkFrameFunction,
  526. SnodeVirtualNetworkConfigFunction,
  527. SnodeEventCallback);
  528. #ifdef ZT_USE_MINIUPNPC
  529. // Bind a secondary port for use with uPnP, since some NAT routers
  530. // (cough Ubiquity Edge cough) barf up a lung if you do both conventional
  531. // NAT-t and uPnP from behind the same port. I think this is a bug, but
  532. // everyone else's router bugs are our problem. :P
  533. for(int k=0;k<512;++k) {
  534. unsigned int mapperPort = 40000 + (((_port + 1) * (k + 1)) % 25500);
  535. char uniqueName[64];
  536. _v4UpnpLocalAddress = InetAddress(0,mapperPort);
  537. _v4UpnpUdpSocket = _phy.udpBind((const struct sockaddr *)&_v4UpnpLocalAddress,reinterpret_cast<void *>(&_v4UpnpLocalAddress),ZT_UDP_DESIRED_BUF_SIZE);
  538. if (_v4UpnpUdpSocket) {
  539. Utils::snprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.16llx",_node->address());
  540. _portMapper = new PortMapper(mapperPort,uniqueName);
  541. break;
  542. }
  543. }
  544. #endif
  545. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  546. _controller = new SqliteNetworkController(_node,(_homePath + ZT_PATH_SEPARATOR_S + ZT_CONTROLLER_DB_PATH).c_str(),(_homePath + ZT_PATH_SEPARATOR_S + "circuitTestResults.d").c_str());
  547. _node->setNetconfMaster((void *)_controller);
  548. #endif
  549. #ifdef ZT_ENABLE_CLUSTER
  550. if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str())) {
  551. _clusterDefinition = new ClusterDefinition(_node->address(),(_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str());
  552. if (_clusterDefinition->size() > 0) {
  553. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  554. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  555. PhySocket *cs = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&(m->clusterEndpoint)));
  556. if (cs) {
  557. if (_clusterMessageSocket) {
  558. _phy.close(_clusterMessageSocket,false);
  559. _phy.close(cs,false);
  560. Mutex::Lock _l(_termReason_m);
  561. _termReason = ONE_UNRECOVERABLE_ERROR;
  562. _fatalErrorMessage = "Cluster: can't determine my cluster member ID: able to bind more than one cluster message socket IP/port!";
  563. return _termReason;
  564. }
  565. _clusterMessageSocket = cs;
  566. _clusterMemberId = m->id;
  567. }
  568. }
  569. if (!_clusterMessageSocket) {
  570. Mutex::Lock _l(_termReason_m);
  571. _termReason = ONE_UNRECOVERABLE_ERROR;
  572. _fatalErrorMessage = "Cluster: can't determine my cluster member ID: unable to bind to any cluster message socket IP/port.";
  573. return _termReason;
  574. }
  575. if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S + "cluster-geo.exe").c_str()))
  576. _clusterGeoIpService = new ClusterGeoIpService((_homePath + ZT_PATH_SEPARATOR_S + "cluster-geo.exe").c_str());
  577. const ClusterDefinition::MemberDefinition &me = (*_clusterDefinition)[_clusterMemberId];
  578. InetAddress endpoints[255];
  579. unsigned int numEndpoints = 0;
  580. for(std::vector<InetAddress>::const_iterator i(me.zeroTierEndpoints.begin());i!=me.zeroTierEndpoints.end();++i)
  581. endpoints[numEndpoints++] = *i;
  582. if (_node->clusterInit(
  583. _clusterMemberId,
  584. reinterpret_cast<const struct sockaddr_storage *>(endpoints),
  585. numEndpoints,
  586. me.x,
  587. me.y,
  588. me.z,
  589. &SclusterSendFunction,
  590. this,
  591. (_clusterGeoIpService) ? &SclusterGeoIpFunction : 0,
  592. this) == ZT_RESULT_OK) {
  593. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  594. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  595. if (m->id != _clusterMemberId)
  596. _node->clusterAddMember(m->id);
  597. }
  598. }
  599. } else {
  600. delete _clusterDefinition;
  601. _clusterDefinition = (ClusterDefinition *)0;
  602. }
  603. }
  604. #endif
  605. _controlPlane = new ControlPlane(this,_node,(_homePath + ZT_PATH_SEPARATOR_S + "ui").c_str());
  606. _controlPlane->addAuthToken(authToken.c_str());
  607. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  608. _controlPlane->setController(_controller);
  609. #endif
  610. { // Remember networks from previous session
  611. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S + "networks.d").c_str()));
  612. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  613. std::size_t dot = f->find_last_of('.');
  614. if ((dot == 16)&&(f->substr(16) == ".conf"))
  615. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()));
  616. }
  617. }
  618. // Start two background threads to handle expensive ops out of line
  619. Thread::start(_node);
  620. Thread::start(_node);
  621. _nextBackgroundTaskDeadline = 0;
  622. uint64_t clockShouldBe = OSUtils::now();
  623. _lastRestart = clockShouldBe;
  624. uint64_t lastTapMulticastGroupCheck = 0;
  625. uint64_t lastTcpFallbackResolve = 0;
  626. 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
  627. #ifdef ZT_AUTO_UPDATE
  628. uint64_t lastSoftwareUpdateCheck = 0;
  629. #endif // ZT_AUTO_UPDATE
  630. for(;;) {
  631. _run_m.lock();
  632. if (!_run) {
  633. _run_m.unlock();
  634. _termReason_m.lock();
  635. _termReason = ONE_NORMAL_TERMINATION;
  636. _termReason_m.unlock();
  637. break;
  638. } else _run_m.unlock();
  639. uint64_t now = OSUtils::now();
  640. uint64_t dl = _nextBackgroundTaskDeadline;
  641. if (dl <= now) {
  642. _node->processBackgroundTasks(now,&_nextBackgroundTaskDeadline);
  643. dl = _nextBackgroundTaskDeadline;
  644. }
  645. // Attempt to detect sleep/wake events by detecting delay overruns
  646. if ((now > clockShouldBe)&&((now - clockShouldBe) > 2000))
  647. _lastRestart = now;
  648. #ifdef ZT_AUTO_UPDATE
  649. if ((now - lastSoftwareUpdateCheck) >= ZT_AUTO_UPDATE_CHECK_PERIOD) {
  650. lastSoftwareUpdateCheck = now;
  651. Thread::start(&backgroundSoftwareUpdateChecker);
  652. }
  653. #endif // ZT_AUTO_UPDATE
  654. if ((now - lastTcpFallbackResolve) >= ZT_TCP_FALLBACK_RERESOLVE_DELAY) {
  655. lastTcpFallbackResolve = now;
  656. _tcpFallbackResolver.resolveNow();
  657. }
  658. if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2)))
  659. _phy.close(_tcpFallbackTunnel->sock);
  660. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  661. lastTapMulticastGroupCheck = now;
  662. Mutex::Lock _l(_taps_m);
  663. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t) {
  664. std::vector<MulticastGroup> added,removed;
  665. t->second->scanMulticastGroups(added,removed);
  666. for(std::vector<MulticastGroup>::iterator m(added.begin());m!=added.end();++m)
  667. _node->multicastSubscribe(t->first,m->mac().toInt(),m->adi());
  668. for(std::vector<MulticastGroup>::iterator m(removed.begin());m!=removed.end();++m)
  669. _node->multicastUnsubscribe(t->first,m->mac().toInt(),m->adi());
  670. }
  671. }
  672. if ((now - lastLocalInterfaceAddressCheck) >= ZT_LOCAL_INTERFACE_CHECK_INTERVAL) {
  673. lastLocalInterfaceAddressCheck = now;
  674. #ifdef __UNIX_LIKE__
  675. std::vector<std::string> ztDevices;
  676. {
  677. Mutex::Lock _l(_taps_m);
  678. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t)
  679. ztDevices.push_back(t->second->deviceName());
  680. }
  681. _node->clearLocalInterfaceAddresses();
  682. #ifdef ZT_USE_MINIUPNPC
  683. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  684. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  685. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  686. #endif
  687. struct ifaddrs *ifatbl = (struct ifaddrs *)0;
  688. if ((getifaddrs(&ifatbl) == 0)&&(ifatbl)) {
  689. struct ifaddrs *ifa = ifatbl;
  690. while (ifa) {
  691. if ((ifa->ifa_name)&&(ifa->ifa_addr)&&(!isBlacklistedLocalInterfaceForZeroTierTraffic(ifa->ifa_name))) {
  692. bool isZT = false;
  693. for(std::vector<std::string>::const_iterator d(ztDevices.begin());d!=ztDevices.end();++d) {
  694. if (*d == ifa->ifa_name) {
  695. isZT = true;
  696. break;
  697. }
  698. }
  699. if (!isZT) {
  700. InetAddress ip(ifa->ifa_addr);
  701. ip.setPort(_port);
  702. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip));
  703. }
  704. }
  705. ifa = ifa->ifa_next;
  706. }
  707. freeifaddrs(ifatbl);
  708. }
  709. #endif // __UNIX_LIKE__
  710. #ifdef __WINDOWS__
  711. std::vector<NET_LUID> ztDevices;
  712. {
  713. Mutex::Lock _l(_taps_m);
  714. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t)
  715. ztDevices.push_back(t->second->luid());
  716. }
  717. char aabuf[16384];
  718. ULONG aalen = sizeof(aabuf);
  719. if (GetAdaptersAddresses(AF_UNSPEC,GAA_FLAG_SKIP_ANYCAST|GAA_FLAG_SKIP_MULTICAST|GAA_FLAG_SKIP_DNS_SERVER,(void *)0,reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf),&aalen) == NO_ERROR) {
  720. PIP_ADAPTER_ADDRESSES a = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf);
  721. while (a) {
  722. bool isZT = false;
  723. for(std::vector<NET_LUID>::const_iterator d(ztDevices.begin());d!=ztDevices.end();++d) {
  724. if (a->Luid.Value == d->Value) {
  725. isZT = true;
  726. break;
  727. }
  728. }
  729. if (!isZT) {
  730. PIP_ADAPTER_UNICAST_ADDRESS ua = a->FirstUnicastAddress;
  731. while (ua) {
  732. InetAddress ip(ua->Address.lpSockaddr);
  733. ip.setPort(_port);
  734. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip));
  735. ua = ua->Next;
  736. }
  737. }
  738. a = a->Next;
  739. }
  740. }
  741. #endif // __WINDOWS__
  742. }
  743. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  744. clockShouldBe = now + (uint64_t)delay;
  745. _phy.poll(delay);
  746. }
  747. } catch (std::exception &exc) {
  748. Mutex::Lock _l(_termReason_m);
  749. _termReason = ONE_UNRECOVERABLE_ERROR;
  750. _fatalErrorMessage = exc.what();
  751. } catch ( ... ) {
  752. Mutex::Lock _l(_termReason_m);
  753. _termReason = ONE_UNRECOVERABLE_ERROR;
  754. _fatalErrorMessage = "unexpected exception in main thread";
  755. }
  756. try {
  757. while (!_tcpConnections.empty())
  758. _phy.close((*_tcpConnections.begin())->sock);
  759. } catch ( ... ) {}
  760. {
  761. Mutex::Lock _l(_taps_m);
  762. for(std::map< uint64_t,EthernetTap * >::iterator t(_taps.begin());t!=_taps.end();++t)
  763. delete t->second;
  764. _taps.clear();
  765. }
  766. delete _controlPlane;
  767. _controlPlane = (ControlPlane *)0;
  768. delete _node;
  769. _node = (Node *)0;
  770. return _termReason;
  771. }
  772. virtual ReasonForTermination reasonForTermination() const
  773. {
  774. Mutex::Lock _l(_termReason_m);
  775. return _termReason;
  776. }
  777. virtual std::string fatalErrorMessage() const
  778. {
  779. Mutex::Lock _l(_termReason_m);
  780. return _fatalErrorMessage;
  781. }
  782. virtual std::string portDeviceName(uint64_t nwid) const
  783. {
  784. Mutex::Lock _l(_taps_m);
  785. std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.find(nwid));
  786. if (t != _taps.end())
  787. return t->second->deviceName();
  788. return std::string();
  789. }
  790. virtual bool tcpFallbackActive() const
  791. {
  792. return (_tcpFallbackTunnel != (TcpConnection *)0);
  793. }
  794. virtual void terminate()
  795. {
  796. _run_m.lock();
  797. _run = false;
  798. _run_m.unlock();
  799. _phy.whack();
  800. }
  801. // Begin private implementation methods
  802. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
  803. {
  804. #ifdef ZT_ENABLE_CLUSTER
  805. if (sock == _clusterMessageSocket) {
  806. _lastDirectReceiveFromGlobal = OSUtils::now();
  807. _node->clusterHandleIncomingMessage(data,len);
  808. return;
  809. }
  810. #endif
  811. #ifdef ZT_BREAK_UDP
  812. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  813. return;
  814. #endif
  815. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  816. _lastDirectReceiveFromGlobal = OSUtils::now();
  817. ZT_ResultCode rc = _node->processWirePacket(
  818. OSUtils::now(),
  819. reinterpret_cast<const struct sockaddr_storage *>(*uptr),
  820. (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
  821. data,
  822. len,
  823. &_nextBackgroundTaskDeadline);
  824. if (ZT_ResultCode_isFatal(rc)) {
  825. char tmp[256];
  826. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  827. Mutex::Lock _l(_termReason_m);
  828. _termReason = ONE_UNRECOVERABLE_ERROR;
  829. _fatalErrorMessage = tmp;
  830. this->terminate();
  831. }
  832. }
  833. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  834. {
  835. if (!success)
  836. return;
  837. // Outgoing TCP connections are always TCP fallback tunnel connections.
  838. TcpConnection *tc = new TcpConnection();
  839. _tcpConnections.insert(tc);
  840. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  841. tc->shouldKeepAlive = true;
  842. tc->parent = this;
  843. tc->sock = sock;
  844. // from and parser are not used
  845. tc->messageSize = 0; // unused
  846. tc->lastActivity = OSUtils::now();
  847. // HTTP stuff is not used
  848. tc->writeBuf = "";
  849. *uptr = (void *)tc;
  850. // Send "hello" message
  851. tc->writeBuf.push_back((char)0x17);
  852. tc->writeBuf.push_back((char)0x03);
  853. tc->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  854. tc->writeBuf.push_back((char)0x00);
  855. tc->writeBuf.push_back((char)0x04); // mlen == 4
  856. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MAJOR);
  857. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MINOR);
  858. tc->writeBuf.push_back((char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff));
  859. tc->writeBuf.push_back((char)(ZEROTIER_ONE_VERSION_REVISION & 0xff));
  860. _phy.setNotifyWritable(sock,true);
  861. _tcpFallbackTunnel = tc;
  862. }
  863. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  864. {
  865. // Incoming TCP connections are HTTP JSON API requests.
  866. TcpConnection *tc = new TcpConnection();
  867. _tcpConnections.insert(tc);
  868. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  869. tc->shouldKeepAlive = true;
  870. tc->parent = this;
  871. tc->sock = sockN;
  872. tc->from = from;
  873. http_parser_init(&(tc->parser),HTTP_REQUEST);
  874. tc->parser.data = (void *)tc;
  875. tc->messageSize = 0;
  876. tc->lastActivity = OSUtils::now();
  877. tc->currentHeaderField = "";
  878. tc->currentHeaderValue = "";
  879. tc->url = "";
  880. tc->status = "";
  881. tc->headers.clear();
  882. tc->body = "";
  883. tc->writeBuf = "";
  884. *uptrN = (void *)tc;
  885. }
  886. inline void phyOnTcpClose(PhySocket *sock,void **uptr)
  887. {
  888. TcpConnection *tc = (TcpConnection *)*uptr;
  889. if (tc) {
  890. if (tc == _tcpFallbackTunnel)
  891. _tcpFallbackTunnel = (TcpConnection *)0;
  892. _tcpConnections.erase(tc);
  893. delete tc;
  894. }
  895. }
  896. inline void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  897. {
  898. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  899. switch(tc->type) {
  900. case TcpConnection::TCP_HTTP_INCOMING:
  901. case TcpConnection::TCP_HTTP_OUTGOING:
  902. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  903. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK)) {
  904. _phy.close(sock);
  905. return;
  906. }
  907. break;
  908. case TcpConnection::TCP_TUNNEL_OUTGOING:
  909. tc->body.append((const char *)data,len);
  910. while (tc->body.length() >= 5) {
  911. const char *data = tc->body.data();
  912. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  913. if (tc->body.length() >= (mlen + 5)) {
  914. InetAddress from;
  915. unsigned long plen = mlen; // payload length, modified if there's an IP header
  916. data += 5; // skip forward past pseudo-TLS junk and mlen
  917. if (plen == 4) {
  918. // Hello message, which isn't sent by proxy and would be ignored by client
  919. } else if (plen) {
  920. // Messages should contain IPv4 or IPv6 source IP address data
  921. switch(data[0]) {
  922. case 4: // IPv4
  923. if (plen >= 7) {
  924. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  925. data += 7; // type + 4 byte IP + 2 byte port
  926. plen -= 7;
  927. } else {
  928. _phy.close(sock);
  929. return;
  930. }
  931. break;
  932. case 6: // IPv6
  933. if (plen >= 19) {
  934. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  935. data += 19; // type + 16 byte IP + 2 byte port
  936. plen -= 19;
  937. } else {
  938. _phy.close(sock);
  939. return;
  940. }
  941. break;
  942. case 0: // none/omitted
  943. ++data;
  944. --plen;
  945. break;
  946. default: // invalid address type
  947. _phy.close(sock);
  948. return;
  949. }
  950. if (from) {
  951. ZT_ResultCode rc = _node->processWirePacket(
  952. OSUtils::now(),
  953. &ZT_SOCKADDR_NULL,
  954. reinterpret_cast<struct sockaddr_storage *>(&from),
  955. data,
  956. plen,
  957. &_nextBackgroundTaskDeadline);
  958. if (ZT_ResultCode_isFatal(rc)) {
  959. char tmp[256];
  960. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  961. Mutex::Lock _l(_termReason_m);
  962. _termReason = ONE_UNRECOVERABLE_ERROR;
  963. _fatalErrorMessage = tmp;
  964. this->terminate();
  965. _phy.close(sock);
  966. return;
  967. }
  968. }
  969. }
  970. if (tc->body.length() > (mlen + 5))
  971. tc->body = tc->body.substr(mlen + 5);
  972. else tc->body = "";
  973. } else break;
  974. }
  975. break;
  976. }
  977. }
  978. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  979. {
  980. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  981. Mutex::Lock _l(tc->writeBuf_m);
  982. if (tc->writeBuf.length() > 0) {
  983. long sent = (long)_phy.streamSend(sock,tc->writeBuf.data(),(unsigned long)tc->writeBuf.length(),true);
  984. if (sent > 0) {
  985. tc->lastActivity = OSUtils::now();
  986. if ((unsigned long)sent >= (unsigned long)tc->writeBuf.length()) {
  987. tc->writeBuf = "";
  988. _phy.setNotifyWritable(sock,false);
  989. if (!tc->shouldKeepAlive)
  990. _phy.close(sock); // will call close handler to delete from _tcpConnections
  991. } else {
  992. tc->writeBuf = tc->writeBuf.substr(sent);
  993. }
  994. }
  995. } else {
  996. _phy.setNotifyWritable(sock,false);
  997. }
  998. }
  999. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  1000. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  1001. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  1002. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  1003. inline void phyOnUnixWritable(PhySocket *sock,void **uptr) {}
  1004. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  1005. {
  1006. Mutex::Lock _l(_taps_m);
  1007. std::map< uint64_t,EthernetTap * >::iterator t(_taps.find(nwid));
  1008. switch(op) {
  1009. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  1010. if (t == _taps.end()) {
  1011. try {
  1012. char friendlyName[1024];
  1013. Utils::snprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  1014. t = _taps.insert(std::pair< uint64_t,EthernetTap *>(nwid,new EthernetTap(
  1015. _homePath.c_str(),
  1016. MAC(nwc->mac),
  1017. nwc->mtu,
  1018. (unsigned int)ZT_IF_METRIC,
  1019. nwid,
  1020. friendlyName,
  1021. StapFrameHandler,
  1022. (void *)this))).first;
  1023. } catch (std::exception &exc) {
  1024. #ifdef __WINDOWS__
  1025. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1026. if (tapFailLog) {
  1027. fprintf(tapFailLog,"%.16llx: %s"ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1028. fclose(tapFailLog);
  1029. }
  1030. #else
  1031. fprintf(stderr,"ERROR: unable to configure virtual network port: %s"ZT_EOL_S,exc.what());
  1032. #endif
  1033. return -999;
  1034. } catch ( ... ) {
  1035. return -999; // tap init failed
  1036. }
  1037. }
  1038. // fall through...
  1039. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1040. if (t != _taps.end()) {
  1041. t->second->setEnabled(nwc->enabled != 0);
  1042. std::vector<InetAddress> &assignedIps = _tapAssignedIps[nwid];
  1043. std::vector<InetAddress> newAssignedIps;
  1044. for(unsigned int i=0;i<nwc->assignedAddressCount;++i)
  1045. newAssignedIps.push_back(InetAddress(nwc->assignedAddresses[i]));
  1046. std::sort(newAssignedIps.begin(),newAssignedIps.end());
  1047. newAssignedIps.erase(std::unique(newAssignedIps.begin(),newAssignedIps.end()),newAssignedIps.end());
  1048. for(std::vector<InetAddress>::iterator ip(newAssignedIps.begin());ip!=newAssignedIps.end();++ip) {
  1049. if (!std::binary_search(assignedIps.begin(),assignedIps.end(),*ip))
  1050. if (!t->second->addIp(*ip))
  1051. fprintf(stderr,"ERROR: unable to add ip address %s"ZT_EOL_S, ip->toString().c_str());
  1052. }
  1053. for(std::vector<InetAddress>::iterator ip(assignedIps.begin());ip!=assignedIps.end();++ip) {
  1054. if (!std::binary_search(newAssignedIps.begin(),newAssignedIps.end(),*ip))
  1055. if (!t->second->removeIp(*ip))
  1056. fprintf(stderr,"ERROR: unable to remove ip address %s"ZT_EOL_S, ip->toString().c_str());
  1057. }
  1058. assignedIps.swap(newAssignedIps);
  1059. } else {
  1060. return -999; // tap init failed
  1061. }
  1062. break;
  1063. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1064. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1065. if (t != _taps.end()) {
  1066. #ifdef __WINDOWS__
  1067. std::string winInstanceId(t->second->instanceId());
  1068. #endif
  1069. delete t->second;
  1070. _taps.erase(t);
  1071. _tapAssignedIps.erase(nwid);
  1072. #ifdef __WINDOWS__
  1073. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1074. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1075. #endif
  1076. }
  1077. break;
  1078. }
  1079. return 0;
  1080. }
  1081. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1082. {
  1083. switch(event) {
  1084. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  1085. Mutex::Lock _l(_termReason_m);
  1086. _termReason = ONE_IDENTITY_COLLISION;
  1087. _fatalErrorMessage = "identity/address collision";
  1088. this->terminate();
  1089. } break;
  1090. case ZT_EVENT_TRACE: {
  1091. if (metaData) {
  1092. ::fprintf(stderr,"%s"ZT_EOL_S,(const char *)metaData);
  1093. ::fflush(stderr);
  1094. }
  1095. } break;
  1096. default:
  1097. break;
  1098. }
  1099. }
  1100. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1101. {
  1102. std::string p(_dataStorePrepPath(name));
  1103. if (!p.length())
  1104. return -2;
  1105. FILE *f = fopen(p.c_str(),"rb");
  1106. if (!f)
  1107. return -1;
  1108. if (fseek(f,0,SEEK_END) != 0) {
  1109. fclose(f);
  1110. return -2;
  1111. }
  1112. long ts = ftell(f);
  1113. if (ts < 0) {
  1114. fclose(f);
  1115. return -2;
  1116. }
  1117. *totalSize = (unsigned long)ts;
  1118. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  1119. fclose(f);
  1120. return -2;
  1121. }
  1122. long n = (long)fread(buf,1,bufSize,f);
  1123. fclose(f);
  1124. return n;
  1125. }
  1126. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  1127. {
  1128. std::string p(_dataStorePrepPath(name));
  1129. if (!p.length())
  1130. return -2;
  1131. if (!data) {
  1132. OSUtils::rm(p.c_str());
  1133. return 0;
  1134. }
  1135. FILE *f = fopen(p.c_str(),"wb");
  1136. if (!f)
  1137. return -1;
  1138. if (fwrite(data,len,1,f) == 1) {
  1139. fclose(f);
  1140. if (secure)
  1141. OSUtils::lockDownFile(p.c_str(),false);
  1142. return 0;
  1143. } else {
  1144. fclose(f);
  1145. OSUtils::rm(p.c_str());
  1146. return -1;
  1147. }
  1148. }
  1149. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1150. {
  1151. #ifdef ZT_USE_MINIUPNPC
  1152. if ((localAddr->ss_family == AF_INET)&&(reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port == reinterpret_cast<const struct sockaddr_in *>(&_v4UpnpLocalAddress)->sin_port)) {
  1153. #ifdef ZT_BREAK_UDP
  1154. if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
  1155. #endif
  1156. if (addr->ss_family == AF_INET) {
  1157. if (ttl)
  1158. _phy.setIp4UdpTtl(_v4UpnpUdpSocket,ttl);
  1159. const int result = ((_phy.udpSend(_v4UpnpUdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
  1160. if (ttl)
  1161. _phy.setIp4UdpTtl(_v4UpnpUdpSocket,255);
  1162. return result;
  1163. } else {
  1164. return -1;
  1165. }
  1166. #ifdef ZT_BREAK_UDP
  1167. }
  1168. #endif
  1169. }
  1170. #endif // ZT_USE_MINIUPNPC
  1171. int result = -1;
  1172. switch(addr->ss_family) {
  1173. case AF_INET:
  1174. #ifdef ZT_BREAK_UDP
  1175. if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
  1176. #endif
  1177. if (_v4UdpSocket) {
  1178. if (ttl)
  1179. _phy.setIp4UdpTtl(_v4UdpSocket,ttl);
  1180. result = ((_phy.udpSend(_v4UdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
  1181. if (ttl)
  1182. _phy.setIp4UdpTtl(_v4UdpSocket,255);
  1183. }
  1184. #ifdef ZT_BREAK_UDP
  1185. }
  1186. #endif
  1187. #ifdef ZT_TCP_FALLBACK_RELAY
  1188. // TCP fallback tunnel support
  1189. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  1190. uint64_t now = OSUtils::now();
  1191. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  1192. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  1193. // valid direct traffic we'll stop using it and close the socket after a while.
  1194. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  1195. if (_tcpFallbackTunnel) {
  1196. Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
  1197. if (!_tcpFallbackTunnel->writeBuf.length())
  1198. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  1199. unsigned long mlen = len + 7;
  1200. _tcpFallbackTunnel->writeBuf.push_back((char)0x17);
  1201. _tcpFallbackTunnel->writeBuf.push_back((char)0x03);
  1202. _tcpFallbackTunnel->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1203. _tcpFallbackTunnel->writeBuf.push_back((char)((mlen >> 8) & 0xff));
  1204. _tcpFallbackTunnel->writeBuf.push_back((char)(mlen & 0xff));
  1205. _tcpFallbackTunnel->writeBuf.push_back((char)4); // IPv4
  1206. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  1207. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  1208. _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
  1209. result = 0;
  1210. } else if (((now - _lastSendToGlobal) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobal) > (ZT_PING_CHECK_INVERVAL / 2))) {
  1211. std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
  1212. if (tunnelIps.empty()) {
  1213. if (!_tcpFallbackResolver.running())
  1214. _tcpFallbackResolver.resolveNow();
  1215. } else {
  1216. bool connected = false;
  1217. InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
  1218. addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
  1219. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
  1220. }
  1221. }
  1222. }
  1223. _lastSendToGlobal = now;
  1224. }
  1225. #endif // ZT_TCP_FALLBACK_RELAY
  1226. break;
  1227. case AF_INET6:
  1228. #ifdef ZT_BREAK_UDP
  1229. if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
  1230. #endif
  1231. if (_v6UdpSocket)
  1232. result = ((_phy.udpSend(_v6UdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
  1233. #ifdef ZT_BREAK_UDP
  1234. }
  1235. #endif
  1236. break;
  1237. default:
  1238. return -1;
  1239. }
  1240. return result;
  1241. }
  1242. inline void nodeVirtualNetworkFrameFunction(uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1243. {
  1244. Mutex::Lock _l(_taps_m);
  1245. std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.find(nwid));
  1246. if (t != _taps.end())
  1247. t->second->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1248. }
  1249. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1250. {
  1251. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1252. }
  1253. inline void onHttpRequestToServer(TcpConnection *tc)
  1254. {
  1255. char tmpn[256];
  1256. std::string data;
  1257. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1258. unsigned int scode = 404;
  1259. try {
  1260. if (_controlPlane)
  1261. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  1262. else scode = 500;
  1263. } catch ( ... ) {
  1264. scode = 500;
  1265. }
  1266. const char *scodestr;
  1267. switch(scode) {
  1268. case 200: scodestr = "OK"; break;
  1269. case 400: scodestr = "Bad Request"; break;
  1270. case 401: scodestr = "Unauthorized"; break;
  1271. case 403: scodestr = "Forbidden"; break;
  1272. case 404: scodestr = "Not Found"; break;
  1273. case 500: scodestr = "Internal Server Error"; break;
  1274. case 501: scodestr = "Not Implemented"; break;
  1275. case 503: scodestr = "Service Unavailable"; break;
  1276. default: scodestr = "Error"; break;
  1277. }
  1278. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  1279. {
  1280. Mutex::Lock _l(tc->writeBuf_m);
  1281. tc->writeBuf.assign(tmpn);
  1282. tc->writeBuf.append("Content-Type: ");
  1283. tc->writeBuf.append(contentType);
  1284. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  1285. tc->writeBuf.append(tmpn);
  1286. if (!tc->shouldKeepAlive)
  1287. tc->writeBuf.append("Connection: close\r\n");
  1288. tc->writeBuf.append("\r\n");
  1289. if (tc->parser.method != HTTP_HEAD)
  1290. tc->writeBuf.append(data);
  1291. }
  1292. _phy.setNotifyWritable(tc->sock,true);
  1293. }
  1294. inline void onHttpResponseFromClient(TcpConnection *tc)
  1295. {
  1296. if (!tc->shouldKeepAlive)
  1297. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConnections
  1298. }
  1299. std::string _dataStorePrepPath(const char *name) const
  1300. {
  1301. std::string p(_homePath);
  1302. p.push_back(ZT_PATH_SEPARATOR);
  1303. char lastc = (char)0;
  1304. for(const char *n=name;(*n);++n) {
  1305. if ((*n == '.')&&(lastc == '.'))
  1306. return std::string(); // don't allow ../../ stuff as a precaution
  1307. if (*n == '/') {
  1308. OSUtils::mkdir(p.c_str());
  1309. p.push_back(ZT_PATH_SEPARATOR);
  1310. } else p.push_back(*n);
  1311. lastc = *n;
  1312. }
  1313. return p;
  1314. }
  1315. const std::string _homePath;
  1316. BackgroundResolver _tcpFallbackResolver;
  1317. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  1318. SqliteNetworkController *_controller;
  1319. #endif
  1320. Phy<OneServiceImpl *> _phy;
  1321. Node *_node;
  1322. InetAddress _v4LocalAddress,_v6LocalAddress;
  1323. PhySocket *_v4UdpSocket;
  1324. PhySocket *_v6UdpSocket;
  1325. PhySocket *_v4TcpListenSocket;
  1326. PhySocket *_v6TcpListenSocket;
  1327. ControlPlane *_controlPlane;
  1328. uint64_t _lastDirectReceiveFromGlobal;
  1329. uint64_t _lastSendToGlobal;
  1330. uint64_t _lastRestart;
  1331. volatile uint64_t _nextBackgroundTaskDeadline;
  1332. std::map< uint64_t,EthernetTap * > _taps;
  1333. std::map< uint64_t,std::vector<InetAddress> > _tapAssignedIps; // ZeroTier assigned IPs, not user or dhcp assigned
  1334. Mutex _taps_m;
  1335. std::set< TcpConnection * > _tcpConnections; // no mutex for this since it's done in the main loop thread only
  1336. TcpConnection *_tcpFallbackTunnel;
  1337. ReasonForTermination _termReason;
  1338. std::string _fatalErrorMessage;
  1339. Mutex _termReason_m;
  1340. unsigned int _port;
  1341. #ifdef ZT_USE_MINIUPNPC
  1342. InetAddress _v4UpnpLocalAddress;
  1343. PhySocket *_v4UpnpUdpSocket;
  1344. PortMapper *_portMapper;
  1345. #endif
  1346. #ifdef ZT_ENABLE_CLUSTER
  1347. PhySocket *_clusterMessageSocket;
  1348. ClusterGeoIpService *_clusterGeoIpService;
  1349. ClusterDefinition *_clusterDefinition;
  1350. unsigned int _clusterMemberId;
  1351. #endif
  1352. bool _run;
  1353. Mutex _run_m;
  1354. };
  1355. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  1356. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,op,nwconf); }
  1357. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData)
  1358. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1359. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1360. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  1361. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  1362. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  1363. 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)
  1364. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localAddr,addr,data,len,ttl); }
  1365. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1366. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,sourceMac,destMac,etherType,vlanId,data,len); }
  1367. #ifdef ZT_ENABLE_CLUSTER
  1368. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len)
  1369. {
  1370. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1371. const ClusterDefinition::MemberDefinition &md = (*(impl->_clusterDefinition))[toMemberId];
  1372. if (md.clusterEndpoint)
  1373. impl->_phy.udpSend(impl->_clusterMessageSocket,reinterpret_cast<const struct sockaddr *>(&(md.clusterEndpoint)),data,len);
  1374. }
  1375. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z)
  1376. {
  1377. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1378. return (int)(impl->_clusterGeoIpService->locate(*(reinterpret_cast<const InetAddress *>(addr)),*x,*y,*z));
  1379. }
  1380. #endif
  1381. 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)
  1382. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1383. static int ShttpOnMessageBegin(http_parser *parser)
  1384. {
  1385. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1386. tc->currentHeaderField = "";
  1387. tc->currentHeaderValue = "";
  1388. tc->messageSize = 0;
  1389. tc->url = "";
  1390. tc->status = "";
  1391. tc->headers.clear();
  1392. tc->body = "";
  1393. return 0;
  1394. }
  1395. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  1396. {
  1397. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1398. tc->messageSize += (unsigned long)length;
  1399. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1400. return -1;
  1401. tc->url.append(ptr,length);
  1402. return 0;
  1403. }
  1404. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1405. {
  1406. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1407. tc->messageSize += (unsigned long)length;
  1408. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1409. return -1;
  1410. tc->status.append(ptr,length);
  1411. return 0;
  1412. }
  1413. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1414. {
  1415. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1416. tc->messageSize += (unsigned long)length;
  1417. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1418. return -1;
  1419. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1420. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1421. tc->currentHeaderField = "";
  1422. tc->currentHeaderValue = "";
  1423. }
  1424. for(size_t i=0;i<length;++i)
  1425. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1426. return 0;
  1427. }
  1428. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1429. {
  1430. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1431. tc->messageSize += (unsigned long)length;
  1432. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1433. return -1;
  1434. tc->currentHeaderValue.append(ptr,length);
  1435. return 0;
  1436. }
  1437. static int ShttpOnHeadersComplete(http_parser *parser)
  1438. {
  1439. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1440. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  1441. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1442. return 0;
  1443. }
  1444. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  1445. {
  1446. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1447. tc->messageSize += (unsigned long)length;
  1448. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1449. return -1;
  1450. tc->body.append(ptr,length);
  1451. return 0;
  1452. }
  1453. static int ShttpOnMessageComplete(http_parser *parser)
  1454. {
  1455. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1456. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  1457. tc->lastActivity = OSUtils::now();
  1458. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  1459. tc->parent->onHttpRequestToServer(tc);
  1460. } else {
  1461. tc->parent->onHttpResponseFromClient(tc);
  1462. }
  1463. return 0;
  1464. }
  1465. } // anonymous namespace
  1466. std::string OneService::platformDefaultHomePath()
  1467. {
  1468. #ifdef __UNIX_LIKE__
  1469. #ifdef __APPLE__
  1470. // /Library/... on Apple
  1471. return std::string("/Library/Application Support/ZeroTier/One");
  1472. #else
  1473. #ifdef __BSD__
  1474. // BSD likes /var/db instead of /var/lib
  1475. return std::string("/var/db/zerotier-one");
  1476. #else
  1477. // Use /var/lib for Linux and other *nix
  1478. return std::string("/var/lib/zerotier-one");
  1479. #endif
  1480. #endif
  1481. #else // not __UNIX_LIKE__
  1482. #ifdef __WINDOWS__
  1483. // Look up app data folder on Windows, e.g. C:\ProgramData\...
  1484. char buf[16384];
  1485. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_COMMON_APPDATA,NULL,0,buf)))
  1486. return (std::string(buf) + "\\ZeroTier\\One");
  1487. else return std::string("C:\\ZeroTier\\One");
  1488. #else
  1489. return std::string(); // UNKNOWN PLATFORM
  1490. #endif
  1491. #endif // __UNIX_LIKE__ or not...
  1492. }
  1493. std::string OneService::autoUpdateUrl()
  1494. {
  1495. #ifdef ZT_AUTO_UPDATE
  1496. /*
  1497. #if defined(__LINUX__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1498. if (sizeof(void *) == 8)
  1499. return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x64-LATEST.nfo";
  1500. else return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x86-LATEST.nfo";
  1501. #endif
  1502. */
  1503. #if defined(__APPLE__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1504. return "http://download.zerotier.com/update/mac_intel/";
  1505. #endif
  1506. #ifdef __WINDOWS__
  1507. return "http://download.zerotier.com/update/win_intel/";
  1508. #endif
  1509. #endif // ZT_AUTO_UPDATE
  1510. return std::string();
  1511. }
  1512. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  1513. OneService::~OneService() {}
  1514. } // namespace ZeroTier