OneService.cpp 68 KB

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