OneService.cpp 47 KB

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