OneService.cpp 47 KB

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