OneService.cpp 44 KB

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