OneService.cpp 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 ZeroTier, Inc. https://www.zerotier.com/
  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. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <stdint.h>
  30. #include <string>
  31. #include <map>
  32. #include <vector>
  33. #include <algorithm>
  34. #include <list>
  35. #include "../version.h"
  36. #include "../include/ZeroTierOne.h"
  37. #include "../node/Constants.hpp"
  38. #include "../node/Mutex.hpp"
  39. #include "../node/Node.hpp"
  40. #include "../node/Utils.hpp"
  41. #include "../node/InetAddress.hpp"
  42. #include "../node/MAC.hpp"
  43. #include "../node/Identity.hpp"
  44. #include "../node/World.hpp"
  45. #include "../node/Salsa20.hpp"
  46. #include "../node/Poly1305.hpp"
  47. #include "../node/SHA512.hpp"
  48. #include "../osdep/Phy.hpp"
  49. #include "../osdep/Thread.hpp"
  50. #include "../osdep/OSUtils.hpp"
  51. #include "../osdep/Http.hpp"
  52. #include "../osdep/PortMapper.hpp"
  53. #include "../osdep/Binder.hpp"
  54. #include "../osdep/ManagedRoute.hpp"
  55. #include "OneService.hpp"
  56. #include "SoftwareUpdater.hpp"
  57. #ifdef __WINDOWS__
  58. #include <WinSock2.h>
  59. #include <Windows.h>
  60. #include <ShlObj.h>
  61. #include <netioapi.h>
  62. #include <iphlpapi.h>
  63. #else
  64. #include <sys/types.h>
  65. #include <sys/socket.h>
  66. #include <sys/wait.h>
  67. #include <unistd.h>
  68. #include <ifaddrs.h>
  69. #endif
  70. #ifdef ZT_USE_SYSTEM_HTTP_PARSER
  71. #include <http_parser.h>
  72. #else
  73. #include "../ext/http-parser/http_parser.h"
  74. #endif
  75. #if ZT_VAULT_SUPPORT
  76. extern "C" {
  77. #include <curl/curl.h>
  78. }
  79. #endif
  80. #include "../ext/json/json.hpp"
  81. using json = nlohmann::json;
  82. #include "../controller/EmbeddedNetworkController.hpp"
  83. #ifdef ZT_USE_TEST_TAP
  84. #include "../osdep/TestEthernetTap.hpp"
  85. namespace ZeroTier { typedef TestEthernetTap EthernetTap; }
  86. #else
  87. #ifdef ZT_SDK
  88. #include "../controller/EmbeddedNetworkController.hpp"
  89. #include "../node/Node.hpp"
  90. // Use the virtual netcon endpoint instead of a tun/tap port driver
  91. #include "../include/VirtualTap.h"
  92. namespace ZeroTier { typedef VirtualTap EthernetTap; }
  93. #else
  94. #ifdef __APPLE__
  95. #include "../osdep/OSXEthernetTap.hpp"
  96. namespace ZeroTier { typedef OSXEthernetTap EthernetTap; }
  97. #endif // __APPLE__
  98. #ifdef __LINUX__
  99. #include "../osdep/LinuxEthernetTap.hpp"
  100. namespace ZeroTier { typedef LinuxEthernetTap EthernetTap; }
  101. #endif // __LINUX__
  102. #ifdef __WINDOWS__
  103. #include "../osdep/WindowsEthernetTap.hpp"
  104. namespace ZeroTier { typedef WindowsEthernetTap EthernetTap; }
  105. #endif // __WINDOWS__
  106. #ifdef __FreeBSD__
  107. #include "../osdep/BSDEthernetTap.hpp"
  108. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  109. #endif // __FreeBSD__
  110. #ifdef __NetBSD__
  111. #include "../osdep/NetBSDEthernetTap.hpp"
  112. namespace ZeroTier { typedef NetBSDEthernetTap EthernetTap; }
  113. #endif // __NetBSD__
  114. #ifdef __OpenBSD__
  115. #include "../osdep/BSDEthernetTap.hpp"
  116. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  117. #endif // __OpenBSD__
  118. #endif // ZT_SERVICE_NETCON
  119. #endif // ZT_USE_TEST_TAP
  120. // Sanity limits for HTTP
  121. #define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 64)
  122. #define ZT_MAX_HTTP_CONNECTIONS 65536
  123. // Interface metric for ZeroTier taps -- this ensures that if we are on WiFi and also
  124. // bridged via ZeroTier to the same LAN traffic will (if the OS is sane) prefer WiFi.
  125. #define ZT_IF_METRIC 5000
  126. // How often to check for new multicast subscriptions on a tap device
  127. #define ZT_TAP_CHECK_MULTICAST_INTERVAL 5000
  128. // TCP fallback relay (run by ZeroTier, Inc. -- this will eventually go away)
  129. #define ZT_TCP_FALLBACK_RELAY "204.80.128.1/443"
  130. // Frequency at which we re-resolve the TCP fallback relay
  131. #define ZT_TCP_FALLBACK_RERESOLVE_DELAY 86400000
  132. // Attempt to engage TCP fallback after this many ms of no reply to packets sent to global-scope IPs
  133. #define ZT_TCP_FALLBACK_AFTER 60000
  134. // How often to check for local interface addresses
  135. #define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 60000
  136. // Maximum write buffer size for outgoing TCP connections (sanity limit)
  137. #define ZT_TCP_MAX_WRITEQ_SIZE 33554432
  138. // TCP activity timeout
  139. #define ZT_TCP_ACTIVITY_TIMEOUT 60000
  140. #if ZT_VAULT_SUPPORT
  141. size_t curlResponseWrite(void *ptr, size_t size, size_t nmemb, std::string *data)
  142. {
  143. data->append((char*)ptr, size * nmemb);
  144. return size * nmemb;
  145. }
  146. #endif
  147. namespace ZeroTier {
  148. namespace {
  149. // Fake TLS hello for TCP tunnel outgoing connections (TUNNELED mode)
  150. static const char ZT_TCP_TUNNEL_HELLO[9] = { 0x17,0x03,0x03,0x00,0x04,(char)ZEROTIER_ONE_VERSION_MAJOR,(char)ZEROTIER_ONE_VERSION_MINOR,(char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff),(char)(ZEROTIER_ONE_VERSION_REVISION & 0xff) };
  151. static std::string _trimString(const std::string &s)
  152. {
  153. unsigned long end = (unsigned long)s.length();
  154. while (end) {
  155. char c = s[end - 1];
  156. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  157. --end;
  158. else break;
  159. }
  160. unsigned long start = 0;
  161. while (start < end) {
  162. char c = s[start];
  163. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  164. ++start;
  165. else break;
  166. }
  167. return s.substr(start,end - start);
  168. }
  169. static void _networkToJson(nlohmann::json &nj,const ZT_VirtualNetworkConfig *nc,const std::string &portDeviceName,const OneService::NetworkSettings &localSettings)
  170. {
  171. char tmp[256];
  172. const char *nstatus = "",*ntype = "";
  173. switch(nc->status) {
  174. case ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION: nstatus = "REQUESTING_CONFIGURATION"; break;
  175. case ZT_NETWORK_STATUS_OK: nstatus = "OK"; break;
  176. case ZT_NETWORK_STATUS_ACCESS_DENIED: nstatus = "ACCESS_DENIED"; break;
  177. case ZT_NETWORK_STATUS_NOT_FOUND: nstatus = "NOT_FOUND"; break;
  178. case ZT_NETWORK_STATUS_PORT_ERROR: nstatus = "PORT_ERROR"; break;
  179. case ZT_NETWORK_STATUS_CLIENT_TOO_OLD: nstatus = "CLIENT_TOO_OLD"; break;
  180. }
  181. switch(nc->type) {
  182. case ZT_NETWORK_TYPE_PRIVATE: ntype = "PRIVATE"; break;
  183. case ZT_NETWORK_TYPE_PUBLIC: ntype = "PUBLIC"; break;
  184. }
  185. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",nc->nwid);
  186. nj["id"] = tmp;
  187. nj["nwid"] = tmp;
  188. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(unsigned int)((nc->mac >> 40) & 0xff),(unsigned int)((nc->mac >> 32) & 0xff),(unsigned int)((nc->mac >> 24) & 0xff),(unsigned int)((nc->mac >> 16) & 0xff),(unsigned int)((nc->mac >> 8) & 0xff),(unsigned int)(nc->mac & 0xff));
  189. nj["mac"] = tmp;
  190. nj["name"] = nc->name;
  191. nj["status"] = nstatus;
  192. nj["type"] = ntype;
  193. nj["mtu"] = nc->mtu;
  194. nj["dhcp"] = (bool)(nc->dhcp != 0);
  195. nj["bridge"] = (bool)(nc->bridge != 0);
  196. nj["broadcastEnabled"] = (bool)(nc->broadcastEnabled != 0);
  197. nj["portError"] = nc->portError;
  198. nj["netconfRevision"] = nc->netconfRevision;
  199. nj["portDeviceName"] = portDeviceName;
  200. nj["allowManaged"] = localSettings.allowManaged;
  201. nj["allowGlobal"] = localSettings.allowGlobal;
  202. nj["allowDefault"] = localSettings.allowDefault;
  203. nlohmann::json aa = nlohmann::json::array();
  204. for(unsigned int i=0;i<nc->assignedAddressCount;++i) {
  205. aa.push_back(reinterpret_cast<const InetAddress *>(&(nc->assignedAddresses[i]))->toString(tmp));
  206. }
  207. nj["assignedAddresses"] = aa;
  208. nlohmann::json ra = nlohmann::json::array();
  209. for(unsigned int i=0;i<nc->routeCount;++i) {
  210. nlohmann::json rj;
  211. rj["target"] = reinterpret_cast<const InetAddress *>(&(nc->routes[i].target))->toString(tmp);
  212. if (nc->routes[i].via.ss_family == nc->routes[i].target.ss_family)
  213. rj["via"] = reinterpret_cast<const InetAddress *>(&(nc->routes[i].via))->toIpString(tmp);
  214. else rj["via"] = nlohmann::json();
  215. rj["flags"] = (int)nc->routes[i].flags;
  216. rj["metric"] = (int)nc->routes[i].metric;
  217. ra.push_back(rj);
  218. }
  219. nj["routes"] = ra;
  220. }
  221. static void _peerToJson(nlohmann::json &pj,const ZT_Peer *peer)
  222. {
  223. char tmp[256];
  224. const char *prole = "";
  225. switch(peer->role) {
  226. case ZT_PEER_ROLE_LEAF: prole = "LEAF"; break;
  227. case ZT_PEER_ROLE_MOON: prole = "MOON"; break;
  228. case ZT_PEER_ROLE_PLANET: prole = "PLANET"; break;
  229. }
  230. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.10llx",peer->address);
  231. pj["address"] = tmp;
  232. pj["versionMajor"] = peer->versionMajor;
  233. pj["versionMinor"] = peer->versionMinor;
  234. pj["versionRev"] = peer->versionRev;
  235. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%d.%d.%d",peer->versionMajor,peer->versionMinor,peer->versionRev);
  236. pj["version"] = tmp;
  237. pj["latency"] = peer->latency;
  238. pj["role"] = prole;
  239. nlohmann::json pa = nlohmann::json::array();
  240. for(unsigned int i=0;i<peer->pathCount;++i) {
  241. int64_t lastSend = peer->paths[i].lastSend;
  242. int64_t lastReceive = peer->paths[i].lastReceive;
  243. nlohmann::json j;
  244. j["address"] = reinterpret_cast<const InetAddress *>(&(peer->paths[i].address))->toString(tmp);
  245. j["lastSend"] = (lastSend < 0) ? 0 : lastSend;
  246. j["lastReceive"] = (lastReceive < 0) ? 0 : lastReceive;
  247. j["trustedPathId"] = peer->paths[i].trustedPathId;
  248. j["active"] = (bool)(peer->paths[i].expired == 0);
  249. j["expired"] = (bool)(peer->paths[i].expired != 0);
  250. j["preferred"] = (bool)(peer->paths[i].preferred != 0);
  251. pa.push_back(j);
  252. }
  253. pj["paths"] = pa;
  254. }
  255. static void _peerAggregateLinkToJson(nlohmann::json &pj,const ZT_Peer *peer)
  256. {
  257. char tmp[256];
  258. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.10llx",peer->address);
  259. pj["aggregateLinkLatency"] = peer->latency;
  260. nlohmann::json pa = nlohmann::json::array();
  261. for(unsigned int i=0;i<peer->pathCount;++i) {
  262. int64_t lastSend = peer->paths[i].lastSend;
  263. int64_t lastReceive = peer->paths[i].lastReceive;
  264. nlohmann::json j;
  265. j["address"] = reinterpret_cast<const InetAddress *>(&(peer->paths[i].address))->toString(tmp);
  266. j["lastSend"] = (lastSend < 0) ? 0 : lastSend;
  267. j["lastReceive"] = (lastReceive < 0) ? 0 : lastReceive;
  268. //j["trustedPathId"] = peer->paths[i].trustedPathId;
  269. //j["active"] = (bool)(peer->paths[i].expired == 0);
  270. //j["expired"] = (bool)(peer->paths[i].expired != 0);
  271. //j["preferred"] = (bool)(peer->paths[i].preferred != 0);
  272. j["latency"] = peer->paths[i].latency;
  273. j["pdv"] = peer->paths[i].packetDelayVariance;
  274. //j["throughputDisturbCoeff"] = peer->paths[i].throughputDisturbCoeff;
  275. //j["packetErrorRatio"] = peer->paths[i].packetErrorRatio;
  276. //j["packetLossRatio"] = peer->paths[i].packetLossRatio;
  277. j["stability"] = peer->paths[i].stability;
  278. j["throughput"] = peer->paths[i].throughput;
  279. //j["maxThroughput"] = peer->paths[i].maxThroughput;
  280. j["allocation"] = peer->paths[i].allocation;
  281. j["ifname"] = peer->paths[i].ifname;
  282. pa.push_back(j);
  283. }
  284. pj["paths"] = pa;
  285. }
  286. static void _moonToJson(nlohmann::json &mj,const World &world)
  287. {
  288. char tmp[4096];
  289. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",world.id());
  290. mj["id"] = tmp;
  291. mj["timestamp"] = world.timestamp();
  292. mj["signature"] = Utils::hex(world.signature().data,ZT_C25519_SIGNATURE_LEN,tmp);
  293. mj["updatesMustBeSignedBy"] = Utils::hex(world.updatesMustBeSignedBy().data,ZT_C25519_PUBLIC_KEY_LEN,tmp);
  294. nlohmann::json ra = nlohmann::json::array();
  295. for(std::vector<World::Root>::const_iterator r(world.roots().begin());r!=world.roots().end();++r) {
  296. nlohmann::json rj;
  297. rj["identity"] = r->identity.toString(false,tmp);
  298. nlohmann::json eps = nlohmann::json::array();
  299. for(std::vector<InetAddress>::const_iterator a(r->stableEndpoints.begin());a!=r->stableEndpoints.end();++a)
  300. eps.push_back(a->toString(tmp));
  301. rj["stableEndpoints"] = eps;
  302. ra.push_back(rj);
  303. }
  304. mj["roots"] = ra;
  305. mj["waiting"] = false;
  306. }
  307. class OneServiceImpl;
  308. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
  309. static void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData);
  310. static void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len);
  311. static int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen);
  312. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,void *tptr,int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl);
  313. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  314. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr);
  315. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result);
  316. static void StapFrameHandler(void *uptr,void *tptr,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. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  320. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  321. #else
  322. static int ShttpOnStatus(http_parser *parser);
  323. #endif
  324. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  325. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  326. static int ShttpOnHeadersComplete(http_parser *parser);
  327. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  328. static int ShttpOnMessageComplete(http_parser *parser);
  329. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 1)
  330. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  331. ShttpOnMessageBegin,
  332. ShttpOnUrl,
  333. ShttpOnStatus,
  334. ShttpOnHeaderField,
  335. ShttpOnValue,
  336. ShttpOnHeadersComplete,
  337. ShttpOnBody,
  338. ShttpOnMessageComplete
  339. };
  340. #else
  341. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  342. ShttpOnMessageBegin,
  343. ShttpOnUrl,
  344. ShttpOnHeaderField,
  345. ShttpOnValue,
  346. ShttpOnHeadersComplete,
  347. ShttpOnBody,
  348. ShttpOnMessageComplete
  349. };
  350. #endif
  351. /**
  352. * A TCP connection and related state and buffers
  353. */
  354. struct TcpConnection
  355. {
  356. enum {
  357. TCP_UNCATEGORIZED_INCOMING, // uncategorized incoming connection
  358. TCP_HTTP_INCOMING,
  359. TCP_HTTP_OUTGOING,
  360. TCP_TUNNEL_OUTGOING // TUNNELED mode proxy outbound connection
  361. } type;
  362. OneServiceImpl *parent;
  363. PhySocket *sock;
  364. InetAddress remoteAddr;
  365. uint64_t lastReceive;
  366. // Used for inbound HTTP connections
  367. http_parser parser;
  368. unsigned long messageSize;
  369. std::string currentHeaderField;
  370. std::string currentHeaderValue;
  371. std::string url;
  372. std::string status;
  373. std::map< std::string,std::string > headers;
  374. std::string readq;
  375. std::string writeq;
  376. Mutex writeq_m;
  377. };
  378. class OneServiceImpl : public OneService
  379. {
  380. public:
  381. // begin member variables --------------------------------------------------
  382. const std::string _homePath;
  383. std::string _authToken;
  384. std::string _controllerDbPath;
  385. const std::string _networksPath;
  386. const std::string _moonsPath;
  387. EmbeddedNetworkController *_controller;
  388. Phy<OneServiceImpl *> _phy;
  389. Node *_node;
  390. SoftwareUpdater *_updater;
  391. PhySocket *_localControlSocket4;
  392. PhySocket *_localControlSocket6;
  393. bool _updateAutoApply;
  394. bool _allowTcpFallbackRelay;
  395. unsigned int _multipathMode;
  396. unsigned int _primaryPort;
  397. unsigned int _secondaryPort;
  398. unsigned int _tertiaryPort;
  399. volatile unsigned int _udpPortPickerCounter;
  400. // Local configuration and memo-ized information from it
  401. json _localConfig;
  402. Hashtable< uint64_t,std::vector<InetAddress> > _v4Hints;
  403. Hashtable< uint64_t,std::vector<InetAddress> > _v6Hints;
  404. Hashtable< uint64_t,std::vector<InetAddress> > _v4Blacklists;
  405. Hashtable< uint64_t,std::vector<InetAddress> > _v6Blacklists;
  406. std::vector< InetAddress > _globalV4Blacklist;
  407. std::vector< InetAddress > _globalV6Blacklist;
  408. std::vector< InetAddress > _allowManagementFrom;
  409. std::vector< std::string > _interfacePrefixBlacklist;
  410. Mutex _localConfig_m;
  411. /*
  412. * To attempt to handle NAT/gateway craziness we use three local UDP ports:
  413. *
  414. * [0] is the normal/default port, usually 9993
  415. * [1] is a port derived from our ZeroTier address
  416. * [2] is a port computed from the normal/default for use with uPnP/NAT-PMP mappings
  417. *
  418. * [2] exists because on some gateways trying to do regular NAT-t interferes
  419. * destructively with uPnP port mapping behavior in very weird buggy ways.
  420. * It's only used if uPnP/NAT-PMP is enabled in this build.
  421. */
  422. unsigned int _ports[3];
  423. Binder _binder;
  424. // Time we last received a packet from a global address
  425. uint64_t _lastDirectReceiveFromGlobal;
  426. #ifdef ZT_TCP_FALLBACK_RELAY
  427. uint64_t _lastSendToGlobalV4;
  428. #endif
  429. // Last potential sleep/wake event
  430. uint64_t _lastRestart;
  431. // Deadline for the next background task service function
  432. volatile int64_t _nextBackgroundTaskDeadline;
  433. // Configured networks
  434. struct NetworkState
  435. {
  436. NetworkState() :
  437. tap((EthernetTap *)0)
  438. {
  439. // Real defaults are in network 'up' code in network event handler
  440. settings.allowManaged = true;
  441. settings.allowGlobal = false;
  442. settings.allowDefault = false;
  443. }
  444. EthernetTap *tap;
  445. ZT_VirtualNetworkConfig config; // memcpy() of raw config from core
  446. std::vector<InetAddress> managedIps;
  447. std::list< SharedPtr<ManagedRoute> > managedRoutes;
  448. NetworkSettings settings;
  449. };
  450. std::map<uint64_t,NetworkState> _nets;
  451. Mutex _nets_m;
  452. // Active TCP/IP connections
  453. std::vector< TcpConnection * > _tcpConnections;
  454. Mutex _tcpConnections_m;
  455. TcpConnection *_tcpFallbackTunnel;
  456. // Termination status information
  457. ReasonForTermination _termReason;
  458. std::string _fatalErrorMessage;
  459. Mutex _termReason_m;
  460. // uPnP/NAT-PMP port mapper if enabled
  461. bool _portMappingEnabled; // local.conf settings
  462. #ifdef ZT_USE_MINIUPNPC
  463. PortMapper *_portMapper;
  464. #endif
  465. // HashiCorp Vault Settings
  466. #if ZT_VAULT_SUPPORT
  467. bool _vaultEnabled;
  468. std::string _vaultURL;
  469. std::string _vaultToken;
  470. std::string _vaultPath; // defaults to cubbyhole/zerotier/identity.secret for per-access key storage
  471. #endif
  472. // Set to false to force service to stop
  473. volatile bool _run;
  474. Mutex _run_m;
  475. // end member variables ----------------------------------------------------
  476. OneServiceImpl(const char *hp,unsigned int port) :
  477. _homePath((hp) ? hp : ".")
  478. ,_controllerDbPath(_homePath + ZT_PATH_SEPARATOR_S "controller.d")
  479. ,_networksPath(_homePath + ZT_PATH_SEPARATOR_S "networks.d")
  480. ,_moonsPath(_homePath + ZT_PATH_SEPARATOR_S "moons.d")
  481. ,_controller((EmbeddedNetworkController *)0)
  482. ,_phy(this,false,true)
  483. ,_node((Node *)0)
  484. ,_updater((SoftwareUpdater *)0)
  485. ,_localControlSocket4((PhySocket *)0)
  486. ,_localControlSocket6((PhySocket *)0)
  487. ,_updateAutoApply(false)
  488. ,_primaryPort(port)
  489. ,_udpPortPickerCounter(0)
  490. ,_lastDirectReceiveFromGlobal(0)
  491. #ifdef ZT_TCP_FALLBACK_RELAY
  492. ,_lastSendToGlobalV4(0)
  493. #endif
  494. ,_lastRestart(0)
  495. ,_nextBackgroundTaskDeadline(0)
  496. ,_tcpFallbackTunnel((TcpConnection *)0)
  497. ,_termReason(ONE_STILL_RUNNING)
  498. ,_portMappingEnabled(true)
  499. #ifdef ZT_USE_MINIUPNPC
  500. ,_portMapper((PortMapper *)0)
  501. #endif
  502. #ifdef ZT_VAULT_SUPPORT
  503. ,_vaultEnabled(false)
  504. ,_vaultURL()
  505. ,_vaultToken()
  506. ,_vaultPath("cubbyhole/zerotier")
  507. #endif
  508. ,_run(true)
  509. {
  510. _ports[0] = 0;
  511. _ports[1] = 0;
  512. _ports[2] = 0;
  513. #if ZT_VAULT_SUPPORT
  514. curl_global_init(CURL_GLOBAL_DEFAULT);
  515. #endif
  516. }
  517. virtual ~OneServiceImpl()
  518. {
  519. _binder.closeAll(_phy);
  520. _phy.close(_localControlSocket4);
  521. _phy.close(_localControlSocket6);
  522. #if ZT_VAULT_SUPPORT
  523. curl_global_cleanup();
  524. #endif
  525. #ifdef ZT_USE_MINIUPNPC
  526. delete _portMapper;
  527. #endif
  528. delete _controller;
  529. }
  530. virtual ReasonForTermination run()
  531. {
  532. try {
  533. {
  534. const std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S "authtoken.secret");
  535. if (!OSUtils::readFile(authTokenPath.c_str(),_authToken)) {
  536. unsigned char foo[24];
  537. Utils::getSecureRandom(foo,sizeof(foo));
  538. _authToken = "";
  539. for(unsigned int i=0;i<sizeof(foo);++i)
  540. _authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  541. if (!OSUtils::writeFile(authTokenPath.c_str(),_authToken)) {
  542. Mutex::Lock _l(_termReason_m);
  543. _termReason = ONE_UNRECOVERABLE_ERROR;
  544. _fatalErrorMessage = "authtoken.secret could not be written";
  545. return _termReason;
  546. } else {
  547. OSUtils::lockDownFile(authTokenPath.c_str(),false);
  548. }
  549. }
  550. _authToken = _trimString(_authToken);
  551. }
  552. {
  553. struct ZT_Node_Callbacks cb;
  554. cb.version = 0;
  555. cb.stateGetFunction = SnodeStateGetFunction;
  556. cb.statePutFunction = SnodeStatePutFunction;
  557. cb.wirePacketSendFunction = SnodeWirePacketSendFunction;
  558. cb.virtualNetworkFrameFunction = SnodeVirtualNetworkFrameFunction;
  559. cb.virtualNetworkConfigFunction = SnodeVirtualNetworkConfigFunction;
  560. cb.eventCallback = SnodeEventCallback;
  561. cb.pathCheckFunction = SnodePathCheckFunction;
  562. cb.pathLookupFunction = SnodePathLookupFunction;
  563. _node = new Node(this,(void *)0,&cb,OSUtils::now());
  564. }
  565. // Read local configuration
  566. std::vector<InetAddress> explicitBind;
  567. {
  568. std::map<InetAddress,ZT_PhysicalPathConfiguration> ppc;
  569. // LEGACY: support old "trustedpaths" flat file
  570. FILE *trustpaths = fopen((_homePath + ZT_PATH_SEPARATOR_S "trustedpaths").c_str(),"r");
  571. if (trustpaths) {
  572. fprintf(stderr,"WARNING: 'trustedpaths' flat file format is deprecated in favor of path definitions in local.conf" ZT_EOL_S);
  573. char buf[1024];
  574. while (fgets(buf,sizeof(buf),trustpaths)) {
  575. int fno = 0;
  576. char *saveptr = (char *)0;
  577. uint64_t trustedPathId = 0;
  578. InetAddress trustedPathNetwork;
  579. for(char *f=Utils::stok(buf,"=\r\n \t",&saveptr);(f);f=Utils::stok((char *)0,"=\r\n \t",&saveptr)) {
  580. if (fno == 0) {
  581. trustedPathId = Utils::hexStrToU64(f);
  582. } else if (fno == 1) {
  583. trustedPathNetwork = InetAddress(f);
  584. } else break;
  585. ++fno;
  586. }
  587. if ( (trustedPathId != 0) && ((trustedPathNetwork.ss_family == AF_INET)||(trustedPathNetwork.ss_family == AF_INET6)) && (trustedPathNetwork.netmaskBits() > 0) ) {
  588. ppc[trustedPathNetwork].trustedPathId = trustedPathId;
  589. ppc[trustedPathNetwork].mtu = 0; // use default
  590. }
  591. }
  592. fclose(trustpaths);
  593. }
  594. // Read local config file
  595. Mutex::Lock _l2(_localConfig_m);
  596. std::string lcbuf;
  597. if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S "local.conf").c_str(),lcbuf)) {
  598. try {
  599. _localConfig = OSUtils::jsonParse(lcbuf);
  600. if (!_localConfig.is_object()) {
  601. fprintf(stderr,"WARNING: unable to parse local.conf (root element is not a JSON object)" ZT_EOL_S);
  602. }
  603. } catch ( ... ) {
  604. fprintf(stderr,"WARNING: unable to parse local.conf (invalid JSON)" ZT_EOL_S);
  605. }
  606. }
  607. // Get any trusted paths in local.conf (we'll parse the rest of physical[] elsewhere)
  608. json &physical = _localConfig["physical"];
  609. if (physical.is_object()) {
  610. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  611. InetAddress net(OSUtils::jsonString(phy.key(),"").c_str());
  612. if (net) {
  613. if (phy.value().is_object()) {
  614. uint64_t tpid;
  615. if ((tpid = OSUtils::jsonInt(phy.value()["trustedPathId"],0ULL)) != 0ULL) {
  616. if ((net.ss_family == AF_INET)||(net.ss_family == AF_INET6))
  617. ppc[net].trustedPathId = tpid;
  618. }
  619. ppc[net].mtu = (int)OSUtils::jsonInt(phy.value()["mtu"],0ULL); // 0 means use default
  620. }
  621. }
  622. }
  623. }
  624. json &settings = _localConfig["settings"];
  625. if (settings.is_object()) {
  626. // Allow controller DB path to be put somewhere else
  627. const std::string cdbp(OSUtils::jsonString(settings["controllerDbPath"],""));
  628. if (cdbp.length() > 0)
  629. _controllerDbPath = cdbp;
  630. // Bind to wildcard instead of to specific interfaces (disables full tunnel capability)
  631. json &bind = settings["bind"];
  632. if (bind.is_array()) {
  633. for(unsigned long i=0;i<bind.size();++i) {
  634. const std::string ips(OSUtils::jsonString(bind[i],""));
  635. if (ips.length() > 0) {
  636. InetAddress ip(ips.c_str());
  637. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6))
  638. explicitBind.push_back(ip);
  639. }
  640. }
  641. }
  642. }
  643. // Set trusted paths if there are any
  644. if (ppc.size() > 0) {
  645. for(std::map<InetAddress,ZT_PhysicalPathConfiguration>::iterator i(ppc.begin());i!=ppc.end();++i)
  646. _node->setPhysicalPathConfiguration(reinterpret_cast<const struct sockaddr_storage *>(&(i->first)),&(i->second));
  647. }
  648. }
  649. // Apply other runtime configuration from local.conf
  650. applyLocalConfig();
  651. // Make sure we can use the primary port, and hunt for one if configured to do so
  652. const int portTrials = (_primaryPort == 0) ? 256 : 1; // if port is 0, pick random
  653. for(int k=0;k<portTrials;++k) {
  654. if (_primaryPort == 0) {
  655. unsigned int randp = 0;
  656. Utils::getSecureRandom(&randp,sizeof(randp));
  657. _primaryPort = 20000 + (randp % 45500);
  658. }
  659. if (_trialBind(_primaryPort)) {
  660. _ports[0] = _primaryPort;
  661. } else {
  662. _primaryPort = 0;
  663. }
  664. }
  665. if (_ports[0] == 0) {
  666. Mutex::Lock _l(_termReason_m);
  667. _termReason = ONE_UNRECOVERABLE_ERROR;
  668. _fatalErrorMessage = "cannot bind to local control interface port";
  669. return _termReason;
  670. }
  671. // Bind TCP control socket to 127.0.0.1 and ::1 as well for loopback TCP control socket queries
  672. {
  673. struct sockaddr_in lo4;
  674. memset(&lo4,0,sizeof(lo4));
  675. lo4.sin_family = AF_INET;
  676. lo4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001);
  677. lo4.sin_port = Utils::hton((uint16_t)_ports[0]);
  678. _localControlSocket4 = _phy.tcpListen((const struct sockaddr *)&lo4);
  679. struct sockaddr_in6 lo6;
  680. memset(&lo6,0,sizeof(lo6));
  681. lo6.sin6_family = AF_INET6;
  682. lo6.sin6_addr.s6_addr[15] = 1;
  683. lo6.sin6_port = lo4.sin_port;
  684. _localControlSocket6 = _phy.tcpListen((const struct sockaddr *)&lo6);
  685. }
  686. // Save primary port to a file so CLIs and GUIs can learn it easily
  687. char portstr[64];
  688. OSUtils::ztsnprintf(portstr,sizeof(portstr),"%u",_ports[0]);
  689. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S "zerotier-one.port").c_str(),std::string(portstr));
  690. // Attempt to bind to a secondary port chosen from our ZeroTier address.
  691. // This exists because there are buggy NATs out there that fail if more
  692. // than one device behind the same NAT tries to use the same internal
  693. // private address port number. Buggy NATs are a running theme.
  694. _ports[1] = (_secondaryPort == 0) ? 20000 + ((unsigned int)_node->address() % 45500) : _secondaryPort;
  695. for(int i=0;;++i) {
  696. if (i > 1000) {
  697. _ports[1] = 0;
  698. break;
  699. } else if (++_ports[1] >= 65536) {
  700. _ports[1] = 20000;
  701. }
  702. if (_trialBind(_ports[1]))
  703. break;
  704. }
  705. #ifdef ZT_USE_MINIUPNPC
  706. if (_portMappingEnabled) {
  707. // If we're running uPnP/NAT-PMP, bind a *third* port for that. We can't
  708. // use the other two ports for that because some NATs do really funky
  709. // stuff with ports that are explicitly mapped that breaks things.
  710. if (_ports[1]) {
  711. _ports[2] = (_tertiaryPort == 0) ? _ports[1] : _tertiaryPort;
  712. for(int i=0;;++i) {
  713. if (i > 1000) {
  714. _ports[2] = 0;
  715. break;
  716. } else if (++_ports[2] >= 65536) {
  717. _ports[2] = 20000;
  718. }
  719. if (_trialBind(_ports[2]))
  720. break;
  721. }
  722. if (_ports[2]) {
  723. char uniqueName[64];
  724. OSUtils::ztsnprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]);
  725. _portMapper = new PortMapper(_ports[2],uniqueName);
  726. }
  727. }
  728. }
  729. #endif
  730. // Delete legacy iddb.d if present (cleanup)
  731. OSUtils::rmDashRf((_homePath + ZT_PATH_SEPARATOR_S "iddb.d").c_str());
  732. // Network controller is now enabled by default for desktop and server
  733. _controller = new EmbeddedNetworkController(_node,_controllerDbPath.c_str());
  734. _node->setNetconfMaster((void *)_controller);
  735. // Join existing networks in networks.d
  736. {
  737. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S "networks.d").c_str()));
  738. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  739. std::size_t dot = f->find_last_of('.');
  740. if ((dot == 16)&&(f->substr(16) == ".conf"))
  741. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()),(void *)0,(void *)0);
  742. }
  743. }
  744. // Orbit existing moons in moons.d
  745. {
  746. std::vector<std::string> moonsDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S "moons.d").c_str()));
  747. for(std::vector<std::string>::iterator f(moonsDotD.begin());f!=moonsDotD.end();++f) {
  748. std::size_t dot = f->find_last_of('.');
  749. if ((dot == 16)&&(f->substr(16) == ".moon"))
  750. _node->orbit((void *)0,Utils::hexStrToU64(f->substr(0,dot).c_str()),0);
  751. }
  752. }
  753. // Main I/O loop
  754. _nextBackgroundTaskDeadline = 0;
  755. int64_t clockShouldBe = OSUtils::now();
  756. _lastRestart = clockShouldBe;
  757. int64_t lastTapMulticastGroupCheck = 0;
  758. int64_t lastBindRefresh = 0;
  759. int64_t lastUpdateCheck = clockShouldBe;
  760. int64_t lastMultipathModeUpdate = 0;
  761. int64_t lastCleanedPeersDb = 0;
  762. int64_t lastLocalInterfaceAddressCheck = (clockShouldBe - ZT_LOCAL_INTERFACE_CHECK_INTERVAL) + 15000; // do this in 15s to give portmapper time to configure and other things time to settle
  763. for(;;) {
  764. _run_m.lock();
  765. if (!_run) {
  766. _run_m.unlock();
  767. _termReason_m.lock();
  768. _termReason = ONE_NORMAL_TERMINATION;
  769. _termReason_m.unlock();
  770. break;
  771. } else {
  772. _run_m.unlock();
  773. }
  774. const int64_t now = OSUtils::now();
  775. // Attempt to detect sleep/wake events by detecting delay overruns
  776. bool restarted = false;
  777. if ((now > clockShouldBe)&&((now - clockShouldBe) > 10000)) {
  778. _lastRestart = now;
  779. restarted = true;
  780. }
  781. // Check for updates (if enabled)
  782. if ((_updater)&&((now - lastUpdateCheck) > 10000)) {
  783. lastUpdateCheck = now;
  784. if (_updater->check(now) && _updateAutoApply)
  785. _updater->apply();
  786. }
  787. // Refresh bindings in case device's interfaces have changed, and also sync routes to update any shadow routes (e.g. shadow default)
  788. if (((now - lastBindRefresh) >= (_multipathMode ? ZT_BINDER_REFRESH_PERIOD / 8 : ZT_BINDER_REFRESH_PERIOD))||(restarted)) {
  789. lastBindRefresh = now;
  790. unsigned int p[3];
  791. unsigned int pc = 0;
  792. for(int i=0;i<3;++i) {
  793. if (_ports[i])
  794. p[pc++] = _ports[i];
  795. }
  796. _binder.refresh(_phy,p,pc,explicitBind,*this);
  797. {
  798. Mutex::Lock _l(_nets_m);
  799. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n) {
  800. if (n->second.tap)
  801. syncManagedStuff(n->second,false,true);
  802. }
  803. }
  804. }
  805. // Update multipath mode (if needed)
  806. if (((now - lastMultipathModeUpdate) >= ZT_BINDER_REFRESH_PERIOD / 8)||(restarted)) {
  807. lastMultipathModeUpdate = now;
  808. _node->setMultipathMode(_multipathMode);
  809. }
  810. // Run background task processor in core if it's time to do so
  811. int64_t dl = _nextBackgroundTaskDeadline;
  812. if (dl <= now) {
  813. _node->processBackgroundTasks((void *)0,now,&_nextBackgroundTaskDeadline);
  814. dl = _nextBackgroundTaskDeadline;
  815. }
  816. // Close TCP fallback tunnel if we have direct UDP
  817. if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2)))
  818. _phy.close(_tcpFallbackTunnel->sock);
  819. // Sync multicast group memberships
  820. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  821. lastTapMulticastGroupCheck = now;
  822. std::vector< std::pair< uint64_t,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> > > > mgChanges;
  823. {
  824. Mutex::Lock _l(_nets_m);
  825. mgChanges.reserve(_nets.size() + 1);
  826. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  827. if (n->second.tap) {
  828. mgChanges.push_back(std::pair< uint64_t,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> > >(n->first,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> >()));
  829. n->second.tap->scanMulticastGroups(mgChanges.back().second.first,mgChanges.back().second.second);
  830. }
  831. }
  832. }
  833. for(std::vector< std::pair< uint64_t,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> > > >::iterator c(mgChanges.begin());c!=mgChanges.end();++c) {
  834. for(std::vector<MulticastGroup>::iterator m(c->second.first.begin());m!=c->second.first.end();++m)
  835. _node->multicastSubscribe((void *)0,c->first,m->mac().toInt(),m->adi());
  836. for(std::vector<MulticastGroup>::iterator m(c->second.second.begin());m!=c->second.second.end();++m)
  837. _node->multicastUnsubscribe(c->first,m->mac().toInt(),m->adi());
  838. }
  839. }
  840. // Sync information about physical network interfaces
  841. if ((now - lastLocalInterfaceAddressCheck) >= (_multipathMode ? ZT_LOCAL_INTERFACE_CHECK_INTERVAL / 8 : ZT_LOCAL_INTERFACE_CHECK_INTERVAL)) {
  842. lastLocalInterfaceAddressCheck = now;
  843. _node->clearLocalInterfaceAddresses();
  844. #ifdef ZT_USE_MINIUPNPC
  845. if (_portMapper) {
  846. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  847. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  848. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  849. }
  850. #endif
  851. std::vector<InetAddress> boundAddrs(_binder.allBoundLocalInterfaceAddresses());
  852. for(std::vector<InetAddress>::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i)
  853. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*i)));
  854. }
  855. // Clean peers.d periodically
  856. if ((now - lastCleanedPeersDb) >= 3600000) {
  857. lastCleanedPeersDb = now;
  858. OSUtils::cleanDirectory((_homePath + ZT_PATH_SEPARATOR_S "peers.d").c_str(),now - 2592000000LL); // delete older than 30 days
  859. }
  860. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  861. clockShouldBe = now + (uint64_t)delay;
  862. _phy.poll(delay);
  863. }
  864. } catch (std::exception &e) {
  865. Mutex::Lock _l(_termReason_m);
  866. _termReason = ONE_UNRECOVERABLE_ERROR;
  867. _fatalErrorMessage = std::string("unexpected exception in main thread: ")+e.what();
  868. } catch ( ... ) {
  869. Mutex::Lock _l(_termReason_m);
  870. _termReason = ONE_UNRECOVERABLE_ERROR;
  871. _fatalErrorMessage = "unexpected exception in main thread: unknown exception";
  872. }
  873. try {
  874. Mutex::Lock _l(_tcpConnections_m);
  875. while (!_tcpConnections.empty())
  876. _phy.close((*_tcpConnections.begin())->sock);
  877. } catch ( ... ) {}
  878. {
  879. Mutex::Lock _l(_nets_m);
  880. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n)
  881. delete n->second.tap;
  882. _nets.clear();
  883. }
  884. delete _updater;
  885. _updater = (SoftwareUpdater *)0;
  886. delete _node;
  887. _node = (Node *)0;
  888. return _termReason;
  889. }
  890. virtual ReasonForTermination reasonForTermination() const
  891. {
  892. Mutex::Lock _l(_termReason_m);
  893. return _termReason;
  894. }
  895. virtual std::string fatalErrorMessage() const
  896. {
  897. Mutex::Lock _l(_termReason_m);
  898. return _fatalErrorMessage;
  899. }
  900. virtual std::string portDeviceName(uint64_t nwid) const
  901. {
  902. Mutex::Lock _l(_nets_m);
  903. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  904. if ((n != _nets.end())&&(n->second.tap))
  905. return n->second.tap->deviceName();
  906. else return std::string();
  907. }
  908. #ifdef ZT_SDK
  909. virtual void leave(const uint64_t hp)
  910. {
  911. _node->leave(hp, NULL, NULL);
  912. }
  913. virtual void join(const uint64_t hp)
  914. {
  915. _node->join(hp, NULL, NULL);
  916. }
  917. virtual std::string givenHomePath()
  918. {
  919. return _homePath;
  920. }
  921. std::vector<ZT_VirtualNetworkRoute> *getRoutes(uint64_t nwid)
  922. {
  923. Mutex::Lock _l(_nets_m);
  924. NetworkState &n = _nets[nwid];
  925. std::vector<ZT_VirtualNetworkRoute> *routes = new std::vector<ZT_VirtualNetworkRoute>();
  926. for(int i=0; i<ZT_MAX_NETWORK_ROUTES; i++) {
  927. routes->push_back(n.config.routes[i]);
  928. }
  929. return routes;
  930. }
  931. virtual Node *getNode()
  932. {
  933. return _node;
  934. }
  935. virtual void removeNets()
  936. {
  937. Mutex::Lock _l(_nets_m);
  938. std::map<uint64_t,NetworkState>::iterator i;
  939. for(i = _nets.begin(); i != _nets.end(); i++)
  940. delete i->second.tap;
  941. }
  942. #endif // ZT_SDK
  943. virtual void terminate()
  944. {
  945. _run_m.lock();
  946. _run = false;
  947. _run_m.unlock();
  948. _phy.whack();
  949. }
  950. virtual bool getNetworkSettings(const uint64_t nwid,NetworkSettings &settings) const
  951. {
  952. Mutex::Lock _l(_nets_m);
  953. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  954. if (n == _nets.end())
  955. return false;
  956. settings = n->second.settings;
  957. return true;
  958. }
  959. virtual bool setNetworkSettings(const uint64_t nwid,const NetworkSettings &settings)
  960. {
  961. Mutex::Lock _l(_nets_m);
  962. std::map<uint64_t,NetworkState>::iterator n(_nets.find(nwid));
  963. if (n == _nets.end())
  964. return false;
  965. n->second.settings = settings;
  966. char nlcpath[4096];
  967. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_networksPath.c_str(),nwid);
  968. FILE *out = fopen(nlcpath,"w");
  969. if (out) {
  970. fprintf(out,"allowManaged=%d\n",(int)n->second.settings.allowManaged);
  971. fprintf(out,"allowGlobal=%d\n",(int)n->second.settings.allowGlobal);
  972. fprintf(out,"allowDefault=%d\n",(int)n->second.settings.allowDefault);
  973. fclose(out);
  974. }
  975. if (n->second.tap)
  976. syncManagedStuff(n->second,true,true);
  977. return true;
  978. }
  979. // =========================================================================
  980. // Internal implementation methods for control plane, route setup, etc.
  981. // =========================================================================
  982. inline unsigned int handleControlPlaneHttpRequest(
  983. const InetAddress &fromAddress,
  984. unsigned int httpMethod,
  985. const std::string &path,
  986. const std::map<std::string,std::string> &headers,
  987. const std::string &body,
  988. std::string &responseBody,
  989. std::string &responseContentType)
  990. {
  991. char tmp[256];
  992. unsigned int scode = 404;
  993. json res;
  994. std::vector<std::string> ps(OSUtils::split(path.c_str(),"/","",""));
  995. std::map<std::string,std::string> urlArgs;
  996. /* Note: this is kind of restricted in what it'll take. It does not support
  997. * URL encoding, and /'s in URL args will screw it up. But the only URL args
  998. * it really uses in ?jsonp=funcionName, and otherwise it just takes simple
  999. * paths to simply-named resources. */
  1000. if (ps.size() > 0) {
  1001. std::size_t qpos = ps[ps.size() - 1].find('?');
  1002. if (qpos != std::string::npos) {
  1003. std::string args(ps[ps.size() - 1].substr(qpos + 1));
  1004. ps[ps.size() - 1] = ps[ps.size() - 1].substr(0,qpos);
  1005. std::vector<std::string> asplit(OSUtils::split(args.c_str(),"&","",""));
  1006. for(std::vector<std::string>::iterator a(asplit.begin());a!=asplit.end();++a) {
  1007. std::size_t eqpos = a->find('=');
  1008. if (eqpos == std::string::npos)
  1009. urlArgs[*a] = "";
  1010. else urlArgs[a->substr(0,eqpos)] = a->substr(eqpos + 1);
  1011. }
  1012. }
  1013. } else {
  1014. return 404;
  1015. }
  1016. bool isAuth = false;
  1017. {
  1018. std::map<std::string,std::string>::const_iterator ah(headers.find("x-zt1-auth"));
  1019. if ((ah != headers.end())&&(_authToken == ah->second)) {
  1020. isAuth = true;
  1021. } else {
  1022. ah = urlArgs.find("auth");
  1023. if ((ah != urlArgs.end())&&(_authToken == ah->second))
  1024. isAuth = true;
  1025. }
  1026. }
  1027. #ifdef __SYNOLOGY__
  1028. // Authenticate via Synology's built-in cgi script
  1029. if (!isAuth) {
  1030. int synotoken_pos = path.find("SynoToken");
  1031. int argpos = path.find("?");
  1032. if(synotoken_pos != std::string::npos && argpos != std::string::npos) {
  1033. std::string cookie = path.substr(argpos+1, synotoken_pos-(argpos+1));
  1034. std::string synotoken = path.substr(synotoken_pos);
  1035. std::string cookie_val = cookie.substr(cookie.find("=")+1);
  1036. std::string synotoken_val = synotoken.substr(synotoken.find("=")+1);
  1037. // Set necessary env for auth script
  1038. std::map<std::string,std::string>::const_iterator ah2(headers.find("x-forwarded-for"));
  1039. setenv("HTTP_COOKIE", cookie_val.c_str(), true);
  1040. setenv("HTTP_X_SYNO_TOKEN", synotoken_val.c_str(), true);
  1041. setenv("REMOTE_ADDR", ah2->second.c_str(),true);
  1042. char user[256], buf[1024];
  1043. FILE *fp = NULL;
  1044. bzero(user, 256);
  1045. fp = popen("/usr/syno/synoman/webman/modules/authenticate.cgi", "r");
  1046. if(!fp)
  1047. isAuth = false;
  1048. else {
  1049. bzero(buf, sizeof(buf));
  1050. fread(buf, 1024, 1, fp);
  1051. if(strlen(buf) > 0) {
  1052. snprintf(user, 256, "%s", buf);
  1053. isAuth = true;
  1054. }
  1055. }
  1056. pclose(fp);
  1057. }
  1058. }
  1059. #endif
  1060. if (httpMethod == HTTP_GET) {
  1061. if (isAuth) {
  1062. if (ps[0] == "status") {
  1063. ZT_NodeStatus status;
  1064. _node->status(&status);
  1065. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.10llx",status.address);
  1066. res["address"] = tmp;
  1067. res["publicIdentity"] = status.publicIdentity;
  1068. res["online"] = (bool)(status.online != 0);
  1069. res["tcpFallbackActive"] = (_tcpFallbackTunnel != (TcpConnection *)0);
  1070. res["versionMajor"] = ZEROTIER_ONE_VERSION_MAJOR;
  1071. res["versionMinor"] = ZEROTIER_ONE_VERSION_MINOR;
  1072. res["versionRev"] = ZEROTIER_ONE_VERSION_REVISION;
  1073. res["versionBuild"] = ZEROTIER_ONE_VERSION_BUILD;
  1074. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%d.%d.%d",ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  1075. res["version"] = tmp;
  1076. res["clock"] = OSUtils::now();
  1077. {
  1078. Mutex::Lock _l(_localConfig_m);
  1079. res["config"] = _localConfig;
  1080. }
  1081. json &settings = res["config"]["settings"];
  1082. settings["primaryPort"] = OSUtils::jsonInt(settings["primaryPort"],(uint64_t)_primaryPort) & 0xffff;
  1083. settings["allowTcpFallbackRelay"] = OSUtils::jsonBool(settings["allowTcpFallbackRelay"],_allowTcpFallbackRelay);
  1084. if (_multipathMode) {
  1085. json &multipathConfig = res["multipath"];
  1086. ZT_PeerList *pl = _node->peers();
  1087. char peerAddrStr[256];
  1088. if (pl) {
  1089. for(unsigned long i=0;i<pl->peerCount;++i) {
  1090. if (pl->peers[i].hadAggregateLink) {
  1091. nlohmann::json pj;
  1092. _peerAggregateLinkToJson(pj,&(pl->peers[i]));
  1093. OSUtils::ztsnprintf(peerAddrStr,sizeof(peerAddrStr),"%.10llx",pl->peers[i].address);
  1094. multipathConfig[peerAddrStr] = (pj);
  1095. }
  1096. }
  1097. }
  1098. }
  1099. #ifdef ZT_USE_MINIUPNPC
  1100. settings["portMappingEnabled"] = OSUtils::jsonBool(settings["portMappingEnabled"],true);
  1101. #else
  1102. settings["portMappingEnabled"] = false; // not supported in build
  1103. #endif
  1104. #ifndef ZT_SDK
  1105. settings["softwareUpdate"] = OSUtils::jsonString(settings["softwareUpdate"],ZT_SOFTWARE_UPDATE_DEFAULT);
  1106. settings["softwareUpdateChannel"] = OSUtils::jsonString(settings["softwareUpdateChannel"],ZT_SOFTWARE_UPDATE_DEFAULT_CHANNEL);
  1107. #endif
  1108. const World planet(_node->planet());
  1109. res["planetWorldId"] = planet.id();
  1110. res["planetWorldTimestamp"] = planet.timestamp();
  1111. scode = 200;
  1112. } else if (ps[0] == "moon") {
  1113. std::vector<World> moons(_node->moons());
  1114. if (ps.size() == 1) {
  1115. // Return [array] of all moons
  1116. res = json::array();
  1117. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  1118. json mj;
  1119. _moonToJson(mj,*m);
  1120. res.push_back(mj);
  1121. }
  1122. scode = 200;
  1123. } else {
  1124. // Return a single moon by ID
  1125. const uint64_t id = Utils::hexStrToU64(ps[1].c_str());
  1126. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  1127. if (m->id() == id) {
  1128. _moonToJson(res,*m);
  1129. scode = 200;
  1130. break;
  1131. }
  1132. }
  1133. }
  1134. } else if (ps[0] == "network") {
  1135. ZT_VirtualNetworkList *nws = _node->networks();
  1136. if (nws) {
  1137. if (ps.size() == 1) {
  1138. // Return [array] of all networks
  1139. res = nlohmann::json::array();
  1140. for(unsigned long i=0;i<nws->networkCount;++i) {
  1141. OneService::NetworkSettings localSettings;
  1142. getNetworkSettings(nws->networks[i].nwid,localSettings);
  1143. nlohmann::json nj;
  1144. _networkToJson(nj,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
  1145. res.push_back(nj);
  1146. }
  1147. scode = 200;
  1148. } else if (ps.size() == 2) {
  1149. // Return a single network by ID or 404 if not found
  1150. const uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  1151. for(unsigned long i=0;i<nws->networkCount;++i) {
  1152. if (nws->networks[i].nwid == wantnw) {
  1153. OneService::NetworkSettings localSettings;
  1154. getNetworkSettings(nws->networks[i].nwid,localSettings);
  1155. _networkToJson(res,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
  1156. scode = 200;
  1157. break;
  1158. }
  1159. }
  1160. } else scode = 404;
  1161. _node->freeQueryResult((void *)nws);
  1162. } else scode = 500;
  1163. } else if (ps[0] == "peer") {
  1164. ZT_PeerList *pl = _node->peers();
  1165. if (pl) {
  1166. if (ps.size() == 1) {
  1167. // Return [array] of all peers
  1168. res = nlohmann::json::array();
  1169. for(unsigned long i=0;i<pl->peerCount;++i) {
  1170. nlohmann::json pj;
  1171. _peerToJson(pj,&(pl->peers[i]));
  1172. res.push_back(pj);
  1173. }
  1174. scode = 200;
  1175. } else if (ps.size() == 2) {
  1176. // Return a single peer by ID or 404 if not found
  1177. uint64_t wantp = Utils::hexStrToU64(ps[1].c_str());
  1178. for(unsigned long i=0;i<pl->peerCount;++i) {
  1179. if (pl->peers[i].address == wantp) {
  1180. _peerToJson(res,&(pl->peers[i]));
  1181. scode = 200;
  1182. break;
  1183. }
  1184. }
  1185. } else scode = 404;
  1186. _node->freeQueryResult((void *)pl);
  1187. } else scode = 500;
  1188. } else {
  1189. if (_controller) {
  1190. scode = _controller->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  1191. } else scode = 404;
  1192. }
  1193. } else scode = 401; // isAuth == false
  1194. } else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) {
  1195. if (isAuth) {
  1196. if (ps[0] == "moon") {
  1197. if (ps.size() == 2) {
  1198. uint64_t seed = 0;
  1199. try {
  1200. json j(OSUtils::jsonParse(body));
  1201. if (j.is_object()) {
  1202. seed = Utils::hexStrToU64(OSUtils::jsonString(j["seed"],"0").c_str());
  1203. }
  1204. } catch ( ... ) {
  1205. // discard invalid JSON
  1206. }
  1207. std::vector<World> moons(_node->moons());
  1208. const uint64_t id = Utils::hexStrToU64(ps[1].c_str());
  1209. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  1210. if (m->id() == id) {
  1211. _moonToJson(res,*m);
  1212. scode = 200;
  1213. break;
  1214. }
  1215. }
  1216. if ((scode != 200)&&(seed != 0)) {
  1217. char tmp[64];
  1218. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",id);
  1219. res["id"] = tmp;
  1220. res["roots"] = json::array();
  1221. res["timestamp"] = 0;
  1222. res["signature"] = json();
  1223. res["updatesMustBeSignedBy"] = json();
  1224. res["waiting"] = true;
  1225. _node->orbit((void *)0,id,seed);
  1226. scode = 200;
  1227. }
  1228. } else scode = 404;
  1229. } else if (ps[0] == "network") {
  1230. if (ps.size() == 2) {
  1231. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  1232. _node->join(wantnw,(void *)0,(void *)0); // does nothing if we are a member
  1233. ZT_VirtualNetworkList *nws = _node->networks();
  1234. if (nws) {
  1235. for(unsigned long i=0;i<nws->networkCount;++i) {
  1236. if (nws->networks[i].nwid == wantnw) {
  1237. OneService::NetworkSettings localSettings;
  1238. getNetworkSettings(nws->networks[i].nwid,localSettings);
  1239. try {
  1240. json j(OSUtils::jsonParse(body));
  1241. if (j.is_object()) {
  1242. json &allowManaged = j["allowManaged"];
  1243. if (allowManaged.is_boolean()) localSettings.allowManaged = (bool)allowManaged;
  1244. json &allowGlobal = j["allowGlobal"];
  1245. if (allowGlobal.is_boolean()) localSettings.allowGlobal = (bool)allowGlobal;
  1246. json &allowDefault = j["allowDefault"];
  1247. if (allowDefault.is_boolean()) localSettings.allowDefault = (bool)allowDefault;
  1248. }
  1249. } catch ( ... ) {
  1250. // discard invalid JSON
  1251. }
  1252. setNetworkSettings(nws->networks[i].nwid,localSettings);
  1253. _networkToJson(res,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
  1254. scode = 200;
  1255. break;
  1256. }
  1257. }
  1258. _node->freeQueryResult((void *)nws);
  1259. } else scode = 500;
  1260. } else scode = 404;
  1261. } else {
  1262. if (_controller)
  1263. scode = _controller->handleControlPlaneHttpPOST(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  1264. else scode = 404;
  1265. }
  1266. } else scode = 401; // isAuth == false
  1267. } else if (httpMethod == HTTP_DELETE) {
  1268. if (isAuth) {
  1269. if (ps[0] == "moon") {
  1270. if (ps.size() == 2) {
  1271. _node->deorbit((void *)0,Utils::hexStrToU64(ps[1].c_str()));
  1272. res["result"] = true;
  1273. scode = 200;
  1274. } // else 404
  1275. } else if (ps[0] == "network") {
  1276. ZT_VirtualNetworkList *nws = _node->networks();
  1277. if (nws) {
  1278. if (ps.size() == 2) {
  1279. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  1280. for(unsigned long i=0;i<nws->networkCount;++i) {
  1281. if (nws->networks[i].nwid == wantnw) {
  1282. _node->leave(wantnw,(void **)0,(void *)0);
  1283. res["result"] = true;
  1284. scode = 200;
  1285. break;
  1286. }
  1287. }
  1288. } // else 404
  1289. _node->freeQueryResult((void *)nws);
  1290. } else scode = 500;
  1291. } else {
  1292. if (_controller)
  1293. scode = _controller->handleControlPlaneHttpDELETE(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  1294. else scode = 404;
  1295. }
  1296. } else scode = 401; // isAuth = false
  1297. } else {
  1298. scode = 400;
  1299. }
  1300. if (responseBody.length() == 0) {
  1301. if ((res.is_object())||(res.is_array()))
  1302. responseBody = OSUtils::jsonDump(res);
  1303. else responseBody = "{}";
  1304. responseContentType = "application/json";
  1305. }
  1306. // Wrap result in jsonp function call if the user included a jsonp= url argument.
  1307. // Also double-check isAuth since forbidding this without auth feels safer.
  1308. std::map<std::string,std::string>::const_iterator jsonp(urlArgs.find("jsonp"));
  1309. if ((isAuth)&&(jsonp != urlArgs.end())&&(responseContentType == "application/json")) {
  1310. if (responseBody.length() > 0)
  1311. responseBody = jsonp->second + "(" + responseBody + ");";
  1312. else responseBody = jsonp->second + "(null);";
  1313. responseContentType = "application/javascript";
  1314. }
  1315. return scode;
  1316. }
  1317. // Must be called after _localConfig is read or modified
  1318. void applyLocalConfig()
  1319. {
  1320. Mutex::Lock _l(_localConfig_m);
  1321. json lc(_localConfig);
  1322. _v4Hints.clear();
  1323. _v6Hints.clear();
  1324. _v4Blacklists.clear();
  1325. _v6Blacklists.clear();
  1326. json &virt = lc["virtual"];
  1327. if (virt.is_object()) {
  1328. for(json::iterator v(virt.begin());v!=virt.end();++v) {
  1329. const std::string nstr = v.key();
  1330. if ((nstr.length() == ZT_ADDRESS_LENGTH_HEX)&&(v.value().is_object())) {
  1331. const Address ztaddr(Utils::hexStrToU64(nstr.c_str()));
  1332. if (ztaddr) {
  1333. const uint64_t ztaddr2 = ztaddr.toInt();
  1334. std::vector<InetAddress> &v4h = _v4Hints[ztaddr2];
  1335. std::vector<InetAddress> &v6h = _v6Hints[ztaddr2];
  1336. std::vector<InetAddress> &v4b = _v4Blacklists[ztaddr2];
  1337. std::vector<InetAddress> &v6b = _v6Blacklists[ztaddr2];
  1338. json &tryAddrs = v.value()["try"];
  1339. if (tryAddrs.is_array()) {
  1340. for(unsigned long i=0;i<tryAddrs.size();++i) {
  1341. const InetAddress ip(OSUtils::jsonString(tryAddrs[i],"").c_str());
  1342. if (ip.ss_family == AF_INET)
  1343. v4h.push_back(ip);
  1344. else if (ip.ss_family == AF_INET6)
  1345. v6h.push_back(ip);
  1346. }
  1347. }
  1348. json &blAddrs = v.value()["blacklist"];
  1349. if (blAddrs.is_array()) {
  1350. for(unsigned long i=0;i<blAddrs.size();++i) {
  1351. const InetAddress ip(OSUtils::jsonString(blAddrs[i],"").c_str());
  1352. if (ip.ss_family == AF_INET)
  1353. v4b.push_back(ip);
  1354. else if (ip.ss_family == AF_INET6)
  1355. v6b.push_back(ip);
  1356. }
  1357. }
  1358. if (v4h.empty()) _v4Hints.erase(ztaddr2);
  1359. if (v6h.empty()) _v6Hints.erase(ztaddr2);
  1360. if (v4b.empty()) _v4Blacklists.erase(ztaddr2);
  1361. if (v6b.empty()) _v6Blacklists.erase(ztaddr2);
  1362. }
  1363. }
  1364. }
  1365. }
  1366. _globalV4Blacklist.clear();
  1367. _globalV6Blacklist.clear();
  1368. json &physical = lc["physical"];
  1369. if (physical.is_object()) {
  1370. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  1371. const InetAddress net(OSUtils::jsonString(phy.key(),"").c_str());
  1372. if ((net)&&(net.netmaskBits() > 0)) {
  1373. if (phy.value().is_object()) {
  1374. if (OSUtils::jsonBool(phy.value()["blacklist"],false)) {
  1375. if (net.ss_family == AF_INET)
  1376. _globalV4Blacklist.push_back(net);
  1377. else if (net.ss_family == AF_INET6)
  1378. _globalV6Blacklist.push_back(net);
  1379. }
  1380. }
  1381. }
  1382. }
  1383. }
  1384. _allowManagementFrom.clear();
  1385. _interfacePrefixBlacklist.clear();
  1386. json &settings = lc["settings"];
  1387. _primaryPort = (unsigned int)OSUtils::jsonInt(settings["primaryPort"],(uint64_t)_primaryPort) & 0xffff;
  1388. _allowTcpFallbackRelay = OSUtils::jsonBool(settings["allowTcpFallbackRelay"],true);
  1389. _secondaryPort = (unsigned int)OSUtils::jsonInt(settings["secondaryPort"],0);
  1390. _tertiaryPort = (unsigned int)OSUtils::jsonInt(settings["tertiaryPort"],0);
  1391. if (_secondaryPort != 0 || _tertiaryPort != 0) {
  1392. fprintf(stderr,"WARNING: using manually-specified ports. This can cause NAT issues." ZT_EOL_S);
  1393. }
  1394. _multipathMode = (unsigned int)OSUtils::jsonInt(settings["multipathMode"],0);
  1395. if (_multipathMode != 0 && _allowTcpFallbackRelay) {
  1396. fprintf(stderr,"WARNING: multipathMode cannot be used with allowTcpFallbackRelay. Disabling allowTcpFallbackRelay" ZT_EOL_S);
  1397. _allowTcpFallbackRelay = false;
  1398. }
  1399. _portMappingEnabled = OSUtils::jsonBool(settings["portMappingEnabled"],true);
  1400. #ifndef ZT_SDK
  1401. const std::string up(OSUtils::jsonString(settings["softwareUpdate"],ZT_SOFTWARE_UPDATE_DEFAULT));
  1402. const bool udist = OSUtils::jsonBool(settings["softwareUpdateDist"],false);
  1403. if (((up == "apply")||(up == "download"))||(udist)) {
  1404. if (!_updater)
  1405. _updater = new SoftwareUpdater(*_node,_homePath);
  1406. _updateAutoApply = (up == "apply");
  1407. _updater->setUpdateDistribution(udist);
  1408. _updater->setChannel(OSUtils::jsonString(settings["softwareUpdateChannel"],ZT_SOFTWARE_UPDATE_DEFAULT_CHANNEL));
  1409. } else {
  1410. delete _updater;
  1411. _updater = (SoftwareUpdater *)0;
  1412. _updateAutoApply = false;
  1413. }
  1414. #endif
  1415. json &ignoreIfs = settings["interfacePrefixBlacklist"];
  1416. if (ignoreIfs.is_array()) {
  1417. for(unsigned long i=0;i<ignoreIfs.size();++i) {
  1418. const std::string tmp(OSUtils::jsonString(ignoreIfs[i],""));
  1419. if (tmp.length() > 0)
  1420. _interfacePrefixBlacklist.push_back(tmp);
  1421. }
  1422. }
  1423. json &amf = settings["allowManagementFrom"];
  1424. if (amf.is_array()) {
  1425. for(unsigned long i=0;i<amf.size();++i) {
  1426. const InetAddress nw(OSUtils::jsonString(amf[i],"").c_str());
  1427. if (nw)
  1428. _allowManagementFrom.push_back(nw);
  1429. }
  1430. }
  1431. }
  1432. #if ZT_VAULT_SUPPORT
  1433. json &vault = settings["vault"];
  1434. if (vault.is_object()) {
  1435. const std::string url(OSUtils::jsonString(vault["vaultURL"], "").c_str());
  1436. if (!url.empty()) {
  1437. _vaultURL = url;
  1438. }
  1439. const std::string token(OSUtils::jsonString(vault["vaultToken"], "").c_str());
  1440. if (!token.empty()) {
  1441. _vaultToken = token;
  1442. }
  1443. const std::string path(OSUtils::jsonString(vault["vaultPath"], "").c_str());
  1444. if (!path.empty()) {
  1445. _vaultPath = path;
  1446. }
  1447. }
  1448. // also check environment variables for values. Environment variables
  1449. // will override local.conf variables
  1450. const std::string envURL(getenv("VAULT_ADDR"));
  1451. if (!envURL.empty()) {
  1452. _vaultURL = envURL;
  1453. }
  1454. const std::string envToken(getenv("VAULT_TOKEN"));
  1455. if (!envToken.empty()) {
  1456. _vaultToken = envToken;
  1457. }
  1458. const std::string envPath(getenv("VAULT_PATH"));
  1459. if (!envPath.empty()) {
  1460. _vaultPath = envPath;
  1461. }
  1462. if (!_vaultURL.empty() && !_vaultToken.empty()) {
  1463. _vaultEnabled = true;
  1464. }
  1465. #endif
  1466. // Checks if a managed IP or route target is allowed
  1467. bool checkIfManagedIsAllowed(const NetworkState &n,const InetAddress &target)
  1468. {
  1469. if (!n.settings.allowManaged)
  1470. return false;
  1471. if (n.settings.allowManagedWhitelist.size() > 0) {
  1472. bool allowed = false;
  1473. for (InetAddress addr : n.settings.allowManagedWhitelist) {
  1474. if (addr.containsAddress(target) && addr.netmaskBits() <= target.netmaskBits()) {
  1475. allowed = true;
  1476. break;
  1477. }
  1478. }
  1479. if (!allowed) return false;
  1480. }
  1481. if (target.isDefaultRoute())
  1482. return n.settings.allowDefault;
  1483. switch(target.ipScope()) {
  1484. case InetAddress::IP_SCOPE_NONE:
  1485. case InetAddress::IP_SCOPE_MULTICAST:
  1486. case InetAddress::IP_SCOPE_LOOPBACK:
  1487. case InetAddress::IP_SCOPE_LINK_LOCAL:
  1488. return false;
  1489. case InetAddress::IP_SCOPE_GLOBAL:
  1490. return n.settings.allowGlobal;
  1491. default:
  1492. return true;
  1493. }
  1494. }
  1495. // Match only an IP from a vector of IPs -- used in syncManagedStuff()
  1496. bool matchIpOnly(const std::vector<InetAddress> &ips,const InetAddress &ip) const
  1497. {
  1498. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1499. if (i->ipsEqual(ip))
  1500. return true;
  1501. }
  1502. return false;
  1503. }
  1504. // Apply or update managed IPs for a configured network (be sure n.tap exists)
  1505. void syncManagedStuff(NetworkState &n,bool syncIps,bool syncRoutes)
  1506. {
  1507. char ipbuf[64];
  1508. // assumes _nets_m is locked
  1509. if (syncIps) {
  1510. std::vector<InetAddress> newManagedIps;
  1511. newManagedIps.reserve(n.config.assignedAddressCount);
  1512. for(unsigned int i=0;i<n.config.assignedAddressCount;++i) {
  1513. const InetAddress *ii = reinterpret_cast<const InetAddress *>(&(n.config.assignedAddresses[i]));
  1514. if (checkIfManagedIsAllowed(n,*ii))
  1515. newManagedIps.push_back(*ii);
  1516. }
  1517. std::sort(newManagedIps.begin(),newManagedIps.end());
  1518. newManagedIps.erase(std::unique(newManagedIps.begin(),newManagedIps.end()),newManagedIps.end());
  1519. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  1520. if (std::find(newManagedIps.begin(),newManagedIps.end(),*ip) == newManagedIps.end()) {
  1521. if (!n.tap->removeIp(*ip))
  1522. fprintf(stderr,"ERROR: unable to remove ip address %s" ZT_EOL_S, ip->toString(ipbuf));
  1523. }
  1524. }
  1525. #ifdef __SYNOLOGY__
  1526. if (!n.tap->addIpSyn(newManagedIps))
  1527. fprintf(stderr,"ERROR: unable to add ip addresses to ifcfg" ZT_EOL_S);
  1528. #else
  1529. for(std::vector<InetAddress>::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) {
  1530. if (std::find(n.managedIps.begin(),n.managedIps.end(),*ip) == n.managedIps.end()) {
  1531. if (!n.tap->addIp(*ip))
  1532. fprintf(stderr,"ERROR: unable to add ip address %s" ZT_EOL_S, ip->toString(ipbuf));
  1533. }
  1534. }
  1535. #endif
  1536. n.managedIps.swap(newManagedIps);
  1537. }
  1538. if (syncRoutes) {
  1539. char tapdev[64];
  1540. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1541. OSUtils::ztsnprintf(tapdev,sizeof(tapdev),"%.16llx",(unsigned long long)n.tap->luid().Value);
  1542. #else
  1543. Utils::scopy(tapdev,sizeof(tapdev),n.tap->deviceName().c_str());
  1544. #endif
  1545. std::vector<InetAddress> myIps(n.tap->ips());
  1546. // Nuke applied routes that are no longer in n.config.routes[] and/or are not allowed
  1547. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();) {
  1548. bool haveRoute = false;
  1549. if ( (checkIfManagedIsAllowed(n,(*mr)->target())) && (((*mr)->via().ss_family != (*mr)->target().ss_family)||(!matchIpOnly(myIps,(*mr)->via()))) ) {
  1550. for(unsigned int i=0;i<n.config.routeCount;++i) {
  1551. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  1552. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  1553. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (strcmp(tapdev,(*mr)->device())==0) ) ) {
  1554. haveRoute = true;
  1555. break;
  1556. }
  1557. }
  1558. }
  1559. if (haveRoute) {
  1560. ++mr;
  1561. } else {
  1562. n.managedRoutes.erase(mr++);
  1563. }
  1564. }
  1565. // Apply routes in n.config.routes[] that we haven't applied yet, and sync those we have in case shadow routes need to change
  1566. for(unsigned int i=0;i<n.config.routeCount;++i) {
  1567. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  1568. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  1569. InetAddress *src = NULL;
  1570. for (unsigned int j=0; j<n.config.assignedAddressCount; ++j) {
  1571. const InetAddress *const tmp = reinterpret_cast<const InetAddress *>(&(n.config.assignedAddresses[j]));
  1572. if (target->isV4() && tmp->isV4()) {
  1573. src = reinterpret_cast<InetAddress *>(&(n.config.assignedAddresses[j]));
  1574. break;
  1575. } else if (target->isV6() && tmp->isV6()) {
  1576. src = reinterpret_cast<InetAddress *>(&(n.config.assignedAddresses[j]));
  1577. break;
  1578. }
  1579. }
  1580. if ( (!checkIfManagedIsAllowed(n,*target)) || ((via->ss_family == target->ss_family)&&(matchIpOnly(myIps,*via))) )
  1581. continue;
  1582. bool haveRoute = false;
  1583. // Ignore routes implied by local managed IPs since adding the IP adds the route
  1584. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  1585. if ((target->netmaskBits() == ip->netmaskBits())&&(target->containsAddress(*ip))) {
  1586. haveRoute = true;
  1587. break;
  1588. }
  1589. }
  1590. if (haveRoute)
  1591. continue;
  1592. #ifndef ZT_SDK
  1593. // If we've already applied this route, just sync it and continue
  1594. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();++mr) {
  1595. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (tapdev == (*mr)->device()) ) ) {
  1596. haveRoute = true;
  1597. (*mr)->sync();
  1598. break;
  1599. }
  1600. }
  1601. if (haveRoute)
  1602. continue;
  1603. // Add and apply new routes
  1604. n.managedRoutes.push_back(SharedPtr<ManagedRoute>(new ManagedRoute(*target,*via,*src,tapdev)));
  1605. if (!n.managedRoutes.back()->sync())
  1606. n.managedRoutes.pop_back();
  1607. #endif
  1608. }
  1609. }
  1610. }
  1611. // =========================================================================
  1612. // Handlers for Node and Phy<> callbacks
  1613. // =========================================================================
  1614. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  1615. {
  1616. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  1617. _lastDirectReceiveFromGlobal = OSUtils::now();
  1618. const ZT_ResultCode rc = _node->processWirePacket(
  1619. (void *)0,
  1620. OSUtils::now(),
  1621. reinterpret_cast<int64_t>(sock),
  1622. reinterpret_cast<const struct sockaddr_storage *>(from), // Phy<> uses sockaddr_storage, so it'll always be that big
  1623. data,
  1624. len,
  1625. &_nextBackgroundTaskDeadline);
  1626. if (ZT_ResultCode_isFatal(rc)) {
  1627. char tmp[256];
  1628. OSUtils::ztsnprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1629. Mutex::Lock _l(_termReason_m);
  1630. _termReason = ONE_UNRECOVERABLE_ERROR;
  1631. _fatalErrorMessage = tmp;
  1632. this->terminate();
  1633. }
  1634. }
  1635. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  1636. {
  1637. if (!success) {
  1638. phyOnTcpClose(sock,uptr);
  1639. return;
  1640. }
  1641. TcpConnection *const tc = reinterpret_cast<TcpConnection *>(*uptr);
  1642. if (!tc) { // sanity check
  1643. _phy.close(sock,true);
  1644. return;
  1645. }
  1646. tc->sock = sock;
  1647. if (tc->type == TcpConnection::TCP_TUNNEL_OUTGOING) {
  1648. if (_tcpFallbackTunnel)
  1649. _phy.close(_tcpFallbackTunnel->sock);
  1650. _tcpFallbackTunnel = tc;
  1651. _phy.streamSend(sock,ZT_TCP_TUNNEL_HELLO,sizeof(ZT_TCP_TUNNEL_HELLO));
  1652. } else {
  1653. _phy.close(sock,true);
  1654. }
  1655. }
  1656. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  1657. {
  1658. if (!from) {
  1659. _phy.close(sockN,false);
  1660. return;
  1661. } else {
  1662. TcpConnection *tc = new TcpConnection();
  1663. {
  1664. Mutex::Lock _l(_tcpConnections_m);
  1665. _tcpConnections.push_back(tc);
  1666. }
  1667. tc->type = TcpConnection::TCP_UNCATEGORIZED_INCOMING;
  1668. tc->parent = this;
  1669. tc->sock = sockN;
  1670. tc->remoteAddr = from;
  1671. tc->lastReceive = OSUtils::now();
  1672. http_parser_init(&(tc->parser),HTTP_REQUEST);
  1673. tc->parser.data = (void *)tc;
  1674. tc->messageSize = 0;
  1675. *uptrN = (void *)tc;
  1676. }
  1677. }
  1678. void phyOnTcpClose(PhySocket *sock,void **uptr)
  1679. {
  1680. TcpConnection *tc = (TcpConnection *)*uptr;
  1681. if (tc) {
  1682. if (tc == _tcpFallbackTunnel) {
  1683. _tcpFallbackTunnel = (TcpConnection *)0;
  1684. }
  1685. {
  1686. Mutex::Lock _l(_tcpConnections_m);
  1687. _tcpConnections.erase(std::remove(_tcpConnections.begin(),_tcpConnections.end(),tc),_tcpConnections.end());
  1688. }
  1689. delete tc;
  1690. }
  1691. }
  1692. void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  1693. {
  1694. try {
  1695. if (!len) return; // sanity check, should never happen
  1696. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1697. tc->lastReceive = OSUtils::now();
  1698. switch(tc->type) {
  1699. case TcpConnection::TCP_UNCATEGORIZED_INCOMING:
  1700. switch(reinterpret_cast<uint8_t *>(data)[0]) {
  1701. // HTTP: GET, PUT, POST, HEAD, DELETE
  1702. case 'G':
  1703. case 'P':
  1704. case 'D':
  1705. case 'H': {
  1706. // This is only allowed from IPs permitted to access the management
  1707. // backplane, which is just 127.0.0.1/::1 unless otherwise configured.
  1708. bool allow;
  1709. {
  1710. Mutex::Lock _l(_localConfig_m);
  1711. if (_allowManagementFrom.size() == 0) {
  1712. allow = (tc->remoteAddr.ipScope() == InetAddress::IP_SCOPE_LOOPBACK);
  1713. } else {
  1714. allow = false;
  1715. for(std::vector<InetAddress>::const_iterator i(_allowManagementFrom.begin());i!=_allowManagementFrom.end();++i) {
  1716. if (i->containsAddress(tc->remoteAddr)) {
  1717. allow = true;
  1718. break;
  1719. }
  1720. }
  1721. }
  1722. }
  1723. if (allow) {
  1724. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  1725. phyOnTcpData(sock,uptr,data,len);
  1726. } else {
  1727. _phy.close(sock);
  1728. }
  1729. } break;
  1730. // Drop unknown protocols
  1731. default:
  1732. _phy.close(sock);
  1733. break;
  1734. }
  1735. return;
  1736. case TcpConnection::TCP_HTTP_INCOMING:
  1737. case TcpConnection::TCP_HTTP_OUTGOING:
  1738. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  1739. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK))
  1740. _phy.close(sock);
  1741. return;
  1742. case TcpConnection::TCP_TUNNEL_OUTGOING:
  1743. tc->readq.append((const char *)data,len);
  1744. while (tc->readq.length() >= 5) {
  1745. const char *data = tc->readq.data();
  1746. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  1747. if (tc->readq.length() >= (mlen + 5)) {
  1748. InetAddress from;
  1749. unsigned long plen = mlen; // payload length, modified if there's an IP header
  1750. data += 5; // skip forward past pseudo-TLS junk and mlen
  1751. if (plen == 4) {
  1752. // Hello message, which isn't sent by proxy and would be ignored by client
  1753. } else if (plen) {
  1754. // Messages should contain IPv4 or IPv6 source IP address data
  1755. switch(data[0]) {
  1756. case 4: // IPv4
  1757. if (plen >= 7) {
  1758. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  1759. data += 7; // type + 4 byte IP + 2 byte port
  1760. plen -= 7;
  1761. } else {
  1762. _phy.close(sock);
  1763. return;
  1764. }
  1765. break;
  1766. case 6: // IPv6
  1767. if (plen >= 19) {
  1768. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  1769. data += 19; // type + 16 byte IP + 2 byte port
  1770. plen -= 19;
  1771. } else {
  1772. _phy.close(sock);
  1773. return;
  1774. }
  1775. break;
  1776. case 0: // none/omitted
  1777. ++data;
  1778. --plen;
  1779. break;
  1780. default: // invalid address type
  1781. _phy.close(sock);
  1782. return;
  1783. }
  1784. if (from) {
  1785. InetAddress fakeTcpLocalInterfaceAddress((uint32_t)0xffffffff,0xffff);
  1786. const ZT_ResultCode rc = _node->processWirePacket(
  1787. (void *)0,
  1788. OSUtils::now(),
  1789. -1,
  1790. reinterpret_cast<struct sockaddr_storage *>(&from),
  1791. data,
  1792. plen,
  1793. &_nextBackgroundTaskDeadline);
  1794. if (ZT_ResultCode_isFatal(rc)) {
  1795. char tmp[256];
  1796. OSUtils::ztsnprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1797. Mutex::Lock _l(_termReason_m);
  1798. _termReason = ONE_UNRECOVERABLE_ERROR;
  1799. _fatalErrorMessage = tmp;
  1800. this->terminate();
  1801. _phy.close(sock);
  1802. return;
  1803. }
  1804. }
  1805. }
  1806. if (tc->readq.length() > (mlen + 5))
  1807. tc->readq.erase(tc->readq.begin(),tc->readq.begin() + (mlen + 5));
  1808. else tc->readq.clear();
  1809. } else break;
  1810. }
  1811. return;
  1812. }
  1813. } catch ( ... ) {
  1814. _phy.close(sock);
  1815. }
  1816. }
  1817. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  1818. {
  1819. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1820. bool closeit = false;
  1821. {
  1822. Mutex::Lock _l(tc->writeq_m);
  1823. if (tc->writeq.length() > 0) {
  1824. long sent = (long)_phy.streamSend(sock,tc->writeq.data(),(unsigned long)tc->writeq.length(),true);
  1825. if (sent > 0) {
  1826. if ((unsigned long)sent >= (unsigned long)tc->writeq.length()) {
  1827. tc->writeq.clear();
  1828. _phy.setNotifyWritable(sock,false);
  1829. if (tc->type == TcpConnection::TCP_HTTP_INCOMING)
  1830. closeit = true; // HTTP keep alive not supported
  1831. } else {
  1832. tc->writeq.erase(tc->writeq.begin(),tc->writeq.begin() + sent);
  1833. }
  1834. }
  1835. } else {
  1836. _phy.setNotifyWritable(sock,false);
  1837. }
  1838. }
  1839. if (closeit)
  1840. _phy.close(sock);
  1841. }
  1842. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  1843. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  1844. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  1845. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  1846. inline void phyOnUnixWritable(PhySocket *sock,void **uptr) {}
  1847. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  1848. {
  1849. Mutex::Lock _l(_nets_m);
  1850. NetworkState &n = _nets[nwid];
  1851. switch(op) {
  1852. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  1853. if (!n.tap) {
  1854. try {
  1855. char friendlyName[128];
  1856. OSUtils::ztsnprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  1857. n.tap = new EthernetTap(
  1858. _homePath.c_str(),
  1859. MAC(nwc->mac),
  1860. nwc->mtu,
  1861. (unsigned int)ZT_IF_METRIC,
  1862. nwid,
  1863. friendlyName,
  1864. StapFrameHandler,
  1865. (void *)this);
  1866. *nuptr = (void *)&n;
  1867. char nlcpath[256];
  1868. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1869. std::string nlcbuf;
  1870. if (OSUtils::readFile(nlcpath,nlcbuf)) {
  1871. Dictionary<4096> nc;
  1872. nc.load(nlcbuf.c_str());
  1873. Buffer<1024> allowManaged;
  1874. if (nc.get("allowManaged", allowManaged) && allowManaged.size() != 0) {
  1875. std::string addresses (allowManaged.begin(), allowManaged.size());
  1876. if (allowManaged.size() <= 5) { // untidy parsing for backward compatibility
  1877. if (allowManaged[0] == '1' || allowManaged[0] == 't' || allowManaged[0] == 'T') {
  1878. n.settings.allowManaged = true;
  1879. } else {
  1880. n.settings.allowManaged = false;
  1881. }
  1882. } else {
  1883. // this should be a list of IP addresses
  1884. n.settings.allowManaged = true;
  1885. size_t pos = 0;
  1886. while (true) {
  1887. size_t nextPos = addresses.find(',', pos);
  1888. std::string address = addresses.substr(pos, (nextPos == std::string::npos ? addresses.size() : nextPos) - pos);
  1889. n.settings.allowManagedWhitelist.push_back(InetAddress(address.c_str()));
  1890. if (nextPos == std::string::npos) break;
  1891. pos = nextPos + 1;
  1892. }
  1893. }
  1894. } else {
  1895. n.settings.allowManaged = true;
  1896. }
  1897. n.settings.allowGlobal = nc.getB("allowGlobal", false);
  1898. n.settings.allowDefault = nc.getB("allowDefault", false);
  1899. }
  1900. } catch (std::exception &exc) {
  1901. #ifdef __WINDOWS__
  1902. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1903. if (tapFailLog) {
  1904. fprintf(tapFailLog,"%.16llx: %s" ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1905. fclose(tapFailLog);
  1906. }
  1907. #else
  1908. fprintf(stderr,"ERROR: unable to configure virtual network port: %s" ZT_EOL_S,exc.what());
  1909. #endif
  1910. _nets.erase(nwid);
  1911. return -999;
  1912. } catch ( ... ) {
  1913. return -999; // tap init failed
  1914. }
  1915. }
  1916. // After setting up tap, fall through to CONFIG_UPDATE since we also want to do this...
  1917. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1918. ZT_FAST_MEMCPY(&(n.config),nwc,sizeof(ZT_VirtualNetworkConfig));
  1919. if (n.tap) { // sanity check
  1920. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1921. // wait for up to 5 seconds for the WindowsEthernetTap to actually be initialized
  1922. //
  1923. // without WindowsEthernetTap::isInitialized() returning true, the won't actually
  1924. // be online yet and setting managed routes on it will fail.
  1925. const int MAX_SLEEP_COUNT = 500;
  1926. for (int i = 0; !n.tap->isInitialized() && i < MAX_SLEEP_COUNT; i++) {
  1927. Sleep(10);
  1928. }
  1929. #endif
  1930. syncManagedStuff(n,true,true);
  1931. n.tap->setMtu(nwc->mtu);
  1932. } else {
  1933. _nets.erase(nwid);
  1934. return -999; // tap init failed
  1935. }
  1936. break;
  1937. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1938. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1939. if (n.tap) { // sanity check
  1940. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1941. std::string winInstanceId(n.tap->instanceId());
  1942. #endif
  1943. *nuptr = (void *)0;
  1944. delete n.tap;
  1945. _nets.erase(nwid);
  1946. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1947. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1948. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1949. #endif
  1950. if (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY) {
  1951. char nlcpath[256];
  1952. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1953. OSUtils::rm(nlcpath);
  1954. }
  1955. } else {
  1956. _nets.erase(nwid);
  1957. }
  1958. break;
  1959. }
  1960. return 0;
  1961. }
  1962. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1963. {
  1964. switch(event) {
  1965. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  1966. Mutex::Lock _l(_termReason_m);
  1967. _termReason = ONE_IDENTITY_COLLISION;
  1968. _fatalErrorMessage = "identity/address collision";
  1969. this->terminate();
  1970. } break;
  1971. case ZT_EVENT_TRACE: {
  1972. if (metaData) {
  1973. ::fprintf(stderr,"%s" ZT_EOL_S,(const char *)metaData);
  1974. ::fflush(stderr);
  1975. }
  1976. } break;
  1977. case ZT_EVENT_USER_MESSAGE: {
  1978. const ZT_UserMessage *um = reinterpret_cast<const ZT_UserMessage *>(metaData);
  1979. if ((um->typeId == ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE)&&(_updater)) {
  1980. _updater->handleSoftwareUpdateUserMessage(um->origin,um->data,um->length);
  1981. }
  1982. } break;
  1983. case ZT_EVENT_REMOTE_TRACE: {
  1984. const ZT_RemoteTrace *rt = reinterpret_cast<const ZT_RemoteTrace *>(metaData);
  1985. if ((rt)&&(rt->len > 0)&&(rt->len <= ZT_MAX_REMOTE_TRACE_SIZE)&&(rt->data))
  1986. _controller->handleRemoteTrace(*rt);
  1987. }
  1988. default:
  1989. break;
  1990. }
  1991. }
  1992. #if ZT_VAULT_SUPPORT
  1993. inline bool nodeVaultPutIdentity(enum ZT_StateObjectType type, const void *data, int len)
  1994. {
  1995. bool retval = false;
  1996. if (type != ZT_STATE_OBJECT_IDENTITY_PUBLIC && type != ZT_STATE_OBJECT_IDENTITY_SECRET) {
  1997. return retval;
  1998. }
  1999. CURL *curl = curl_easy_init();
  2000. if (curl) {
  2001. char token[512] = { 0 };
  2002. snprintf(token, sizeof(token), "X-Vault-Token: %s", _vaultToken.c_str());
  2003. struct curl_slist *chunk = NULL;
  2004. chunk = curl_slist_append(chunk, token);
  2005. char content_type[512] = { 0 };
  2006. snprintf(content_type, sizeof(content_type), "Content-Type: application/json");
  2007. chunk = curl_slist_append(chunk, content_type);
  2008. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
  2009. char url[2048] = { 0 };
  2010. snprintf(url, sizeof(url), "%s/v1/%s", _vaultURL.c_str(), _vaultPath.c_str());
  2011. curl_easy_setopt(curl, CURLOPT_URL, url);
  2012. json d = json::object();
  2013. if (type == ZT_STATE_OBJECT_IDENTITY_PUBLIC) {
  2014. std::string key((const char*)data, len);
  2015. d["public"] = key;
  2016. }
  2017. else if (type == ZT_STATE_OBJECT_IDENTITY_SECRET) {
  2018. std::string key((const char*)data, len);
  2019. d["secret"] = key;
  2020. }
  2021. if (!d.empty()) {
  2022. std::string post = d.dump();
  2023. if (!post.empty()) {
  2024. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post.c_str());
  2025. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, post.length());
  2026. #ifndef NDEBUG
  2027. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  2028. #endif
  2029. CURLcode res = curl_easy_perform(curl);
  2030. if (res == CURLE_OK) {
  2031. long response_code = 0;
  2032. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
  2033. if (response_code == 200 || response_code == 204) {
  2034. retval = true;
  2035. }
  2036. }
  2037. }
  2038. }
  2039. curl_easy_cleanup(curl);
  2040. curl = NULL;
  2041. curl_slist_free_all(chunk);
  2042. chunk = NULL;
  2043. }
  2044. return retval;
  2045. }
  2046. #endif
  2047. inline void nodeStatePutFunction(enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)
  2048. {
  2049. #if ZT_VAULT_SUPPORT
  2050. if (_vaultEnabled && (type == ZT_STATE_OBJECT_IDENTITY_SECRET || type == ZT_STATE_OBJECT_IDENTITY_PUBLIC)) {
  2051. if (nodeVaultPutIdentity(type, data, len)) {
  2052. // value successfully written to Vault
  2053. return;
  2054. }
  2055. // else fallback to disk
  2056. }
  2057. #endif
  2058. char p[1024];
  2059. FILE *f;
  2060. bool secure = false;
  2061. char dirname[1024];
  2062. dirname[0] = 0;
  2063. switch(type) {
  2064. case ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  2065. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str());
  2066. break;
  2067. case ZT_STATE_OBJECT_IDENTITY_SECRET:
  2068. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str());
  2069. secure = true;
  2070. break;
  2071. case ZT_STATE_OBJECT_PLANET:
  2072. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "planet",_homePath.c_str());
  2073. break;
  2074. case ZT_STATE_OBJECT_MOON:
  2075. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "moons.d",_homePath.c_str());
  2076. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.moon",dirname,(unsigned long long)id[0]);
  2077. break;
  2078. case ZT_STATE_OBJECT_NETWORK_CONFIG:
  2079. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "networks.d",_homePath.c_str());
  2080. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.conf",dirname,(unsigned long long)id[0]);
  2081. secure = true;
  2082. break;
  2083. case ZT_STATE_OBJECT_PEER:
  2084. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "peers.d",_homePath.c_str());
  2085. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.10llx.peer",dirname,(unsigned long long)id[0]);
  2086. break;
  2087. default:
  2088. return;
  2089. }
  2090. if (len >= 0) {
  2091. // Check to see if we've already written this first. This reduces
  2092. // redundant writes and I/O overhead on most platforms and has
  2093. // little effect on others.
  2094. f = fopen(p,"rb");
  2095. if (f) {
  2096. char buf[65535];
  2097. long l = (long)fread(buf,1,sizeof(buf),f);
  2098. fclose(f);
  2099. if ((l == (long)len)&&(memcmp(data,buf,l) == 0))
  2100. return;
  2101. }
  2102. f = fopen(p,"wb");
  2103. if ((!f)&&(dirname[0])) { // create subdirectory if it does not exist
  2104. OSUtils::mkdir(dirname);
  2105. f = fopen(p,"wb");
  2106. }
  2107. if (f) {
  2108. if (fwrite(data,len,1,f) != 1)
  2109. fprintf(stderr,"WARNING: unable to write to file: %s (I/O error)" ZT_EOL_S,p);
  2110. fclose(f);
  2111. if (secure)
  2112. OSUtils::lockDownFile(p,false);
  2113. } else {
  2114. fprintf(stderr,"WARNING: unable to write to file: %s (unable to open)" ZT_EOL_S,p);
  2115. }
  2116. } else {
  2117. OSUtils::rm(p);
  2118. }
  2119. }
  2120. #if ZT_VAULT_SUPPORT
  2121. inline int nodeVaultGetIdentity(enum ZT_StateObjectType type, void *data, unsigned int maxlen)
  2122. {
  2123. if (type != ZT_STATE_OBJECT_IDENTITY_SECRET && type != ZT_STATE_OBJECT_IDENTITY_PUBLIC) {
  2124. return -1;
  2125. }
  2126. int ret = -1;
  2127. CURL *curl = curl_easy_init();
  2128. if (curl) {
  2129. char token[512] = { 0 };
  2130. snprintf(token, sizeof(token), "X-Vault-Token: %s", _vaultToken.c_str());
  2131. struct curl_slist *chunk = NULL;
  2132. chunk = curl_slist_append(chunk, token);
  2133. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
  2134. char url[2048] = { 0 };
  2135. snprintf(url, sizeof(url), "%s/v1/%s", _vaultURL.c_str(), _vaultPath.c_str());
  2136. curl_easy_setopt(curl, CURLOPT_URL, url);
  2137. std::string response;
  2138. std::string res_headers;
  2139. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &curlResponseWrite);
  2140. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
  2141. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &res_headers);
  2142. #ifndef NDEBUG
  2143. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  2144. #endif
  2145. CURLcode res = curl_easy_perform(curl);
  2146. if (res == CURLE_OK) {
  2147. long response_code = 0;
  2148. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
  2149. if (response_code == 200) {
  2150. try {
  2151. json payload = json::parse(response);
  2152. if (!payload["data"].is_null()) {
  2153. json &d = payload["data"];
  2154. if (type == ZT_STATE_OBJECT_IDENTITY_SECRET) {
  2155. std::string secret = OSUtils::jsonString(d["secret"],"");
  2156. if (!secret.empty()) {
  2157. ret = (int)secret.length();
  2158. memcpy(data, secret.c_str(), ret);
  2159. }
  2160. }
  2161. else if (type == ZT_STATE_OBJECT_IDENTITY_PUBLIC) {
  2162. std::string pub = OSUtils::jsonString(d["public"],"");
  2163. if (!pub.empty()) {
  2164. ret = (int)pub.length();
  2165. memcpy(data, pub.c_str(), ret);
  2166. }
  2167. }
  2168. }
  2169. }
  2170. catch (...) {
  2171. ret = -1;
  2172. }
  2173. }
  2174. }
  2175. curl_easy_cleanup(curl);
  2176. curl = NULL;
  2177. curl_slist_free_all(chunk);
  2178. chunk = NULL;
  2179. }
  2180. return ret;
  2181. }
  2182. #endif
  2183. inline int nodeStateGetFunction(enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)
  2184. {
  2185. #if ZT_VAULT_SUPPORT
  2186. if (_vaultEnabled && (type == ZT_STATE_OBJECT_IDENTITY_SECRET || type == ZT_STATE_OBJECT_IDENTITY_PUBLIC) ) {
  2187. int retval = nodeVaultGetIdentity(type, data, maxlen);
  2188. if (retval >= 0)
  2189. return retval;
  2190. // else continue file based lookup
  2191. }
  2192. #endif
  2193. char p[4096];
  2194. switch(type) {
  2195. case ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  2196. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str());
  2197. break;
  2198. case ZT_STATE_OBJECT_IDENTITY_SECRET:
  2199. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str());
  2200. break;
  2201. case ZT_STATE_OBJECT_PLANET:
  2202. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "planet",_homePath.c_str());
  2203. break;
  2204. case ZT_STATE_OBJECT_MOON:
  2205. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "moons.d" ZT_PATH_SEPARATOR_S "%.16llx.moon",_homePath.c_str(),(unsigned long long)id[0]);
  2206. break;
  2207. case ZT_STATE_OBJECT_NETWORK_CONFIG:
  2208. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.conf",_homePath.c_str(),(unsigned long long)id[0]);
  2209. break;
  2210. case ZT_STATE_OBJECT_PEER:
  2211. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "peers.d" ZT_PATH_SEPARATOR_S "%.10llx.peer",_homePath.c_str(),(unsigned long long)id[0]);
  2212. break;
  2213. default:
  2214. return -1;
  2215. }
  2216. FILE *f = fopen(p,"rb");
  2217. if (f) {
  2218. int n = (int)fread(data,1,maxlen,f);
  2219. fclose(f);
  2220. #if ZT_VAULT_SUPPORT
  2221. if (_vaultEnabled && (type == ZT_STATE_OBJECT_IDENTITY_SECRET || type == ZT_STATE_OBJECT_IDENTITY_PUBLIC)) {
  2222. // If we've gotten here while Vault is enabled, Vault does not know the key and it's been
  2223. // read from disk instead.
  2224. //
  2225. // We should put the value in Vault and remove the local file.
  2226. if (nodeVaultPutIdentity(type, data, n)) {
  2227. unlink(p);
  2228. }
  2229. }
  2230. #endif
  2231. if (n >= 0)
  2232. return n;
  2233. }
  2234. return -1;
  2235. }
  2236. inline int nodeWirePacketSendFunction(const int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  2237. {
  2238. #ifdef ZT_TCP_FALLBACK_RELAY
  2239. if(_allowTcpFallbackRelay) {
  2240. if (addr->ss_family == AF_INET) {
  2241. // TCP fallback tunnel support, currently IPv4 only
  2242. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  2243. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  2244. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  2245. // valid direct traffic we'll stop using it and close the socket after a while.
  2246. const int64_t now = OSUtils::now();
  2247. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  2248. if (_tcpFallbackTunnel) {
  2249. bool flushNow = false;
  2250. {
  2251. Mutex::Lock _l(_tcpFallbackTunnel->writeq_m);
  2252. if (_tcpFallbackTunnel->writeq.size() < (1024 * 64)) {
  2253. if (_tcpFallbackTunnel->writeq.length() == 0) {
  2254. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  2255. flushNow = true;
  2256. }
  2257. const unsigned long mlen = len + 7;
  2258. _tcpFallbackTunnel->writeq.push_back((char)0x17);
  2259. _tcpFallbackTunnel->writeq.push_back((char)0x03);
  2260. _tcpFallbackTunnel->writeq.push_back((char)0x03); // fake TLS 1.2 header
  2261. _tcpFallbackTunnel->writeq.push_back((char)((mlen >> 8) & 0xff));
  2262. _tcpFallbackTunnel->writeq.push_back((char)(mlen & 0xff));
  2263. _tcpFallbackTunnel->writeq.push_back((char)4); // IPv4
  2264. _tcpFallbackTunnel->writeq.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  2265. _tcpFallbackTunnel->writeq.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  2266. _tcpFallbackTunnel->writeq.append((const char *)data,len);
  2267. }
  2268. }
  2269. if (flushNow) {
  2270. void *tmpptr = (void *)_tcpFallbackTunnel;
  2271. phyOnTcpWritable(_tcpFallbackTunnel->sock,&tmpptr);
  2272. }
  2273. } else if (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INVERVAL / 2))) {
  2274. const InetAddress addr(ZT_TCP_FALLBACK_RELAY);
  2275. TcpConnection *tc = new TcpConnection();
  2276. {
  2277. Mutex::Lock _l(_tcpConnections_m);
  2278. _tcpConnections.push_back(tc);
  2279. }
  2280. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  2281. tc->remoteAddr = addr;
  2282. tc->lastReceive = OSUtils::now();
  2283. tc->parent = this;
  2284. tc->sock = (PhySocket *)0; // set in connect handler
  2285. tc->messageSize = 0;
  2286. bool connected = false;
  2287. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected,(void *)tc,true);
  2288. }
  2289. }
  2290. _lastSendToGlobalV4 = now;
  2291. }
  2292. }
  2293. }
  2294. #endif // ZT_TCP_FALLBACK_RELAY
  2295. // Even when relaying we still send via UDP. This way if UDP starts
  2296. // working we can instantly "fail forward" to it and stop using TCP
  2297. // proxy fallback, which is slow.
  2298. if ((localSocket != -1)&&(localSocket != 0)&&(_binder.isUdpSocketValid((PhySocket *)((uintptr_t)localSocket)))) {
  2299. if ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),ttl);
  2300. const bool r = _phy.udpSend((PhySocket *)((uintptr_t)localSocket),(const struct sockaddr *)addr,data,len);
  2301. if ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),255);
  2302. return ((r) ? 0 : -1);
  2303. } else {
  2304. return ((_binder.udpSendAll(_phy,addr,data,len,ttl)) ? 0 : -1);
  2305. }
  2306. }
  2307. inline void nodeVirtualNetworkFrameFunction(uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  2308. {
  2309. NetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);
  2310. if ((!n)||(!n->tap))
  2311. return;
  2312. n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  2313. }
  2314. inline int nodePathCheckFunction(uint64_t ztaddr,const int64_t localSocket,const struct sockaddr_storage *remoteAddr)
  2315. {
  2316. // Make sure we're not trying to do ZeroTier-over-ZeroTier
  2317. {
  2318. Mutex::Lock _l(_nets_m);
  2319. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  2320. if (n->second.tap) {
  2321. std::vector<InetAddress> ips(n->second.tap->ips());
  2322. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  2323. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  2324. return 0;
  2325. }
  2326. }
  2327. }
  2328. }
  2329. }
  2330. /* Note: I do not think we need to scan for overlap with managed routes
  2331. * because of the "route forking" and interface binding that we do. This
  2332. * ensures (we hope) that ZeroTier traffic will still take the physical
  2333. * path even if its managed routes override this for other traffic. Will
  2334. * revisit if we see recursion problems. */
  2335. // Check blacklists
  2336. const Hashtable< uint64_t,std::vector<InetAddress> > *blh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  2337. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  2338. if (remoteAddr->ss_family == AF_INET) {
  2339. blh = &_v4Blacklists;
  2340. gbl = &_globalV4Blacklist;
  2341. } else if (remoteAddr->ss_family == AF_INET6) {
  2342. blh = &_v6Blacklists;
  2343. gbl = &_globalV6Blacklist;
  2344. }
  2345. if (blh) {
  2346. Mutex::Lock _l(_localConfig_m);
  2347. const std::vector<InetAddress> *l = blh->get(ztaddr);
  2348. if (l) {
  2349. for(std::vector<InetAddress>::const_iterator a(l->begin());a!=l->end();++a) {
  2350. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  2351. return 0;
  2352. }
  2353. }
  2354. }
  2355. if (gbl) {
  2356. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  2357. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  2358. return 0;
  2359. }
  2360. }
  2361. return 1;
  2362. }
  2363. inline int nodePathLookupFunction(uint64_t ztaddr,int family,struct sockaddr_storage *result)
  2364. {
  2365. const Hashtable< uint64_t,std::vector<InetAddress> > *lh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  2366. if (family < 0)
  2367. lh = (_node->prng() & 1) ? &_v4Hints : &_v6Hints;
  2368. else if (family == AF_INET)
  2369. lh = &_v4Hints;
  2370. else if (family == AF_INET6)
  2371. lh = &_v6Hints;
  2372. else return 0;
  2373. const std::vector<InetAddress> *l = lh->get(ztaddr);
  2374. if ((l)&&(l->size() > 0)) {
  2375. ZT_FAST_MEMCPY(result,&((*l)[(unsigned long)_node->prng() % l->size()]),sizeof(struct sockaddr_storage));
  2376. return 1;
  2377. } else return 0;
  2378. }
  2379. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  2380. {
  2381. _node->processVirtualNetworkFrame((void *)0,OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  2382. }
  2383. inline void onHttpRequestToServer(TcpConnection *tc)
  2384. {
  2385. char tmpn[4096];
  2386. std::string data;
  2387. std::string contentType("text/plain"); // default if not changed in handleRequest()
  2388. unsigned int scode = 404;
  2389. // Note that we check allowed IP ranges when HTTP connections are first detected in
  2390. // phyOnTcpData(). If we made it here the source IP is okay.
  2391. try {
  2392. scode = handleControlPlaneHttpRequest(tc->remoteAddr,tc->parser.method,tc->url,tc->headers,tc->readq,data,contentType);
  2393. } catch (std::exception &exc) {
  2394. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: %s" ZT_EOL_S,exc.what());
  2395. scode = 500;
  2396. } catch ( ... ) {
  2397. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: unknown exception" ZT_EOL_S);
  2398. scode = 500;
  2399. }
  2400. const char *scodestr;
  2401. switch(scode) {
  2402. case 200: scodestr = "OK"; break;
  2403. case 400: scodestr = "Bad Request"; break;
  2404. case 401: scodestr = "Unauthorized"; break;
  2405. case 403: scodestr = "Forbidden"; break;
  2406. case 404: scodestr = "Not Found"; break;
  2407. case 500: scodestr = "Internal Server Error"; break;
  2408. case 501: scodestr = "Not Implemented"; break;
  2409. case 503: scodestr = "Service Unavailable"; break;
  2410. default: scodestr = "Error"; break;
  2411. }
  2412. OSUtils::ztsnprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\nContent-Type: %s\r\nContent-Length: %lu\r\nConnection: close\r\n\r\n",
  2413. scode,
  2414. scodestr,
  2415. contentType.c_str(),
  2416. (unsigned long)data.length());
  2417. {
  2418. Mutex::Lock _l(tc->writeq_m);
  2419. tc->writeq = tmpn;
  2420. if (tc->parser.method != HTTP_HEAD)
  2421. tc->writeq.append(data);
  2422. }
  2423. _phy.setNotifyWritable(tc->sock,true);
  2424. }
  2425. inline void onHttpResponseFromClient(TcpConnection *tc)
  2426. {
  2427. _phy.close(tc->sock);
  2428. }
  2429. bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
  2430. {
  2431. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  2432. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  2433. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  2434. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  2435. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  2436. #endif
  2437. #ifdef __APPLE__
  2438. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  2439. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  2440. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  2441. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  2442. if ((ifname[0] == 'u')&&(ifname[1] == 't')&&(ifname[2] == 'u')&&(ifname[3] == 'n')) return false; // ... as is utun#
  2443. #endif
  2444. {
  2445. Mutex::Lock _l(_localConfig_m);
  2446. for(std::vector<std::string>::const_iterator p(_interfacePrefixBlacklist.begin());p!=_interfacePrefixBlacklist.end();++p) {
  2447. if (!strncmp(p->c_str(),ifname,p->length()))
  2448. return false;
  2449. }
  2450. }
  2451. {
  2452. // Check global blacklists
  2453. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  2454. if (ifaddr.ss_family == AF_INET) {
  2455. gbl = &_globalV4Blacklist;
  2456. } else if (ifaddr.ss_family == AF_INET6) {
  2457. gbl = &_globalV6Blacklist;
  2458. }
  2459. if (gbl) {
  2460. Mutex::Lock _l(_localConfig_m);
  2461. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  2462. if (a->containsAddress(ifaddr))
  2463. return false;
  2464. }
  2465. }
  2466. }
  2467. {
  2468. Mutex::Lock _l(_nets_m);
  2469. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  2470. if (n->second.tap) {
  2471. std::vector<InetAddress> ips(n->second.tap->ips());
  2472. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  2473. if (i->ipsEqual(ifaddr))
  2474. return false;
  2475. }
  2476. }
  2477. }
  2478. }
  2479. return true;
  2480. }
  2481. bool _trialBind(unsigned int port)
  2482. {
  2483. struct sockaddr_in in4;
  2484. struct sockaddr_in6 in6;
  2485. PhySocket *tb;
  2486. memset(&in4,0,sizeof(in4));
  2487. in4.sin_family = AF_INET;
  2488. in4.sin_port = Utils::hton((uint16_t)port);
  2489. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
  2490. if (tb) {
  2491. _phy.close(tb,false);
  2492. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
  2493. if (tb) {
  2494. _phy.close(tb,false);
  2495. return true;
  2496. }
  2497. }
  2498. memset(&in6,0,sizeof(in6));
  2499. in6.sin6_family = AF_INET6;
  2500. in6.sin6_port = Utils::hton((uint16_t)port);
  2501. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
  2502. if (tb) {
  2503. _phy.close(tb,false);
  2504. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
  2505. if (tb) {
  2506. _phy.close(tb,false);
  2507. return true;
  2508. }
  2509. }
  2510. return false;
  2511. }
  2512. };
  2513. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  2514. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  2515. static void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData)
  2516. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  2517. static void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)
  2518. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeStatePutFunction(type,id,data,len); }
  2519. static int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)
  2520. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeStateGetFunction(type,id,data,maxlen); }
  2521. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,void *tptr,int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  2522. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localSocket,addr,data,len,ttl); }
  2523. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  2524. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  2525. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr)
  2526. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(ztaddr,localSocket,remoteAddr); }
  2527. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result)
  2528. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathLookupFunction(ztaddr,family,result); }
  2529. static void StapFrameHandler(void *uptr,void *tptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  2530. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  2531. static int ShttpOnMessageBegin(http_parser *parser)
  2532. {
  2533. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2534. tc->currentHeaderField = "";
  2535. tc->currentHeaderValue = "";
  2536. tc->messageSize = 0;
  2537. tc->url.clear();
  2538. tc->status.clear();
  2539. tc->headers.clear();
  2540. tc->readq.clear();
  2541. return 0;
  2542. }
  2543. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  2544. {
  2545. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2546. tc->messageSize += (unsigned long)length;
  2547. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2548. return -1;
  2549. tc->url.append(ptr,length);
  2550. return 0;
  2551. }
  2552. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  2553. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  2554. #else
  2555. static int ShttpOnStatus(http_parser *parser)
  2556. #endif
  2557. { return 0; }
  2558. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  2559. {
  2560. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2561. tc->messageSize += (unsigned long)length;
  2562. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2563. return -1;
  2564. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  2565. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  2566. tc->currentHeaderField = "";
  2567. tc->currentHeaderValue = "";
  2568. }
  2569. for(size_t i=0;i<length;++i)
  2570. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  2571. return 0;
  2572. }
  2573. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  2574. {
  2575. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2576. tc->messageSize += (unsigned long)length;
  2577. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2578. return -1;
  2579. tc->currentHeaderValue.append(ptr,length);
  2580. return 0;
  2581. }
  2582. static int ShttpOnHeadersComplete(http_parser *parser)
  2583. {
  2584. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2585. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  2586. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  2587. return 0;
  2588. }
  2589. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  2590. {
  2591. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2592. tc->messageSize += (unsigned long)length;
  2593. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2594. return -1;
  2595. tc->readq.append(ptr,length);
  2596. return 0;
  2597. }
  2598. static int ShttpOnMessageComplete(http_parser *parser)
  2599. {
  2600. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2601. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  2602. tc->parent->onHttpRequestToServer(tc);
  2603. } else {
  2604. tc->parent->onHttpResponseFromClient(tc);
  2605. }
  2606. return 0;
  2607. }
  2608. } // anonymous namespace
  2609. std::string OneService::platformDefaultHomePath()
  2610. {
  2611. return OSUtils::platformDefaultHomePath();
  2612. }
  2613. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  2614. OneService::~OneService() {}
  2615. } // namespace ZeroTier