OneService.cpp 77 KB

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