OneService.cpp 77 KB

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