OneService.cpp 76 KB

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