OneService.cpp 100 KB

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