OneService.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711
  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 "../version.h"
  28. #include "../include/ZeroTierOne.h"
  29. #include "../ext/http-parser/http_parser.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 "OneService.hpp"
  44. #include "ControlPlane.hpp"
  45. #include "ClusterGeoIpService.hpp"
  46. #include "ClusterDefinition.hpp"
  47. /**
  48. * Uncomment to enable UDP breakage switch
  49. *
  50. * If this is defined, the presence of a file called /tmp/ZT_BREAK_UDP
  51. * will cause direct UDP TX/RX to stop working. This can be used to
  52. * test TCP tunneling fallback and other robustness features. Deleting
  53. * this file will cause it to start working again.
  54. */
  55. //#define ZT_BREAK_UDP
  56. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  57. #include "../controller/SqliteNetworkController.hpp"
  58. #else
  59. class SqliteNetworkController;
  60. #endif // ZT_ENABLE_NETWORK_CONTROLLER
  61. #ifdef __WINDOWS__
  62. #include <WinSock2.h>
  63. #include <Windows.h>
  64. #include <ShlObj.h>
  65. #include <netioapi.h>
  66. #include <iphlpapi.h>
  67. #else
  68. #include <sys/types.h>
  69. #include <sys/socket.h>
  70. #include <sys/wait.h>
  71. #include <unistd.h>
  72. #include <ifaddrs.h>
  73. #endif
  74. // Include the right tap device driver for this platform -- add new platforms here
  75. #ifdef ZT_SERVICE_NETCON
  76. // In network containers builds, use the virtual netcon endpoint instead of a tun/tap port driver
  77. #include "../netcon/NetconEthernetTap.hpp"
  78. namespace ZeroTier { typedef NetconEthernetTap EthernetTap; }
  79. #else // not ZT_SERVICE_NETCON so pick a tap driver
  80. #ifdef __APPLE__
  81. #include "../osdep/OSXEthernetTap.hpp"
  82. namespace ZeroTier { typedef OSXEthernetTap EthernetTap; }
  83. #endif // __APPLE__
  84. #ifdef __LINUX__
  85. #include "../osdep/LinuxEthernetTap.hpp"
  86. namespace ZeroTier { typedef LinuxEthernetTap EthernetTap; }
  87. #endif // __LINUX__
  88. #ifdef __WINDOWS__
  89. #include "../osdep/WindowsEthernetTap.hpp"
  90. namespace ZeroTier { typedef WindowsEthernetTap EthernetTap; }
  91. #endif // __WINDOWS__
  92. #ifdef __FreeBSD__
  93. #include "../osdep/BSDEthernetTap.hpp"
  94. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  95. #endif // __FreeBSD__
  96. #endif // ZT_SERVICE_NETCON
  97. // Sanity limits for HTTP
  98. #define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 64)
  99. #define ZT_MAX_HTTP_CONNECTIONS 64
  100. // Interface metric for ZeroTier taps
  101. #define ZT_IF_METRIC 32768
  102. // How often to check for new multicast subscriptions on a tap device
  103. #define ZT_TAP_CHECK_MULTICAST_INTERVAL 5000
  104. // Path under ZT1 home for controller database if controller is enabled
  105. #define ZT_CONTROLLER_DB_PATH "controller.db"
  106. // TCP fallback relay host -- geo-distributed using Amazon Route53 geo-aware DNS
  107. #define ZT_TCP_FALLBACK_RELAY "tcp-fallback.zerotier.com"
  108. #define ZT_TCP_FALLBACK_RELAY_PORT 443
  109. // Frequency at which we re-resolve the TCP fallback relay
  110. #define ZT_TCP_FALLBACK_RERESOLVE_DELAY 86400000
  111. // Attempt to engage TCP fallback after this many ms of no reply to packets sent to global-scope IPs
  112. #define ZT_TCP_FALLBACK_AFTER 60000
  113. // How often to check for local interface addresses
  114. #define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 300000
  115. namespace ZeroTier {
  116. namespace {
  117. #ifdef ZT_AUTO_UPDATE
  118. #define ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE (1024 * 1024 * 64)
  119. #define ZT_AUTO_UPDATE_CHECK_PERIOD 21600000
  120. class BackgroundSoftwareUpdateChecker
  121. {
  122. public:
  123. bool isValidSigningIdentity(const Identity &id)
  124. {
  125. return (
  126. /* 0005 */ (id == Identity("ba57ea350e:0:9d4be6d7f86c5660d5ee1951a3d759aa6e12a84fc0c0b74639500f1dbc1a8c566622e7d1c531967ebceb1e9d1761342f88324a8ba520c93c35f92f35080fa23f"))
  127. /* 0006 */ ||(id == Identity("5067b21b83:0:8af477730f5055c48135b84bed6720a35bca4c0e34be4060a4c636288b1ec22217eb22709d610c66ed464c643130c51411bbb0294eef12fbe8ecc1a1e2c63a7a"))
  128. /* 0007 */ ||(id == Identity("4f5e97a8f1:0:57880d056d7baeb04bbc057d6f16e6cb41388570e87f01492fce882485f65a798648595610a3ad49885604e7fb1db2dd3c2c534b75e42c3c0b110ad07b4bb138"))
  129. /* 0008 */ ||(id == Identity("580bbb8e15:0:ad5ef31155bebc6bc413991992387e083fed26d699997ef76e7c947781edd47d1997161fa56ba337b1a2b44b129fd7c7197ce5185382f06011bc88d1363b4ddd"))
  130. );
  131. }
  132. void doUpdateCheck()
  133. {
  134. std::string url(OneService::autoUpdateUrl());
  135. if ((url.length() <= 7)||(url.substr(0,7) != "http://"))
  136. return;
  137. std::string httpHost;
  138. std::string httpPath;
  139. {
  140. std::size_t slashIdx = url.substr(7).find_first_of('/');
  141. if (slashIdx == std::string::npos) {
  142. httpHost = url.substr(7);
  143. httpPath = "/";
  144. } else {
  145. httpHost = url.substr(7,slashIdx);
  146. httpPath = url.substr(slashIdx + 7);
  147. }
  148. }
  149. if (httpHost.length() == 0)
  150. return;
  151. std::vector<InetAddress> ips(OSUtils::resolve(httpHost.c_str()));
  152. for(std::vector<InetAddress>::iterator ip(ips.begin());ip!=ips.end();++ip) {
  153. if (!ip->port())
  154. ip->setPort(80);
  155. std::string nfoPath = httpPath + "LATEST.nfo";
  156. std::map<std::string,std::string> requestHeaders,responseHeaders;
  157. std::string body;
  158. requestHeaders["Host"] = httpHost;
  159. 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);
  160. //fprintf(stderr,"UPDATE %s %s %u %lu\n",ip->toString().c_str(),nfoPath.c_str(),scode,body.length());
  161. if ((scode == 200)&&(body.length() > 0)) {
  162. /* NFO fields:
  163. *
  164. * file=<filename>
  165. * signedBy=<signing identity>
  166. * ed25519=<ed25519 ECC signature of archive>
  167. * vMajor=<major version>
  168. * vMinor=<minor version>
  169. * vRevision=<revision> */
  170. Dictionary nfo(body);
  171. unsigned int vMajor = Utils::strToUInt(nfo.get("vMajor","0").c_str());
  172. unsigned int vMinor = Utils::strToUInt(nfo.get("vMinor","0").c_str());
  173. unsigned int vRevision = Utils::strToUInt(nfo.get("vRevision","0").c_str());
  174. if (Utils::compareVersion(vMajor,vMinor,vRevision,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION) <= 0) {
  175. //fprintf(stderr,"UPDATE %u.%u.%u is not newer than our version\n",vMajor,vMinor,vRevision);
  176. return;
  177. }
  178. Identity signedBy;
  179. if ((!signedBy.fromString(nfo.get("signedBy","")))||(!isValidSigningIdentity(signedBy))) {
  180. //fprintf(stderr,"UPDATE invalid signedBy or not authorized signing identity.\n");
  181. return;
  182. }
  183. std::string filePath(nfo.get("file",""));
  184. if ((!filePath.length())||(filePath.find("..") != std::string::npos))
  185. return;
  186. filePath = httpPath + filePath;
  187. std::string fileData;
  188. if (Http::GET(ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE,60000,reinterpret_cast<const struct sockaddr *>(&(*ip)),filePath.c_str(),requestHeaders,responseHeaders,fileData) != 200) {
  189. //fprintf(stderr,"UPDATE GET %s failed\n",filePath.c_str());
  190. return;
  191. }
  192. std::string ed25519(Utils::unhex(nfo.get("ed25519","")));
  193. if ((ed25519.length() == 0)||(!signedBy.verify(fileData.data(),(unsigned int)fileData.length(),ed25519.data(),(unsigned int)ed25519.length()))) {
  194. //fprintf(stderr,"UPDATE %s failed signature check!\n",filePath.c_str());
  195. return;
  196. }
  197. /* --------------------------------------------------------------- */
  198. /* We made it! Begin OS-specific installation code. */
  199. #ifdef __APPLE__
  200. /* OSX version is in the form of a MacOSX .pkg file, so we will
  201. * launch installer (normally in /usr/sbin) to install it. It will
  202. * then turn around and shut down the service, update files, and
  203. * relaunch. */
  204. {
  205. char bashp[128],pkgp[128];
  206. Utils::snprintf(bashp,sizeof(bashp),"/tmp/ZeroTierOne-update-%u.%u.%u.sh",vMajor,vMinor,vRevision);
  207. Utils::snprintf(pkgp,sizeof(pkgp),"/tmp/ZeroTierOne-update-%u.%u.%u.pkg",vMajor,vMinor,vRevision);
  208. FILE *pkg = fopen(pkgp,"w");
  209. if ((!pkg)||(fwrite(fileData.data(),fileData.length(),1,pkg) != 1)) {
  210. fclose(pkg);
  211. unlink(bashp);
  212. unlink(pkgp);
  213. fprintf(stderr,"UPDATE error writing %s\n",pkgp);
  214. return;
  215. }
  216. fclose(pkg);
  217. FILE *bash = fopen(bashp,"w");
  218. if (!bash) {
  219. fclose(pkg);
  220. unlink(bashp);
  221. unlink(pkgp);
  222. fprintf(stderr,"UPDATE error writing %s\n",bashp);
  223. return;
  224. }
  225. fprintf(bash,
  226. "#!/bin/bash\n"
  227. "export PATH=/bin:/usr/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/sbin\n"
  228. "sleep 1\n"
  229. "installer -pkg \"%s\" -target /\n"
  230. "sleep 1\n"
  231. "rm -f \"%s\" \"%s\"\n"
  232. "exit 0\n",
  233. pkgp,
  234. pkgp,
  235. bashp);
  236. fclose(bash);
  237. long pid = (long)vfork();
  238. if (pid == 0) {
  239. setsid(); // detach from parent so that shell isn't killed when parent is killed
  240. signal(SIGHUP,SIG_IGN);
  241. signal(SIGTERM,SIG_IGN);
  242. signal(SIGQUIT,SIG_IGN);
  243. execl("/bin/bash","/bin/bash",bashp,(char *)0);
  244. exit(0);
  245. }
  246. }
  247. #endif // __APPLE__
  248. #ifdef __WINDOWS__
  249. /* Windows version comes in the form of .MSI package that
  250. * takes care of everything. */
  251. {
  252. char tempp[512],batp[512],msip[512],cmdline[512];
  253. if (GetTempPathA(sizeof(tempp),tempp) <= 0)
  254. return;
  255. CreateDirectoryA(tempp,(LPSECURITY_ATTRIBUTES)0);
  256. Utils::snprintf(batp,sizeof(batp),"%s\\ZeroTierOne-update-%u.%u.%u.bat",tempp,vMajor,vMinor,vRevision);
  257. Utils::snprintf(msip,sizeof(msip),"%s\\ZeroTierOne-update-%u.%u.%u.msi",tempp,vMajor,vMinor,vRevision);
  258. FILE *msi = fopen(msip,"wb");
  259. if ((!msi)||(fwrite(fileData.data(),(size_t)fileData.length(),1,msi) != 1)) {
  260. fclose(msi);
  261. return;
  262. }
  263. fclose(msi);
  264. FILE *bat = fopen(batp,"wb");
  265. if (!bat)
  266. return;
  267. fprintf(bat,
  268. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  269. "NET.EXE STOP \"ZeroTierOneService\"\r\n"
  270. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  271. "MSIEXEC.EXE /i \"%s\" /qn\r\n"
  272. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  273. "NET.EXE START \"ZeroTierOneService\"\r\n"
  274. "DEL \"%s\"\r\n"
  275. "DEL \"%s\"\r\n",
  276. msip,
  277. msip,
  278. batp);
  279. fclose(bat);
  280. STARTUPINFOA si;
  281. PROCESS_INFORMATION pi;
  282. memset(&si,0,sizeof(si));
  283. memset(&pi,0,sizeof(pi));
  284. Utils::snprintf(cmdline,sizeof(cmdline),"CMD.EXE /c \"%s\"",batp);
  285. CreateProcessA(NULL,cmdline,NULL,NULL,FALSE,CREATE_NO_WINDOW|CREATE_NEW_PROCESS_GROUP,NULL,NULL,&si,&pi);
  286. }
  287. #endif // __WINDOWS__
  288. /* --------------------------------------------------------------- */
  289. return;
  290. } // else try to fetch from next IP address
  291. }
  292. }
  293. void threadMain()
  294. throw()
  295. {
  296. try {
  297. this->doUpdateCheck();
  298. } catch ( ... ) {}
  299. }
  300. };
  301. static BackgroundSoftwareUpdateChecker backgroundSoftwareUpdateChecker;
  302. #endif // ZT_AUTO_UPDATE
  303. static bool isBlacklistedLocalInterfaceForZeroTierTraffic(const char *ifn)
  304. {
  305. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  306. if ((ifn[0] == 'l')&&(ifn[1] == 'o')) return true; // loopback
  307. if ((ifn[0] == 'z')&&(ifn[1] == 't')) return true; // sanity check: zt#
  308. if ((ifn[0] == 't')&&(ifn[1] == 'u')&&(ifn[2] == 'n')) return true; // tun# is probably an OpenVPN tunnel or similar
  309. if ((ifn[0] == 't')&&(ifn[1] == 'a')&&(ifn[2] == 'p')) return true; // tap# is probably an OpenVPN tunnel or similar
  310. #endif
  311. #ifdef __APPLE__
  312. if ((ifn[0] == 'l')&&(ifn[1] == 'o')) return true; // loopback
  313. if ((ifn[0] == 'z')&&(ifn[1] == 't')) return true; // sanity check: zt#
  314. if ((ifn[0] == 't')&&(ifn[1] == 'u')&&(ifn[2] == 'n')) return true; // tun# is probably an OpenVPN tunnel or similar
  315. if ((ifn[0] == 't')&&(ifn[1] == 'a')&&(ifn[2] == 'p')) return true; // tap# is probably an OpenVPN tunnel or similar
  316. if ((ifn[0] == 'u')&&(ifn[1] == 't')&&(ifn[2] == 'u')&&(ifn[3] == 'n')) return true; // ... as is utun#
  317. #endif
  318. return false;
  319. }
  320. static std::string _trimString(const std::string &s)
  321. {
  322. unsigned long end = (unsigned long)s.length();
  323. while (end) {
  324. char c = s[end - 1];
  325. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  326. --end;
  327. else break;
  328. }
  329. unsigned long start = 0;
  330. while (start < end) {
  331. char c = s[start];
  332. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  333. ++start;
  334. else break;
  335. }
  336. return s.substr(start,end - start);
  337. }
  338. class OneServiceImpl;
  339. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
  340. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData);
  341. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize);
  342. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure);
  343. 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);
  344. 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);
  345. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr);
  346. #ifdef ZT_ENABLE_CLUSTER
  347. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len);
  348. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z);
  349. #endif
  350. 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);
  351. static int ShttpOnMessageBegin(http_parser *parser);
  352. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  353. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  354. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  355. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  356. static int ShttpOnHeadersComplete(http_parser *parser);
  357. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  358. static int ShttpOnMessageComplete(http_parser *parser);
  359. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  360. ShttpOnMessageBegin,
  361. ShttpOnUrl,
  362. ShttpOnStatus,
  363. ShttpOnHeaderField,
  364. ShttpOnValue,
  365. ShttpOnHeadersComplete,
  366. ShttpOnBody,
  367. ShttpOnMessageComplete
  368. };
  369. struct TcpConnection
  370. {
  371. enum {
  372. TCP_HTTP_INCOMING,
  373. TCP_HTTP_OUTGOING, // not currently used
  374. TCP_TUNNEL_OUTGOING // fale-SSL outgoing tunnel -- HTTP-related fields are not used
  375. } type;
  376. bool shouldKeepAlive;
  377. OneServiceImpl *parent;
  378. PhySocket *sock;
  379. InetAddress from;
  380. http_parser parser;
  381. unsigned long messageSize;
  382. uint64_t lastActivity;
  383. std::string currentHeaderField;
  384. std::string currentHeaderValue;
  385. std::string url;
  386. std::string status;
  387. std::map< std::string,std::string > headers;
  388. std::string body;
  389. std::string writeBuf;
  390. Mutex writeBuf_m;
  391. };
  392. // Use a bigger buffer on AMD64 since these are likely to be bigger and
  393. // servers. Otherwise use a smaller buffer. This makes no difference
  394. // except under very high load.
  395. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__))
  396. #define ZT_UDP_DESIRED_BUF_SIZE 1048576
  397. #else
  398. #define ZT_UDP_DESIRED_BUF_SIZE 131072
  399. #endif
  400. class OneServiceImpl : public OneService
  401. {
  402. public:
  403. OneServiceImpl(const char *hp,unsigned int port) :
  404. _homePath((hp) ? hp : ".")
  405. ,_tcpFallbackResolver(ZT_TCP_FALLBACK_RELAY)
  406. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  407. ,_controller((SqliteNetworkController *)0)
  408. #endif
  409. ,_phy(this,false,true)
  410. ,_node((Node *)0)
  411. ,_controlPlane((ControlPlane *)0)
  412. ,_lastDirectReceiveFromGlobal(0)
  413. ,_lastSendToGlobal(0)
  414. ,_lastRestart(0)
  415. ,_nextBackgroundTaskDeadline(0)
  416. ,_tcpFallbackTunnel((TcpConnection *)0)
  417. ,_termReason(ONE_STILL_RUNNING)
  418. ,_port(0)
  419. #ifdef ZT_USE_MINIUPNPC
  420. ,_v4UpnpUdpSocket((PhySocket *)0)
  421. ,_portMapper((PortMapper *)0)
  422. #endif
  423. #ifdef ZT_ENABLE_CLUSTER
  424. ,_clusterMessageSocket((PhySocket *)0)
  425. ,_clusterGeoIpService((ClusterGeoIpService *)0)
  426. ,_clusterDefinition((ClusterDefinition *)0)
  427. ,_clusterMemberId(0)
  428. #endif
  429. ,_run(true)
  430. {
  431. const int portTrials = (port == 0) ? 256 : 1; // if port is 0, pick random
  432. for(int k=0;k<portTrials;++k) {
  433. if (port == 0) {
  434. unsigned int randp = 0;
  435. Utils::getSecureRandom(&randp,sizeof(randp));
  436. port = 40000 + (randp % 25500);
  437. }
  438. _v4LocalAddress = InetAddress((uint32_t)0,port);
  439. _v4UdpSocket = _phy.udpBind((const struct sockaddr *)&_v4LocalAddress,reinterpret_cast<void *>(&_v4LocalAddress),ZT_UDP_DESIRED_BUF_SIZE);
  440. if (_v4UdpSocket) {
  441. struct sockaddr_in in4;
  442. memset(&in4,0,sizeof(in4));
  443. in4.sin_family = AF_INET;
  444. in4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001); // right now we just listen for TCP @localhost
  445. in4.sin_port = Utils::hton((uint16_t)port);
  446. _v4TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
  447. if (_v4TcpListenSocket) {
  448. _v6LocalAddress = InetAddress("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",16,port);
  449. _v6UdpSocket = _phy.udpBind((const struct sockaddr *)&_v6LocalAddress,reinterpret_cast<void *>(&_v6LocalAddress),ZT_UDP_DESIRED_BUF_SIZE);
  450. struct sockaddr_in6 in6;
  451. memset((void *)&in6,0,sizeof(in6));
  452. in6.sin6_family = AF_INET6;
  453. in6.sin6_port = in4.sin_port;
  454. in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
  455. _v6TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
  456. _port = port;
  457. break; // success!
  458. } else {
  459. _phy.close(_v4UdpSocket,false);
  460. }
  461. }
  462. port = 0;
  463. }
  464. if (_port == 0)
  465. throw std::runtime_error("cannot bind to port");
  466. char portstr[64];
  467. Utils::snprintf(portstr,sizeof(portstr),"%u",_port);
  468. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),std::string(portstr));
  469. }
  470. virtual ~OneServiceImpl()
  471. {
  472. _phy.close(_v4UdpSocket);
  473. _phy.close(_v6UdpSocket);
  474. _phy.close(_v4TcpListenSocket);
  475. _phy.close(_v6TcpListenSocket);
  476. #ifdef ZT_ENABLE_CLUSTER
  477. _phy.close(_clusterMessageSocket);
  478. #endif
  479. #ifdef ZT_USE_MINIUPNPC
  480. _phy.close(_v4UpnpUdpSocket);
  481. delete _portMapper;
  482. #endif
  483. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  484. delete _controller;
  485. #endif
  486. #ifdef ZT_ENABLE_CLUSTER
  487. delete _clusterGeoIpService;
  488. delete _clusterDefinition;
  489. #endif
  490. }
  491. virtual ReasonForTermination run()
  492. {
  493. try {
  494. std::string authToken;
  495. {
  496. std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  497. if (!OSUtils::readFile(authTokenPath.c_str(),authToken)) {
  498. unsigned char foo[24];
  499. Utils::getSecureRandom(foo,sizeof(foo));
  500. authToken = "";
  501. for(unsigned int i=0;i<sizeof(foo);++i)
  502. authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  503. if (!OSUtils::writeFile(authTokenPath.c_str(),authToken)) {
  504. Mutex::Lock _l(_termReason_m);
  505. _termReason = ONE_UNRECOVERABLE_ERROR;
  506. _fatalErrorMessage = "authtoken.secret could not be written";
  507. return _termReason;
  508. } else OSUtils::lockDownFile(authTokenPath.c_str(),false);
  509. }
  510. }
  511. authToken = _trimString(authToken);
  512. _node = new Node(
  513. OSUtils::now(),
  514. this,
  515. SnodeDataStoreGetFunction,
  516. SnodeDataStorePutFunction,
  517. SnodeWirePacketSendFunction,
  518. SnodeVirtualNetworkFrameFunction,
  519. SnodeVirtualNetworkConfigFunction,
  520. SnodePathCheckFunction,
  521. SnodeEventCallback);
  522. #ifdef ZT_USE_MINIUPNPC
  523. // Bind a secondary port for use with uPnP, since some NAT routers
  524. // (cough Ubiquity Edge cough) barf up a lung if you do both conventional
  525. // NAT-t and uPnP from behind the same port. I think this is a bug, but
  526. // everyone else's router bugs are our problem. :P
  527. for(int k=0;k<512;++k) {
  528. unsigned int mapperPort = 40000 + (((_port + 1) * (k + 1)) % 25500);
  529. char uniqueName[64];
  530. _v4UpnpLocalAddress = InetAddress(0,mapperPort);
  531. _v4UpnpUdpSocket = _phy.udpBind((const struct sockaddr *)&_v4UpnpLocalAddress,reinterpret_cast<void *>(&_v4UpnpLocalAddress),ZT_UDP_DESIRED_BUF_SIZE);
  532. if (_v4UpnpUdpSocket) {
  533. Utils::snprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx",_node->address());
  534. _portMapper = new PortMapper(mapperPort,uniqueName);
  535. break;
  536. }
  537. }
  538. #endif
  539. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  540. _controller = new SqliteNetworkController(_node,(_homePath + ZT_PATH_SEPARATOR_S + ZT_CONTROLLER_DB_PATH).c_str(),(_homePath + ZT_PATH_SEPARATOR_S + "circuitTestResults.d").c_str());
  541. _node->setNetconfMaster((void *)_controller);
  542. #endif
  543. #ifdef ZT_ENABLE_CLUSTER
  544. if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str())) {
  545. _clusterDefinition = new ClusterDefinition(_node->address(),(_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str());
  546. if (_clusterDefinition->size() > 0) {
  547. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  548. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  549. PhySocket *cs = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&(m->clusterEndpoint)));
  550. if (cs) {
  551. if (_clusterMessageSocket) {
  552. _phy.close(_clusterMessageSocket,false);
  553. _phy.close(cs,false);
  554. Mutex::Lock _l(_termReason_m);
  555. _termReason = ONE_UNRECOVERABLE_ERROR;
  556. _fatalErrorMessage = "Cluster: can't determine my cluster member ID: able to bind more than one cluster message socket IP/port!";
  557. return _termReason;
  558. }
  559. _clusterMessageSocket = cs;
  560. _clusterMemberId = m->id;
  561. }
  562. }
  563. if (!_clusterMessageSocket) {
  564. Mutex::Lock _l(_termReason_m);
  565. _termReason = ONE_UNRECOVERABLE_ERROR;
  566. _fatalErrorMessage = "Cluster: can't determine my cluster member ID: unable to bind to any cluster message socket IP/port.";
  567. return _termReason;
  568. }
  569. if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S + "cluster-geo.exe").c_str()))
  570. _clusterGeoIpService = new ClusterGeoIpService((_homePath + ZT_PATH_SEPARATOR_S + "cluster-geo.exe").c_str());
  571. const ClusterDefinition::MemberDefinition &me = (*_clusterDefinition)[_clusterMemberId];
  572. InetAddress endpoints[255];
  573. unsigned int numEndpoints = 0;
  574. for(std::vector<InetAddress>::const_iterator i(me.zeroTierEndpoints.begin());i!=me.zeroTierEndpoints.end();++i)
  575. endpoints[numEndpoints++] = *i;
  576. if (_node->clusterInit(
  577. _clusterMemberId,
  578. reinterpret_cast<const struct sockaddr_storage *>(endpoints),
  579. numEndpoints,
  580. me.x,
  581. me.y,
  582. me.z,
  583. &SclusterSendFunction,
  584. this,
  585. (_clusterGeoIpService) ? &SclusterGeoIpFunction : 0,
  586. this) == ZT_RESULT_OK) {
  587. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  588. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  589. if (m->id != _clusterMemberId)
  590. _node->clusterAddMember(m->id);
  591. }
  592. }
  593. } else {
  594. delete _clusterDefinition;
  595. _clusterDefinition = (ClusterDefinition *)0;
  596. }
  597. }
  598. #endif
  599. _controlPlane = new ControlPlane(this,_node,(_homePath + ZT_PATH_SEPARATOR_S + "ui").c_str());
  600. _controlPlane->addAuthToken(authToken.c_str());
  601. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  602. _controlPlane->setController(_controller);
  603. #endif
  604. { // Remember networks from previous session
  605. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S + "networks.d").c_str()));
  606. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  607. std::size_t dot = f->find_last_of('.');
  608. if ((dot == 16)&&(f->substr(16) == ".conf"))
  609. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()),(void *)0);
  610. }
  611. }
  612. // Start two background threads to handle expensive ops out of line
  613. Thread::start(_node);
  614. Thread::start(_node);
  615. _nextBackgroundTaskDeadline = 0;
  616. uint64_t clockShouldBe = OSUtils::now();
  617. _lastRestart = clockShouldBe;
  618. uint64_t lastTapMulticastGroupCheck = 0;
  619. uint64_t lastTcpFallbackResolve = 0;
  620. 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
  621. #ifdef ZT_AUTO_UPDATE
  622. uint64_t lastSoftwareUpdateCheck = 0;
  623. #endif // ZT_AUTO_UPDATE
  624. for(;;) {
  625. _run_m.lock();
  626. if (!_run) {
  627. _run_m.unlock();
  628. _termReason_m.lock();
  629. _termReason = ONE_NORMAL_TERMINATION;
  630. _termReason_m.unlock();
  631. break;
  632. } else _run_m.unlock();
  633. uint64_t now = OSUtils::now();
  634. uint64_t dl = _nextBackgroundTaskDeadline;
  635. if (dl <= now) {
  636. _node->processBackgroundTasks(now,&_nextBackgroundTaskDeadline);
  637. dl = _nextBackgroundTaskDeadline;
  638. }
  639. // Attempt to detect sleep/wake events by detecting delay overruns
  640. if ((now > clockShouldBe)&&((now - clockShouldBe) > 2000))
  641. _lastRestart = now;
  642. #ifdef ZT_AUTO_UPDATE
  643. if ((now - lastSoftwareUpdateCheck) >= ZT_AUTO_UPDATE_CHECK_PERIOD) {
  644. lastSoftwareUpdateCheck = now;
  645. Thread::start(&backgroundSoftwareUpdateChecker);
  646. }
  647. #endif // ZT_AUTO_UPDATE
  648. if ((now - lastTcpFallbackResolve) >= ZT_TCP_FALLBACK_RERESOLVE_DELAY) {
  649. lastTcpFallbackResolve = now;
  650. _tcpFallbackResolver.resolveNow();
  651. }
  652. if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2)))
  653. _phy.close(_tcpFallbackTunnel->sock);
  654. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  655. lastTapMulticastGroupCheck = now;
  656. Mutex::Lock _l(_taps_m);
  657. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t) {
  658. std::vector<MulticastGroup> added,removed;
  659. t->second->scanMulticastGroups(added,removed);
  660. for(std::vector<MulticastGroup>::iterator m(added.begin());m!=added.end();++m)
  661. _node->multicastSubscribe(t->first,m->mac().toInt(),m->adi());
  662. for(std::vector<MulticastGroup>::iterator m(removed.begin());m!=removed.end();++m)
  663. _node->multicastUnsubscribe(t->first,m->mac().toInt(),m->adi());
  664. }
  665. }
  666. if ((now - lastLocalInterfaceAddressCheck) >= ZT_LOCAL_INTERFACE_CHECK_INTERVAL) {
  667. lastLocalInterfaceAddressCheck = now;
  668. _node->clearLocalInterfaceAddresses();
  669. #ifdef ZT_USE_MINIUPNPC
  670. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  671. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  672. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  673. #endif
  674. #ifdef __UNIX_LIKE__
  675. std::vector<std::string> ztDevices;
  676. {
  677. Mutex::Lock _l(_taps_m);
  678. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t)
  679. ztDevices.push_back(t->second->deviceName());
  680. }
  681. struct ifaddrs *ifatbl = (struct ifaddrs *)0;
  682. if ((getifaddrs(&ifatbl) == 0)&&(ifatbl)) {
  683. struct ifaddrs *ifa = ifatbl;
  684. while (ifa) {
  685. if ((ifa->ifa_name)&&(ifa->ifa_addr)&&(!isBlacklistedLocalInterfaceForZeroTierTraffic(ifa->ifa_name))) {
  686. bool isZT = false;
  687. for(std::vector<std::string>::const_iterator d(ztDevices.begin());d!=ztDevices.end();++d) {
  688. if (*d == ifa->ifa_name) {
  689. isZT = true;
  690. break;
  691. }
  692. }
  693. if (!isZT) {
  694. InetAddress ip(ifa->ifa_addr);
  695. ip.setPort(_port);
  696. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip));
  697. }
  698. }
  699. ifa = ifa->ifa_next;
  700. }
  701. freeifaddrs(ifatbl);
  702. }
  703. #endif // __UNIX_LIKE__
  704. #ifdef __WINDOWS__
  705. std::vector<NET_LUID> ztDevices;
  706. {
  707. Mutex::Lock _l(_taps_m);
  708. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t)
  709. ztDevices.push_back(t->second->luid());
  710. }
  711. char aabuf[16384];
  712. ULONG aalen = sizeof(aabuf);
  713. if (GetAdaptersAddresses(AF_UNSPEC,GAA_FLAG_SKIP_ANYCAST|GAA_FLAG_SKIP_MULTICAST|GAA_FLAG_SKIP_DNS_SERVER,(void *)0,reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf),&aalen) == NO_ERROR) {
  714. PIP_ADAPTER_ADDRESSES a = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf);
  715. while (a) {
  716. bool isZT = false;
  717. for(std::vector<NET_LUID>::const_iterator d(ztDevices.begin());d!=ztDevices.end();++d) {
  718. if (a->Luid.Value == d->Value) {
  719. isZT = true;
  720. break;
  721. }
  722. }
  723. if (!isZT) {
  724. PIP_ADAPTER_UNICAST_ADDRESS ua = a->FirstUnicastAddress;
  725. while (ua) {
  726. InetAddress ip(ua->Address.lpSockaddr);
  727. ip.setPort(_port);
  728. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip));
  729. ua = ua->Next;
  730. }
  731. }
  732. a = a->Next;
  733. }
  734. }
  735. #endif // __WINDOWS__
  736. }
  737. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  738. clockShouldBe = now + (uint64_t)delay;
  739. _phy.poll(delay);
  740. }
  741. } catch (std::exception &exc) {
  742. Mutex::Lock _l(_termReason_m);
  743. _termReason = ONE_UNRECOVERABLE_ERROR;
  744. _fatalErrorMessage = exc.what();
  745. } catch ( ... ) {
  746. Mutex::Lock _l(_termReason_m);
  747. _termReason = ONE_UNRECOVERABLE_ERROR;
  748. _fatalErrorMessage = "unexpected exception in main thread";
  749. }
  750. try {
  751. while (!_tcpConnections.empty())
  752. _phy.close((*_tcpConnections.begin())->sock);
  753. } catch ( ... ) {}
  754. {
  755. Mutex::Lock _l(_taps_m);
  756. for(std::map< uint64_t,EthernetTap * >::iterator t(_taps.begin());t!=_taps.end();++t)
  757. delete t->second;
  758. _taps.clear();
  759. }
  760. delete _controlPlane;
  761. _controlPlane = (ControlPlane *)0;
  762. delete _node;
  763. _node = (Node *)0;
  764. return _termReason;
  765. }
  766. virtual ReasonForTermination reasonForTermination() const
  767. {
  768. Mutex::Lock _l(_termReason_m);
  769. return _termReason;
  770. }
  771. virtual std::string fatalErrorMessage() const
  772. {
  773. Mutex::Lock _l(_termReason_m);
  774. return _fatalErrorMessage;
  775. }
  776. virtual std::string portDeviceName(uint64_t nwid) const
  777. {
  778. Mutex::Lock _l(_taps_m);
  779. std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.find(nwid));
  780. if (t != _taps.end())
  781. return t->second->deviceName();
  782. return std::string();
  783. }
  784. virtual bool tcpFallbackActive() const
  785. {
  786. return (_tcpFallbackTunnel != (TcpConnection *)0);
  787. }
  788. virtual void terminate()
  789. {
  790. _run_m.lock();
  791. _run = false;
  792. _run_m.unlock();
  793. _phy.whack();
  794. }
  795. // Begin private implementation methods
  796. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
  797. {
  798. #ifdef ZT_ENABLE_CLUSTER
  799. if (sock == _clusterMessageSocket) {
  800. _lastDirectReceiveFromGlobal = OSUtils::now();
  801. _node->clusterHandleIncomingMessage(data,len);
  802. return;
  803. }
  804. #endif
  805. #ifdef ZT_BREAK_UDP
  806. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  807. return;
  808. #endif
  809. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  810. _lastDirectReceiveFromGlobal = OSUtils::now();
  811. ZT_ResultCode rc = _node->processWirePacket(
  812. OSUtils::now(),
  813. reinterpret_cast<const struct sockaddr_storage *>(*uptr),
  814. (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
  815. data,
  816. len,
  817. &_nextBackgroundTaskDeadline);
  818. if (ZT_ResultCode_isFatal(rc)) {
  819. char tmp[256];
  820. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  821. Mutex::Lock _l(_termReason_m);
  822. _termReason = ONE_UNRECOVERABLE_ERROR;
  823. _fatalErrorMessage = tmp;
  824. this->terminate();
  825. }
  826. }
  827. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  828. {
  829. if (!success)
  830. return;
  831. // Outgoing TCP connections are always TCP fallback tunnel connections.
  832. TcpConnection *tc = new TcpConnection();
  833. _tcpConnections.insert(tc);
  834. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  835. tc->shouldKeepAlive = true;
  836. tc->parent = this;
  837. tc->sock = sock;
  838. // from and parser are not used
  839. tc->messageSize = 0; // unused
  840. tc->lastActivity = OSUtils::now();
  841. // HTTP stuff is not used
  842. tc->writeBuf = "";
  843. *uptr = (void *)tc;
  844. // Send "hello" message
  845. tc->writeBuf.push_back((char)0x17);
  846. tc->writeBuf.push_back((char)0x03);
  847. tc->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  848. tc->writeBuf.push_back((char)0x00);
  849. tc->writeBuf.push_back((char)0x04); // mlen == 4
  850. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MAJOR);
  851. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MINOR);
  852. tc->writeBuf.push_back((char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff));
  853. tc->writeBuf.push_back((char)(ZEROTIER_ONE_VERSION_REVISION & 0xff));
  854. _phy.setNotifyWritable(sock,true);
  855. _tcpFallbackTunnel = tc;
  856. }
  857. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  858. {
  859. // Incoming TCP connections are HTTP JSON API requests.
  860. TcpConnection *tc = new TcpConnection();
  861. _tcpConnections.insert(tc);
  862. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  863. tc->shouldKeepAlive = true;
  864. tc->parent = this;
  865. tc->sock = sockN;
  866. tc->from = from;
  867. http_parser_init(&(tc->parser),HTTP_REQUEST);
  868. tc->parser.data = (void *)tc;
  869. tc->messageSize = 0;
  870. tc->lastActivity = OSUtils::now();
  871. tc->currentHeaderField = "";
  872. tc->currentHeaderValue = "";
  873. tc->url = "";
  874. tc->status = "";
  875. tc->headers.clear();
  876. tc->body = "";
  877. tc->writeBuf = "";
  878. *uptrN = (void *)tc;
  879. }
  880. inline void phyOnTcpClose(PhySocket *sock,void **uptr)
  881. {
  882. TcpConnection *tc = (TcpConnection *)*uptr;
  883. if (tc) {
  884. if (tc == _tcpFallbackTunnel)
  885. _tcpFallbackTunnel = (TcpConnection *)0;
  886. _tcpConnections.erase(tc);
  887. delete tc;
  888. }
  889. }
  890. inline void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  891. {
  892. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  893. switch(tc->type) {
  894. case TcpConnection::TCP_HTTP_INCOMING:
  895. case TcpConnection::TCP_HTTP_OUTGOING:
  896. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  897. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK)) {
  898. _phy.close(sock);
  899. return;
  900. }
  901. break;
  902. case TcpConnection::TCP_TUNNEL_OUTGOING:
  903. tc->body.append((const char *)data,len);
  904. while (tc->body.length() >= 5) {
  905. const char *data = tc->body.data();
  906. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  907. if (tc->body.length() >= (mlen + 5)) {
  908. InetAddress from;
  909. unsigned long plen = mlen; // payload length, modified if there's an IP header
  910. data += 5; // skip forward past pseudo-TLS junk and mlen
  911. if (plen == 4) {
  912. // Hello message, which isn't sent by proxy and would be ignored by client
  913. } else if (plen) {
  914. // Messages should contain IPv4 or IPv6 source IP address data
  915. switch(data[0]) {
  916. case 4: // IPv4
  917. if (plen >= 7) {
  918. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  919. data += 7; // type + 4 byte IP + 2 byte port
  920. plen -= 7;
  921. } else {
  922. _phy.close(sock);
  923. return;
  924. }
  925. break;
  926. case 6: // IPv6
  927. if (plen >= 19) {
  928. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  929. data += 19; // type + 16 byte IP + 2 byte port
  930. plen -= 19;
  931. } else {
  932. _phy.close(sock);
  933. return;
  934. }
  935. break;
  936. case 0: // none/omitted
  937. ++data;
  938. --plen;
  939. break;
  940. default: // invalid address type
  941. _phy.close(sock);
  942. return;
  943. }
  944. if (from) {
  945. ZT_ResultCode rc = _node->processWirePacket(
  946. OSUtils::now(),
  947. &ZT_SOCKADDR_NULL,
  948. reinterpret_cast<struct sockaddr_storage *>(&from),
  949. data,
  950. plen,
  951. &_nextBackgroundTaskDeadline);
  952. if (ZT_ResultCode_isFatal(rc)) {
  953. char tmp[256];
  954. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  955. Mutex::Lock _l(_termReason_m);
  956. _termReason = ONE_UNRECOVERABLE_ERROR;
  957. _fatalErrorMessage = tmp;
  958. this->terminate();
  959. _phy.close(sock);
  960. return;
  961. }
  962. }
  963. }
  964. if (tc->body.length() > (mlen + 5))
  965. tc->body = tc->body.substr(mlen + 5);
  966. else tc->body = "";
  967. } else break;
  968. }
  969. break;
  970. }
  971. }
  972. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  973. {
  974. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  975. Mutex::Lock _l(tc->writeBuf_m);
  976. if (tc->writeBuf.length() > 0) {
  977. long sent = (long)_phy.streamSend(sock,tc->writeBuf.data(),(unsigned long)tc->writeBuf.length(),true);
  978. if (sent > 0) {
  979. tc->lastActivity = OSUtils::now();
  980. if ((unsigned long)sent >= (unsigned long)tc->writeBuf.length()) {
  981. tc->writeBuf = "";
  982. _phy.setNotifyWritable(sock,false);
  983. if (!tc->shouldKeepAlive)
  984. _phy.close(sock); // will call close handler to delete from _tcpConnections
  985. } else {
  986. tc->writeBuf = tc->writeBuf.substr(sent);
  987. }
  988. }
  989. } else {
  990. _phy.setNotifyWritable(sock,false);
  991. }
  992. }
  993. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  994. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  995. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  996. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  997. inline void phyOnUnixWritable(PhySocket *sock,void **uptr,bool lwip_invoked) {}
  998. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  999. {
  1000. Mutex::Lock _l(_taps_m);
  1001. std::map< uint64_t,EthernetTap * >::iterator t(_taps.find(nwid));
  1002. switch(op) {
  1003. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  1004. if (t == _taps.end()) {
  1005. try {
  1006. char friendlyName[1024];
  1007. Utils::snprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  1008. t = _taps.insert(std::pair< uint64_t,EthernetTap *>(nwid,new EthernetTap(
  1009. _homePath.c_str(),
  1010. MAC(nwc->mac),
  1011. nwc->mtu,
  1012. (unsigned int)ZT_IF_METRIC,
  1013. nwid,
  1014. friendlyName,
  1015. StapFrameHandler,
  1016. (void *)this))).first;
  1017. *nuptr = (void *)t->second;
  1018. } catch (std::exception &exc) {
  1019. #ifdef __WINDOWS__
  1020. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1021. if (tapFailLog) {
  1022. fprintf(tapFailLog,"%.16llx: %s"ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1023. fclose(tapFailLog);
  1024. }
  1025. #else
  1026. fprintf(stderr,"ERROR: unable to configure virtual network port: %s"ZT_EOL_S,exc.what());
  1027. #endif
  1028. return -999;
  1029. } catch ( ... ) {
  1030. return -999; // tap init failed
  1031. }
  1032. }
  1033. // fall through...
  1034. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1035. if (t != _taps.end()) {
  1036. t->second->setEnabled(nwc->enabled != 0);
  1037. std::vector<InetAddress> &assignedIps = _tapAssignedIps[nwid];
  1038. std::vector<InetAddress> newAssignedIps;
  1039. for(unsigned int i=0;i<nwc->assignedAddressCount;++i)
  1040. newAssignedIps.push_back(InetAddress(nwc->assignedAddresses[i]));
  1041. std::sort(newAssignedIps.begin(),newAssignedIps.end());
  1042. newAssignedIps.erase(std::unique(newAssignedIps.begin(),newAssignedIps.end()),newAssignedIps.end());
  1043. for(std::vector<InetAddress>::iterator ip(newAssignedIps.begin());ip!=newAssignedIps.end();++ip) {
  1044. if (!std::binary_search(assignedIps.begin(),assignedIps.end(),*ip))
  1045. if (!t->second->addIp(*ip))
  1046. fprintf(stderr,"ERROR: unable to add ip address %s"ZT_EOL_S, ip->toString().c_str());
  1047. }
  1048. for(std::vector<InetAddress>::iterator ip(assignedIps.begin());ip!=assignedIps.end();++ip) {
  1049. if (!std::binary_search(newAssignedIps.begin(),newAssignedIps.end(),*ip))
  1050. if (!t->second->removeIp(*ip))
  1051. fprintf(stderr,"ERROR: unable to remove ip address %s"ZT_EOL_S, ip->toString().c_str());
  1052. }
  1053. assignedIps.swap(newAssignedIps);
  1054. } else {
  1055. return -999; // tap init failed
  1056. }
  1057. break;
  1058. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1059. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1060. if (t != _taps.end()) {
  1061. #ifdef __WINDOWS__
  1062. std::string winInstanceId(t->second->instanceId());
  1063. #endif
  1064. *nuptr = (void *)0;
  1065. delete t->second;
  1066. _taps.erase(t);
  1067. _tapAssignedIps.erase(nwid);
  1068. #ifdef __WINDOWS__
  1069. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1070. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1071. #endif
  1072. }
  1073. break;
  1074. }
  1075. return 0;
  1076. }
  1077. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1078. {
  1079. switch(event) {
  1080. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  1081. Mutex::Lock _l(_termReason_m);
  1082. _termReason = ONE_IDENTITY_COLLISION;
  1083. _fatalErrorMessage = "identity/address collision";
  1084. this->terminate();
  1085. } break;
  1086. case ZT_EVENT_TRACE: {
  1087. if (metaData) {
  1088. ::fprintf(stderr,"%s"ZT_EOL_S,(const char *)metaData);
  1089. ::fflush(stderr);
  1090. }
  1091. } break;
  1092. default:
  1093. break;
  1094. }
  1095. }
  1096. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1097. {
  1098. std::string p(_dataStorePrepPath(name));
  1099. if (!p.length())
  1100. return -2;
  1101. FILE *f = fopen(p.c_str(),"rb");
  1102. if (!f)
  1103. return -1;
  1104. if (fseek(f,0,SEEK_END) != 0) {
  1105. fclose(f);
  1106. return -2;
  1107. }
  1108. long ts = ftell(f);
  1109. if (ts < 0) {
  1110. fclose(f);
  1111. return -2;
  1112. }
  1113. *totalSize = (unsigned long)ts;
  1114. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  1115. fclose(f);
  1116. return -2;
  1117. }
  1118. long n = (long)fread(buf,1,bufSize,f);
  1119. fclose(f);
  1120. return n;
  1121. }
  1122. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  1123. {
  1124. std::string p(_dataStorePrepPath(name));
  1125. if (!p.length())
  1126. return -2;
  1127. if (!data) {
  1128. OSUtils::rm(p.c_str());
  1129. return 0;
  1130. }
  1131. FILE *f = fopen(p.c_str(),"wb");
  1132. if (!f)
  1133. return -1;
  1134. if (fwrite(data,len,1,f) == 1) {
  1135. fclose(f);
  1136. if (secure)
  1137. OSUtils::lockDownFile(p.c_str(),false);
  1138. return 0;
  1139. } else {
  1140. fclose(f);
  1141. OSUtils::rm(p.c_str());
  1142. return -1;
  1143. }
  1144. }
  1145. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1146. {
  1147. #ifdef ZT_USE_MINIUPNPC
  1148. if ((localAddr->ss_family == AF_INET)&&(reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port == reinterpret_cast<const struct sockaddr_in *>(&_v4UpnpLocalAddress)->sin_port)) {
  1149. #ifdef ZT_BREAK_UDP
  1150. if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
  1151. #endif
  1152. if (addr->ss_family == AF_INET) {
  1153. if (ttl)
  1154. _phy.setIp4UdpTtl(_v4UpnpUdpSocket,ttl);
  1155. const int result = ((_phy.udpSend(_v4UpnpUdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
  1156. if (ttl)
  1157. _phy.setIp4UdpTtl(_v4UpnpUdpSocket,255);
  1158. return result;
  1159. } else {
  1160. return -1;
  1161. }
  1162. #ifdef ZT_BREAK_UDP
  1163. }
  1164. #endif
  1165. }
  1166. #endif // ZT_USE_MINIUPNPC
  1167. int result = -1;
  1168. switch(addr->ss_family) {
  1169. case AF_INET:
  1170. #ifdef ZT_BREAK_UDP
  1171. if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
  1172. #endif
  1173. if (_v4UdpSocket) {
  1174. if (ttl)
  1175. _phy.setIp4UdpTtl(_v4UdpSocket,ttl);
  1176. result = ((_phy.udpSend(_v4UdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
  1177. if (ttl)
  1178. _phy.setIp4UdpTtl(_v4UdpSocket,255);
  1179. }
  1180. #ifdef ZT_BREAK_UDP
  1181. }
  1182. #endif
  1183. #ifdef ZT_TCP_FALLBACK_RELAY
  1184. // TCP fallback tunnel support
  1185. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  1186. uint64_t now = OSUtils::now();
  1187. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  1188. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  1189. // valid direct traffic we'll stop using it and close the socket after a while.
  1190. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  1191. if (_tcpFallbackTunnel) {
  1192. Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
  1193. if (!_tcpFallbackTunnel->writeBuf.length())
  1194. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  1195. unsigned long mlen = len + 7;
  1196. _tcpFallbackTunnel->writeBuf.push_back((char)0x17);
  1197. _tcpFallbackTunnel->writeBuf.push_back((char)0x03);
  1198. _tcpFallbackTunnel->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1199. _tcpFallbackTunnel->writeBuf.push_back((char)((mlen >> 8) & 0xff));
  1200. _tcpFallbackTunnel->writeBuf.push_back((char)(mlen & 0xff));
  1201. _tcpFallbackTunnel->writeBuf.push_back((char)4); // IPv4
  1202. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  1203. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  1204. _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
  1205. result = 0;
  1206. } else if (((now - _lastSendToGlobal) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobal) > (ZT_PING_CHECK_INVERVAL / 2))) {
  1207. std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
  1208. if (tunnelIps.empty()) {
  1209. if (!_tcpFallbackResolver.running())
  1210. _tcpFallbackResolver.resolveNow();
  1211. } else {
  1212. bool connected = false;
  1213. InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
  1214. addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
  1215. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
  1216. }
  1217. }
  1218. }
  1219. _lastSendToGlobal = now;
  1220. }
  1221. #endif // ZT_TCP_FALLBACK_RELAY
  1222. break;
  1223. case AF_INET6:
  1224. #ifdef ZT_BREAK_UDP
  1225. if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
  1226. #endif
  1227. if (_v6UdpSocket)
  1228. result = ((_phy.udpSend(_v6UdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
  1229. #ifdef ZT_BREAK_UDP
  1230. }
  1231. #endif
  1232. break;
  1233. default:
  1234. return -1;
  1235. }
  1236. return result;
  1237. }
  1238. 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)
  1239. {
  1240. EthernetTap *tap = reinterpret_cast<EthernetTap *>(*nuptr);
  1241. if (!tap)
  1242. return;
  1243. tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1244. }
  1245. inline int nodePathCheckFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1246. {
  1247. Mutex::Lock _l(_taps_m);
  1248. for(std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.begin());t!=_taps.end();++t) {
  1249. if (t->second) {
  1250. std::vector<InetAddress> ips(t->second->ips());
  1251. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1252. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  1253. return 0;
  1254. }
  1255. }
  1256. }
  1257. }
  1258. return 1;
  1259. }
  1260. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1261. {
  1262. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1263. }
  1264. inline void onHttpRequestToServer(TcpConnection *tc)
  1265. {
  1266. char tmpn[256];
  1267. std::string data;
  1268. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1269. unsigned int scode = 404;
  1270. try {
  1271. if (_controlPlane)
  1272. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  1273. else scode = 500;
  1274. } catch ( ... ) {
  1275. scode = 500;
  1276. }
  1277. const char *scodestr;
  1278. switch(scode) {
  1279. case 200: scodestr = "OK"; break;
  1280. case 400: scodestr = "Bad Request"; break;
  1281. case 401: scodestr = "Unauthorized"; break;
  1282. case 403: scodestr = "Forbidden"; break;
  1283. case 404: scodestr = "Not Found"; break;
  1284. case 500: scodestr = "Internal Server Error"; break;
  1285. case 501: scodestr = "Not Implemented"; break;
  1286. case 503: scodestr = "Service Unavailable"; break;
  1287. default: scodestr = "Error"; break;
  1288. }
  1289. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  1290. {
  1291. Mutex::Lock _l(tc->writeBuf_m);
  1292. tc->writeBuf.assign(tmpn);
  1293. tc->writeBuf.append("Content-Type: ");
  1294. tc->writeBuf.append(contentType);
  1295. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  1296. tc->writeBuf.append(tmpn);
  1297. if (!tc->shouldKeepAlive)
  1298. tc->writeBuf.append("Connection: close\r\n");
  1299. tc->writeBuf.append("\r\n");
  1300. if (tc->parser.method != HTTP_HEAD)
  1301. tc->writeBuf.append(data);
  1302. }
  1303. _phy.setNotifyWritable(tc->sock,true);
  1304. }
  1305. inline void onHttpResponseFromClient(TcpConnection *tc)
  1306. {
  1307. if (!tc->shouldKeepAlive)
  1308. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConnections
  1309. }
  1310. std::string _dataStorePrepPath(const char *name) const
  1311. {
  1312. std::string p(_homePath);
  1313. p.push_back(ZT_PATH_SEPARATOR);
  1314. char lastc = (char)0;
  1315. for(const char *n=name;(*n);++n) {
  1316. if ((*n == '.')&&(lastc == '.'))
  1317. return std::string(); // don't allow ../../ stuff as a precaution
  1318. if (*n == '/') {
  1319. OSUtils::mkdir(p.c_str());
  1320. p.push_back(ZT_PATH_SEPARATOR);
  1321. } else p.push_back(*n);
  1322. lastc = *n;
  1323. }
  1324. return p;
  1325. }
  1326. const std::string _homePath;
  1327. BackgroundResolver _tcpFallbackResolver;
  1328. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  1329. SqliteNetworkController *_controller;
  1330. #endif
  1331. Phy<OneServiceImpl *> _phy;
  1332. Node *_node;
  1333. InetAddress _v4LocalAddress,_v6LocalAddress;
  1334. PhySocket *_v4UdpSocket;
  1335. PhySocket *_v6UdpSocket;
  1336. PhySocket *_v4TcpListenSocket;
  1337. PhySocket *_v6TcpListenSocket;
  1338. ControlPlane *_controlPlane;
  1339. uint64_t _lastDirectReceiveFromGlobal;
  1340. uint64_t _lastSendToGlobal;
  1341. uint64_t _lastRestart;
  1342. volatile uint64_t _nextBackgroundTaskDeadline;
  1343. std::map< uint64_t,EthernetTap * > _taps;
  1344. std::map< uint64_t,std::vector<InetAddress> > _tapAssignedIps; // ZeroTier assigned IPs, not user or dhcp assigned
  1345. Mutex _taps_m;
  1346. std::set< TcpConnection * > _tcpConnections; // no mutex for this since it's done in the main loop thread only
  1347. TcpConnection *_tcpFallbackTunnel;
  1348. ReasonForTermination _termReason;
  1349. std::string _fatalErrorMessage;
  1350. Mutex _termReason_m;
  1351. unsigned int _port;
  1352. #ifdef ZT_USE_MINIUPNPC
  1353. InetAddress _v4UpnpLocalAddress;
  1354. PhySocket *_v4UpnpUdpSocket;
  1355. PortMapper *_portMapper;
  1356. #endif
  1357. #ifdef ZT_ENABLE_CLUSTER
  1358. PhySocket *_clusterMessageSocket;
  1359. ClusterGeoIpService *_clusterGeoIpService;
  1360. ClusterDefinition *_clusterDefinition;
  1361. unsigned int _clusterMemberId;
  1362. #endif
  1363. bool _run;
  1364. Mutex _run_m;
  1365. };
  1366. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  1367. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  1368. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData)
  1369. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1370. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1371. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  1372. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  1373. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  1374. 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)
  1375. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localAddr,addr,data,len,ttl); }
  1376. 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)
  1377. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  1378. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1379. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(localAddr,remoteAddr); }
  1380. #ifdef ZT_ENABLE_CLUSTER
  1381. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len)
  1382. {
  1383. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1384. const ClusterDefinition::MemberDefinition &md = (*(impl->_clusterDefinition))[toMemberId];
  1385. if (md.clusterEndpoint)
  1386. impl->_phy.udpSend(impl->_clusterMessageSocket,reinterpret_cast<const struct sockaddr *>(&(md.clusterEndpoint)),data,len);
  1387. }
  1388. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z)
  1389. {
  1390. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1391. return (int)(impl->_clusterGeoIpService->locate(*(reinterpret_cast<const InetAddress *>(addr)),*x,*y,*z));
  1392. }
  1393. #endif
  1394. 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)
  1395. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1396. static int ShttpOnMessageBegin(http_parser *parser)
  1397. {
  1398. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1399. tc->currentHeaderField = "";
  1400. tc->currentHeaderValue = "";
  1401. tc->messageSize = 0;
  1402. tc->url = "";
  1403. tc->status = "";
  1404. tc->headers.clear();
  1405. tc->body = "";
  1406. return 0;
  1407. }
  1408. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  1409. {
  1410. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1411. tc->messageSize += (unsigned long)length;
  1412. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1413. return -1;
  1414. tc->url.append(ptr,length);
  1415. return 0;
  1416. }
  1417. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1418. {
  1419. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1420. tc->messageSize += (unsigned long)length;
  1421. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1422. return -1;
  1423. tc->status.append(ptr,length);
  1424. return 0;
  1425. }
  1426. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1427. {
  1428. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1429. tc->messageSize += (unsigned long)length;
  1430. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1431. return -1;
  1432. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1433. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1434. tc->currentHeaderField = "";
  1435. tc->currentHeaderValue = "";
  1436. }
  1437. for(size_t i=0;i<length;++i)
  1438. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1439. return 0;
  1440. }
  1441. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1442. {
  1443. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1444. tc->messageSize += (unsigned long)length;
  1445. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1446. return -1;
  1447. tc->currentHeaderValue.append(ptr,length);
  1448. return 0;
  1449. }
  1450. static int ShttpOnHeadersComplete(http_parser *parser)
  1451. {
  1452. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1453. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  1454. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1455. return 0;
  1456. }
  1457. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  1458. {
  1459. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1460. tc->messageSize += (unsigned long)length;
  1461. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1462. return -1;
  1463. tc->body.append(ptr,length);
  1464. return 0;
  1465. }
  1466. static int ShttpOnMessageComplete(http_parser *parser)
  1467. {
  1468. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1469. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  1470. tc->lastActivity = OSUtils::now();
  1471. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  1472. tc->parent->onHttpRequestToServer(tc);
  1473. } else {
  1474. tc->parent->onHttpResponseFromClient(tc);
  1475. }
  1476. return 0;
  1477. }
  1478. } // anonymous namespace
  1479. std::string OneService::platformDefaultHomePath()
  1480. {
  1481. #ifdef __UNIX_LIKE__
  1482. #ifdef __APPLE__
  1483. // /Library/... on Apple
  1484. return std::string("/Library/Application Support/ZeroTier/One");
  1485. #else
  1486. #ifdef __BSD__
  1487. // BSD likes /var/db instead of /var/lib
  1488. return std::string("/var/db/zerotier-one");
  1489. #else
  1490. // Use /var/lib for Linux and other *nix
  1491. return std::string("/var/lib/zerotier-one");
  1492. #endif
  1493. #endif
  1494. #else // not __UNIX_LIKE__
  1495. #ifdef __WINDOWS__
  1496. // Look up app data folder on Windows, e.g. C:\ProgramData\...
  1497. char buf[16384];
  1498. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_COMMON_APPDATA,NULL,0,buf)))
  1499. return (std::string(buf) + "\\ZeroTier\\One");
  1500. else return std::string("C:\\ZeroTier\\One");
  1501. #else
  1502. return std::string(); // UNKNOWN PLATFORM
  1503. #endif
  1504. #endif // __UNIX_LIKE__ or not...
  1505. }
  1506. std::string OneService::autoUpdateUrl()
  1507. {
  1508. #ifdef ZT_AUTO_UPDATE
  1509. /*
  1510. #if defined(__LINUX__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1511. if (sizeof(void *) == 8)
  1512. return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x64-LATEST.nfo";
  1513. else return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x86-LATEST.nfo";
  1514. #endif
  1515. */
  1516. #if defined(__APPLE__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1517. return "http://download.zerotier.com/update/mac_intel/";
  1518. #endif
  1519. #ifdef __WINDOWS__
  1520. return "http://download.zerotier.com/update/win_intel/";
  1521. #endif
  1522. #endif // ZT_AUTO_UPDATE
  1523. return std::string();
  1524. }
  1525. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  1526. OneService::~OneService() {}
  1527. } // namespace ZeroTier