OneService.cpp 49 KB

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