OneService.cpp 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670
  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 __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,unsigned int ttl);
  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. // Use a bigger buffer on AMD64 since these are likely to be bigger and
  378. // servers. Otherwise use a smaller buffer. This makes no difference
  379. // except under very high load.
  380. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__))
  381. #define ZT_UDP_DESIRED_BUF_SIZE 1048576
  382. #else
  383. #define ZT_UDP_DESIRED_BUF_SIZE 131072
  384. #endif
  385. class OneServiceImpl : public OneService
  386. {
  387. public:
  388. OneServiceImpl(const char *hp,unsigned int port) :
  389. _homePath((hp) ? hp : ".")
  390. ,_tcpFallbackResolver(ZT_TCP_FALLBACK_RELAY)
  391. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  392. ,_controller((SqliteNetworkController *)0)
  393. #endif
  394. ,_phy(this,false,true)
  395. ,_node((Node *)0)
  396. ,_controlPlane((ControlPlane *)0)
  397. ,_lastDirectReceiveFromGlobal(0)
  398. ,_lastSendToGlobal(0)
  399. ,_lastRestart(0)
  400. ,_nextBackgroundTaskDeadline(0)
  401. ,_tcpFallbackTunnel((TcpConnection *)0)
  402. ,_termReason(ONE_STILL_RUNNING)
  403. ,_port(0)
  404. #ifdef ZT_USE_MINIUPNPC
  405. ,_v4UpnpUdpSocket((PhySocket *)0)
  406. ,_portMapper((PortMapper *)0)
  407. #endif
  408. #ifdef ZT_ENABLE_CLUSTER
  409. ,_clusterMessageSocket((PhySocket *)0)
  410. ,_clusterGeoIpService((ClusterGeoIpService *)0)
  411. ,_clusterDefinition((ClusterDefinition *)0)
  412. ,_clusterMemberId(0)
  413. #endif
  414. ,_run(true)
  415. {
  416. const int portTrials = (port == 0) ? 256 : 1; // if port is 0, pick random
  417. for(int k=0;k<portTrials;++k) {
  418. if (port == 0) {
  419. unsigned int randp = 0;
  420. Utils::getSecureRandom(&randp,sizeof(randp));
  421. port = 40000 + (randp % 25500);
  422. }
  423. _v4LocalAddress = InetAddress((uint32_t)0,port);
  424. _v4UdpSocket = _phy.udpBind((const struct sockaddr *)&_v4LocalAddress,reinterpret_cast<void *>(&_v4LocalAddress),ZT_UDP_DESIRED_BUF_SIZE);
  425. if (_v4UdpSocket) {
  426. struct sockaddr_in in4;
  427. memset(&in4,0,sizeof(in4));
  428. in4.sin_family = AF_INET;
  429. in4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001); // right now we just listen for TCP @localhost
  430. in4.sin_port = Utils::hton((uint16_t)port);
  431. _v4TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
  432. if (_v4TcpListenSocket) {
  433. _v6LocalAddress = InetAddress("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",16,port);
  434. _v6UdpSocket = _phy.udpBind((const struct sockaddr *)&_v6LocalAddress,reinterpret_cast<void *>(&_v6LocalAddress),ZT_UDP_DESIRED_BUF_SIZE);
  435. struct sockaddr_in6 in6;
  436. memset((void *)&in6,0,sizeof(in6));
  437. in6.sin6_family = AF_INET6;
  438. in6.sin6_port = in4.sin_port;
  439. in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
  440. _v6TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
  441. _port = port;
  442. break; // success!
  443. } else {
  444. _phy.close(_v4UdpSocket,false);
  445. }
  446. }
  447. port = 0;
  448. }
  449. if (_port == 0)
  450. throw std::runtime_error("cannot bind to port");
  451. char portstr[64];
  452. Utils::snprintf(portstr,sizeof(portstr),"%u",_port);
  453. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),std::string(portstr));
  454. }
  455. virtual ~OneServiceImpl()
  456. {
  457. _phy.close(_v4UdpSocket);
  458. _phy.close(_v6UdpSocket);
  459. _phy.close(_v4TcpListenSocket);
  460. _phy.close(_v6TcpListenSocket);
  461. #ifdef ZT_ENABLE_CLUSTER
  462. _phy.close(_clusterMessageSocket);
  463. #endif
  464. #ifdef ZT_USE_MINIUPNPC
  465. _phy.close(_v4UpnpUdpSocket);
  466. delete _portMapper;
  467. #endif
  468. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  469. delete _controller;
  470. #endif
  471. #ifdef ZT_ENABLE_CLUSTER
  472. delete _clusterGeoIpService;
  473. delete _clusterDefinition;
  474. #endif
  475. }
  476. virtual ReasonForTermination run()
  477. {
  478. try {
  479. std::string authToken;
  480. {
  481. std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  482. if (!OSUtils::readFile(authTokenPath.c_str(),authToken)) {
  483. unsigned char foo[24];
  484. Utils::getSecureRandom(foo,sizeof(foo));
  485. authToken = "";
  486. for(unsigned int i=0;i<sizeof(foo);++i)
  487. authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  488. if (!OSUtils::writeFile(authTokenPath.c_str(),authToken)) {
  489. Mutex::Lock _l(_termReason_m);
  490. _termReason = ONE_UNRECOVERABLE_ERROR;
  491. _fatalErrorMessage = "authtoken.secret could not be written";
  492. return _termReason;
  493. } else OSUtils::lockDownFile(authTokenPath.c_str(),false);
  494. }
  495. }
  496. authToken = _trimString(authToken);
  497. _node = new Node(
  498. OSUtils::now(),
  499. this,
  500. SnodeDataStoreGetFunction,
  501. SnodeDataStorePutFunction,
  502. SnodeWirePacketSendFunction,
  503. SnodeVirtualNetworkFrameFunction,
  504. SnodeVirtualNetworkConfigFunction,
  505. SnodeEventCallback);
  506. #ifdef ZT_USE_MINIUPNPC
  507. // Bind a secondary port for use with uPnP, since some NAT routers
  508. // (cough Ubiquity Edge cough) barf up a lung if you do both conventional
  509. // NAT-t and uPnP from behind the same port. I think this is a bug, but
  510. // everyone else's router bugs are our problem. :P
  511. for(int k=0;k<512;++k) {
  512. unsigned int mapperPort = 40000 + (((_port + 1) * (k + 1)) % 25500);
  513. char uniqueName[64];
  514. _v4UpnpLocalAddress = InetAddress(0,mapperPort);
  515. _v4UpnpUdpSocket = _phy.udpBind((const struct sockaddr *)&_v4UpnpLocalAddress,reinterpret_cast<void *>(&_v4UpnpLocalAddress),ZT_UDP_DESIRED_BUF_SIZE);
  516. if (_v4UpnpUdpSocket) {
  517. Utils::snprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.16llx",_node->address());
  518. _portMapper = new PortMapper(mapperPort,uniqueName);
  519. break;
  520. }
  521. }
  522. #endif
  523. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  524. _controller = new SqliteNetworkController(_node,(_homePath + ZT_PATH_SEPARATOR_S + ZT_CONTROLLER_DB_PATH).c_str(),(_homePath + ZT_PATH_SEPARATOR_S + "circuitTestResults.d").c_str());
  525. _node->setNetconfMaster((void *)_controller);
  526. #endif
  527. #ifdef ZT_ENABLE_CLUSTER
  528. if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str())) {
  529. _clusterDefinition = new ClusterDefinition(_node->address(),(_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str());
  530. if (_clusterDefinition->size() > 0) {
  531. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  532. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  533. PhySocket *cs = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&(m->clusterEndpoint)));
  534. if (cs) {
  535. if (_clusterMessageSocket) {
  536. _phy.close(_clusterMessageSocket,false);
  537. _phy.close(cs,false);
  538. Mutex::Lock _l(_termReason_m);
  539. _termReason = ONE_UNRECOVERABLE_ERROR;
  540. _fatalErrorMessage = "Cluster: can't determine my cluster member ID: able to bind more than one cluster message socket IP/port!";
  541. return _termReason;
  542. }
  543. _clusterMessageSocket = cs;
  544. _clusterMemberId = m->id;
  545. }
  546. }
  547. if (!_clusterMessageSocket) {
  548. Mutex::Lock _l(_termReason_m);
  549. _termReason = ONE_UNRECOVERABLE_ERROR;
  550. _fatalErrorMessage = "Cluster: can't determine my cluster member ID: unable to bind to any cluster message socket IP/port.";
  551. return _termReason;
  552. }
  553. if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S + "cluster-geo.exe").c_str()))
  554. _clusterGeoIpService = new ClusterGeoIpService((_homePath + ZT_PATH_SEPARATOR_S + "cluster-geo.exe").c_str());
  555. const ClusterDefinition::MemberDefinition &me = (*_clusterDefinition)[_clusterMemberId];
  556. InetAddress endpoints[255];
  557. unsigned int numEndpoints = 0;
  558. for(std::vector<InetAddress>::const_iterator i(me.zeroTierEndpoints.begin());i!=me.zeroTierEndpoints.end();++i)
  559. endpoints[numEndpoints++] = *i;
  560. if (_node->clusterInit(
  561. _clusterMemberId,
  562. reinterpret_cast<const struct sockaddr_storage *>(endpoints),
  563. numEndpoints,
  564. me.x,
  565. me.y,
  566. me.z,
  567. &SclusterSendFunction,
  568. this,
  569. (_clusterGeoIpService) ? &SclusterGeoIpFunction : 0,
  570. this) == ZT_RESULT_OK) {
  571. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  572. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  573. if (m->id != _clusterMemberId)
  574. _node->clusterAddMember(m->id);
  575. }
  576. }
  577. } else {
  578. delete _clusterDefinition;
  579. _clusterDefinition = (ClusterDefinition *)0;
  580. }
  581. }
  582. #endif
  583. _controlPlane = new ControlPlane(this,_node,(_homePath + ZT_PATH_SEPARATOR_S + "ui").c_str());
  584. _controlPlane->addAuthToken(authToken.c_str());
  585. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  586. _controlPlane->setController(_controller);
  587. #endif
  588. { // Remember networks from previous session
  589. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S + "networks.d").c_str()));
  590. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  591. std::size_t dot = f->find_last_of('.');
  592. if ((dot == 16)&&(f->substr(16) == ".conf"))
  593. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()));
  594. }
  595. }
  596. // Start two background threads to handle expensive ops out of line
  597. Thread::start(_node);
  598. Thread::start(_node);
  599. _nextBackgroundTaskDeadline = 0;
  600. uint64_t clockShouldBe = OSUtils::now();
  601. _lastRestart = clockShouldBe;
  602. uint64_t lastTapMulticastGroupCheck = 0;
  603. uint64_t lastTcpFallbackResolve = 0;
  604. 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
  605. #ifdef ZT_AUTO_UPDATE
  606. uint64_t lastSoftwareUpdateCheck = 0;
  607. #endif // ZT_AUTO_UPDATE
  608. for(;;) {
  609. _run_m.lock();
  610. if (!_run) {
  611. _run_m.unlock();
  612. _termReason_m.lock();
  613. _termReason = ONE_NORMAL_TERMINATION;
  614. _termReason_m.unlock();
  615. break;
  616. } else _run_m.unlock();
  617. uint64_t now = OSUtils::now();
  618. uint64_t dl = _nextBackgroundTaskDeadline;
  619. if (dl <= now) {
  620. _node->processBackgroundTasks(now,&_nextBackgroundTaskDeadline);
  621. dl = _nextBackgroundTaskDeadline;
  622. }
  623. // Attempt to detect sleep/wake events by detecting delay overruns
  624. if ((now > clockShouldBe)&&((now - clockShouldBe) > 2000))
  625. _lastRestart = now;
  626. #ifdef ZT_AUTO_UPDATE
  627. if ((now - lastSoftwareUpdateCheck) >= ZT_AUTO_UPDATE_CHECK_PERIOD) {
  628. lastSoftwareUpdateCheck = now;
  629. Thread::start(&backgroundSoftwareUpdateChecker);
  630. }
  631. #endif // ZT_AUTO_UPDATE
  632. if ((now - lastTcpFallbackResolve) >= ZT_TCP_FALLBACK_RERESOLVE_DELAY) {
  633. lastTcpFallbackResolve = now;
  634. _tcpFallbackResolver.resolveNow();
  635. }
  636. if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2)))
  637. _phy.close(_tcpFallbackTunnel->sock);
  638. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  639. lastTapMulticastGroupCheck = now;
  640. Mutex::Lock _l(_taps_m);
  641. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t) {
  642. std::vector<MulticastGroup> added,removed;
  643. t->second->scanMulticastGroups(added,removed);
  644. for(std::vector<MulticastGroup>::iterator m(added.begin());m!=added.end();++m)
  645. _node->multicastSubscribe(t->first,m->mac().toInt(),m->adi());
  646. for(std::vector<MulticastGroup>::iterator m(removed.begin());m!=removed.end();++m)
  647. _node->multicastUnsubscribe(t->first,m->mac().toInt(),m->adi());
  648. }
  649. }
  650. if ((now - lastLocalInterfaceAddressCheck) >= ZT_LOCAL_INTERFACE_CHECK_INTERVAL) {
  651. lastLocalInterfaceAddressCheck = now;
  652. #ifdef __UNIX_LIKE__
  653. std::vector<std::string> ztDevices;
  654. {
  655. Mutex::Lock _l(_taps_m);
  656. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t)
  657. ztDevices.push_back(t->second->deviceName());
  658. }
  659. _node->clearLocalInterfaceAddresses();
  660. #ifdef ZT_USE_MINIUPNPC
  661. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  662. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  663. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  664. #endif
  665. struct ifaddrs *ifatbl = (struct ifaddrs *)0;
  666. if ((getifaddrs(&ifatbl) == 0)&&(ifatbl)) {
  667. struct ifaddrs *ifa = ifatbl;
  668. while (ifa) {
  669. if ((ifa->ifa_name)&&(ifa->ifa_addr)) {
  670. bool isZT = false;
  671. for(std::vector<std::string>::const_iterator d(ztDevices.begin());d!=ztDevices.end();++d) {
  672. if (*d == ifa->ifa_name) {
  673. isZT = true;
  674. break;
  675. }
  676. }
  677. if (!isZT) {
  678. InetAddress ip(ifa->ifa_addr);
  679. ip.setPort(_port);
  680. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip));
  681. }
  682. }
  683. ifa = ifa->ifa_next;
  684. }
  685. freeifaddrs(ifatbl);
  686. }
  687. #endif // __UNIX_LIKE__
  688. #ifdef __WINDOWS__
  689. std::vector<NET_LUID> ztDevices;
  690. {
  691. Mutex::Lock _l(_taps_m);
  692. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t)
  693. ztDevices.push_back(t->second->luid());
  694. }
  695. char aabuf[16384];
  696. ULONG aalen = sizeof(aabuf);
  697. 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) {
  698. PIP_ADAPTER_ADDRESSES a = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf);
  699. while (a) {
  700. bool isZT = false;
  701. for(std::vector<NET_LUID>::const_iterator d(ztDevices.begin());d!=ztDevices.end();++d) {
  702. if (a->Luid.Value == d->Value) {
  703. isZT = true;
  704. break;
  705. }
  706. }
  707. if (!isZT) {
  708. PIP_ADAPTER_UNICAST_ADDRESS ua = a->FirstUnicastAddress;
  709. while (ua) {
  710. InetAddress ip(ua->Address.lpSockaddr);
  711. ip.setPort(_port);
  712. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip));
  713. ua = ua->Next;
  714. }
  715. }
  716. a = a->Next;
  717. }
  718. }
  719. #endif // __WINDOWS__
  720. }
  721. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  722. clockShouldBe = now + (uint64_t)delay;
  723. _phy.poll(delay);
  724. }
  725. } catch (std::exception &exc) {
  726. Mutex::Lock _l(_termReason_m);
  727. _termReason = ONE_UNRECOVERABLE_ERROR;
  728. _fatalErrorMessage = exc.what();
  729. } catch ( ... ) {
  730. Mutex::Lock _l(_termReason_m);
  731. _termReason = ONE_UNRECOVERABLE_ERROR;
  732. _fatalErrorMessage = "unexpected exception in main thread";
  733. }
  734. try {
  735. while (!_tcpConnections.empty())
  736. _phy.close((*_tcpConnections.begin())->sock);
  737. } catch ( ... ) {}
  738. {
  739. Mutex::Lock _l(_taps_m);
  740. for(std::map< uint64_t,EthernetTap * >::iterator t(_taps.begin());t!=_taps.end();++t)
  741. delete t->second;
  742. _taps.clear();
  743. }
  744. delete _controlPlane;
  745. _controlPlane = (ControlPlane *)0;
  746. delete _node;
  747. _node = (Node *)0;
  748. return _termReason;
  749. }
  750. virtual ReasonForTermination reasonForTermination() const
  751. {
  752. Mutex::Lock _l(_termReason_m);
  753. return _termReason;
  754. }
  755. virtual std::string fatalErrorMessage() const
  756. {
  757. Mutex::Lock _l(_termReason_m);
  758. return _fatalErrorMessage;
  759. }
  760. virtual std::string portDeviceName(uint64_t nwid) const
  761. {
  762. Mutex::Lock _l(_taps_m);
  763. std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.find(nwid));
  764. if (t != _taps.end())
  765. return t->second->deviceName();
  766. return std::string();
  767. }
  768. virtual bool tcpFallbackActive() const
  769. {
  770. return (_tcpFallbackTunnel != (TcpConnection *)0);
  771. }
  772. virtual void terminate()
  773. {
  774. _run_m.lock();
  775. _run = false;
  776. _run_m.unlock();
  777. _phy.whack();
  778. }
  779. // Begin private implementation methods
  780. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
  781. {
  782. #ifdef ZT_ENABLE_CLUSTER
  783. if (sock == _clusterMessageSocket) {
  784. _lastDirectReceiveFromGlobal = OSUtils::now();
  785. _node->clusterHandleIncomingMessage(data,len);
  786. return;
  787. }
  788. #endif
  789. #ifdef ZT_BREAK_UDP
  790. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  791. return;
  792. #endif
  793. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  794. _lastDirectReceiveFromGlobal = OSUtils::now();
  795. ZT_ResultCode rc = _node->processWirePacket(
  796. OSUtils::now(),
  797. reinterpret_cast<const struct sockaddr_storage *>(*uptr),
  798. (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
  799. data,
  800. len,
  801. &_nextBackgroundTaskDeadline);
  802. if (ZT_ResultCode_isFatal(rc)) {
  803. char tmp[256];
  804. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  805. Mutex::Lock _l(_termReason_m);
  806. _termReason = ONE_UNRECOVERABLE_ERROR;
  807. _fatalErrorMessage = tmp;
  808. this->terminate();
  809. }
  810. }
  811. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  812. {
  813. if (!success)
  814. return;
  815. // Outgoing TCP connections are always TCP fallback tunnel connections.
  816. TcpConnection *tc = new TcpConnection();
  817. _tcpConnections.insert(tc);
  818. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  819. tc->shouldKeepAlive = true;
  820. tc->parent = this;
  821. tc->sock = sock;
  822. // from and parser are not used
  823. tc->messageSize = 0; // unused
  824. tc->lastActivity = OSUtils::now();
  825. // HTTP stuff is not used
  826. tc->writeBuf = "";
  827. *uptr = (void *)tc;
  828. // Send "hello" message
  829. tc->writeBuf.push_back((char)0x17);
  830. tc->writeBuf.push_back((char)0x03);
  831. tc->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  832. tc->writeBuf.push_back((char)0x00);
  833. tc->writeBuf.push_back((char)0x04); // mlen == 4
  834. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MAJOR);
  835. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MINOR);
  836. tc->writeBuf.push_back((char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff));
  837. tc->writeBuf.push_back((char)(ZEROTIER_ONE_VERSION_REVISION & 0xff));
  838. _phy.setNotifyWritable(sock,true);
  839. _tcpFallbackTunnel = tc;
  840. }
  841. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  842. {
  843. // Incoming TCP connections are HTTP JSON API requests.
  844. TcpConnection *tc = new TcpConnection();
  845. _tcpConnections.insert(tc);
  846. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  847. tc->shouldKeepAlive = true;
  848. tc->parent = this;
  849. tc->sock = sockN;
  850. tc->from = from;
  851. http_parser_init(&(tc->parser),HTTP_REQUEST);
  852. tc->parser.data = (void *)tc;
  853. tc->messageSize = 0;
  854. tc->lastActivity = OSUtils::now();
  855. tc->currentHeaderField = "";
  856. tc->currentHeaderValue = "";
  857. tc->url = "";
  858. tc->status = "";
  859. tc->headers.clear();
  860. tc->body = "";
  861. tc->writeBuf = "";
  862. *uptrN = (void *)tc;
  863. }
  864. inline void phyOnTcpClose(PhySocket *sock,void **uptr)
  865. {
  866. TcpConnection *tc = (TcpConnection *)*uptr;
  867. if (tc) {
  868. if (tc == _tcpFallbackTunnel)
  869. _tcpFallbackTunnel = (TcpConnection *)0;
  870. _tcpConnections.erase(tc);
  871. delete tc;
  872. }
  873. }
  874. inline void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  875. {
  876. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  877. switch(tc->type) {
  878. case TcpConnection::TCP_HTTP_INCOMING:
  879. case TcpConnection::TCP_HTTP_OUTGOING:
  880. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  881. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK)) {
  882. _phy.close(sock);
  883. return;
  884. }
  885. break;
  886. case TcpConnection::TCP_TUNNEL_OUTGOING:
  887. tc->body.append((const char *)data,len);
  888. while (tc->body.length() >= 5) {
  889. const char *data = tc->body.data();
  890. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  891. if (tc->body.length() >= (mlen + 5)) {
  892. InetAddress from;
  893. unsigned long plen = mlen; // payload length, modified if there's an IP header
  894. data += 5; // skip forward past pseudo-TLS junk and mlen
  895. if (plen == 4) {
  896. // Hello message, which isn't sent by proxy and would be ignored by client
  897. } else if (plen) {
  898. // Messages should contain IPv4 or IPv6 source IP address data
  899. switch(data[0]) {
  900. case 4: // IPv4
  901. if (plen >= 7) {
  902. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  903. data += 7; // type + 4 byte IP + 2 byte port
  904. plen -= 7;
  905. } else {
  906. _phy.close(sock);
  907. return;
  908. }
  909. break;
  910. case 6: // IPv6
  911. if (plen >= 19) {
  912. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  913. data += 19; // type + 16 byte IP + 2 byte port
  914. plen -= 19;
  915. } else {
  916. _phy.close(sock);
  917. return;
  918. }
  919. break;
  920. case 0: // none/omitted
  921. ++data;
  922. --plen;
  923. break;
  924. default: // invalid address type
  925. _phy.close(sock);
  926. return;
  927. }
  928. if (from) {
  929. ZT_ResultCode rc = _node->processWirePacket(
  930. OSUtils::now(),
  931. &ZT_SOCKADDR_NULL,
  932. reinterpret_cast<struct sockaddr_storage *>(&from),
  933. data,
  934. plen,
  935. &_nextBackgroundTaskDeadline);
  936. if (ZT_ResultCode_isFatal(rc)) {
  937. char tmp[256];
  938. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  939. Mutex::Lock _l(_termReason_m);
  940. _termReason = ONE_UNRECOVERABLE_ERROR;
  941. _fatalErrorMessage = tmp;
  942. this->terminate();
  943. _phy.close(sock);
  944. return;
  945. }
  946. }
  947. }
  948. if (tc->body.length() > (mlen + 5))
  949. tc->body = tc->body.substr(mlen + 5);
  950. else tc->body = "";
  951. } else break;
  952. }
  953. break;
  954. }
  955. }
  956. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  957. {
  958. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  959. Mutex::Lock _l(tc->writeBuf_m);
  960. if (tc->writeBuf.length() > 0) {
  961. long sent = (long)_phy.streamSend(sock,tc->writeBuf.data(),(unsigned long)tc->writeBuf.length(),true);
  962. if (sent > 0) {
  963. tc->lastActivity = OSUtils::now();
  964. if ((unsigned long)sent >= (unsigned long)tc->writeBuf.length()) {
  965. tc->writeBuf = "";
  966. _phy.setNotifyWritable(sock,false);
  967. if (!tc->shouldKeepAlive)
  968. _phy.close(sock); // will call close handler to delete from _tcpConnections
  969. } else {
  970. tc->writeBuf = tc->writeBuf.substr(sent);
  971. }
  972. }
  973. } else {
  974. _phy.setNotifyWritable(sock,false);
  975. }
  976. }
  977. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  978. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  979. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  980. inline void phyOnUnixWritable(PhySocket *sock,void **uptr) {}
  981. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  982. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  983. {
  984. Mutex::Lock _l(_taps_m);
  985. std::map< uint64_t,EthernetTap * >::iterator t(_taps.find(nwid));
  986. switch(op) {
  987. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  988. if (t == _taps.end()) {
  989. try {
  990. char friendlyName[1024];
  991. Utils::snprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  992. t = _taps.insert(std::pair< uint64_t,EthernetTap *>(nwid,new EthernetTap(
  993. _homePath.c_str(),
  994. MAC(nwc->mac),
  995. nwc->mtu,
  996. (unsigned int)ZT_IF_METRIC,
  997. nwid,
  998. friendlyName,
  999. StapFrameHandler,
  1000. (void *)this))).first;
  1001. } catch (std::exception &exc) {
  1002. #ifdef __WINDOWS__
  1003. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1004. if (tapFailLog) {
  1005. fprintf(tapFailLog,"%.16llx: %s"ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1006. fclose(tapFailLog);
  1007. }
  1008. #else
  1009. fprintf(stderr,"ERROR: unable to configure virtual network port: %s"ZT_EOL_S,exc.what());
  1010. #endif
  1011. return -999;
  1012. } catch ( ... ) {
  1013. return -999; // tap init failed
  1014. }
  1015. }
  1016. // fall through...
  1017. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1018. if (t != _taps.end()) {
  1019. t->second->setEnabled(nwc->enabled != 0);
  1020. std::vector<InetAddress> &assignedIps = _tapAssignedIps[nwid];
  1021. std::vector<InetAddress> newAssignedIps;
  1022. for(unsigned int i=0;i<nwc->assignedAddressCount;++i)
  1023. newAssignedIps.push_back(InetAddress(nwc->assignedAddresses[i]));
  1024. std::sort(newAssignedIps.begin(),newAssignedIps.end());
  1025. newAssignedIps.erase(std::unique(newAssignedIps.begin(),newAssignedIps.end()),newAssignedIps.end());
  1026. for(std::vector<InetAddress>::iterator ip(newAssignedIps.begin());ip!=newAssignedIps.end();++ip) {
  1027. if (!std::binary_search(assignedIps.begin(),assignedIps.end(),*ip))
  1028. if (!t->second->addIp(*ip))
  1029. fprintf(stderr,"ERROR: unable to add ip address %s"ZT_EOL_S, ip->toString().c_str());
  1030. }
  1031. for(std::vector<InetAddress>::iterator ip(assignedIps.begin());ip!=assignedIps.end();++ip) {
  1032. if (!std::binary_search(newAssignedIps.begin(),newAssignedIps.end(),*ip))
  1033. if (!t->second->removeIp(*ip))
  1034. fprintf(stderr,"ERROR: unable to remove ip address %s"ZT_EOL_S, ip->toString().c_str());
  1035. }
  1036. assignedIps.swap(newAssignedIps);
  1037. } else {
  1038. return -999; // tap init failed
  1039. }
  1040. break;
  1041. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1042. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1043. if (t != _taps.end()) {
  1044. #ifdef __WINDOWS__
  1045. std::string winInstanceId(t->second->instanceId());
  1046. #endif
  1047. delete t->second;
  1048. _taps.erase(t);
  1049. _tapAssignedIps.erase(nwid);
  1050. #ifdef __WINDOWS__
  1051. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1052. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1053. #endif
  1054. }
  1055. break;
  1056. }
  1057. return 0;
  1058. }
  1059. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1060. {
  1061. switch(event) {
  1062. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  1063. Mutex::Lock _l(_termReason_m);
  1064. _termReason = ONE_IDENTITY_COLLISION;
  1065. _fatalErrorMessage = "identity/address collision";
  1066. this->terminate();
  1067. } break;
  1068. case ZT_EVENT_TRACE: {
  1069. if (metaData) {
  1070. ::fprintf(stderr,"%s"ZT_EOL_S,(const char *)metaData);
  1071. ::fflush(stderr);
  1072. }
  1073. } break;
  1074. default:
  1075. break;
  1076. }
  1077. }
  1078. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1079. {
  1080. std::string p(_dataStorePrepPath(name));
  1081. if (!p.length())
  1082. return -2;
  1083. FILE *f = fopen(p.c_str(),"rb");
  1084. if (!f)
  1085. return -1;
  1086. if (fseek(f,0,SEEK_END) != 0) {
  1087. fclose(f);
  1088. return -2;
  1089. }
  1090. long ts = ftell(f);
  1091. if (ts < 0) {
  1092. fclose(f);
  1093. return -2;
  1094. }
  1095. *totalSize = (unsigned long)ts;
  1096. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  1097. fclose(f);
  1098. return -2;
  1099. }
  1100. long n = (long)fread(buf,1,bufSize,f);
  1101. fclose(f);
  1102. return n;
  1103. }
  1104. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  1105. {
  1106. std::string p(_dataStorePrepPath(name));
  1107. if (!p.length())
  1108. return -2;
  1109. if (!data) {
  1110. OSUtils::rm(p.c_str());
  1111. return 0;
  1112. }
  1113. FILE *f = fopen(p.c_str(),"wb");
  1114. if (!f)
  1115. return -1;
  1116. if (fwrite(data,len,1,f) == 1) {
  1117. fclose(f);
  1118. if (secure)
  1119. OSUtils::lockDownFile(p.c_str(),false);
  1120. return 0;
  1121. } else {
  1122. fclose(f);
  1123. OSUtils::rm(p.c_str());
  1124. return -1;
  1125. }
  1126. }
  1127. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1128. {
  1129. #ifdef ZT_USE_MINIUPNPC
  1130. if ((localAddr->ss_family == AF_INET)&&(reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port == reinterpret_cast<const struct sockaddr_in *>(&_v4UpnpLocalAddress)->sin_port)) {
  1131. #ifdef ZT_BREAK_UDP
  1132. if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
  1133. #endif
  1134. if (addr->ss_family == AF_INET) {
  1135. if (ttl)
  1136. _phy.setIp4UdpTtl(_v4UpnpUdpSocket,ttl);
  1137. const int result = ((_phy.udpSend(_v4UpnpUdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
  1138. if (ttl)
  1139. _phy.setIp4UdpTtl(_v4UpnpUdpSocket,255);
  1140. return result;
  1141. } else {
  1142. return -1;
  1143. }
  1144. #ifdef ZT_BREAK_UDP
  1145. }
  1146. #endif
  1147. }
  1148. #endif // ZT_USE_MINIUPNPC
  1149. int result = -1;
  1150. switch(addr->ss_family) {
  1151. case AF_INET:
  1152. #ifdef ZT_BREAK_UDP
  1153. if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
  1154. #endif
  1155. if (_v4UdpSocket) {
  1156. if (ttl)
  1157. _phy.setIp4UdpTtl(_v4UdpSocket,ttl);
  1158. result = ((_phy.udpSend(_v4UdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
  1159. if (ttl)
  1160. _phy.setIp4UdpTtl(_v4UdpSocket,255);
  1161. }
  1162. #ifdef ZT_BREAK_UDP
  1163. }
  1164. #endif
  1165. #ifdef ZT_TCP_FALLBACK_RELAY
  1166. // TCP fallback tunnel support
  1167. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  1168. uint64_t now = OSUtils::now();
  1169. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  1170. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  1171. // valid direct traffic we'll stop using it and close the socket after a while.
  1172. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  1173. if (_tcpFallbackTunnel) {
  1174. Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
  1175. if (!_tcpFallbackTunnel->writeBuf.length())
  1176. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  1177. unsigned long mlen = len + 7;
  1178. _tcpFallbackTunnel->writeBuf.push_back((char)0x17);
  1179. _tcpFallbackTunnel->writeBuf.push_back((char)0x03);
  1180. _tcpFallbackTunnel->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1181. _tcpFallbackTunnel->writeBuf.push_back((char)((mlen >> 8) & 0xff));
  1182. _tcpFallbackTunnel->writeBuf.push_back((char)(mlen & 0xff));
  1183. _tcpFallbackTunnel->writeBuf.push_back((char)4); // IPv4
  1184. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  1185. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  1186. _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
  1187. result = 0;
  1188. } else if (((now - _lastSendToGlobal) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobal) > (ZT_PING_CHECK_INVERVAL / 2))) {
  1189. std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
  1190. if (tunnelIps.empty()) {
  1191. if (!_tcpFallbackResolver.running())
  1192. _tcpFallbackResolver.resolveNow();
  1193. } else {
  1194. bool connected = false;
  1195. InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
  1196. addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
  1197. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
  1198. }
  1199. }
  1200. }
  1201. _lastSendToGlobal = now;
  1202. }
  1203. #endif // ZT_TCP_FALLBACK_RELAY
  1204. break;
  1205. case AF_INET6:
  1206. #ifdef ZT_BREAK_UDP
  1207. if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
  1208. #endif
  1209. if (_v6UdpSocket)
  1210. result = ((_phy.udpSend(_v6UdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
  1211. #ifdef ZT_BREAK_UDP
  1212. }
  1213. #endif
  1214. break;
  1215. default:
  1216. return -1;
  1217. }
  1218. return result;
  1219. }
  1220. inline void nodeVirtualNetworkFrameFunction(uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1221. {
  1222. Mutex::Lock _l(_taps_m);
  1223. std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.find(nwid));
  1224. if (t != _taps.end())
  1225. t->second->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1226. }
  1227. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1228. {
  1229. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1230. }
  1231. inline void onHttpRequestToServer(TcpConnection *tc)
  1232. {
  1233. char tmpn[256];
  1234. std::string data;
  1235. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1236. unsigned int scode = 404;
  1237. try {
  1238. if (_controlPlane)
  1239. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  1240. else scode = 500;
  1241. } catch ( ... ) {
  1242. scode = 500;
  1243. }
  1244. const char *scodestr;
  1245. switch(scode) {
  1246. case 200: scodestr = "OK"; break;
  1247. case 400: scodestr = "Bad Request"; break;
  1248. case 401: scodestr = "Unauthorized"; break;
  1249. case 403: scodestr = "Forbidden"; break;
  1250. case 404: scodestr = "Not Found"; break;
  1251. case 500: scodestr = "Internal Server Error"; break;
  1252. case 501: scodestr = "Not Implemented"; break;
  1253. case 503: scodestr = "Service Unavailable"; break;
  1254. default: scodestr = "Error"; break;
  1255. }
  1256. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  1257. {
  1258. Mutex::Lock _l(tc->writeBuf_m);
  1259. tc->writeBuf.assign(tmpn);
  1260. tc->writeBuf.append("Content-Type: ");
  1261. tc->writeBuf.append(contentType);
  1262. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  1263. tc->writeBuf.append(tmpn);
  1264. if (!tc->shouldKeepAlive)
  1265. tc->writeBuf.append("Connection: close\r\n");
  1266. tc->writeBuf.append("\r\n");
  1267. if (tc->parser.method != HTTP_HEAD)
  1268. tc->writeBuf.append(data);
  1269. }
  1270. _phy.setNotifyWritable(tc->sock,true);
  1271. }
  1272. inline void onHttpResponseFromClient(TcpConnection *tc)
  1273. {
  1274. if (!tc->shouldKeepAlive)
  1275. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConnections
  1276. }
  1277. std::string _dataStorePrepPath(const char *name) const
  1278. {
  1279. std::string p(_homePath);
  1280. p.push_back(ZT_PATH_SEPARATOR);
  1281. char lastc = (char)0;
  1282. for(const char *n=name;(*n);++n) {
  1283. if ((*n == '.')&&(lastc == '.'))
  1284. return std::string(); // don't allow ../../ stuff as a precaution
  1285. if (*n == '/') {
  1286. OSUtils::mkdir(p.c_str());
  1287. p.push_back(ZT_PATH_SEPARATOR);
  1288. } else p.push_back(*n);
  1289. lastc = *n;
  1290. }
  1291. return p;
  1292. }
  1293. const std::string _homePath;
  1294. BackgroundResolver _tcpFallbackResolver;
  1295. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  1296. SqliteNetworkController *_controller;
  1297. #endif
  1298. Phy<OneServiceImpl *> _phy;
  1299. Node *_node;
  1300. InetAddress _v4LocalAddress,_v6LocalAddress;
  1301. PhySocket *_v4UdpSocket;
  1302. PhySocket *_v6UdpSocket;
  1303. PhySocket *_v4TcpListenSocket;
  1304. PhySocket *_v6TcpListenSocket;
  1305. ControlPlane *_controlPlane;
  1306. uint64_t _lastDirectReceiveFromGlobal;
  1307. uint64_t _lastSendToGlobal;
  1308. uint64_t _lastRestart;
  1309. volatile uint64_t _nextBackgroundTaskDeadline;
  1310. std::map< uint64_t,EthernetTap * > _taps;
  1311. std::map< uint64_t,std::vector<InetAddress> > _tapAssignedIps; // ZeroTier assigned IPs, not user or dhcp assigned
  1312. Mutex _taps_m;
  1313. std::set< TcpConnection * > _tcpConnections; // no mutex for this since it's done in the main loop thread only
  1314. TcpConnection *_tcpFallbackTunnel;
  1315. ReasonForTermination _termReason;
  1316. std::string _fatalErrorMessage;
  1317. Mutex _termReason_m;
  1318. unsigned int _port;
  1319. #ifdef ZT_USE_MINIUPNPC
  1320. InetAddress _v4UpnpLocalAddress;
  1321. PhySocket *_v4UpnpUdpSocket;
  1322. PortMapper *_portMapper;
  1323. #endif
  1324. #ifdef ZT_ENABLE_CLUSTER
  1325. PhySocket *_clusterMessageSocket;
  1326. ClusterGeoIpService *_clusterGeoIpService;
  1327. ClusterDefinition *_clusterDefinition;
  1328. unsigned int _clusterMemberId;
  1329. #endif
  1330. bool _run;
  1331. Mutex _run_m;
  1332. };
  1333. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  1334. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,op,nwconf); }
  1335. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData)
  1336. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1337. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1338. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  1339. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  1340. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  1341. 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)
  1342. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localAddr,addr,data,len,ttl); }
  1343. 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)
  1344. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,sourceMac,destMac,etherType,vlanId,data,len); }
  1345. #ifdef ZT_ENABLE_CLUSTER
  1346. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len)
  1347. {
  1348. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1349. const ClusterDefinition::MemberDefinition &md = (*(impl->_clusterDefinition))[toMemberId];
  1350. if (md.clusterEndpoint)
  1351. impl->_phy.udpSend(impl->_clusterMessageSocket,reinterpret_cast<const struct sockaddr *>(&(md.clusterEndpoint)),data,len);
  1352. }
  1353. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z)
  1354. {
  1355. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1356. return (int)(impl->_clusterGeoIpService->locate(*(reinterpret_cast<const InetAddress *>(addr)),*x,*y,*z));
  1357. }
  1358. #endif
  1359. 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)
  1360. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1361. static int ShttpOnMessageBegin(http_parser *parser)
  1362. {
  1363. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1364. tc->currentHeaderField = "";
  1365. tc->currentHeaderValue = "";
  1366. tc->messageSize = 0;
  1367. tc->url = "";
  1368. tc->status = "";
  1369. tc->headers.clear();
  1370. tc->body = "";
  1371. return 0;
  1372. }
  1373. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  1374. {
  1375. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1376. tc->messageSize += (unsigned long)length;
  1377. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1378. return -1;
  1379. tc->url.append(ptr,length);
  1380. return 0;
  1381. }
  1382. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1383. {
  1384. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1385. tc->messageSize += (unsigned long)length;
  1386. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1387. return -1;
  1388. tc->status.append(ptr,length);
  1389. return 0;
  1390. }
  1391. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1392. {
  1393. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1394. tc->messageSize += (unsigned long)length;
  1395. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1396. return -1;
  1397. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1398. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1399. tc->currentHeaderField = "";
  1400. tc->currentHeaderValue = "";
  1401. }
  1402. for(size_t i=0;i<length;++i)
  1403. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1404. return 0;
  1405. }
  1406. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1407. {
  1408. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1409. tc->messageSize += (unsigned long)length;
  1410. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1411. return -1;
  1412. tc->currentHeaderValue.append(ptr,length);
  1413. return 0;
  1414. }
  1415. static int ShttpOnHeadersComplete(http_parser *parser)
  1416. {
  1417. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1418. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  1419. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1420. return 0;
  1421. }
  1422. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  1423. {
  1424. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1425. tc->messageSize += (unsigned long)length;
  1426. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1427. return -1;
  1428. tc->body.append(ptr,length);
  1429. return 0;
  1430. }
  1431. static int ShttpOnMessageComplete(http_parser *parser)
  1432. {
  1433. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1434. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  1435. tc->lastActivity = OSUtils::now();
  1436. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  1437. tc->parent->onHttpRequestToServer(tc);
  1438. } else {
  1439. tc->parent->onHttpResponseFromClient(tc);
  1440. }
  1441. return 0;
  1442. }
  1443. } // anonymous namespace
  1444. std::string OneService::platformDefaultHomePath()
  1445. {
  1446. #ifdef __UNIX_LIKE__
  1447. #ifdef __APPLE__
  1448. // /Library/... on Apple
  1449. return std::string("/Library/Application Support/ZeroTier/One");
  1450. #else
  1451. #ifdef __BSD__
  1452. // BSD likes /var/db instead of /var/lib
  1453. return std::string("/var/db/zerotier-one");
  1454. #else
  1455. // Use /var/lib for Linux and other *nix
  1456. return std::string("/var/lib/zerotier-one");
  1457. #endif
  1458. #endif
  1459. #else // not __UNIX_LIKE__
  1460. #ifdef __WINDOWS__
  1461. // Look up app data folder on Windows, e.g. C:\ProgramData\...
  1462. char buf[16384];
  1463. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_COMMON_APPDATA,NULL,0,buf)))
  1464. return (std::string(buf) + "\\ZeroTier\\One");
  1465. else return std::string("C:\\ZeroTier\\One");
  1466. #else
  1467. return std::string(); // UNKNOWN PLATFORM
  1468. #endif
  1469. #endif // __UNIX_LIKE__ or not...
  1470. }
  1471. std::string OneService::autoUpdateUrl()
  1472. {
  1473. #ifdef ZT_AUTO_UPDATE
  1474. /*
  1475. #if defined(__LINUX__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1476. if (sizeof(void *) == 8)
  1477. return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x64-LATEST.nfo";
  1478. else return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x86-LATEST.nfo";
  1479. #endif
  1480. */
  1481. #if defined(__APPLE__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  1482. return "http://download.zerotier.com/update/mac_intel/";
  1483. #endif
  1484. #ifdef __WINDOWS__
  1485. return "http://download.zerotier.com/update/win_intel/";
  1486. #endif
  1487. #endif // ZT_AUTO_UPDATE
  1488. return std::string();
  1489. }
  1490. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  1491. OneService::~OneService() {}
  1492. } // namespace ZeroTier