OneService.cpp 51 KB

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