OneService.cpp 43 KB

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