OneService.cpp 64 KB

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