OneService.cpp 46 KB

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