OneService.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <stdint.h>
  31. #include <string>
  32. #include <map>
  33. #include <set>
  34. #include <vector>
  35. #include <algorithm>
  36. #include "../version.h"
  37. #include "../include/ZeroTierOne.h"
  38. #include "../ext/http-parser/http_parser.h"
  39. #include "../node/Constants.hpp"
  40. #include "../node/Mutex.hpp"
  41. #include "../node/Node.hpp"
  42. #include "../node/Utils.hpp"
  43. #include "../node/InetAddress.hpp"
  44. #include "../node/MAC.hpp"
  45. #include "../node/Identity.hpp"
  46. #include "../osdep/Phy.hpp"
  47. #include "../osdep/Thread.hpp"
  48. #include "../osdep/OSUtils.hpp"
  49. #include "../osdep/Http.hpp"
  50. #include "../osdep/BackgroundResolver.hpp"
  51. #include "OneService.hpp"
  52. #include "ControlPlane.hpp"
  53. /**
  54. * Uncomment to enable UDP breakage switch
  55. *
  56. * If this is defined, the presence of a file called /tmp/ZT_BREAK_UDP
  57. * will cause direct UDP TX/RX to stop working. This can be used to
  58. * test TCP tunneling fallback and other robustness features. Deleting
  59. * this file will cause it to start working again.
  60. */
  61. //#define ZT_BREAK_UDP
  62. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  63. #include "../controller/SqliteNetworkController.hpp"
  64. #else
  65. class SqliteNetworkController;
  66. #endif // ZT_ENABLE_NETWORK_CONTROLLER
  67. #ifdef __WINDOWS__
  68. #include <WinSock2.h>
  69. #include <Windows.h>
  70. #include <ShlObj.h>
  71. #include <netioapi.h>
  72. #include <iphlpapi.h>
  73. #else
  74. #include <sys/types.h>
  75. #include <sys/socket.h>
  76. #include <sys/wait.h>
  77. #include <unistd.h>
  78. #include <ifaddrs.h>
  79. #endif
  80. // Include the right tap device driver for this platform -- add new platforms here
  81. #ifdef __APPLE__
  82. #include "../osdep/OSXEthernetTap.hpp"
  83. namespace ZeroTier { typedef OSXEthernetTap EthernetTap; }
  84. #endif
  85. #ifdef __LINUX__
  86. #include "../osdep/LinuxEthernetTap.hpp"
  87. namespace ZeroTier { typedef LinuxEthernetTap EthernetTap; }
  88. #endif
  89. #ifdef __WINDOWS__
  90. #include "../osdep/WindowsEthernetTap.hpp"
  91. namespace ZeroTier { typedef WindowsEthernetTap EthernetTap; }
  92. #endif
  93. #ifdef __FreeBSD__
  94. #include "../osdep/BSDEthernetTap.hpp"
  95. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  96. #endif
  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 30000
  104. // Path under ZT1 home for controller database if controller is enabled
  105. #define ZT1_CONTROLLER_DB_PATH "controller.db"
  106. // TCP fallback relay host -- geo-distributed using Amazon Route53 geo-aware DNS
  107. #define ZT1_TCP_FALLBACK_RELAY "tcp-fallback.zerotier.com"
  108. #define ZT1_TCP_FALLBACK_RELAY_PORT 443
  109. // Frequency at which we re-resolve the TCP fallback relay
  110. #define ZT1_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 ZT1_TCP_FALLBACK_AFTER 60000
  113. // How often to check for local interface addresses
  114. #define ZT1_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. class OneServiceImpl;
  304. static int SnodeVirtualNetworkConfigFunction(ZT1_Node *node,void *uptr,uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwconf);
  305. static void SnodeEventCallback(ZT1_Node *node,void *uptr,enum ZT1_Event event,const void *metaData);
  306. static long SnodeDataStoreGetFunction(ZT1_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize);
  307. static int SnodeDataStorePutFunction(ZT1_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure);
  308. static int SnodeWirePacketSendFunction(ZT1_Node *node,void *uptr,const struct sockaddr_storage *addr,const void *data,unsigned int len);
  309. static void SnodeVirtualNetworkFrameFunction(ZT1_Node *node,void *uptr,uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  310. 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);
  311. static int ShttpOnMessageBegin(http_parser *parser);
  312. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  313. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  314. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  315. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  316. static int ShttpOnHeadersComplete(http_parser *parser);
  317. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  318. static int ShttpOnMessageComplete(http_parser *parser);
  319. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  320. ShttpOnMessageBegin,
  321. ShttpOnUrl,
  322. ShttpOnStatus,
  323. ShttpOnHeaderField,
  324. ShttpOnValue,
  325. ShttpOnHeadersComplete,
  326. ShttpOnBody,
  327. ShttpOnMessageComplete
  328. };
  329. struct TcpConnection
  330. {
  331. enum {
  332. TCP_HTTP_INCOMING,
  333. TCP_HTTP_OUTGOING, // not currently used
  334. TCP_TUNNEL_OUTGOING // fale-SSL outgoing tunnel -- HTTP-related fields are not used
  335. } type;
  336. bool shouldKeepAlive;
  337. OneServiceImpl *parent;
  338. PhySocket *sock;
  339. InetAddress from;
  340. http_parser parser;
  341. unsigned long messageSize;
  342. uint64_t lastActivity;
  343. std::string currentHeaderField;
  344. std::string currentHeaderValue;
  345. std::string url;
  346. std::string status;
  347. std::map< std::string,std::string > headers;
  348. std::string body;
  349. std::string writeBuf;
  350. Mutex writeBuf_m;
  351. };
  352. class OneServiceImpl : public OneService
  353. {
  354. public:
  355. OneServiceImpl(const char *hp,unsigned int port,const char *overrideRootTopology) :
  356. _homePath((hp) ? hp : "."),
  357. _tcpFallbackResolver(ZT1_TCP_FALLBACK_RELAY),
  358. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  359. _controller((_homePath + ZT_PATH_SEPARATOR_S + ZT1_CONTROLLER_DB_PATH).c_str()),
  360. #endif
  361. _phy(this,false),
  362. _overrideRootTopology((overrideRootTopology) ? overrideRootTopology : ""),
  363. _node((Node *)0),
  364. _controlPlane((ControlPlane *)0),
  365. _lastDirectReceiveFromGlobal(0),
  366. _lastSendToGlobal(0),
  367. _lastRestart(0),
  368. _nextBackgroundTaskDeadline(0),
  369. _tcpFallbackTunnel((TcpConnection *)0),
  370. _termReason(ONE_STILL_RUNNING),
  371. _port(port),
  372. _run(true)
  373. {
  374. struct sockaddr_in in4;
  375. struct sockaddr_in6 in6;
  376. ::memset((void *)&in4,0,sizeof(in4));
  377. in4.sin_family = AF_INET;
  378. in4.sin_port = Utils::hton((uint16_t)port);
  379. _v4UdpSocket = _phy.udpBind((const struct sockaddr *)&in4,this,131072);
  380. if (!_v4UdpSocket)
  381. throw std::runtime_error("cannot bind to port (UDP/IPv4)");
  382. in4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001); // right now we just listen for TCP @localhost
  383. _v4TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
  384. if (!_v4TcpListenSocket) {
  385. _phy.close(_v4UdpSocket);
  386. throw std::runtime_error("cannot bind to port (TCP/IPv4)");
  387. }
  388. ::memset((void *)&in6,0,sizeof(in6));
  389. in6.sin6_family = AF_INET6;
  390. in6.sin6_port = in4.sin_port;
  391. _v6UdpSocket = _phy.udpBind((const struct sockaddr *)&in6,this,131072);
  392. in6.sin6_addr.s6_addr[15] = 1; // listen for TCP only at localhost
  393. _v6TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
  394. char portstr[64];
  395. Utils::snprintf(portstr,sizeof(portstr),"%u",port);
  396. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),std::string(portstr));
  397. }
  398. virtual ~OneServiceImpl()
  399. {
  400. _phy.close(_v4UdpSocket);
  401. _phy.close(_v6UdpSocket);
  402. _phy.close(_v4TcpListenSocket);
  403. _phy.close(_v6TcpListenSocket);
  404. }
  405. virtual ReasonForTermination run()
  406. {
  407. try {
  408. std::string authToken;
  409. {
  410. std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  411. if (!OSUtils::readFile(authTokenPath.c_str(),authToken)) {
  412. unsigned char foo[24];
  413. Utils::getSecureRandom(foo,sizeof(foo));
  414. authToken = "";
  415. for(unsigned int i=0;i<sizeof(foo);++i)
  416. authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  417. if (!OSUtils::writeFile(authTokenPath.c_str(),authToken)) {
  418. Mutex::Lock _l(_termReason_m);
  419. _termReason = ONE_UNRECOVERABLE_ERROR;
  420. _fatalErrorMessage = "authtoken.secret could not be written";
  421. return _termReason;
  422. } else OSUtils::lockDownFile(authTokenPath.c_str(),false);
  423. }
  424. }
  425. authToken = Utils::trim(authToken);
  426. _node = new Node(
  427. OSUtils::now(),
  428. this,
  429. SnodeDataStoreGetFunction,
  430. SnodeDataStorePutFunction,
  431. SnodeWirePacketSendFunction,
  432. SnodeVirtualNetworkFrameFunction,
  433. SnodeVirtualNetworkConfigFunction,
  434. SnodeEventCallback,
  435. ((_overrideRootTopology.length() > 0) ? _overrideRootTopology.c_str() : (const char *)0));
  436. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  437. _node->setNetconfMaster((void *)&_controller);
  438. #endif
  439. _controlPlane = new ControlPlane(this,_node,(_homePath + ZT_PATH_SEPARATOR_S + "ui").c_str());
  440. _controlPlane->addAuthToken(authToken.c_str());
  441. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  442. _controlPlane->setController(&_controller);
  443. #endif
  444. { // Remember networks from previous session
  445. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S + "networks.d").c_str()));
  446. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  447. std::size_t dot = f->find_last_of('.');
  448. if ((dot == 16)&&(f->substr(16) == ".conf"))
  449. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()));
  450. }
  451. }
  452. _nextBackgroundTaskDeadline = 0;
  453. uint64_t clockShouldBe = OSUtils::now();
  454. _lastRestart = clockShouldBe;
  455. uint64_t lastTapMulticastGroupCheck = 0;
  456. uint64_t lastTcpFallbackResolve = 0;
  457. uint64_t lastLocalInterfaceAddressCheck = 0;
  458. #ifdef ZT_AUTO_UPDATE
  459. uint64_t lastSoftwareUpdateCheck = 0;
  460. #endif // ZT_AUTO_UPDATE
  461. for(;;) {
  462. _run_m.lock();
  463. if (!_run) {
  464. _run_m.unlock();
  465. _termReason_m.lock();
  466. _termReason = ONE_NORMAL_TERMINATION;
  467. _termReason_m.unlock();
  468. break;
  469. } else _run_m.unlock();
  470. uint64_t now = OSUtils::now();
  471. uint64_t dl = _nextBackgroundTaskDeadline;
  472. if (dl <= now) {
  473. _node->processBackgroundTasks(now,&_nextBackgroundTaskDeadline);
  474. dl = _nextBackgroundTaskDeadline;
  475. }
  476. // Attempt to detect sleep/wake events by detecting delay overruns
  477. if ((now > clockShouldBe)&&((now - clockShouldBe) > 2000))
  478. _lastRestart = now;
  479. #ifdef ZT_AUTO_UPDATE
  480. if ((now - lastSoftwareUpdateCheck) >= ZT_AUTO_UPDATE_CHECK_PERIOD) {
  481. lastSoftwareUpdateCheck = OSUtils::now();
  482. Thread::start(&backgroundSoftwareUpdateChecker);
  483. }
  484. #endif // ZT_AUTO_UPDATE
  485. if ((now - lastTcpFallbackResolve) >= ZT1_TCP_FALLBACK_RERESOLVE_DELAY) {
  486. lastTcpFallbackResolve = now;
  487. _tcpFallbackResolver.resolveNow();
  488. }
  489. if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT1_TCP_FALLBACK_AFTER / 2)))
  490. _phy.close(_tcpFallbackTunnel->sock);
  491. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  492. lastTapMulticastGroupCheck = now;
  493. Mutex::Lock _l(_taps_m);
  494. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t) {
  495. std::vector<MulticastGroup> added,removed;
  496. t->second->scanMulticastGroups(added,removed);
  497. for(std::vector<MulticastGroup>::iterator m(added.begin());m!=added.end();++m)
  498. _node->multicastSubscribe(t->first,m->mac().toInt(),m->adi());
  499. for(std::vector<MulticastGroup>::iterator m(removed.begin());m!=removed.end();++m)
  500. _node->multicastUnsubscribe(t->first,m->mac().toInt(),m->adi());
  501. }
  502. }
  503. if ((now - lastLocalInterfaceAddressCheck) >= ZT1_LOCAL_INTERFACE_CHECK_INTERVAL) {
  504. lastLocalInterfaceAddressCheck = now;
  505. #ifdef __UNIX_LIKE__
  506. std::vector<std::string> ztDevices;
  507. {
  508. Mutex::Lock _l(_taps_m);
  509. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t)
  510. ztDevices.push_back(t->second->deviceName());
  511. }
  512. struct ifaddrs *ifatbl = (struct ifaddrs *)0;
  513. if ((getifaddrs(&ifatbl) == 0)&&(ifatbl)) {
  514. _node->clearLocalInterfaceAddresses();
  515. struct ifaddrs *ifa = ifatbl;
  516. while (ifa) {
  517. if ((ifa->ifa_name)&&(ifa->ifa_addr)) {
  518. bool isZT = false;
  519. for(std::vector<std::string>::const_iterator d(ztDevices.begin());d!=ztDevices.end();++d) {
  520. if (*d == ifa->ifa_name) {
  521. isZT = true;
  522. break;
  523. }
  524. }
  525. if (!isZT) {
  526. InetAddress ip(ifa->ifa_addr);
  527. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6)) {
  528. switch(ip.ipScope()) {
  529. case InetAddress::IP_SCOPE_LINK_LOCAL:
  530. case InetAddress::IP_SCOPE_PRIVATE:
  531. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  532. case InetAddress::IP_SCOPE_SHARED:
  533. case InetAddress::IP_SCOPE_GLOBAL:
  534. ip.setPort(_port);
  535. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip),0,ZT1_LOCAL_INTERFACE_ADDRESS_TRUST_NORMAL,0);
  536. break;
  537. default:
  538. break;
  539. }
  540. }
  541. }
  542. }
  543. ifa = ifa->ifa_next;
  544. }
  545. freeifaddrs(ifatbl);
  546. }
  547. #endif // __UNIX_LIKE__
  548. #ifdef __WINDOWS__
  549. std::vector<NET_LUID> ztDevices;
  550. {
  551. Mutex::Lock _l(_taps_m);
  552. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t)
  553. ztDevices.push_back(t->second->luid());
  554. }
  555. char aabuf[16384];
  556. ULONG aalen = sizeof(aabuf);
  557. 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) {
  558. PIP_ADAPTER_ADDRESSES a = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf);
  559. while (a) {
  560. bool isZT = false;
  561. for(std::vector<NET_LUID>::const_iterator d(ztDevices.begin());d!=ztDevices.end();++d) {
  562. if (a->Luid.Value == d->Value) {
  563. isZT = true;
  564. break;
  565. }
  566. }
  567. if (!isZT) {
  568. PIP_ADAPTER_UNICAST_ADDRESS ua = a->FirstUnicastAddress;
  569. while (ua) {
  570. InetAddress ip(ua->Address.lpSockaddr);
  571. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6)) {
  572. switch(ip.ipScope()) {
  573. case InetAddress::IP_SCOPE_LINK_LOCAL:
  574. case InetAddress::IP_SCOPE_PRIVATE:
  575. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  576. case InetAddress::IP_SCOPE_SHARED:
  577. case InetAddress::IP_SCOPE_GLOBAL:
  578. ip.setPort(_port);
  579. printf("found %s on %S\r\n",ip.toString().c_str(),a->FriendlyName);
  580. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip),0,ZT1_LOCAL_INTERFACE_ADDRESS_TRUST_NORMAL,0);
  581. break;
  582. default:
  583. break;
  584. }
  585. }
  586. ua = ua->Next;
  587. }
  588. }
  589. a = a->Next;
  590. }
  591. }
  592. #endif // __WINDOWS__
  593. }
  594. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  595. clockShouldBe = now + (uint64_t)delay;
  596. _phy.poll(delay);
  597. }
  598. } catch (std::exception &exc) {
  599. Mutex::Lock _l(_termReason_m);
  600. _termReason = ONE_UNRECOVERABLE_ERROR;
  601. _fatalErrorMessage = exc.what();
  602. } catch ( ... ) {
  603. Mutex::Lock _l(_termReason_m);
  604. _termReason = ONE_UNRECOVERABLE_ERROR;
  605. _fatalErrorMessage = "unexpected exception in main thread";
  606. }
  607. try {
  608. while (!_tcpConnections.empty())
  609. _phy.close((*_tcpConnections.begin())->sock);
  610. } catch ( ... ) {}
  611. {
  612. Mutex::Lock _l(_taps_m);
  613. for(std::map< uint64_t,EthernetTap * >::iterator t(_taps.begin());t!=_taps.end();++t)
  614. delete t->second;
  615. _taps.clear();
  616. }
  617. delete _controlPlane;
  618. _controlPlane = (ControlPlane *)0;
  619. delete _node;
  620. _node = (Node *)0;
  621. return _termReason;
  622. }
  623. virtual ReasonForTermination reasonForTermination() const
  624. {
  625. Mutex::Lock _l(_termReason_m);
  626. return _termReason;
  627. }
  628. virtual std::string fatalErrorMessage() const
  629. {
  630. Mutex::Lock _l(_termReason_m);
  631. return _fatalErrorMessage;
  632. }
  633. virtual std::string portDeviceName(uint64_t nwid) const
  634. {
  635. Mutex::Lock _l(_taps_m);
  636. std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.find(nwid));
  637. if (t != _taps.end())
  638. return t->second->deviceName();
  639. return std::string();
  640. }
  641. virtual bool tcpFallbackActive() const
  642. {
  643. return (_tcpFallbackTunnel != (TcpConnection *)0);
  644. }
  645. virtual void terminate()
  646. {
  647. _run_m.lock();
  648. _run = false;
  649. _run_m.unlock();
  650. _phy.whack();
  651. }
  652. // Begin private implementation methods
  653. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
  654. {
  655. #ifdef ZT_BREAK_UDP
  656. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  657. return;
  658. #endif
  659. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  660. _lastDirectReceiveFromGlobal = OSUtils::now();
  661. ZT1_ResultCode rc = _node->processWirePacket(
  662. OSUtils::now(),
  663. (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
  664. data,
  665. len,
  666. &_nextBackgroundTaskDeadline);
  667. if (ZT1_ResultCode_isFatal(rc)) {
  668. char tmp[256];
  669. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  670. Mutex::Lock _l(_termReason_m);
  671. _termReason = ONE_UNRECOVERABLE_ERROR;
  672. _fatalErrorMessage = tmp;
  673. this->terminate();
  674. }
  675. }
  676. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  677. {
  678. if (!success)
  679. return;
  680. // Outgoing TCP connections are always TCP fallback tunnel connections.
  681. TcpConnection *tc = new TcpConnection();
  682. _tcpConnections.insert(tc);
  683. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  684. tc->shouldKeepAlive = true;
  685. tc->parent = this;
  686. tc->sock = sock;
  687. // from and parser are not used
  688. tc->messageSize = 0; // unused
  689. tc->lastActivity = OSUtils::now();
  690. // HTTP stuff is not used
  691. tc->writeBuf = "";
  692. *uptr = (void *)tc;
  693. // Send "hello" message
  694. tc->writeBuf.push_back((char)0x17);
  695. tc->writeBuf.push_back((char)0x03);
  696. tc->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  697. tc->writeBuf.push_back((char)0x00);
  698. tc->writeBuf.push_back((char)0x04); // mlen == 4
  699. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MAJOR);
  700. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MINOR);
  701. tc->writeBuf.push_back((char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff));
  702. tc->writeBuf.push_back((char)(ZEROTIER_ONE_VERSION_REVISION & 0xff));
  703. _phy.tcpSetNotifyWritable(sock,true);
  704. _tcpFallbackTunnel = tc;
  705. }
  706. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  707. {
  708. // Incoming TCP connections are HTTP JSON API requests.
  709. TcpConnection *tc = new TcpConnection();
  710. _tcpConnections.insert(tc);
  711. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  712. tc->shouldKeepAlive = true;
  713. tc->parent = this;
  714. tc->sock = sockN;
  715. tc->from = from;
  716. http_parser_init(&(tc->parser),HTTP_REQUEST);
  717. tc->parser.data = (void *)tc;
  718. tc->messageSize = 0;
  719. tc->lastActivity = OSUtils::now();
  720. tc->currentHeaderField = "";
  721. tc->currentHeaderValue = "";
  722. tc->url = "";
  723. tc->status = "";
  724. tc->headers.clear();
  725. tc->body = "";
  726. tc->writeBuf = "";
  727. *uptrN = (void *)tc;
  728. }
  729. inline void phyOnTcpClose(PhySocket *sock,void **uptr)
  730. {
  731. TcpConnection *tc = (TcpConnection *)*uptr;
  732. if (tc) {
  733. if (tc == _tcpFallbackTunnel)
  734. _tcpFallbackTunnel = (TcpConnection *)0;
  735. _tcpConnections.erase(tc);
  736. delete tc;
  737. }
  738. }
  739. inline void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  740. {
  741. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  742. switch(tc->type) {
  743. case TcpConnection::TCP_HTTP_INCOMING:
  744. case TcpConnection::TCP_HTTP_OUTGOING:
  745. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  746. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK)) {
  747. _phy.close(sock);
  748. return;
  749. }
  750. break;
  751. case TcpConnection::TCP_TUNNEL_OUTGOING:
  752. tc->body.append((const char *)data,len);
  753. while (tc->body.length() >= 5) {
  754. const char *data = tc->body.data();
  755. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  756. if (tc->body.length() >= (mlen + 5)) {
  757. InetAddress from;
  758. unsigned long plen = mlen; // payload length, modified if there's an IP header
  759. data += 5; // skip forward past pseudo-TLS junk and mlen
  760. if (plen == 4) {
  761. // Hello message, which isn't sent by proxy and would be ignored by client
  762. } else if (plen) {
  763. // Messages should contain IPv4 or IPv6 source IP address data
  764. switch(data[0]) {
  765. case 4: // IPv4
  766. if (plen >= 7) {
  767. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  768. data += 7; // type + 4 byte IP + 2 byte port
  769. plen -= 7;
  770. } else {
  771. _phy.close(sock);
  772. return;
  773. }
  774. break;
  775. case 6: // IPv6
  776. if (plen >= 19) {
  777. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  778. data += 19; // type + 16 byte IP + 2 byte port
  779. plen -= 19;
  780. } else {
  781. _phy.close(sock);
  782. return;
  783. }
  784. break;
  785. case 0: // none/omitted
  786. ++data;
  787. --plen;
  788. break;
  789. default: // invalid address type
  790. _phy.close(sock);
  791. return;
  792. }
  793. if (from) {
  794. ZT1_ResultCode rc = _node->processWirePacket(
  795. OSUtils::now(),
  796. reinterpret_cast<struct sockaddr_storage *>(&from),
  797. data,
  798. plen,
  799. &_nextBackgroundTaskDeadline);
  800. if (ZT1_ResultCode_isFatal(rc)) {
  801. char tmp[256];
  802. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  803. Mutex::Lock _l(_termReason_m);
  804. _termReason = ONE_UNRECOVERABLE_ERROR;
  805. _fatalErrorMessage = tmp;
  806. this->terminate();
  807. _phy.close(sock);
  808. return;
  809. }
  810. }
  811. }
  812. if (tc->body.length() > (mlen + 5))
  813. tc->body = tc->body.substr(mlen + 5);
  814. else tc->body = "";
  815. } else break;
  816. }
  817. break;
  818. }
  819. }
  820. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  821. {
  822. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  823. Mutex::Lock _l(tc->writeBuf_m);
  824. if (tc->writeBuf.length() > 0) {
  825. long sent = (long)_phy.tcpSend(sock,tc->writeBuf.data(),(unsigned long)tc->writeBuf.length(),true);
  826. if (sent > 0) {
  827. tc->lastActivity = OSUtils::now();
  828. if ((unsigned long)sent >= (unsigned long)tc->writeBuf.length()) {
  829. tc->writeBuf = "";
  830. _phy.tcpSetNotifyWritable(sock,false);
  831. if (!tc->shouldKeepAlive)
  832. _phy.close(sock); // will call close handler to delete from _tcpConnections
  833. } else {
  834. tc->writeBuf = tc->writeBuf.substr(sent);
  835. }
  836. }
  837. } else {
  838. _phy.tcpSetNotifyWritable(sock,false);
  839. }
  840. }
  841. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwc)
  842. {
  843. Mutex::Lock _l(_taps_m);
  844. std::map< uint64_t,EthernetTap * >::iterator t(_taps.find(nwid));
  845. switch(op) {
  846. case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  847. if (t == _taps.end()) {
  848. try {
  849. char friendlyName[1024];
  850. Utils::snprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  851. t = _taps.insert(std::pair< uint64_t,EthernetTap *>(nwid,new EthernetTap(
  852. _homePath.c_str(),
  853. MAC(nwc->mac),
  854. nwc->mtu,
  855. (unsigned int)ZT_IF_METRIC,
  856. nwid,
  857. friendlyName,
  858. StapFrameHandler,
  859. (void *)this))).first;
  860. } catch ( ... ) {
  861. return -999; // tap init failed
  862. }
  863. }
  864. // fall through...
  865. case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  866. if (t != _taps.end()) {
  867. t->second->setEnabled(nwc->enabled != 0);
  868. std::vector<InetAddress> &assignedIps = _tapAssignedIps[nwid];
  869. std::vector<InetAddress> newAssignedIps;
  870. for(unsigned int i=0;i<nwc->assignedAddressCount;++i)
  871. newAssignedIps.push_back(InetAddress(nwc->assignedAddresses[i]));
  872. std::sort(newAssignedIps.begin(),newAssignedIps.end());
  873. newAssignedIps.erase(std::unique(newAssignedIps.begin(),newAssignedIps.end()),newAssignedIps.end());
  874. for(std::vector<InetAddress>::iterator ip(newAssignedIps.begin());ip!=newAssignedIps.end();++ip) {
  875. if (!std::binary_search(assignedIps.begin(),assignedIps.end(),*ip))
  876. t->second->addIp(*ip);
  877. }
  878. for(std::vector<InetAddress>::iterator ip(assignedIps.begin());ip!=assignedIps.end();++ip) {
  879. if (!std::binary_search(newAssignedIps.begin(),newAssignedIps.end(),*ip))
  880. t->second->removeIp(*ip);
  881. }
  882. assignedIps.swap(newAssignedIps);
  883. } else {
  884. return -999; // tap init failed
  885. }
  886. break;
  887. case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  888. case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  889. if (t != _taps.end()) {
  890. #ifdef __WINDOWS__
  891. std::string winInstanceId(t->second->instanceId());
  892. #endif
  893. delete t->second;
  894. _taps.erase(t);
  895. _tapAssignedIps.erase(nwid);
  896. #ifdef __WINDOWS__
  897. if ((op == ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  898. WindowsEthernetTap::deletePersistentTapDevice(_homePath.c_str(),winInstanceId.c_str());
  899. #endif
  900. }
  901. break;
  902. }
  903. return 0;
  904. }
  905. inline void nodeEventCallback(enum ZT1_Event event,const void *metaData)
  906. {
  907. switch(event) {
  908. case ZT1_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  909. Mutex::Lock _l(_termReason_m);
  910. _termReason = ONE_IDENTITY_COLLISION;
  911. _fatalErrorMessage = "identity/address collision";
  912. this->terminate();
  913. } break;
  914. case ZT1_EVENT_TRACE: {
  915. if (metaData) {
  916. ::fprintf(stderr,"%s"ZT_EOL_S,(const char *)metaData);
  917. ::fflush(stderr);
  918. }
  919. } break;
  920. default:
  921. break;
  922. }
  923. }
  924. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  925. {
  926. std::string p(_dataStorePrepPath(name));
  927. if (!p.length())
  928. return -2;
  929. FILE *f = fopen(p.c_str(),"rb");
  930. if (!f)
  931. return -1;
  932. if (fseek(f,0,SEEK_END) != 0) {
  933. fclose(f);
  934. return -2;
  935. }
  936. long ts = ftell(f);
  937. if (ts < 0) {
  938. fclose(f);
  939. return -2;
  940. }
  941. *totalSize = (unsigned long)ts;
  942. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  943. fclose(f);
  944. return -2;
  945. }
  946. long n = (long)fread(buf,1,bufSize,f);
  947. fclose(f);
  948. return n;
  949. }
  950. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  951. {
  952. std::string p(_dataStorePrepPath(name));
  953. if (!p.length())
  954. return -2;
  955. if (!data) {
  956. OSUtils::rm(p.c_str());
  957. return 0;
  958. }
  959. FILE *f = fopen(p.c_str(),"wb");
  960. if (!f)
  961. return -1;
  962. if (fwrite(data,len,1,f) == 1) {
  963. fclose(f);
  964. if (secure)
  965. OSUtils::lockDownFile(p.c_str(),false);
  966. return 0;
  967. } else {
  968. fclose(f);
  969. OSUtils::rm(p.c_str());
  970. return -1;
  971. }
  972. }
  973. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *addr,const void *data,unsigned int len)
  974. {
  975. int result = -1;
  976. switch(addr->ss_family) {
  977. case AF_INET:
  978. #ifdef ZT_BREAK_UDP
  979. if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
  980. #endif
  981. if (_v4UdpSocket)
  982. result = ((_phy.udpSend(_v4UdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
  983. #ifdef ZT_BREAK_UDP
  984. }
  985. #endif
  986. #ifdef ZT1_TCP_FALLBACK_RELAY
  987. // TCP fallback tunnel support
  988. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  989. uint64_t now = OSUtils::now();
  990. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  991. // IP address in ZT1_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  992. // valid direct traffic we'll stop using it and close the socket after a while.
  993. if (((now - _lastDirectReceiveFromGlobal) > ZT1_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT1_TCP_FALLBACK_AFTER)) {
  994. if (_tcpFallbackTunnel) {
  995. Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
  996. if (!_tcpFallbackTunnel->writeBuf.length())
  997. _phy.tcpSetNotifyWritable(_tcpFallbackTunnel->sock,true);
  998. unsigned long mlen = len + 7;
  999. _tcpFallbackTunnel->writeBuf.push_back((char)0x17);
  1000. _tcpFallbackTunnel->writeBuf.push_back((char)0x03);
  1001. _tcpFallbackTunnel->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1002. _tcpFallbackTunnel->writeBuf.push_back((char)((mlen >> 8) & 0xff));
  1003. _tcpFallbackTunnel->writeBuf.push_back((char)(mlen & 0xff));
  1004. _tcpFallbackTunnel->writeBuf.push_back((char)4); // IPv4
  1005. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  1006. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  1007. _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
  1008. result = 0;
  1009. } else if (((now - _lastSendToGlobal) < ZT1_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobal) > (ZT_PING_CHECK_INVERVAL / 2))) {
  1010. std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
  1011. if (tunnelIps.empty()) {
  1012. if (!_tcpFallbackResolver.running())
  1013. _tcpFallbackResolver.resolveNow();
  1014. } else {
  1015. bool connected = false;
  1016. InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
  1017. addr.setPort(ZT1_TCP_FALLBACK_RELAY_PORT);
  1018. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
  1019. }
  1020. }
  1021. }
  1022. _lastSendToGlobal = now;
  1023. }
  1024. #endif // ZT1_TCP_FALLBACK_RELAY
  1025. break;
  1026. case AF_INET6:
  1027. #ifdef ZT_BREAK_UDP
  1028. if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
  1029. #endif
  1030. if (_v6UdpSocket)
  1031. result = ((_phy.udpSend(_v6UdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
  1032. #ifdef ZT_BREAK_UDP
  1033. }
  1034. #endif
  1035. break;
  1036. default:
  1037. return -1;
  1038. }
  1039. return result;
  1040. }
  1041. inline void nodeVirtualNetworkFrameFunction(uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1042. {
  1043. Mutex::Lock _l(_taps_m);
  1044. std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.find(nwid));
  1045. if (t != _taps.end())
  1046. t->second->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1047. }
  1048. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1049. {
  1050. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1051. }
  1052. inline void onHttpRequestToServer(TcpConnection *tc)
  1053. {
  1054. char tmpn[256];
  1055. std::string data;
  1056. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1057. unsigned int scode = 404;
  1058. try {
  1059. if (_controlPlane)
  1060. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  1061. else scode = 500;
  1062. } catch ( ... ) {
  1063. scode = 500;
  1064. }
  1065. const char *scodestr;
  1066. switch(scode) {
  1067. case 200: scodestr = "OK"; break;
  1068. case 400: scodestr = "Bad Request"; break;
  1069. case 401: scodestr = "Unauthorized"; break;
  1070. case 403: scodestr = "Forbidden"; break;
  1071. case 404: scodestr = "Not Found"; break;
  1072. case 500: scodestr = "Internal Server Error"; break;
  1073. case 501: scodestr = "Not Implemented"; break;
  1074. case 503: scodestr = "Service Unavailable"; break;
  1075. default: scodestr = "Error"; break;
  1076. }
  1077. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  1078. {
  1079. Mutex::Lock _l(tc->writeBuf_m);
  1080. tc->writeBuf.assign(tmpn);
  1081. tc->writeBuf.append("Content-Type: ");
  1082. tc->writeBuf.append(contentType);
  1083. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  1084. tc->writeBuf.append(tmpn);
  1085. if (!tc->shouldKeepAlive)
  1086. tc->writeBuf.append("Connection: close\r\n");
  1087. tc->writeBuf.append("\r\n");
  1088. if (tc->parser.method != HTTP_HEAD)
  1089. tc->writeBuf.append(data);
  1090. }
  1091. _phy.tcpSetNotifyWritable(tc->sock,true);
  1092. }
  1093. inline void onHttpResponseFromClient(TcpConnection *tc)
  1094. {
  1095. if (!tc->shouldKeepAlive)
  1096. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConnections
  1097. }
  1098. private:
  1099. std::string _dataStorePrepPath(const char *name) const
  1100. {
  1101. std::string p(_homePath);
  1102. p.push_back(ZT_PATH_SEPARATOR);
  1103. char lastc = (char)0;
  1104. for(const char *n=name;(*n);++n) {
  1105. if ((*n == '.')&&(lastc == '.'))
  1106. return std::string(); // don't allow ../../ stuff as a precaution
  1107. if (*n == '/') {
  1108. OSUtils::mkdir(p.c_str());
  1109. p.push_back(ZT_PATH_SEPARATOR);
  1110. } else p.push_back(*n);
  1111. lastc = *n;
  1112. }
  1113. return p;
  1114. }
  1115. const std::string _homePath;
  1116. BackgroundResolver _tcpFallbackResolver;
  1117. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  1118. SqliteNetworkController _controller;
  1119. #endif
  1120. Phy<OneServiceImpl *> _phy;
  1121. std::string _overrideRootTopology;
  1122. Node *_node;
  1123. PhySocket *_v4UdpSocket;
  1124. PhySocket *_v6UdpSocket;
  1125. PhySocket *_v4TcpListenSocket;
  1126. PhySocket *_v6TcpListenSocket;
  1127. ControlPlane *_controlPlane;
  1128. uint64_t _lastDirectReceiveFromGlobal;
  1129. uint64_t _lastSendToGlobal;
  1130. uint64_t _lastRestart;
  1131. volatile uint64_t _nextBackgroundTaskDeadline;
  1132. std::map< uint64_t,EthernetTap * > _taps;
  1133. std::map< uint64_t,std::vector<InetAddress> > _tapAssignedIps; // ZeroTier assigned IPs, not user or dhcp assigned
  1134. Mutex _taps_m;
  1135. std::set< TcpConnection * > _tcpConnections; // no mutex for this since it's done in the main loop thread only
  1136. TcpConnection *_tcpFallbackTunnel;
  1137. ReasonForTermination _termReason;
  1138. std::string _fatalErrorMessage;
  1139. Mutex _termReason_m;
  1140. unsigned int _port;
  1141. bool _run;
  1142. Mutex _run_m;
  1143. };
  1144. static int SnodeVirtualNetworkConfigFunction(ZT1_Node *node,void *uptr,uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwconf)
  1145. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,op,nwconf); }
  1146. static void SnodeEventCallback(ZT1_Node *node,void *uptr,enum ZT1_Event event,const void *metaData)
  1147. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1148. static long SnodeDataStoreGetFunction(ZT1_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1149. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  1150. static int SnodeDataStorePutFunction(ZT1_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  1151. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  1152. static int SnodeWirePacketSendFunction(ZT1_Node *node,void *uptr,const struct sockaddr_storage *addr,const void *data,unsigned int len)
  1153. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(addr,data,len); }
  1154. static void SnodeVirtualNetworkFrameFunction(ZT1_Node *node,void *uptr,uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1155. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,sourceMac,destMac,etherType,vlanId,data,len); }
  1156. 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)
  1157. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1158. static int ShttpOnMessageBegin(http_parser *parser)
  1159. {
  1160. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1161. tc->currentHeaderField = "";
  1162. tc->currentHeaderValue = "";
  1163. tc->messageSize = 0;
  1164. tc->url = "";
  1165. tc->status = "";
  1166. tc->headers.clear();
  1167. tc->body = "";
  1168. return 0;
  1169. }
  1170. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  1171. {
  1172. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1173. tc->messageSize += (unsigned long)length;
  1174. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1175. return -1;
  1176. tc->url.append(ptr,length);
  1177. return 0;
  1178. }
  1179. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1180. {
  1181. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1182. tc->messageSize += (unsigned long)length;
  1183. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1184. return -1;
  1185. tc->status.append(ptr,length);
  1186. return 0;
  1187. }
  1188. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1189. {
  1190. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1191. tc->messageSize += (unsigned long)length;
  1192. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1193. return -1;
  1194. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1195. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1196. tc->currentHeaderField = "";
  1197. tc->currentHeaderValue = "";
  1198. }
  1199. for(size_t i=0;i<length;++i)
  1200. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1201. return 0;
  1202. }
  1203. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1204. {
  1205. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1206. tc->messageSize += (unsigned long)length;
  1207. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1208. return -1;
  1209. tc->currentHeaderValue.append(ptr,length);
  1210. return 0;
  1211. }
  1212. static int ShttpOnHeadersComplete(http_parser *parser)
  1213. {
  1214. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1215. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  1216. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1217. return 0;
  1218. }
  1219. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  1220. {
  1221. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1222. tc->messageSize += (unsigned long)length;
  1223. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1224. return -1;
  1225. tc->body.append(ptr,length);
  1226. return 0;
  1227. }
  1228. static int ShttpOnMessageComplete(http_parser *parser)
  1229. {
  1230. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1231. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  1232. tc->lastActivity = OSUtils::now();
  1233. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  1234. tc->parent->onHttpRequestToServer(tc);
  1235. } else {
  1236. tc->parent->onHttpResponseFromClient(tc);
  1237. }
  1238. return 0;
  1239. }
  1240. } // anonymous namespace
  1241. std::string OneService::platformDefaultHomePath()
  1242. {
  1243. #ifdef __UNIX_LIKE__
  1244. #ifdef __APPLE__
  1245. // /Library/... on Apple
  1246. return std::string("/Library/Application Support/ZeroTier/One");
  1247. #else
  1248. #ifdef __BSD__
  1249. // BSD likes /var/db instead of /var/lib
  1250. return std::string("/var/db/zerotier-one");
  1251. #else
  1252. // Use /var/lib for Linux and other *nix
  1253. return std::string("/var/lib/zerotier-one");
  1254. #endif
  1255. #endif
  1256. #else // not __UNIX_LIKE__
  1257. #ifdef __WINDOWS__
  1258. // Look up app data folder on Windows, e.g. C:\ProgramData\...
  1259. char buf[16384];
  1260. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_COMMON_APPDATA,NULL,0,buf)))
  1261. return (std::string(buf) + "\\ZeroTier\\One");
  1262. else return std::string("C:\\ZeroTier\\One");
  1263. #else
  1264. return std::string(); // UNKNOWN PLATFORM
  1265. #endif
  1266. #endif // __UNIX_LIKE__ or not...
  1267. }
  1268. std::string OneService::autoUpdateUrl()
  1269. {
  1270. #ifdef ZT_AUTO_UPDATE
  1271. /*
  1272. #if defined(__LINUX__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1273. if (sizeof(void *) == 8)
  1274. return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x64-LATEST.nfo";
  1275. else return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x86-LATEST.nfo";
  1276. #endif
  1277. */
  1278. #if defined(__APPLE__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1279. return "http://download.zerotier.com/update/mac_intel/";
  1280. #endif
  1281. #ifdef __WINDOWS__
  1282. return "http://download.zerotier.com/update/win_intel/";
  1283. #endif
  1284. #endif // ZT_AUTO_UPDATE
  1285. return std::string();
  1286. }
  1287. OneService *OneService::newInstance(const char *hp,unsigned int port,const char *overrideRootTopology) { return new OneServiceImpl(hp,port,overrideRootTopology); }
  1288. OneService::~OneService() {}
  1289. } // namespace ZeroTier