OneService.cpp 68 KB

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