OneService.cpp 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275
  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. #ifdef __WINDOWS__
  1488. // wait for up to 5 seconds for the WindowsEthernetTap to actually be initialized
  1489. //
  1490. // without WindowsEthernetTap::isInitialized() returning true, the won't actually
  1491. // be online yet and setting managed routes on it will fail.
  1492. const int MAX_SLEEP_COUNT = 500;
  1493. for (int i = 0; !n.tap->isInitialized() && i < MAX_SLEEP_COUNT; i++) {
  1494. Sleep(10);
  1495. }
  1496. #endif
  1497. syncManagedStuff(n,true,true);
  1498. } else {
  1499. _nets.erase(nwid);
  1500. return -999; // tap init failed
  1501. }
  1502. break;
  1503. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1504. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1505. if (n.tap) { // sanity check
  1506. #ifdef __WINDOWS__
  1507. std::string winInstanceId(n.tap->instanceId());
  1508. #endif
  1509. *nuptr = (void *)0;
  1510. delete n.tap;
  1511. _nets.erase(nwid);
  1512. #ifdef __WINDOWS__
  1513. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1514. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1515. #endif
  1516. if (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY) {
  1517. char nlcpath[256];
  1518. Utils::snprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1519. OSUtils::rm(nlcpath);
  1520. }
  1521. } else {
  1522. _nets.erase(nwid);
  1523. }
  1524. break;
  1525. }
  1526. return 0;
  1527. }
  1528. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1529. {
  1530. switch(event) {
  1531. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  1532. Mutex::Lock _l(_termReason_m);
  1533. _termReason = ONE_IDENTITY_COLLISION;
  1534. _fatalErrorMessage = "identity/address collision";
  1535. this->terminate();
  1536. } break;
  1537. case ZT_EVENT_TRACE: {
  1538. if (metaData) {
  1539. ::fprintf(stderr,"%s" ZT_EOL_S,(const char *)metaData);
  1540. ::fflush(stderr);
  1541. }
  1542. } break;
  1543. default:
  1544. break;
  1545. }
  1546. }
  1547. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1548. {
  1549. std::string p(_dataStorePrepPath(name));
  1550. if (!p.length())
  1551. return -2;
  1552. FILE *f = fopen(p.c_str(),"rb");
  1553. if (!f)
  1554. return -1;
  1555. if (fseek(f,0,SEEK_END) != 0) {
  1556. fclose(f);
  1557. return -2;
  1558. }
  1559. long ts = ftell(f);
  1560. if (ts < 0) {
  1561. fclose(f);
  1562. return -2;
  1563. }
  1564. *totalSize = (unsigned long)ts;
  1565. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  1566. fclose(f);
  1567. return -2;
  1568. }
  1569. long n = (long)fread(buf,1,bufSize,f);
  1570. fclose(f);
  1571. return n;
  1572. }
  1573. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  1574. {
  1575. std::string p(_dataStorePrepPath(name));
  1576. if (!p.length())
  1577. return -2;
  1578. if (!data) {
  1579. OSUtils::rm(p.c_str());
  1580. return 0;
  1581. }
  1582. FILE *f = fopen(p.c_str(),"wb");
  1583. if (!f)
  1584. return -1;
  1585. if (fwrite(data,len,1,f) == 1) {
  1586. fclose(f);
  1587. if (secure)
  1588. OSUtils::lockDownFile(p.c_str(),false);
  1589. return 0;
  1590. } else {
  1591. fclose(f);
  1592. OSUtils::rm(p.c_str());
  1593. return -1;
  1594. }
  1595. }
  1596. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1597. {
  1598. unsigned int fromBindingNo = 0;
  1599. if (addr->ss_family == AF_INET) {
  1600. if (reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port == 0) {
  1601. // If sender is sending from wildcard (null address), choose the secondary backup
  1602. // port 1/4 of the time. (but only for IPv4)
  1603. fromBindingNo = (++_udpPortPickerCounter & 0x4) >> 2;
  1604. if (!_ports[fromBindingNo])
  1605. fromBindingNo = 0;
  1606. } else {
  1607. const uint16_t lp = reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port;
  1608. if (lp == _portsBE[1])
  1609. fromBindingNo = 1;
  1610. else if (lp == _portsBE[2])
  1611. fromBindingNo = 2;
  1612. }
  1613. #ifdef ZT_TCP_FALLBACK_RELAY
  1614. // TCP fallback tunnel support, currently IPv4 only
  1615. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  1616. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  1617. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  1618. // valid direct traffic we'll stop using it and close the socket after a while.
  1619. const uint64_t now = OSUtils::now();
  1620. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  1621. if (_tcpFallbackTunnel) {
  1622. Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
  1623. if (!_tcpFallbackTunnel->writeBuf.length())
  1624. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  1625. unsigned long mlen = len + 7;
  1626. _tcpFallbackTunnel->writeBuf.push_back((char)0x17);
  1627. _tcpFallbackTunnel->writeBuf.push_back((char)0x03);
  1628. _tcpFallbackTunnel->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1629. _tcpFallbackTunnel->writeBuf.push_back((char)((mlen >> 8) & 0xff));
  1630. _tcpFallbackTunnel->writeBuf.push_back((char)(mlen & 0xff));
  1631. _tcpFallbackTunnel->writeBuf.push_back((char)4); // IPv4
  1632. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  1633. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  1634. _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
  1635. } else if (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INVERVAL / 2))) {
  1636. std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
  1637. if (tunnelIps.empty()) {
  1638. if (!_tcpFallbackResolver.running())
  1639. _tcpFallbackResolver.resolveNow();
  1640. } else {
  1641. bool connected = false;
  1642. InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
  1643. addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
  1644. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
  1645. }
  1646. }
  1647. }
  1648. _lastSendToGlobalV4 = now;
  1649. }
  1650. #endif // ZT_TCP_FALLBACK_RELAY
  1651. } else if (addr->ss_family == AF_INET6) {
  1652. if (reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port != 0) {
  1653. const uint16_t lp = reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port;
  1654. if (lp == _portsBE[1])
  1655. fromBindingNo = 1;
  1656. else if (lp == _portsBE[2])
  1657. fromBindingNo = 2;
  1658. }
  1659. } else {
  1660. return -1;
  1661. }
  1662. #ifdef ZT_BREAK_UDP
  1663. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  1664. return 0; // silently break UDP
  1665. #endif
  1666. return (_bindings[fromBindingNo].udpSend(_phy,*(reinterpret_cast<const InetAddress *>(localAddr)),*(reinterpret_cast<const InetAddress *>(addr)),data,len,ttl)) ? 0 : -1;
  1667. }
  1668. 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)
  1669. {
  1670. NetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);
  1671. if ((!n)||(!n->tap))
  1672. return;
  1673. n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1674. }
  1675. inline int nodePathCheckFunction(uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1676. {
  1677. // Make sure we're not trying to do ZeroTier-over-ZeroTier
  1678. {
  1679. Mutex::Lock _l(_nets_m);
  1680. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1681. if (n->second.tap) {
  1682. std::vector<InetAddress> ips(n->second.tap->ips());
  1683. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1684. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  1685. return 0;
  1686. }
  1687. }
  1688. }
  1689. }
  1690. }
  1691. /* Note: I do not think we need to scan for overlap with managed routes
  1692. * because of the "route forking" and interface binding that we do. This
  1693. * ensures (we hope) that ZeroTier traffic will still take the physical
  1694. * path even if its managed routes override this for other traffic. Will
  1695. * revisit if we see recursion problems. */
  1696. // Check blacklists
  1697. const Hashtable< uint64_t,std::vector<InetAddress> > *blh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  1698. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  1699. if (remoteAddr->ss_family == AF_INET) {
  1700. blh = &_v4Blacklists;
  1701. gbl = &_globalV4Blacklist;
  1702. } else if (remoteAddr->ss_family == AF_INET6) {
  1703. blh = &_v6Blacklists;
  1704. gbl = &_globalV6Blacklist;
  1705. }
  1706. if (blh) {
  1707. Mutex::Lock _l(_localConfig_m);
  1708. const std::vector<InetAddress> *l = blh->get(ztaddr);
  1709. if (l) {
  1710. for(std::vector<InetAddress>::const_iterator a(l->begin());a!=l->end();++a) {
  1711. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  1712. return 0;
  1713. }
  1714. }
  1715. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  1716. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  1717. return 0;
  1718. }
  1719. }
  1720. return 1;
  1721. }
  1722. inline int nodePathLookupFunction(uint64_t ztaddr,int family,struct sockaddr_storage *result)
  1723. {
  1724. const Hashtable< uint64_t,std::vector<InetAddress> > *lh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  1725. if (family < 0)
  1726. lh = (_node->prng() & 1) ? &_v4Hints : &_v6Hints;
  1727. else if (family == AF_INET)
  1728. lh = &_v4Hints;
  1729. else if (family == AF_INET6)
  1730. lh = &_v6Hints;
  1731. else return 0;
  1732. const std::vector<InetAddress> *l = lh->get(ztaddr);
  1733. if ((l)&&(l->size() > 0)) {
  1734. memcpy(result,&((*l)[(unsigned long)_node->prng() % l->size()]),sizeof(struct sockaddr_storage));
  1735. return 1;
  1736. } else return 0;
  1737. }
  1738. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1739. {
  1740. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1741. }
  1742. inline void onHttpRequestToServer(TcpConnection *tc)
  1743. {
  1744. char tmpn[256];
  1745. std::string data;
  1746. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1747. unsigned int scode = 404;
  1748. bool allow;
  1749. {
  1750. Mutex::Lock _l(_localConfig_m);
  1751. if (_allowManagementFrom.size() == 0) {
  1752. allow = (tc->from.ipScope() == InetAddress::IP_SCOPE_LOOPBACK);
  1753. } else {
  1754. allow = false;
  1755. for(std::vector<InetAddress>::const_iterator i(_allowManagementFrom.begin());i!=_allowManagementFrom.end();++i) {
  1756. if (i->containsAddress(tc->from)) {
  1757. allow = true;
  1758. break;
  1759. }
  1760. }
  1761. }
  1762. }
  1763. if (allow) {
  1764. try {
  1765. if (_controlPlane)
  1766. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  1767. else scode = 500;
  1768. } catch (std::exception &exc) {
  1769. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: %s" ZT_EOL_S,exc.what());
  1770. scode = 500;
  1771. } catch ( ... ) {
  1772. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: unknown exceptino" ZT_EOL_S);
  1773. scode = 500;
  1774. }
  1775. } else {
  1776. scode = 401;
  1777. }
  1778. const char *scodestr;
  1779. switch(scode) {
  1780. case 200: scodestr = "OK"; break;
  1781. case 400: scodestr = "Bad Request"; break;
  1782. case 401: scodestr = "Unauthorized"; break;
  1783. case 403: scodestr = "Forbidden"; break;
  1784. case 404: scodestr = "Not Found"; break;
  1785. case 500: scodestr = "Internal Server Error"; break;
  1786. case 501: scodestr = "Not Implemented"; break;
  1787. case 503: scodestr = "Service Unavailable"; break;
  1788. default: scodestr = "Error"; break;
  1789. }
  1790. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  1791. {
  1792. Mutex::Lock _l(tc->writeBuf_m);
  1793. tc->writeBuf.assign(tmpn);
  1794. tc->writeBuf.append("Content-Type: ");
  1795. tc->writeBuf.append(contentType);
  1796. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  1797. tc->writeBuf.append(tmpn);
  1798. if (!tc->shouldKeepAlive)
  1799. tc->writeBuf.append("Connection: close\r\n");
  1800. tc->writeBuf.append("\r\n");
  1801. if (tc->parser.method != HTTP_HEAD)
  1802. tc->writeBuf.append(data);
  1803. }
  1804. _phy.setNotifyWritable(tc->sock,true);
  1805. }
  1806. inline void onHttpResponseFromClient(TcpConnection *tc)
  1807. {
  1808. if (!tc->shouldKeepAlive)
  1809. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConnections
  1810. }
  1811. bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
  1812. {
  1813. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  1814. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  1815. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  1816. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  1817. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  1818. #endif
  1819. #ifdef __APPLE__
  1820. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  1821. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  1822. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  1823. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  1824. if ((ifname[0] == 'u')&&(ifname[1] == 't')&&(ifname[2] == 'u')&&(ifname[3] == 'n')) return false; // ... as is utun#
  1825. #endif
  1826. {
  1827. Mutex::Lock _l(_localConfig_m);
  1828. for(std::vector<std::string>::const_iterator p(_interfacePrefixBlacklist.begin());p!=_interfacePrefixBlacklist.end();++p) {
  1829. if (!strncmp(p->c_str(),ifname,p->length()))
  1830. return false;
  1831. }
  1832. }
  1833. {
  1834. Mutex::Lock _l(_nets_m);
  1835. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1836. if (n->second.tap) {
  1837. std::vector<InetAddress> ips(n->second.tap->ips());
  1838. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1839. if (i->ipsEqual(ifaddr))
  1840. return false;
  1841. }
  1842. }
  1843. }
  1844. }
  1845. return true;
  1846. }
  1847. std::string _dataStorePrepPath(const char *name) const
  1848. {
  1849. std::string p(_homePath);
  1850. p.push_back(ZT_PATH_SEPARATOR);
  1851. char lastc = (char)0;
  1852. for(const char *n=name;(*n);++n) {
  1853. if ((*n == '.')&&(lastc == '.'))
  1854. return std::string(); // don't allow ../../ stuff as a precaution
  1855. if (*n == '/') {
  1856. OSUtils::mkdir(p.c_str());
  1857. p.push_back(ZT_PATH_SEPARATOR);
  1858. } else p.push_back(*n);
  1859. lastc = *n;
  1860. }
  1861. return p;
  1862. }
  1863. bool _trialBind(unsigned int port)
  1864. {
  1865. struct sockaddr_in in4;
  1866. struct sockaddr_in6 in6;
  1867. PhySocket *tb;
  1868. memset(&in4,0,sizeof(in4));
  1869. in4.sin_family = AF_INET;
  1870. in4.sin_port = Utils::hton((uint16_t)port);
  1871. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
  1872. if (tb) {
  1873. _phy.close(tb,false);
  1874. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
  1875. if (tb) {
  1876. _phy.close(tb,false);
  1877. return true;
  1878. }
  1879. }
  1880. memset(&in6,0,sizeof(in6));
  1881. in6.sin6_family = AF_INET6;
  1882. in6.sin6_port = Utils::hton((uint16_t)port);
  1883. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
  1884. if (tb) {
  1885. _phy.close(tb,false);
  1886. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
  1887. if (tb) {
  1888. _phy.close(tb,false);
  1889. return true;
  1890. }
  1891. }
  1892. return false;
  1893. }
  1894. };
  1895. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  1896. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  1897. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData)
  1898. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1899. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1900. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  1901. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  1902. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  1903. 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)
  1904. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localAddr,addr,data,len,ttl); }
  1905. 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)
  1906. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  1907. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1908. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(ztaddr,localAddr,remoteAddr); }
  1909. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,int family,struct sockaddr_storage *result)
  1910. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathLookupFunction(ztaddr,family,result); }
  1911. #ifdef ZT_ENABLE_CLUSTER
  1912. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len)
  1913. {
  1914. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1915. const ClusterDefinition::MemberDefinition &md = (*(impl->_clusterDefinition))[toMemberId];
  1916. if (md.clusterEndpoint)
  1917. impl->_phy.udpSend(impl->_clusterMessageSocket,reinterpret_cast<const struct sockaddr *>(&(md.clusterEndpoint)),data,len);
  1918. }
  1919. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z)
  1920. {
  1921. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1922. return (int)(impl->_clusterDefinition->geo().locate(*(reinterpret_cast<const InetAddress *>(addr)),*x,*y,*z));
  1923. }
  1924. #endif
  1925. 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)
  1926. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1927. static int ShttpOnMessageBegin(http_parser *parser)
  1928. {
  1929. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1930. tc->currentHeaderField = "";
  1931. tc->currentHeaderValue = "";
  1932. tc->messageSize = 0;
  1933. tc->url = "";
  1934. tc->status = "";
  1935. tc->headers.clear();
  1936. tc->body = "";
  1937. return 0;
  1938. }
  1939. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  1940. {
  1941. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1942. tc->messageSize += (unsigned long)length;
  1943. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1944. return -1;
  1945. tc->url.append(ptr,length);
  1946. return 0;
  1947. }
  1948. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  1949. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1950. #else
  1951. static int ShttpOnStatus(http_parser *parser)
  1952. #endif
  1953. {
  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. tc->status.append(ptr,length);
  1960. */
  1961. return 0;
  1962. }
  1963. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1964. {
  1965. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1966. tc->messageSize += (unsigned long)length;
  1967. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1968. return -1;
  1969. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1970. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1971. tc->currentHeaderField = "";
  1972. tc->currentHeaderValue = "";
  1973. }
  1974. for(size_t i=0;i<length;++i)
  1975. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1976. return 0;
  1977. }
  1978. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1979. {
  1980. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1981. tc->messageSize += (unsigned long)length;
  1982. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1983. return -1;
  1984. tc->currentHeaderValue.append(ptr,length);
  1985. return 0;
  1986. }
  1987. static int ShttpOnHeadersComplete(http_parser *parser)
  1988. {
  1989. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1990. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  1991. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1992. return 0;
  1993. }
  1994. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  1995. {
  1996. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1997. tc->messageSize += (unsigned long)length;
  1998. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1999. return -1;
  2000. tc->body.append(ptr,length);
  2001. return 0;
  2002. }
  2003. static int ShttpOnMessageComplete(http_parser *parser)
  2004. {
  2005. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2006. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  2007. tc->lastActivity = OSUtils::now();
  2008. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  2009. tc->parent->onHttpRequestToServer(tc);
  2010. } else {
  2011. tc->parent->onHttpResponseFromClient(tc);
  2012. }
  2013. return 0;
  2014. }
  2015. } // anonymous namespace
  2016. std::string OneService::platformDefaultHomePath()
  2017. {
  2018. return OSUtils::platformDefaultHomePath();
  2019. }
  2020. std::string OneService::autoUpdateUrl()
  2021. {
  2022. #ifdef ZT_AUTO_UPDATE
  2023. /*
  2024. #if defined(__LINUX__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  2025. if (sizeof(void *) == 8)
  2026. return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x64-LATEST.nfo";
  2027. else return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x86-LATEST.nfo";
  2028. #endif
  2029. */
  2030. #if defined(__APPLE__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  2031. return "http://download.zerotier.com/update/mac_intel/";
  2032. #endif
  2033. #ifdef __WINDOWS__
  2034. return "http://download.zerotier.com/update/win_intel/";
  2035. #endif
  2036. #endif // ZT_AUTO_UPDATE
  2037. return std::string();
  2038. }
  2039. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  2040. OneService::~OneService() {}
  2041. } // namespace ZeroTier