OneService.cpp 77 KB

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