OneService.cpp 71 KB

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