OneService.cpp 71 KB

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