OneService.cpp 58 KB

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