OneService.cpp 44 KB

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