OneService.cpp 55 KB

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