OneService.cpp 39 KB

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