OneService.cpp 48 KB

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