OneService.cpp 68 KB

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