OneService.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  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. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <stdint.h>
  22. #include <string>
  23. #include <map>
  24. #include <set>
  25. #include <vector>
  26. #include <algorithm>
  27. #include "../version.h"
  28. #include "../include/ZeroTierOne.h"
  29. #include "../ext/http-parser/http_parser.h"
  30. #include "../node/Constants.hpp"
  31. #include "../node/Mutex.hpp"
  32. #include "../node/Node.hpp"
  33. #include "../node/Utils.hpp"
  34. #include "../node/InetAddress.hpp"
  35. #include "../node/MAC.hpp"
  36. #include "../node/Identity.hpp"
  37. #include "../osdep/Phy.hpp"
  38. #include "../osdep/Thread.hpp"
  39. #include "../osdep/OSUtils.hpp"
  40. #include "../osdep/Http.hpp"
  41. #include "../osdep/BackgroundResolver.hpp"
  42. #include "../osdep/PortMapper.hpp"
  43. #include "OneService.hpp"
  44. #include "ControlPlane.hpp"
  45. #include "ClusterGeoIpService.hpp"
  46. #include "ClusterDefinition.hpp"
  47. /**
  48. * Uncomment to enable UDP breakage switch
  49. *
  50. * If this is defined, the presence of a file called /tmp/ZT_BREAK_UDP
  51. * will cause direct UDP TX/RX to stop working. This can be used to
  52. * test TCP tunneling fallback and other robustness features. Deleting
  53. * this file will cause it to start working again.
  54. */
  55. //#define ZT_BREAK_UDP
  56. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  57. #include "../controller/SqliteNetworkController.hpp"
  58. #else
  59. class SqliteNetworkController;
  60. #endif // ZT_ENABLE_NETWORK_CONTROLLER
  61. #ifdef __WINDOWS__
  62. #include <WinSock2.h>
  63. #include <Windows.h>
  64. #include <ShlObj.h>
  65. #include <netioapi.h>
  66. #include <iphlpapi.h>
  67. #else
  68. #include <sys/types.h>
  69. #include <sys/socket.h>
  70. #include <sys/wait.h>
  71. #include <unistd.h>
  72. #include <ifaddrs.h>
  73. #endif
  74. // Include the right tap device driver for this platform -- add new platforms here
  75. #ifdef ZT_SERVICE_NETCON
  76. // In network containers builds, use the virtual netcon endpoint instead of a tun/tap port driver
  77. #include "../netcon/NetconEthernetTap.hpp"
  78. namespace ZeroTier { typedef NetconEthernetTap EthernetTap; }
  79. #else // not ZT_SERVICE_NETCON so pick a tap driver
  80. #ifdef __APPLE__
  81. #include "../osdep/OSXEthernetTap.hpp"
  82. namespace ZeroTier { typedef OSXEthernetTap EthernetTap; }
  83. #endif // __APPLE__
  84. #ifdef __LINUX__
  85. #include "../osdep/LinuxEthernetTap.hpp"
  86. namespace ZeroTier { typedef LinuxEthernetTap EthernetTap; }
  87. #endif // __LINUX__
  88. #ifdef __WINDOWS__
  89. #include "../osdep/WindowsEthernetTap.hpp"
  90. namespace ZeroTier { typedef WindowsEthernetTap EthernetTap; }
  91. #endif // __WINDOWS__
  92. #ifdef __FreeBSD__
  93. #include "../osdep/BSDEthernetTap.hpp"
  94. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  95. #endif // __FreeBSD__
  96. #endif // ZT_SERVICE_NETCON
  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 5000
  104. // Path under ZT1 home for controller database if controller is enabled
  105. #define ZT_CONTROLLER_DB_PATH "controller.db"
  106. // TCP fallback relay host -- geo-distributed using Amazon Route53 geo-aware DNS
  107. #define ZT_TCP_FALLBACK_RELAY "tcp-fallback.zerotier.com"
  108. #define ZT_TCP_FALLBACK_RELAY_PORT 443
  109. // Frequency at which we re-resolve the TCP fallback relay
  110. #define ZT_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 ZT_TCP_FALLBACK_AFTER 60000
  113. // How often to check for local interface addresses
  114. #define ZT_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. /* 0001 - 0004 : obsolete, used in old versions */
  127. /* 0005 */ (id == Identity("ba57ea350e:0:9d4be6d7f86c5660d5ee1951a3d759aa6e12a84fc0c0b74639500f1dbc1a8c566622e7d1c531967ebceb1e9d1761342f88324a8ba520c93c35f92f35080fa23f"))
  128. /* 0006 */ ||(id == Identity("5067b21b83:0:8af477730f5055c48135b84bed6720a35bca4c0e34be4060a4c636288b1ec22217eb22709d610c66ed464c643130c51411bbb0294eef12fbe8ecc1a1e2c63a7a"))
  129. /* 0007 */ ||(id == Identity("4f5e97a8f1:0:57880d056d7baeb04bbc057d6f16e6cb41388570e87f01492fce882485f65a798648595610a3ad49885604e7fb1db2dd3c2c534b75e42c3c0b110ad07b4bb138"))
  130. /* 0008 */ ||(id == Identity("580bbb8e15:0:ad5ef31155bebc6bc413991992387e083fed26d699997ef76e7c947781edd47d1997161fa56ba337b1a2b44b129fd7c7197ce5185382f06011bc88d1363b4ddd"))
  131. );
  132. }
  133. void doUpdateCheck()
  134. {
  135. std::string url(OneService::autoUpdateUrl());
  136. if ((url.length() <= 7)||(url.substr(0,7) != "http://"))
  137. return;
  138. std::string httpHost;
  139. std::string httpPath;
  140. {
  141. std::size_t slashIdx = url.substr(7).find_first_of('/');
  142. if (slashIdx == std::string::npos) {
  143. httpHost = url.substr(7);
  144. httpPath = "/";
  145. } else {
  146. httpHost = url.substr(7,slashIdx);
  147. httpPath = url.substr(slashIdx + 7);
  148. }
  149. }
  150. if (httpHost.length() == 0)
  151. return;
  152. std::vector<InetAddress> ips(OSUtils::resolve(httpHost.c_str()));
  153. for(std::vector<InetAddress>::iterator ip(ips.begin());ip!=ips.end();++ip) {
  154. if (!ip->port())
  155. ip->setPort(80);
  156. std::string nfoPath = httpPath + "LATEST.nfo";
  157. std::map<std::string,std::string> requestHeaders,responseHeaders;
  158. std::string body;
  159. requestHeaders["Host"] = httpHost;
  160. unsigned int scode = Http::GET(ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE,60000,reinterpret_cast<const struct sockaddr *>(&(*ip)),nfoPath.c_str(),requestHeaders,responseHeaders,body);
  161. //fprintf(stderr,"UPDATE %s %s %u %lu\n",ip->toString().c_str(),nfoPath.c_str(),scode,body.length());
  162. if ((scode == 200)&&(body.length() > 0)) {
  163. /* NFO fields:
  164. *
  165. * file=<filename>
  166. * signedBy=<signing identity>
  167. * ed25519=<ed25519 ECC signature of archive>
  168. * vMajor=<major version>
  169. * vMinor=<minor version>
  170. * vRevision=<revision> */
  171. Dictionary nfo(body);
  172. unsigned int vMajor = Utils::strToUInt(nfo.get("vMajor","0").c_str());
  173. unsigned int vMinor = Utils::strToUInt(nfo.get("vMinor","0").c_str());
  174. unsigned int vRevision = Utils::strToUInt(nfo.get("vRevision","0").c_str());
  175. if (Utils::compareVersion(vMajor,vMinor,vRevision,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION) <= 0) {
  176. //fprintf(stderr,"UPDATE %u.%u.%u is not newer than our version\n",vMajor,vMinor,vRevision);
  177. return;
  178. }
  179. Identity signedBy;
  180. if ((!signedBy.fromString(nfo.get("signedBy","")))||(!isValidSigningIdentity(signedBy))) {
  181. //fprintf(stderr,"UPDATE invalid signedBy or not authorized signing identity.\n");
  182. return;
  183. }
  184. std::string filePath(nfo.get("file",""));
  185. if ((!filePath.length())||(filePath.find("..") != std::string::npos))
  186. return;
  187. filePath = httpPath + filePath;
  188. std::string fileData;
  189. if (Http::GET(ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE,60000,reinterpret_cast<const struct sockaddr *>(&(*ip)),filePath.c_str(),requestHeaders,responseHeaders,fileData) != 200) {
  190. //fprintf(stderr,"UPDATE GET %s failed\n",filePath.c_str());
  191. return;
  192. }
  193. std::string ed25519(Utils::unhex(nfo.get("ed25519","")));
  194. if ((ed25519.length() == 0)||(!signedBy.verify(fileData.data(),(unsigned int)fileData.length(),ed25519.data(),(unsigned int)ed25519.length()))) {
  195. //fprintf(stderr,"UPDATE %s failed signature check!\n",filePath.c_str());
  196. return;
  197. }
  198. /* --------------------------------------------------------------- */
  199. /* We made it! Begin OS-specific installation code. */
  200. #ifdef __APPLE__
  201. /* OSX version is in the form of a MacOSX .pkg file, so we will
  202. * launch installer (normally in /usr/sbin) to install it. It will
  203. * then turn around and shut down the service, update files, and
  204. * relaunch. */
  205. {
  206. char bashp[128],pkgp[128];
  207. Utils::snprintf(bashp,sizeof(bashp),"/tmp/ZeroTierOne-update-%u.%u.%u.sh",vMajor,vMinor,vRevision);
  208. Utils::snprintf(pkgp,sizeof(pkgp),"/tmp/ZeroTierOne-update-%u.%u.%u.pkg",vMajor,vMinor,vRevision);
  209. FILE *pkg = fopen(pkgp,"w");
  210. if ((!pkg)||(fwrite(fileData.data(),fileData.length(),1,pkg) != 1)) {
  211. fclose(pkg);
  212. unlink(bashp);
  213. unlink(pkgp);
  214. fprintf(stderr,"UPDATE error writing %s\n",pkgp);
  215. return;
  216. }
  217. fclose(pkg);
  218. FILE *bash = fopen(bashp,"w");
  219. if (!bash) {
  220. fclose(pkg);
  221. unlink(bashp);
  222. unlink(pkgp);
  223. fprintf(stderr,"UPDATE error writing %s\n",bashp);
  224. return;
  225. }
  226. fprintf(bash,
  227. "#!/bin/bash\n"
  228. "export PATH=/bin:/usr/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/sbin\n"
  229. "sleep 1\n"
  230. "installer -pkg \"%s\" -target /\n"
  231. "sleep 1\n"
  232. "rm -f \"%s\" \"%s\"\n"
  233. "exit 0\n",
  234. pkgp,
  235. pkgp,
  236. bashp);
  237. fclose(bash);
  238. long pid = (long)vfork();
  239. if (pid == 0) {
  240. setsid(); // detach from parent so that shell isn't killed when parent is killed
  241. signal(SIGHUP,SIG_IGN);
  242. signal(SIGTERM,SIG_IGN);
  243. signal(SIGQUIT,SIG_IGN);
  244. execl("/bin/bash","/bin/bash",bashp,(char *)0);
  245. exit(0);
  246. }
  247. }
  248. #endif // __APPLE__
  249. #ifdef __WINDOWS__
  250. /* Windows version comes in the form of .MSI package that
  251. * takes care of everything. */
  252. {
  253. char tempp[512],batp[512],msip[512],cmdline[512];
  254. if (GetTempPathA(sizeof(tempp),tempp) <= 0)
  255. return;
  256. CreateDirectoryA(tempp,(LPSECURITY_ATTRIBUTES)0);
  257. Utils::snprintf(batp,sizeof(batp),"%s\\ZeroTierOne-update-%u.%u.%u.bat",tempp,vMajor,vMinor,vRevision);
  258. Utils::snprintf(msip,sizeof(msip),"%s\\ZeroTierOne-update-%u.%u.%u.msi",tempp,vMajor,vMinor,vRevision);
  259. FILE *msi = fopen(msip,"wb");
  260. if ((!msi)||(fwrite(fileData.data(),(size_t)fileData.length(),1,msi) != 1)) {
  261. fclose(msi);
  262. return;
  263. }
  264. fclose(msi);
  265. FILE *bat = fopen(batp,"wb");
  266. if (!bat)
  267. return;
  268. fprintf(bat,
  269. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  270. "NET.EXE STOP \"ZeroTierOneService\"\r\n"
  271. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  272. "MSIEXEC.EXE /i \"%s\" /qn\r\n"
  273. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  274. "NET.EXE START \"ZeroTierOneService\"\r\n"
  275. "DEL \"%s\"\r\n"
  276. "DEL \"%s\"\r\n",
  277. msip,
  278. msip,
  279. batp);
  280. fclose(bat);
  281. STARTUPINFOA si;
  282. PROCESS_INFORMATION pi;
  283. memset(&si,0,sizeof(si));
  284. memset(&pi,0,sizeof(pi));
  285. Utils::snprintf(cmdline,sizeof(cmdline),"CMD.EXE /c \"%s\"",batp);
  286. CreateProcessA(NULL,cmdline,NULL,NULL,FALSE,CREATE_NO_WINDOW|CREATE_NEW_PROCESS_GROUP,NULL,NULL,&si,&pi);
  287. }
  288. #endif // __WINDOWS__
  289. /* --------------------------------------------------------------- */
  290. return;
  291. } // else try to fetch from next IP address
  292. }
  293. }
  294. void threadMain()
  295. throw()
  296. {
  297. try {
  298. this->doUpdateCheck();
  299. } catch ( ... ) {}
  300. }
  301. };
  302. static BackgroundSoftwareUpdateChecker backgroundSoftwareUpdateChecker;
  303. #endif // ZT_AUTO_UPDATE
  304. static bool isBlacklistedLocalInterfaceForZeroTierTraffic(const char *ifn)
  305. {
  306. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  307. if ((ifn[0] == 'l')&&(ifn[1] == 'o')) return true; // loopback
  308. if ((ifn[0] == 'z')&&(ifn[1] == 't')) return true; // sanity check: zt#
  309. if ((ifn[0] == 't')&&(ifn[1] == 'u')&&(ifn[2] == 'n')) return true; // tun# is probably an OpenVPN tunnel or similar
  310. if ((ifn[0] == 't')&&(ifn[1] == 'a')&&(ifn[2] == 'p')) return true; // tap# is probably an OpenVPN tunnel or similar
  311. #endif
  312. #ifdef __APPLE__
  313. if ((ifn[0] == 'l')&&(ifn[1] == 'o')) return true; // loopback
  314. if ((ifn[0] == 'z')&&(ifn[1] == 't')) return true; // sanity check: zt#
  315. if ((ifn[0] == 't')&&(ifn[1] == 'u')&&(ifn[2] == 'n')) return true; // tun# is probably an OpenVPN tunnel or similar
  316. if ((ifn[0] == 't')&&(ifn[1] == 'a')&&(ifn[2] == 'p')) return true; // tap# is probably an OpenVPN tunnel or similar
  317. if ((ifn[0] == 'u')&&(ifn[1] == 't')&&(ifn[2] == 'u')&&(ifn[3] == 'n')) return true; // ... as is utun#
  318. #endif
  319. return false;
  320. }
  321. static std::string _trimString(const std::string &s)
  322. {
  323. unsigned long end = (unsigned long)s.length();
  324. while (end) {
  325. char c = s[end - 1];
  326. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  327. --end;
  328. else break;
  329. }
  330. unsigned long start = 0;
  331. while (start < end) {
  332. char c = s[start];
  333. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  334. ++start;
  335. else break;
  336. }
  337. return s.substr(start,end - start);
  338. }
  339. class OneServiceImpl;
  340. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
  341. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData);
  342. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize);
  343. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure);
  344. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl);
  345. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  346. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr);
  347. #ifdef ZT_ENABLE_CLUSTER
  348. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len);
  349. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z);
  350. #endif
  351. 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);
  352. static int ShttpOnMessageBegin(http_parser *parser);
  353. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  354. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  355. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  356. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  357. static int ShttpOnHeadersComplete(http_parser *parser);
  358. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  359. static int ShttpOnMessageComplete(http_parser *parser);
  360. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  361. ShttpOnMessageBegin,
  362. ShttpOnUrl,
  363. ShttpOnStatus,
  364. ShttpOnHeaderField,
  365. ShttpOnValue,
  366. ShttpOnHeadersComplete,
  367. ShttpOnBody,
  368. ShttpOnMessageComplete
  369. };
  370. struct TcpConnection
  371. {
  372. enum {
  373. TCP_HTTP_INCOMING,
  374. TCP_HTTP_OUTGOING, // not currently used
  375. TCP_TUNNEL_OUTGOING // fale-SSL outgoing tunnel -- HTTP-related fields are not used
  376. } type;
  377. bool shouldKeepAlive;
  378. OneServiceImpl *parent;
  379. PhySocket *sock;
  380. InetAddress from;
  381. http_parser parser;
  382. unsigned long messageSize;
  383. uint64_t lastActivity;
  384. std::string currentHeaderField;
  385. std::string currentHeaderValue;
  386. std::string url;
  387. std::string status;
  388. std::map< std::string,std::string > headers;
  389. std::string body;
  390. std::string writeBuf;
  391. Mutex writeBuf_m;
  392. };
  393. // Use a bigger buffer on AMD64 since these are likely to be bigger and
  394. // servers. Otherwise use a smaller buffer. This makes no difference
  395. // except under very high load.
  396. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__))
  397. #define ZT_UDP_DESIRED_BUF_SIZE 1048576
  398. #else
  399. #define ZT_UDP_DESIRED_BUF_SIZE 131072
  400. #endif
  401. // Used to pseudo-randomize local source port picking
  402. static volatile unsigned int _udpPortPickerCounter = 0;
  403. class OneServiceImpl : public OneService
  404. {
  405. public:
  406. OneServiceImpl(const char *hp,unsigned int port) :
  407. _homePath((hp) ? hp : ".")
  408. ,_tcpFallbackResolver(ZT_TCP_FALLBACK_RELAY)
  409. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  410. ,_controller((SqliteNetworkController *)0)
  411. #endif
  412. ,_phy(this,false,true)
  413. ,_node((Node *)0)
  414. ,_controlPlane((ControlPlane *)0)
  415. ,_lastDirectReceiveFromGlobal(0)
  416. #ifdef ZT_TCP_FALLBACK_RELAY
  417. ,_lastSendToGlobalV4(0)
  418. #endif
  419. ,_lastRestart(0)
  420. ,_nextBackgroundTaskDeadline(0)
  421. ,_tcpFallbackTunnel((TcpConnection *)0)
  422. ,_termReason(ONE_STILL_RUNNING)
  423. ,_port(0)
  424. #ifdef ZT_USE_MINIUPNPC
  425. ,_portMapper((PortMapper *)0)
  426. #endif
  427. #ifdef ZT_ENABLE_CLUSTER
  428. ,_clusterMessageSocket((PhySocket *)0)
  429. ,_clusterGeoIpService((ClusterGeoIpService *)0)
  430. ,_clusterDefinition((ClusterDefinition *)0)
  431. ,_clusterMemberId(0)
  432. #endif
  433. ,_run(true)
  434. {
  435. memset((void *)_udp,0,sizeof(_udp));
  436. const int portTrials = (port == 0) ? 256 : 1; // if port is 0, pick random
  437. for(int k=0;k<portTrials;++k) {
  438. if (port == 0) {
  439. unsigned int randp = 0;
  440. Utils::getSecureRandom(&randp,sizeof(randp));
  441. port = 40000 + (randp % 25500);
  442. }
  443. _udp[0].v4a = InetAddress((uint32_t)0,port);
  444. _udp[0].v4s = _phy.udpBind((const struct sockaddr *)&(_udp[0].v4a),(void *)&(_udp[0].v4a),ZT_UDP_DESIRED_BUF_SIZE);
  445. if (_udp[0].v4s) {
  446. struct sockaddr_in in4;
  447. memset(&in4,0,sizeof(in4));
  448. in4.sin_family = AF_INET;
  449. in4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001); // right now we just listen for TCP @127.0.0.1
  450. in4.sin_port = Utils::hton((uint16_t)port);
  451. _v4TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
  452. if (_v4TcpListenSocket) {
  453. _udp[0].v6a = InetAddress("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",16,port);
  454. _udp[0].v6s = _phy.udpBind((const struct sockaddr *)&(_udp[0].v6a),(void *)&(_udp[0].v6a),ZT_UDP_DESIRED_BUF_SIZE);
  455. struct sockaddr_in6 in6;
  456. memset((void *)&in6,0,sizeof(in6));
  457. in6.sin6_family = AF_INET6;
  458. in6.sin6_port = in4.sin_port;
  459. in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
  460. _v6TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
  461. _port = port;
  462. break; // success!
  463. } else {
  464. _phy.close(_udp[0].v4s,false);
  465. }
  466. }
  467. port = 0;
  468. }
  469. if (_port == 0)
  470. throw std::runtime_error("cannot bind to port");
  471. char portstr[64];
  472. Utils::snprintf(portstr,sizeof(portstr),"%u",_port);
  473. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),std::string(portstr));
  474. }
  475. virtual ~OneServiceImpl()
  476. {
  477. for(int i=0;i<3;++i) {
  478. if (_udp[i].v4s)
  479. _phy.close(_udp[i].v4s);
  480. if (_udp[i].v6s)
  481. _phy.close(_udp[i].v6s);
  482. }
  483. _phy.close(_v4TcpListenSocket);
  484. _phy.close(_v6TcpListenSocket);
  485. #ifdef ZT_ENABLE_CLUSTER
  486. _phy.close(_clusterMessageSocket);
  487. #endif
  488. #ifdef ZT_USE_MINIUPNPC
  489. delete _portMapper;
  490. #endif
  491. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  492. delete _controller;
  493. #endif
  494. #ifdef ZT_ENABLE_CLUSTER
  495. delete _clusterGeoIpService;
  496. delete _clusterDefinition;
  497. #endif
  498. }
  499. virtual ReasonForTermination run()
  500. {
  501. try {
  502. std::string authToken;
  503. {
  504. std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  505. if (!OSUtils::readFile(authTokenPath.c_str(),authToken)) {
  506. unsigned char foo[24];
  507. Utils::getSecureRandom(foo,sizeof(foo));
  508. authToken = "";
  509. for(unsigned int i=0;i<sizeof(foo);++i)
  510. authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  511. if (!OSUtils::writeFile(authTokenPath.c_str(),authToken)) {
  512. Mutex::Lock _l(_termReason_m);
  513. _termReason = ONE_UNRECOVERABLE_ERROR;
  514. _fatalErrorMessage = "authtoken.secret could not be written";
  515. return _termReason;
  516. } else OSUtils::lockDownFile(authTokenPath.c_str(),false);
  517. }
  518. }
  519. authToken = _trimString(authToken);
  520. _node = new Node(
  521. OSUtils::now(),
  522. this,
  523. SnodeDataStoreGetFunction,
  524. SnodeDataStorePutFunction,
  525. SnodeWirePacketSendFunction,
  526. SnodeVirtualNetworkFrameFunction,
  527. SnodeVirtualNetworkConfigFunction,
  528. SnodePathCheckFunction,
  529. SnodeEventCallback);
  530. // Bind secondary randomized port. If this fails we continue anyway.
  531. for(int k=0;k<512;++k) {
  532. const unsigned int randomizedPort = 40000 + (((unsigned int)_node->address() + k) % 25500);
  533. _udp[1].v4a = InetAddress(0,randomizedPort);
  534. _udp[1].v4s = _phy.udpBind((const struct sockaddr *)&(_udp[1].v4a),(void *)&(_udp[1].v4a),ZT_UDP_DESIRED_BUF_SIZE);
  535. if (_udp[1].v4s) {
  536. _udp[1].v6a = InetAddress("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",16,randomizedPort);
  537. _udp[1].v6s = _phy.udpBind((const struct sockaddr *)&(_udp[1].v6a),(void *)&(_udp[1].v6a),ZT_UDP_DESIRED_BUF_SIZE);
  538. if (_udp[1].v6s) {
  539. break;
  540. } else {
  541. _phy.close(_udp[1].v4s);
  542. _udp[1].v4s = (PhySocket *)0;
  543. }
  544. }
  545. }
  546. #ifdef ZT_USE_MINIUPNPC
  547. // Bind tertiary uPnP/NAT-PMP redirect port. If this succeeds start port mapper.
  548. for(int k=0;k<512;++k) {
  549. const unsigned int mapperPort = 40000 + (((_port + 1) * (k + 1)) % 25500);
  550. char uniqueName[64];
  551. _udp[2].v4a = InetAddress(0,mapperPort);
  552. _udp[2].v4s = _phy.udpBind((const struct sockaddr *)&(_udp[2].v4a),(void *)&(_udp[2].v4a),ZT_UDP_DESIRED_BUF_SIZE);
  553. if (_udp[2].v4s) {
  554. Utils::snprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx",_node->address());
  555. _portMapper = new PortMapper(mapperPort,uniqueName);
  556. _udp[2].v6a = InetAddress("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",16,mapperPort);
  557. _udp[2].v6s = _phy.udpBind((const struct sockaddr *)&(_udp[2].v6a),(void *)&(_udp[2].v6a),ZT_UDP_DESIRED_BUF_SIZE); // okay if this fails, but it shouldn't
  558. break;
  559. }
  560. }
  561. #endif
  562. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  563. _controller = new SqliteNetworkController(_node,(_homePath + ZT_PATH_SEPARATOR_S + ZT_CONTROLLER_DB_PATH).c_str(),(_homePath + ZT_PATH_SEPARATOR_S + "circuitTestResults.d").c_str());
  564. _node->setNetconfMaster((void *)_controller);
  565. #endif
  566. #ifdef ZT_ENABLE_CLUSTER
  567. if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str())) {
  568. _clusterDefinition = new ClusterDefinition(_node->address(),(_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str());
  569. if (_clusterDefinition->size() > 0) {
  570. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  571. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  572. PhySocket *cs = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&(m->clusterEndpoint)));
  573. if (cs) {
  574. if (_clusterMessageSocket) {
  575. _phy.close(_clusterMessageSocket,false);
  576. _phy.close(cs,false);
  577. Mutex::Lock _l(_termReason_m);
  578. _termReason = ONE_UNRECOVERABLE_ERROR;
  579. _fatalErrorMessage = "Cluster: can't determine my cluster member ID: able to bind more than one cluster message socket IP/port!";
  580. return _termReason;
  581. }
  582. _clusterMessageSocket = cs;
  583. _clusterMemberId = m->id;
  584. }
  585. }
  586. if (!_clusterMessageSocket) {
  587. Mutex::Lock _l(_termReason_m);
  588. _termReason = ONE_UNRECOVERABLE_ERROR;
  589. _fatalErrorMessage = "Cluster: can't determine my cluster member ID: unable to bind to any cluster message socket IP/port.";
  590. return _termReason;
  591. }
  592. if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S + "cluster-geo.exe").c_str()))
  593. _clusterGeoIpService = new ClusterGeoIpService((_homePath + ZT_PATH_SEPARATOR_S + "cluster-geo.exe").c_str());
  594. const ClusterDefinition::MemberDefinition &me = (*_clusterDefinition)[_clusterMemberId];
  595. InetAddress endpoints[255];
  596. unsigned int numEndpoints = 0;
  597. for(std::vector<InetAddress>::const_iterator i(me.zeroTierEndpoints.begin());i!=me.zeroTierEndpoints.end();++i)
  598. endpoints[numEndpoints++] = *i;
  599. if (_node->clusterInit(
  600. _clusterMemberId,
  601. reinterpret_cast<const struct sockaddr_storage *>(endpoints),
  602. numEndpoints,
  603. me.x,
  604. me.y,
  605. me.z,
  606. &SclusterSendFunction,
  607. this,
  608. (_clusterGeoIpService) ? &SclusterGeoIpFunction : 0,
  609. this) == ZT_RESULT_OK) {
  610. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  611. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  612. if (m->id != _clusterMemberId)
  613. _node->clusterAddMember(m->id);
  614. }
  615. }
  616. } else {
  617. delete _clusterDefinition;
  618. _clusterDefinition = (ClusterDefinition *)0;
  619. }
  620. }
  621. #endif
  622. _controlPlane = new ControlPlane(this,_node,(_homePath + ZT_PATH_SEPARATOR_S + "ui").c_str());
  623. _controlPlane->addAuthToken(authToken.c_str());
  624. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  625. _controlPlane->setController(_controller);
  626. #endif
  627. { // Remember networks from previous session
  628. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S + "networks.d").c_str()));
  629. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  630. std::size_t dot = f->find_last_of('.');
  631. if ((dot == 16)&&(f->substr(16) == ".conf"))
  632. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()),(void *)0);
  633. }
  634. }
  635. // Start two background threads to handle expensive ops out of line
  636. Thread::start(_node);
  637. Thread::start(_node);
  638. _nextBackgroundTaskDeadline = 0;
  639. uint64_t clockShouldBe = OSUtils::now();
  640. _lastRestart = clockShouldBe;
  641. uint64_t lastTapMulticastGroupCheck = 0;
  642. uint64_t lastTcpFallbackResolve = 0;
  643. uint64_t lastLocalInterfaceAddressCheck = (OSUtils::now() - ZT_LOCAL_INTERFACE_CHECK_INTERVAL) + 15000; // do this in 15s to give portmapper time to configure and other things time to settle
  644. #ifdef ZT_AUTO_UPDATE
  645. uint64_t lastSoftwareUpdateCheck = 0;
  646. #endif // ZT_AUTO_UPDATE
  647. for(;;) {
  648. _run_m.lock();
  649. if (!_run) {
  650. _run_m.unlock();
  651. _termReason_m.lock();
  652. _termReason = ONE_NORMAL_TERMINATION;
  653. _termReason_m.unlock();
  654. break;
  655. } else _run_m.unlock();
  656. uint64_t now = OSUtils::now();
  657. uint64_t dl = _nextBackgroundTaskDeadline;
  658. if (dl <= now) {
  659. _node->processBackgroundTasks(now,&_nextBackgroundTaskDeadline);
  660. dl = _nextBackgroundTaskDeadline;
  661. }
  662. // Attempt to detect sleep/wake events by detecting delay overruns
  663. if ((now > clockShouldBe)&&((now - clockShouldBe) > 2000))
  664. _lastRestart = now;
  665. #ifdef ZT_AUTO_UPDATE
  666. if ((now - lastSoftwareUpdateCheck) >= ZT_AUTO_UPDATE_CHECK_PERIOD) {
  667. lastSoftwareUpdateCheck = now;
  668. Thread::start(&backgroundSoftwareUpdateChecker);
  669. }
  670. #endif // ZT_AUTO_UPDATE
  671. if ((now - lastTcpFallbackResolve) >= ZT_TCP_FALLBACK_RERESOLVE_DELAY) {
  672. lastTcpFallbackResolve = now;
  673. _tcpFallbackResolver.resolveNow();
  674. }
  675. if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2)))
  676. _phy.close(_tcpFallbackTunnel->sock);
  677. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  678. lastTapMulticastGroupCheck = now;
  679. Mutex::Lock _l(_taps_m);
  680. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t) {
  681. std::vector<MulticastGroup> added,removed;
  682. t->second->scanMulticastGroups(added,removed);
  683. for(std::vector<MulticastGroup>::iterator m(added.begin());m!=added.end();++m)
  684. _node->multicastSubscribe(t->first,m->mac().toInt(),m->adi());
  685. for(std::vector<MulticastGroup>::iterator m(removed.begin());m!=removed.end();++m)
  686. _node->multicastUnsubscribe(t->first,m->mac().toInt(),m->adi());
  687. }
  688. }
  689. if ((now - lastLocalInterfaceAddressCheck) >= ZT_LOCAL_INTERFACE_CHECK_INTERVAL) {
  690. lastLocalInterfaceAddressCheck = now;
  691. _node->clearLocalInterfaceAddresses();
  692. #ifdef ZT_USE_MINIUPNPC
  693. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  694. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  695. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  696. #endif
  697. #ifdef __UNIX_LIKE__
  698. std::vector<std::string> ztDevices;
  699. {
  700. Mutex::Lock _l(_taps_m);
  701. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t)
  702. ztDevices.push_back(t->second->deviceName());
  703. }
  704. struct ifaddrs *ifatbl = (struct ifaddrs *)0;
  705. if ((getifaddrs(&ifatbl) == 0)&&(ifatbl)) {
  706. struct ifaddrs *ifa = ifatbl;
  707. while (ifa) {
  708. if ((ifa->ifa_name)&&(ifa->ifa_addr)&&(!isBlacklistedLocalInterfaceForZeroTierTraffic(ifa->ifa_name))) {
  709. bool isZT = false;
  710. for(std::vector<std::string>::const_iterator d(ztDevices.begin());d!=ztDevices.end();++d) {
  711. if (*d == ifa->ifa_name) {
  712. isZT = true;
  713. break;
  714. }
  715. }
  716. if (!isZT) {
  717. InetAddress ip(ifa->ifa_addr);
  718. ip.setPort(_port);
  719. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip));
  720. }
  721. }
  722. ifa = ifa->ifa_next;
  723. }
  724. freeifaddrs(ifatbl);
  725. }
  726. #endif // __UNIX_LIKE__
  727. #ifdef __WINDOWS__
  728. std::vector<NET_LUID> ztDevices;
  729. {
  730. Mutex::Lock _l(_taps_m);
  731. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t)
  732. ztDevices.push_back(t->second->luid());
  733. }
  734. char aabuf[16384];
  735. ULONG aalen = sizeof(aabuf);
  736. 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) {
  737. PIP_ADAPTER_ADDRESSES a = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf);
  738. while (a) {
  739. bool isZT = false;
  740. for(std::vector<NET_LUID>::const_iterator d(ztDevices.begin());d!=ztDevices.end();++d) {
  741. if (a->Luid.Value == d->Value) {
  742. isZT = true;
  743. break;
  744. }
  745. }
  746. if (!isZT) {
  747. PIP_ADAPTER_UNICAST_ADDRESS ua = a->FirstUnicastAddress;
  748. while (ua) {
  749. InetAddress ip(ua->Address.lpSockaddr);
  750. ip.setPort(_port);
  751. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip));
  752. ua = ua->Next;
  753. }
  754. }
  755. a = a->Next;
  756. }
  757. }
  758. #endif // __WINDOWS__
  759. }
  760. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  761. clockShouldBe = now + (uint64_t)delay;
  762. _phy.poll(delay);
  763. }
  764. } catch (std::exception &exc) {
  765. Mutex::Lock _l(_termReason_m);
  766. _termReason = ONE_UNRECOVERABLE_ERROR;
  767. _fatalErrorMessage = exc.what();
  768. } catch ( ... ) {
  769. Mutex::Lock _l(_termReason_m);
  770. _termReason = ONE_UNRECOVERABLE_ERROR;
  771. _fatalErrorMessage = "unexpected exception in main thread";
  772. }
  773. try {
  774. while (!_tcpConnections.empty())
  775. _phy.close((*_tcpConnections.begin())->sock);
  776. } catch ( ... ) {}
  777. {
  778. Mutex::Lock _l(_taps_m);
  779. for(std::map< uint64_t,EthernetTap * >::iterator t(_taps.begin());t!=_taps.end();++t)
  780. delete t->second;
  781. _taps.clear();
  782. }
  783. delete _controlPlane;
  784. _controlPlane = (ControlPlane *)0;
  785. delete _node;
  786. _node = (Node *)0;
  787. return _termReason;
  788. }
  789. virtual ReasonForTermination reasonForTermination() const
  790. {
  791. Mutex::Lock _l(_termReason_m);
  792. return _termReason;
  793. }
  794. virtual std::string fatalErrorMessage() const
  795. {
  796. Mutex::Lock _l(_termReason_m);
  797. return _fatalErrorMessage;
  798. }
  799. virtual std::string portDeviceName(uint64_t nwid) const
  800. {
  801. Mutex::Lock _l(_taps_m);
  802. std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.find(nwid));
  803. if (t != _taps.end())
  804. return t->second->deviceName();
  805. return std::string();
  806. }
  807. virtual bool tcpFallbackActive() const
  808. {
  809. return (_tcpFallbackTunnel != (TcpConnection *)0);
  810. }
  811. virtual void terminate()
  812. {
  813. _run_m.lock();
  814. _run = false;
  815. _run_m.unlock();
  816. _phy.whack();
  817. }
  818. // Begin private implementation methods
  819. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
  820. {
  821. #ifdef ZT_ENABLE_CLUSTER
  822. if (sock == _clusterMessageSocket) {
  823. _lastDirectReceiveFromGlobal = OSUtils::now();
  824. _node->clusterHandleIncomingMessage(data,len);
  825. return;
  826. }
  827. #endif
  828. #ifdef ZT_BREAK_UDP
  829. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  830. return;
  831. #endif
  832. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  833. _lastDirectReceiveFromGlobal = OSUtils::now();
  834. const ZT_ResultCode rc = _node->processWirePacket(
  835. OSUtils::now(),
  836. reinterpret_cast<const struct sockaddr_storage *>(*uptr), // *uptr points to InetAddress/sockaddr of local listen port
  837. (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
  838. data,
  839. len,
  840. &_nextBackgroundTaskDeadline);
  841. if (ZT_ResultCode_isFatal(rc)) {
  842. char tmp[256];
  843. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  844. Mutex::Lock _l(_termReason_m);
  845. _termReason = ONE_UNRECOVERABLE_ERROR;
  846. _fatalErrorMessage = tmp;
  847. this->terminate();
  848. }
  849. }
  850. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  851. {
  852. if (!success)
  853. return;
  854. // Outgoing TCP connections are always TCP fallback tunnel connections.
  855. TcpConnection *tc = new TcpConnection();
  856. _tcpConnections.insert(tc);
  857. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  858. tc->shouldKeepAlive = true;
  859. tc->parent = this;
  860. tc->sock = sock;
  861. // from and parser are not used
  862. tc->messageSize = 0; // unused
  863. tc->lastActivity = OSUtils::now();
  864. // HTTP stuff is not used
  865. tc->writeBuf = "";
  866. *uptr = (void *)tc;
  867. // Send "hello" message
  868. tc->writeBuf.push_back((char)0x17);
  869. tc->writeBuf.push_back((char)0x03);
  870. tc->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  871. tc->writeBuf.push_back((char)0x00);
  872. tc->writeBuf.push_back((char)0x04); // mlen == 4
  873. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MAJOR);
  874. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MINOR);
  875. tc->writeBuf.push_back((char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff));
  876. tc->writeBuf.push_back((char)(ZEROTIER_ONE_VERSION_REVISION & 0xff));
  877. _phy.setNotifyWritable(sock,true);
  878. _tcpFallbackTunnel = tc;
  879. }
  880. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  881. {
  882. // Incoming TCP connections are HTTP JSON API requests.
  883. TcpConnection *tc = new TcpConnection();
  884. _tcpConnections.insert(tc);
  885. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  886. tc->shouldKeepAlive = true;
  887. tc->parent = this;
  888. tc->sock = sockN;
  889. tc->from = from;
  890. http_parser_init(&(tc->parser),HTTP_REQUEST);
  891. tc->parser.data = (void *)tc;
  892. tc->messageSize = 0;
  893. tc->lastActivity = OSUtils::now();
  894. tc->currentHeaderField = "";
  895. tc->currentHeaderValue = "";
  896. tc->url = "";
  897. tc->status = "";
  898. tc->headers.clear();
  899. tc->body = "";
  900. tc->writeBuf = "";
  901. *uptrN = (void *)tc;
  902. }
  903. inline void phyOnTcpClose(PhySocket *sock,void **uptr)
  904. {
  905. TcpConnection *tc = (TcpConnection *)*uptr;
  906. if (tc) {
  907. if (tc == _tcpFallbackTunnel)
  908. _tcpFallbackTunnel = (TcpConnection *)0;
  909. _tcpConnections.erase(tc);
  910. delete tc;
  911. }
  912. }
  913. inline void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  914. {
  915. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  916. switch(tc->type) {
  917. case TcpConnection::TCP_HTTP_INCOMING:
  918. case TcpConnection::TCP_HTTP_OUTGOING:
  919. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  920. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK)) {
  921. _phy.close(sock);
  922. return;
  923. }
  924. break;
  925. case TcpConnection::TCP_TUNNEL_OUTGOING:
  926. tc->body.append((const char *)data,len);
  927. while (tc->body.length() >= 5) {
  928. const char *data = tc->body.data();
  929. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  930. if (tc->body.length() >= (mlen + 5)) {
  931. InetAddress from;
  932. unsigned long plen = mlen; // payload length, modified if there's an IP header
  933. data += 5; // skip forward past pseudo-TLS junk and mlen
  934. if (plen == 4) {
  935. // Hello message, which isn't sent by proxy and would be ignored by client
  936. } else if (plen) {
  937. // Messages should contain IPv4 or IPv6 source IP address data
  938. switch(data[0]) {
  939. case 4: // IPv4
  940. if (plen >= 7) {
  941. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  942. data += 7; // type + 4 byte IP + 2 byte port
  943. plen -= 7;
  944. } else {
  945. _phy.close(sock);
  946. return;
  947. }
  948. break;
  949. case 6: // IPv6
  950. if (plen >= 19) {
  951. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  952. data += 19; // type + 16 byte IP + 2 byte port
  953. plen -= 19;
  954. } else {
  955. _phy.close(sock);
  956. return;
  957. }
  958. break;
  959. case 0: // none/omitted
  960. ++data;
  961. --plen;
  962. break;
  963. default: // invalid address type
  964. _phy.close(sock);
  965. return;
  966. }
  967. if (from) {
  968. const ZT_ResultCode rc = _node->processWirePacket(
  969. OSUtils::now(),
  970. reinterpret_cast<struct sockaddr_storage *>(&(_udp[0].v4a)), // TCP tunneled packets are "from" the default local port's address
  971. reinterpret_cast<struct sockaddr_storage *>(&from),
  972. data,
  973. plen,
  974. &_nextBackgroundTaskDeadline);
  975. if (ZT_ResultCode_isFatal(rc)) {
  976. char tmp[256];
  977. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  978. Mutex::Lock _l(_termReason_m);
  979. _termReason = ONE_UNRECOVERABLE_ERROR;
  980. _fatalErrorMessage = tmp;
  981. this->terminate();
  982. _phy.close(sock);
  983. return;
  984. }
  985. }
  986. }
  987. if (tc->body.length() > (mlen + 5))
  988. tc->body = tc->body.substr(mlen + 5);
  989. else tc->body = "";
  990. } else break;
  991. }
  992. break;
  993. }
  994. }
  995. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  996. {
  997. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  998. Mutex::Lock _l(tc->writeBuf_m);
  999. if (tc->writeBuf.length() > 0) {
  1000. long sent = (long)_phy.streamSend(sock,tc->writeBuf.data(),(unsigned long)tc->writeBuf.length(),true);
  1001. if (sent > 0) {
  1002. tc->lastActivity = OSUtils::now();
  1003. if ((unsigned long)sent >= (unsigned long)tc->writeBuf.length()) {
  1004. tc->writeBuf = "";
  1005. _phy.setNotifyWritable(sock,false);
  1006. if (!tc->shouldKeepAlive)
  1007. _phy.close(sock); // will call close handler to delete from _tcpConnections
  1008. } else {
  1009. tc->writeBuf = tc->writeBuf.substr(sent);
  1010. }
  1011. }
  1012. } else {
  1013. _phy.setNotifyWritable(sock,false);
  1014. }
  1015. }
  1016. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  1017. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  1018. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  1019. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  1020. inline void phyOnUnixWritable(PhySocket *sock,void **uptr,bool lwip_invoked) {}
  1021. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  1022. {
  1023. Mutex::Lock _l(_taps_m);
  1024. std::map< uint64_t,EthernetTap * >::iterator t(_taps.find(nwid));
  1025. switch(op) {
  1026. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  1027. if (t == _taps.end()) {
  1028. try {
  1029. char friendlyName[1024];
  1030. Utils::snprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  1031. t = _taps.insert(std::pair< uint64_t,EthernetTap *>(nwid,new EthernetTap(
  1032. _homePath.c_str(),
  1033. MAC(nwc->mac),
  1034. nwc->mtu,
  1035. (unsigned int)ZT_IF_METRIC,
  1036. nwid,
  1037. friendlyName,
  1038. StapFrameHandler,
  1039. (void *)this))).first;
  1040. *nuptr = (void *)t->second;
  1041. } catch (std::exception &exc) {
  1042. #ifdef __WINDOWS__
  1043. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1044. if (tapFailLog) {
  1045. fprintf(tapFailLog,"%.16llx: %s"ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1046. fclose(tapFailLog);
  1047. }
  1048. #else
  1049. fprintf(stderr,"ERROR: unable to configure virtual network port: %s"ZT_EOL_S,exc.what());
  1050. #endif
  1051. return -999;
  1052. } catch ( ... ) {
  1053. return -999; // tap init failed
  1054. }
  1055. }
  1056. // fall through...
  1057. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1058. if (t != _taps.end()) {
  1059. t->second->setEnabled(nwc->enabled != 0);
  1060. std::vector<InetAddress> &assignedIps = _tapAssignedIps[nwid];
  1061. std::vector<InetAddress> newAssignedIps;
  1062. for(unsigned int i=0;i<nwc->assignedAddressCount;++i)
  1063. newAssignedIps.push_back(InetAddress(nwc->assignedAddresses[i]));
  1064. std::sort(newAssignedIps.begin(),newAssignedIps.end());
  1065. newAssignedIps.erase(std::unique(newAssignedIps.begin(),newAssignedIps.end()),newAssignedIps.end());
  1066. for(std::vector<InetAddress>::iterator ip(newAssignedIps.begin());ip!=newAssignedIps.end();++ip) {
  1067. if (!std::binary_search(assignedIps.begin(),assignedIps.end(),*ip))
  1068. if (!t->second->addIp(*ip))
  1069. fprintf(stderr,"ERROR: unable to add ip address %s"ZT_EOL_S, ip->toString().c_str());
  1070. }
  1071. for(std::vector<InetAddress>::iterator ip(assignedIps.begin());ip!=assignedIps.end();++ip) {
  1072. if (!std::binary_search(newAssignedIps.begin(),newAssignedIps.end(),*ip))
  1073. if (!t->second->removeIp(*ip))
  1074. fprintf(stderr,"ERROR: unable to remove ip address %s"ZT_EOL_S, ip->toString().c_str());
  1075. }
  1076. assignedIps.swap(newAssignedIps);
  1077. } else {
  1078. return -999; // tap init failed
  1079. }
  1080. break;
  1081. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1082. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1083. if (t != _taps.end()) {
  1084. #ifdef __WINDOWS__
  1085. std::string winInstanceId(t->second->instanceId());
  1086. #endif
  1087. *nuptr = (void *)0;
  1088. delete t->second;
  1089. _taps.erase(t);
  1090. _tapAssignedIps.erase(nwid);
  1091. #ifdef __WINDOWS__
  1092. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1093. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1094. #endif
  1095. }
  1096. break;
  1097. }
  1098. return 0;
  1099. }
  1100. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1101. {
  1102. switch(event) {
  1103. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  1104. Mutex::Lock _l(_termReason_m);
  1105. _termReason = ONE_IDENTITY_COLLISION;
  1106. _fatalErrorMessage = "identity/address collision";
  1107. this->terminate();
  1108. } break;
  1109. case ZT_EVENT_TRACE: {
  1110. if (metaData) {
  1111. ::fprintf(stderr,"%s"ZT_EOL_S,(const char *)metaData);
  1112. ::fflush(stderr);
  1113. }
  1114. } break;
  1115. default:
  1116. break;
  1117. }
  1118. }
  1119. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1120. {
  1121. std::string p(_dataStorePrepPath(name));
  1122. if (!p.length())
  1123. return -2;
  1124. FILE *f = fopen(p.c_str(),"rb");
  1125. if (!f)
  1126. return -1;
  1127. if (fseek(f,0,SEEK_END) != 0) {
  1128. fclose(f);
  1129. return -2;
  1130. }
  1131. long ts = ftell(f);
  1132. if (ts < 0) {
  1133. fclose(f);
  1134. return -2;
  1135. }
  1136. *totalSize = (unsigned long)ts;
  1137. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  1138. fclose(f);
  1139. return -2;
  1140. }
  1141. long n = (long)fread(buf,1,bufSize,f);
  1142. fclose(f);
  1143. return n;
  1144. }
  1145. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  1146. {
  1147. std::string p(_dataStorePrepPath(name));
  1148. if (!p.length())
  1149. return -2;
  1150. if (!data) {
  1151. OSUtils::rm(p.c_str());
  1152. return 0;
  1153. }
  1154. FILE *f = fopen(p.c_str(),"wb");
  1155. if (!f)
  1156. return -1;
  1157. if (fwrite(data,len,1,f) == 1) {
  1158. fclose(f);
  1159. if (secure)
  1160. OSUtils::lockDownFile(p.c_str(),false);
  1161. return 0;
  1162. } else {
  1163. fclose(f);
  1164. OSUtils::rm(p.c_str());
  1165. return -1;
  1166. }
  1167. }
  1168. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1169. {
  1170. PhySocket *froms = (PhySocket *)0;
  1171. if (addr->ss_family == AF_INET) {
  1172. if (reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port == 0) {
  1173. // If sender specifies any local address, use secondary port 1/4 times
  1174. froms = _udp[(++_udpPortPickerCounter & 0x4) >> 2].v4s;
  1175. } else {
  1176. // If sender specifies a local address, find it by just checking port since right now we always bind wildcard
  1177. for(int k=1;k<=2;++k) {
  1178. // Match fast on port only, since right now we always bind wildcard
  1179. if (reinterpret_cast<const struct sockaddr_in *>(&(_udp[k].v4a))->sin_port == reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port) {
  1180. froms = _udp[k].v4s;
  1181. break;
  1182. }
  1183. }
  1184. }
  1185. if (!froms)
  1186. froms = _udp[0].v4s;
  1187. #ifdef ZT_TCP_FALLBACK_RELAY
  1188. // TCP fallback tunnel support, currently IPv4 only
  1189. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  1190. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  1191. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  1192. // valid direct traffic we'll stop using it and close the socket after a while.
  1193. const uint64_t now = OSUtils::now();
  1194. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  1195. if (_tcpFallbackTunnel) {
  1196. Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
  1197. if (!_tcpFallbackTunnel->writeBuf.length())
  1198. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  1199. unsigned long mlen = len + 7;
  1200. _tcpFallbackTunnel->writeBuf.push_back((char)0x17);
  1201. _tcpFallbackTunnel->writeBuf.push_back((char)0x03);
  1202. _tcpFallbackTunnel->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1203. _tcpFallbackTunnel->writeBuf.push_back((char)((mlen >> 8) & 0xff));
  1204. _tcpFallbackTunnel->writeBuf.push_back((char)(mlen & 0xff));
  1205. _tcpFallbackTunnel->writeBuf.push_back((char)4); // IPv4
  1206. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  1207. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  1208. _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
  1209. } else if (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INVERVAL / 2))) {
  1210. std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
  1211. if (tunnelIps.empty()) {
  1212. if (!_tcpFallbackResolver.running())
  1213. _tcpFallbackResolver.resolveNow();
  1214. } else {
  1215. bool connected = false;
  1216. InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
  1217. addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
  1218. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
  1219. }
  1220. }
  1221. }
  1222. _lastSendToGlobalV4 = now;
  1223. }
  1224. #endif // ZT_TCP_FALLBACK_RELAY
  1225. } else if (addr->ss_family == AF_INET6) {
  1226. if (reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port != 0) {
  1227. // If sender specifies a local address, find it by just checking port since right now we always bind wildcard
  1228. for(int k=1;k<=2;++k) {
  1229. // Match fast on port only, since right now we always bind wildcard
  1230. if (reinterpret_cast<const struct sockaddr_in6 *>(&(_udp[k].v6a))->sin6_port == reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port) {
  1231. froms = _udp[k].v6s;
  1232. break;
  1233. }
  1234. }
  1235. }
  1236. if (!froms)
  1237. froms = _udp[0].v6s;
  1238. } else {
  1239. return -1;
  1240. }
  1241. #ifdef ZT_BREAK_UDP
  1242. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  1243. return 0; // silently break UDP
  1244. #endif
  1245. if ((ttl)&&(addr->ss_family == AF_INET))
  1246. _phy.setIp4UdpTtl(froms,ttl);
  1247. const int result = (_phy.udpSend(froms,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1;
  1248. if ((ttl)&&(addr->ss_family == AF_INET))
  1249. _phy.setIp4UdpTtl(froms,255);
  1250. return result;
  1251. }
  1252. inline void nodeVirtualNetworkFrameFunction(uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1253. {
  1254. EthernetTap *tap = reinterpret_cast<EthernetTap *>(*nuptr);
  1255. if (!tap)
  1256. return;
  1257. tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1258. }
  1259. inline int nodePathCheckFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1260. {
  1261. Mutex::Lock _l(_taps_m);
  1262. for(std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.begin());t!=_taps.end();++t) {
  1263. if (t->second) {
  1264. std::vector<InetAddress> ips(t->second->ips());
  1265. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1266. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  1267. return 0;
  1268. }
  1269. }
  1270. }
  1271. }
  1272. return 1;
  1273. }
  1274. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1275. {
  1276. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1277. }
  1278. inline void onHttpRequestToServer(TcpConnection *tc)
  1279. {
  1280. char tmpn[256];
  1281. std::string data;
  1282. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1283. unsigned int scode = 404;
  1284. try {
  1285. if (_controlPlane)
  1286. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  1287. else scode = 500;
  1288. } catch ( ... ) {
  1289. scode = 500;
  1290. }
  1291. const char *scodestr;
  1292. switch(scode) {
  1293. case 200: scodestr = "OK"; break;
  1294. case 400: scodestr = "Bad Request"; break;
  1295. case 401: scodestr = "Unauthorized"; break;
  1296. case 403: scodestr = "Forbidden"; break;
  1297. case 404: scodestr = "Not Found"; break;
  1298. case 500: scodestr = "Internal Server Error"; break;
  1299. case 501: scodestr = "Not Implemented"; break;
  1300. case 503: scodestr = "Service Unavailable"; break;
  1301. default: scodestr = "Error"; break;
  1302. }
  1303. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  1304. {
  1305. Mutex::Lock _l(tc->writeBuf_m);
  1306. tc->writeBuf.assign(tmpn);
  1307. tc->writeBuf.append("Content-Type: ");
  1308. tc->writeBuf.append(contentType);
  1309. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  1310. tc->writeBuf.append(tmpn);
  1311. if (!tc->shouldKeepAlive)
  1312. tc->writeBuf.append("Connection: close\r\n");
  1313. tc->writeBuf.append("\r\n");
  1314. if (tc->parser.method != HTTP_HEAD)
  1315. tc->writeBuf.append(data);
  1316. }
  1317. _phy.setNotifyWritable(tc->sock,true);
  1318. }
  1319. inline void onHttpResponseFromClient(TcpConnection *tc)
  1320. {
  1321. if (!tc->shouldKeepAlive)
  1322. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConnections
  1323. }
  1324. std::string _dataStorePrepPath(const char *name) const
  1325. {
  1326. std::string p(_homePath);
  1327. p.push_back(ZT_PATH_SEPARATOR);
  1328. char lastc = (char)0;
  1329. for(const char *n=name;(*n);++n) {
  1330. if ((*n == '.')&&(lastc == '.'))
  1331. return std::string(); // don't allow ../../ stuff as a precaution
  1332. if (*n == '/') {
  1333. OSUtils::mkdir(p.c_str());
  1334. p.push_back(ZT_PATH_SEPARATOR);
  1335. } else p.push_back(*n);
  1336. lastc = *n;
  1337. }
  1338. return p;
  1339. }
  1340. const std::string _homePath;
  1341. BackgroundResolver _tcpFallbackResolver;
  1342. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  1343. SqliteNetworkController *_controller;
  1344. #endif
  1345. Phy<OneServiceImpl *> _phy;
  1346. Node *_node;
  1347. /*
  1348. * To properly handle NAT/gateway craziness we use three local UDP ports:
  1349. *
  1350. * [0] is the normal/default port, usually 9993
  1351. * [1] is a port dervied from our ZeroTier address
  1352. * [2] is a port computed from the normal/default for use with uPnP/NAT-PMP mappings
  1353. *
  1354. * [2] exists because on some gateways trying to do regular NAT-t interferes
  1355. * destructively with uPnP port mapping behavior in very weird buggy ways.
  1356. * It's only used if uPnP/NAT-PMP is enabled in this build.
  1357. */
  1358. struct {
  1359. InetAddress v4a,v6a;
  1360. PhySocket *v4s,*v6s;
  1361. } _udp[3];
  1362. PhySocket *_v4TcpListenSocket;
  1363. PhySocket *_v6TcpListenSocket;
  1364. ControlPlane *_controlPlane;
  1365. uint64_t _lastDirectReceiveFromGlobal;
  1366. #ifdef ZT_TCP_FALLBACK_RELAY
  1367. uint64_t _lastSendToGlobalV4;
  1368. #endif
  1369. uint64_t _lastRestart;
  1370. volatile uint64_t _nextBackgroundTaskDeadline;
  1371. std::map< uint64_t,EthernetTap * > _taps;
  1372. std::map< uint64_t,std::vector<InetAddress> > _tapAssignedIps; // ZeroTier assigned IPs, not user or dhcp assigned
  1373. Mutex _taps_m;
  1374. std::set< TcpConnection * > _tcpConnections; // no mutex for this since it's done in the main loop thread only
  1375. TcpConnection *_tcpFallbackTunnel;
  1376. ReasonForTermination _termReason;
  1377. std::string _fatalErrorMessage;
  1378. Mutex _termReason_m;
  1379. unsigned int _port;
  1380. #ifdef ZT_USE_MINIUPNPC
  1381. PortMapper *_portMapper;
  1382. #endif
  1383. #ifdef ZT_ENABLE_CLUSTER
  1384. PhySocket *_clusterMessageSocket;
  1385. ClusterGeoIpService *_clusterGeoIpService;
  1386. ClusterDefinition *_clusterDefinition;
  1387. unsigned int _clusterMemberId;
  1388. #endif
  1389. bool _run;
  1390. Mutex _run_m;
  1391. };
  1392. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  1393. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  1394. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData)
  1395. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1396. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1397. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  1398. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  1399. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  1400. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1401. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localAddr,addr,data,len,ttl); }
  1402. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1403. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  1404. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1405. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(localAddr,remoteAddr); }
  1406. #ifdef ZT_ENABLE_CLUSTER
  1407. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len)
  1408. {
  1409. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1410. const ClusterDefinition::MemberDefinition &md = (*(impl->_clusterDefinition))[toMemberId];
  1411. if (md.clusterEndpoint)
  1412. impl->_phy.udpSend(impl->_clusterMessageSocket,reinterpret_cast<const struct sockaddr *>(&(md.clusterEndpoint)),data,len);
  1413. }
  1414. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z)
  1415. {
  1416. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1417. return (int)(impl->_clusterGeoIpService->locate(*(reinterpret_cast<const InetAddress *>(addr)),*x,*y,*z));
  1418. }
  1419. #endif
  1420. 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)
  1421. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1422. static int ShttpOnMessageBegin(http_parser *parser)
  1423. {
  1424. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1425. tc->currentHeaderField = "";
  1426. tc->currentHeaderValue = "";
  1427. tc->messageSize = 0;
  1428. tc->url = "";
  1429. tc->status = "";
  1430. tc->headers.clear();
  1431. tc->body = "";
  1432. return 0;
  1433. }
  1434. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  1435. {
  1436. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1437. tc->messageSize += (unsigned long)length;
  1438. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1439. return -1;
  1440. tc->url.append(ptr,length);
  1441. return 0;
  1442. }
  1443. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1444. {
  1445. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1446. tc->messageSize += (unsigned long)length;
  1447. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1448. return -1;
  1449. tc->status.append(ptr,length);
  1450. return 0;
  1451. }
  1452. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1453. {
  1454. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1455. tc->messageSize += (unsigned long)length;
  1456. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1457. return -1;
  1458. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1459. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1460. tc->currentHeaderField = "";
  1461. tc->currentHeaderValue = "";
  1462. }
  1463. for(size_t i=0;i<length;++i)
  1464. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1465. return 0;
  1466. }
  1467. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1468. {
  1469. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1470. tc->messageSize += (unsigned long)length;
  1471. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1472. return -1;
  1473. tc->currentHeaderValue.append(ptr,length);
  1474. return 0;
  1475. }
  1476. static int ShttpOnHeadersComplete(http_parser *parser)
  1477. {
  1478. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1479. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  1480. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1481. return 0;
  1482. }
  1483. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  1484. {
  1485. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1486. tc->messageSize += (unsigned long)length;
  1487. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1488. return -1;
  1489. tc->body.append(ptr,length);
  1490. return 0;
  1491. }
  1492. static int ShttpOnMessageComplete(http_parser *parser)
  1493. {
  1494. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1495. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  1496. tc->lastActivity = OSUtils::now();
  1497. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  1498. tc->parent->onHttpRequestToServer(tc);
  1499. } else {
  1500. tc->parent->onHttpResponseFromClient(tc);
  1501. }
  1502. return 0;
  1503. }
  1504. } // anonymous namespace
  1505. std::string OneService::platformDefaultHomePath()
  1506. {
  1507. #ifdef __UNIX_LIKE__
  1508. #ifdef __APPLE__
  1509. // /Library/... on Apple
  1510. return std::string("/Library/Application Support/ZeroTier/One");
  1511. #else
  1512. #ifdef __BSD__
  1513. // BSD likes /var/db instead of /var/lib
  1514. return std::string("/var/db/zerotier-one");
  1515. #else
  1516. // Use /var/lib for Linux and other *nix
  1517. return std::string("/var/lib/zerotier-one");
  1518. #endif
  1519. #endif
  1520. #else // not __UNIX_LIKE__
  1521. #ifdef __WINDOWS__
  1522. // Look up app data folder on Windows, e.g. C:\ProgramData\...
  1523. char buf[16384];
  1524. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_COMMON_APPDATA,NULL,0,buf)))
  1525. return (std::string(buf) + "\\ZeroTier\\One");
  1526. else return std::string("C:\\ZeroTier\\One");
  1527. #else
  1528. return std::string(); // UNKNOWN PLATFORM
  1529. #endif
  1530. #endif // __UNIX_LIKE__ or not...
  1531. }
  1532. std::string OneService::autoUpdateUrl()
  1533. {
  1534. #ifdef ZT_AUTO_UPDATE
  1535. /*
  1536. #if defined(__LINUX__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1537. if (sizeof(void *) == 8)
  1538. return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x64-LATEST.nfo";
  1539. else return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x86-LATEST.nfo";
  1540. #endif
  1541. */
  1542. #if defined(__APPLE__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1543. return "http://download.zerotier.com/update/mac_intel/";
  1544. #endif
  1545. #ifdef __WINDOWS__
  1546. return "http://download.zerotier.com/update/win_intel/";
  1547. #endif
  1548. #endif // ZT_AUTO_UPDATE
  1549. return std::string();
  1550. }
  1551. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  1552. OneService::~OneService() {}
  1553. } // namespace ZeroTier