OneService.cpp 57 KB

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