OneService.cpp 126 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2025-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include <exception>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <stdint.h>
  18. #include <string>
  19. #include <map>
  20. #include <vector>
  21. #include <algorithm>
  22. #include <list>
  23. #include <thread>
  24. #include <mutex>
  25. #include <condition_variable>
  26. #include "../version.h"
  27. #include "../include/ZeroTierOne.h"
  28. #include "../node/Constants.hpp"
  29. #include "../node/Mutex.hpp"
  30. #include "../node/Node.hpp"
  31. #include "../node/Utils.hpp"
  32. #include "../node/InetAddress.hpp"
  33. #include "../node/MAC.hpp"
  34. #include "../node/Identity.hpp"
  35. #include "../node/World.hpp"
  36. #include "../node/Salsa20.hpp"
  37. #include "../node/Poly1305.hpp"
  38. #include "../node/SHA512.hpp"
  39. #include "../node/Bond.hpp"
  40. #include "../node/Peer.hpp"
  41. #include "../osdep/Phy.hpp"
  42. #include "../osdep/OSUtils.hpp"
  43. #include "../osdep/Http.hpp"
  44. #include "../osdep/PortMapper.hpp"
  45. #include "../osdep/Binder.hpp"
  46. #include "../osdep/ManagedRoute.hpp"
  47. #include "../osdep/BlockingQueue.hpp"
  48. #include "OneService.hpp"
  49. #include "SoftwareUpdater.hpp"
  50. #include <cpp-httplib/httplib.h>
  51. #if ZT_SSO_ENABLED
  52. #include <zeroidc.h>
  53. #endif
  54. #ifdef __WINDOWS__
  55. #include <winsock2.h>
  56. #include <windows.h>
  57. #include <shlobj.h>
  58. #include <netioapi.h>
  59. #include <iphlpapi.h>
  60. //#include <unistd.h>
  61. #define stat _stat
  62. #else
  63. #include <sys/types.h>
  64. #include <sys/socket.h>
  65. #include <sys/stat.h>
  66. #include <sys/wait.h>
  67. #include <unistd.h>
  68. #include <ifaddrs.h>
  69. #endif
  70. #ifdef __APPLE__
  71. #include "../osdep/MacDNSHelper.hpp"
  72. #elif defined(__WINDOWS__)
  73. #include "../osdep/WinDNSHelper.hpp"
  74. #include "../osdep/WinFWHelper.hpp"
  75. #endif
  76. #ifdef ZT_USE_SYSTEM_HTTP_PARSER
  77. #include <http_parser.h>
  78. #else
  79. #include "../ext/http-parser/http_parser.h"
  80. #endif
  81. #include "../node/Metrics.hpp"
  82. #if ZT_VAULT_SUPPORT
  83. extern "C" {
  84. #include <curl/curl.h>
  85. }
  86. #endif
  87. #include <nlohmann/json.hpp>
  88. #include <inja/inja.hpp>
  89. using json = nlohmann::json;
  90. #include "../controller/EmbeddedNetworkController.hpp"
  91. #include "../controller/PostgreSQL.hpp"
  92. #include "../controller/Redis.hpp"
  93. #include "../osdep/EthernetTap.hpp"
  94. #ifdef __WINDOWS__
  95. #include "../osdep/WindowsEthernetTap.hpp"
  96. #endif
  97. #ifndef ZT_SOFTWARE_UPDATE_DEFAULT
  98. #define ZT_SOFTWARE_UPDATE_DEFAULT "disable"
  99. #endif
  100. // Sanity limits for HTTP
  101. #define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 64)
  102. #define ZT_MAX_HTTP_CONNECTIONS 65536
  103. // Interface metric for ZeroTier taps -- this ensures that if we are on WiFi and also
  104. // bridged via ZeroTier to the same LAN traffic will (if the OS is sane) prefer WiFi.
  105. #define ZT_IF_METRIC 5000
  106. // How often to check for new multicast subscriptions on a tap device
  107. #define ZT_TAP_CHECK_MULTICAST_INTERVAL 5000
  108. // TCP fallback relay (run by ZeroTier, Inc. -- this will eventually go away)
  109. #ifndef ZT_SDK
  110. #define ZT_TCP_FALLBACK_RELAY "204.80.128.1/443"
  111. #endif
  112. // Frequency at which we re-resolve the TCP fallback relay
  113. #define ZT_TCP_FALLBACK_RERESOLVE_DELAY 86400000
  114. // Attempt to engage TCP fallback after this many ms of no reply to packets sent to global-scope IPs
  115. #define ZT_TCP_FALLBACK_AFTER 60000
  116. // How often to check for local interface addresses
  117. #define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 60000
  118. // Maximum write buffer size for outgoing TCP connections (sanity limit)
  119. #define ZT_TCP_MAX_WRITEQ_SIZE 33554432
  120. // TCP activity timeout
  121. #define ZT_TCP_ACTIVITY_TIMEOUT 60000
  122. #if ZT_VAULT_SUPPORT
  123. size_t curlResponseWrite(void *ptr, size_t size, size_t nmemb, std::string *data)
  124. {
  125. data->append((char*)ptr, size * nmemb);
  126. return size * nmemb;
  127. }
  128. #endif
  129. namespace ZeroTier {
  130. std::string ssoResponseTemplate = R"""(
  131. <!doctype html>
  132. <html class="no-js" lang="">
  133. <head>
  134. <meta charset="utf-8">
  135. <meta http-equiv="x-ua-compatible" content="ie=edge">
  136. <title>Network SSO Login {{ networkId }}</title>
  137. <meta name="description" content="">
  138. <meta name="viewport" content="width=device-width, initial-scale=1">
  139. <style type="text/css">
  140. html,body {
  141. background: #eeeeee;
  142. margin: 0;
  143. padding: 0;
  144. font-family: "System Sans Serif";
  145. font-weight: normal;
  146. font-size: 12pt;
  147. height: 100%;
  148. width: 100%;
  149. }
  150. .container {
  151. position: absolute;
  152. left: 50%;
  153. top: 50%;
  154. -webkit-transform: translate(-50%, -50%);
  155. transform: translate(-50%, -50%);
  156. }
  157. .iconwrapper {
  158. margin: 10px 10px 10px 10px;
  159. }
  160. </style>
  161. </head>
  162. <body>
  163. <div class="container">
  164. <div class="iconwrapper">
  165. <svg id="Layer_1" width="225px" height="225px" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 225 225"><defs><style>.cls-1{fill:#fdb25d;}.cls-2{fill:none;stroke:#000;stroke-miterlimit:10;stroke-width:6.99px;}</style></defs><rect class="cls-1" width="225" height="225" rx="35.74"/><line class="cls-2" x1="25.65" y1="32.64" x2="199.35" y2="32.64"/><line class="cls-2" x1="112.5" y1="201.02" x2="112.5" y2="32.64"/><circle class="cls-2" cx="112.5" cy="115.22" r="56.54"/></svg>
  166. </div>
  167. <div class="text">{{ messageText }}</div>
  168. </div>
  169. </body>
  170. </html>
  171. )""";
  172. bool bearerTokenValid(const std::string authHeader, const std::string &checkToken) {
  173. std::vector<std::string> tokens = OSUtils::split(authHeader.c_str(), " ", NULL, NULL);
  174. if (tokens.size() != 2) {
  175. return false;
  176. }
  177. std::string bearer = tokens[0];
  178. std::string token = tokens[1];
  179. std::transform(bearer.begin(), bearer.end(), bearer.begin(), [](unsigned char c){return std::tolower(c);});
  180. if (bearer != "bearer") {
  181. return false;
  182. }
  183. if (token != checkToken) {
  184. return false;
  185. }
  186. return true;
  187. }
  188. #if ZT_DEBUG==1
  189. std::string dump_headers(const httplib::Headers &headers) {
  190. std::string s;
  191. char buf[BUFSIZ];
  192. for (auto it = headers.begin(); it != headers.end(); ++it) {
  193. const auto &x = *it;
  194. snprintf(buf, sizeof(buf), "%s: %s\n", x.first.c_str(), x.second.c_str());
  195. s += buf;
  196. }
  197. return s;
  198. }
  199. std::string http_log(const httplib::Request &req, const httplib::Response &res) {
  200. std::string s;
  201. char buf[BUFSIZ];
  202. s += "================================\n";
  203. snprintf(buf, sizeof(buf), "%s %s %s", req.method.c_str(),
  204. req.version.c_str(), req.path.c_str());
  205. s += buf;
  206. std::string query;
  207. for (auto it = req.params.begin(); it != req.params.end(); ++it) {
  208. const auto &x = *it;
  209. snprintf(buf, sizeof(buf), "%c%s=%s",
  210. (it == req.params.begin()) ? '?' : '&', x.first.c_str(),
  211. x.second.c_str());
  212. query += buf;
  213. }
  214. snprintf(buf, sizeof(buf), "%s\n", query.c_str());
  215. s += buf;
  216. s += dump_headers(req.headers);
  217. s += "--------------------------------\n";
  218. snprintf(buf, sizeof(buf), "%d %s\n", res.status, res.version.c_str());
  219. s += buf;
  220. s += dump_headers(res.headers);
  221. s += "\n";
  222. if (!res.body.empty()) { s += res.body; }
  223. s += "\n";
  224. return s;
  225. }
  226. #endif
  227. // Configured networks
  228. class NetworkState
  229. {
  230. public:
  231. NetworkState()
  232. : _webPort(9993)
  233. , _tap((EthernetTap *)0)
  234. #if ZT_SSO_ENABLED
  235. , _idc(nullptr)
  236. #endif
  237. {
  238. // Real defaults are in network 'up' code in network event handler
  239. _settings.allowManaged = true;
  240. _settings.allowGlobal = false;
  241. _settings.allowDefault = false;
  242. _settings.allowDNS = false;
  243. memset(&_config, 0, sizeof(ZT_VirtualNetworkConfig));
  244. }
  245. ~NetworkState()
  246. {
  247. this->_managedRoutes.clear();
  248. this->_tap.reset();
  249. #if ZT_SSO_ENABLED
  250. if (_idc) {
  251. zeroidc::zeroidc_stop(_idc);
  252. zeroidc::zeroidc_delete(_idc);
  253. _idc = nullptr;
  254. }
  255. #endif
  256. }
  257. void setWebPort(unsigned int port) {
  258. _webPort = port;
  259. }
  260. void setTap(std::shared_ptr<EthernetTap> tap) {
  261. this->_tap = tap;
  262. }
  263. std::shared_ptr<EthernetTap> tap() const {
  264. return _tap;
  265. }
  266. OneService::NetworkSettings settings() const {
  267. return _settings;
  268. }
  269. void setSettings(const OneService::NetworkSettings &settings) {
  270. _settings = settings;
  271. }
  272. void setAllowManaged(bool allow) {
  273. _settings.allowManaged = allow;
  274. }
  275. bool allowManaged() const {
  276. return _settings.allowManaged;
  277. }
  278. void setAllowGlobal(bool allow) {
  279. _settings.allowGlobal = allow;
  280. }
  281. bool allowGlobal() const {
  282. return _settings.allowGlobal;
  283. }
  284. void setAllowDefault(bool allow) {
  285. _settings.allowDefault = allow;
  286. }
  287. bool allowDefault() const {
  288. return _settings.allowDefault;
  289. }
  290. void setAllowDNS(bool allow) {
  291. _settings.allowDNS = allow;
  292. }
  293. bool allowDNS() const {
  294. return _settings.allowDNS;
  295. }
  296. std::vector<InetAddress> allowManagedWhitelist() const {
  297. return _settings.allowManagedWhitelist;
  298. }
  299. void addToAllowManagedWhiteList(const InetAddress& addr) {
  300. _settings.allowManagedWhitelist.push_back(addr);
  301. }
  302. const ZT_VirtualNetworkConfig& config() {
  303. return _config;
  304. }
  305. void setConfig(const ZT_VirtualNetworkConfig *nwc) {
  306. memcpy(&_config, nwc, sizeof(ZT_VirtualNetworkConfig));
  307. if (_config.ssoEnabled && _config.ssoVersion == 1) {
  308. #if ZT_SSO_ENABLED
  309. if (_idc == nullptr)
  310. {
  311. assert(_config.issuerURL != nullptr);
  312. assert(_config.ssoClientID != nullptr);
  313. assert(_config.centralAuthURL != nullptr);
  314. assert(_config.ssoProvider != nullptr);
  315. _idc = zeroidc::zeroidc_new(
  316. _config.issuerURL,
  317. _config.ssoClientID,
  318. _config.centralAuthURL,
  319. _config.ssoProvider,
  320. _webPort
  321. );
  322. if (_idc == nullptr) {
  323. fprintf(stderr, "idc is null\n");
  324. return;
  325. }
  326. }
  327. zeroidc::zeroidc_set_nonce_and_csrf(
  328. _idc,
  329. _config.ssoState,
  330. _config.ssoNonce
  331. );
  332. char* url = zeroidc::zeroidc_get_auth_url(_idc);
  333. memcpy(_config.authenticationURL, url, strlen(url));
  334. _config.authenticationURL[strlen(url)] = 0;
  335. zeroidc::free_cstr(url);
  336. if (zeroidc::zeroidc_is_running(_idc) && nwc->status == ZT_NETWORK_STATUS_AUTHENTICATION_REQUIRED) {
  337. zeroidc::zeroidc_kick_refresh_thread(_idc);
  338. }
  339. #endif
  340. }
  341. }
  342. std::vector<InetAddress>& managedIps() {
  343. return _managedIps;
  344. }
  345. void setManagedIps(const std::vector<InetAddress> &managedIps) {
  346. _managedIps = managedIps;
  347. }
  348. std::map< InetAddress, SharedPtr<ManagedRoute> >& managedRoutes() {
  349. return _managedRoutes;
  350. }
  351. char* doTokenExchange(const char *code) {
  352. char *ret = nullptr;
  353. #if ZT_SSO_ENABLED
  354. if (_idc == nullptr) {
  355. fprintf(stderr, "ainfo or idc null\n");
  356. return ret;
  357. }
  358. ret = zeroidc::zeroidc_token_exchange(_idc, code);
  359. zeroidc::zeroidc_set_nonce_and_csrf(
  360. _idc,
  361. _config.ssoState,
  362. _config.ssoNonce
  363. );
  364. char* url = zeroidc::zeroidc_get_auth_url(_idc);
  365. memcpy(_config.authenticationURL, url, strlen(url));
  366. _config.authenticationURL[strlen(url)] = 0;
  367. zeroidc::free_cstr(url);
  368. #endif
  369. return ret;
  370. }
  371. uint64_t getExpiryTime() {
  372. #if ZT_SSO_ENABLED
  373. if (_idc == nullptr) {
  374. fprintf(stderr, "idc is null\n");
  375. return 0;
  376. }
  377. return zeroidc::zeroidc_get_exp_time(_idc);
  378. #else
  379. return 0;
  380. #endif
  381. }
  382. private:
  383. unsigned int _webPort;
  384. std::shared_ptr<EthernetTap> _tap;
  385. ZT_VirtualNetworkConfig _config; // memcpy() of raw config from core
  386. std::vector<InetAddress> _managedIps;
  387. std::map< InetAddress, SharedPtr<ManagedRoute> > _managedRoutes;
  388. OneService::NetworkSettings _settings;
  389. #if ZT_SSO_ENABLED
  390. zeroidc::ZeroIDC *_idc;
  391. #endif
  392. };
  393. namespace {
  394. static const InetAddress NULL_INET_ADDR;
  395. // Fake TLS hello for TCP tunnel outgoing connections (TUNNELED mode)
  396. 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) };
  397. static std::string _trimString(const std::string &s)
  398. {
  399. unsigned long end = (unsigned long)s.length();
  400. while (end) {
  401. char c = s[end - 1];
  402. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  403. --end;
  404. else break;
  405. }
  406. unsigned long start = 0;
  407. while (start < end) {
  408. char c = s[start];
  409. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  410. ++start;
  411. else break;
  412. }
  413. return s.substr(start,end - start);
  414. }
  415. static void _networkToJson(nlohmann::json &nj,NetworkState &ns)
  416. {
  417. char tmp[256];
  418. const char *nstatus = "",*ntype = "";
  419. switch(ns.config().status) {
  420. case ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION: nstatus = "REQUESTING_CONFIGURATION"; break;
  421. case ZT_NETWORK_STATUS_OK: nstatus = "OK"; break;
  422. case ZT_NETWORK_STATUS_ACCESS_DENIED: nstatus = "ACCESS_DENIED"; break;
  423. case ZT_NETWORK_STATUS_NOT_FOUND: nstatus = "NOT_FOUND"; break;
  424. case ZT_NETWORK_STATUS_PORT_ERROR: nstatus = "PORT_ERROR"; break;
  425. case ZT_NETWORK_STATUS_CLIENT_TOO_OLD: nstatus = "CLIENT_TOO_OLD"; break;
  426. case ZT_NETWORK_STATUS_AUTHENTICATION_REQUIRED: nstatus = "AUTHENTICATION_REQUIRED"; break;
  427. }
  428. switch(ns.config().type) {
  429. case ZT_NETWORK_TYPE_PRIVATE: ntype = "PRIVATE"; break;
  430. case ZT_NETWORK_TYPE_PUBLIC: ntype = "PUBLIC"; break;
  431. }
  432. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",ns.config().nwid);
  433. nj["id"] = tmp;
  434. nj["nwid"] = tmp;
  435. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(unsigned int)((ns.config().mac >> 40) & 0xff),(unsigned int)((ns.config().mac >> 32) & 0xff),(unsigned int)((ns.config().mac >> 24) & 0xff),(unsigned int)((ns.config().mac >> 16) & 0xff),(unsigned int)((ns.config().mac >> 8) & 0xff),(unsigned int)(ns.config().mac & 0xff));
  436. nj["mac"] = tmp;
  437. nj["name"] = ns.config().name;
  438. nj["status"] = nstatus;
  439. nj["type"] = ntype;
  440. nj["mtu"] = ns.config().mtu;
  441. nj["dhcp"] = (bool)(ns.config().dhcp != 0);
  442. nj["bridge"] = (bool)(ns.config().bridge != 0);
  443. nj["broadcastEnabled"] = (bool)(ns.config().broadcastEnabled != 0);
  444. nj["portError"] = ns.config().portError;
  445. nj["netconfRevision"] = ns.config().netconfRevision;
  446. nj["portDeviceName"] = ns.tap()->deviceName();
  447. OneService::NetworkSettings localSettings = ns.settings();
  448. nj["allowManaged"] = localSettings.allowManaged;
  449. nj["allowGlobal"] = localSettings.allowGlobal;
  450. nj["allowDefault"] = localSettings.allowDefault;
  451. nj["allowDNS"] = localSettings.allowDNS;
  452. nlohmann::json aa = nlohmann::json::array();
  453. for(unsigned int i=0;i<ns.config().assignedAddressCount;++i) {
  454. aa.push_back(reinterpret_cast<const InetAddress *>(&(ns.config().assignedAddresses[i]))->toString(tmp));
  455. }
  456. nj["assignedAddresses"] = aa;
  457. nlohmann::json ra = nlohmann::json::array();
  458. for(unsigned int i=0;i<ns.config().routeCount;++i) {
  459. nlohmann::json rj;
  460. rj["target"] = reinterpret_cast<const InetAddress *>(&(ns.config().routes[i].target))->toString(tmp);
  461. if (ns.config().routes[i].via.ss_family == ns.config().routes[i].target.ss_family)
  462. rj["via"] = reinterpret_cast<const InetAddress *>(&(ns.config().routes[i].via))->toIpString(tmp);
  463. else rj["via"] = nlohmann::json();
  464. rj["flags"] = (int)ns.config().routes[i].flags;
  465. rj["metric"] = (int)ns.config().routes[i].metric;
  466. ra.push_back(rj);
  467. }
  468. nj["routes"] = ra;
  469. nlohmann::json mca = nlohmann::json::array();
  470. for(unsigned int i=0;i<ns.config().multicastSubscriptionCount;++i) {
  471. nlohmann::json m;
  472. m["mac"] = MAC(ns.config().multicastSubscriptions[i].mac).toString(tmp);
  473. m["adi"] = ns.config().multicastSubscriptions[i].adi;
  474. mca.push_back(m);
  475. }
  476. nj["multicastSubscriptions"] = mca;
  477. nlohmann::json m;
  478. m["domain"] = ns.config().dns.domain;
  479. m["servers"] = nlohmann::json::array();
  480. for(int j=0;j<ZT_MAX_DNS_SERVERS;++j) {
  481. InetAddress a(ns.config().dns.server_addr[j]);
  482. if (a.isV4() || a.isV6()) {
  483. char buf[256];
  484. m["servers"].push_back(a.toIpString(buf));
  485. }
  486. }
  487. nj["dns"] = m;
  488. if (ns.config().ssoEnabled) {
  489. const char* authURL = ns.config().authenticationURL;
  490. //fprintf(stderr, "Auth URL: %s\n", authURL);
  491. nj["authenticationURL"] = authURL;
  492. nj["authenticationExpiryTime"] = (ns.getExpiryTime()*1000);
  493. nj["ssoEnabled"] = ns.config().ssoEnabled;
  494. }
  495. }
  496. static void _peerToJson(nlohmann::json &pj,const ZT_Peer *peer, SharedPtr<Bond> &bond, bool isTunneled)
  497. {
  498. char tmp[256];
  499. const char *prole = "";
  500. switch(peer->role) {
  501. case ZT_PEER_ROLE_LEAF: prole = "LEAF"; break;
  502. case ZT_PEER_ROLE_MOON: prole = "MOON"; break;
  503. case ZT_PEER_ROLE_PLANET: prole = "PLANET"; break;
  504. }
  505. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.10llx",peer->address);
  506. pj["address"] = tmp;
  507. pj["versionMajor"] = peer->versionMajor;
  508. pj["versionMinor"] = peer->versionMinor;
  509. pj["versionRev"] = peer->versionRev;
  510. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%d.%d.%d",peer->versionMajor,peer->versionMinor,peer->versionRev);
  511. pj["version"] = tmp;
  512. pj["latency"] = peer->latency;
  513. pj["role"] = prole;
  514. pj["isBonded"] = peer->isBonded;
  515. pj["tunneled"] = isTunneled;
  516. if (bond && peer->isBonded) {
  517. pj["bondingPolicyCode"] = peer->bondingPolicy;
  518. pj["bondingPolicyStr"] = Bond::getPolicyStrByCode(peer->bondingPolicy);
  519. pj["numAliveLinks"] = peer->numAliveLinks;
  520. pj["numTotalLinks"] = peer->numTotalLinks;
  521. pj["failoverInterval"] = bond->getFailoverInterval();
  522. pj["downDelay"] = bond->getDownDelay();
  523. pj["upDelay"] = bond->getUpDelay();
  524. pj["packetsPerLink"] = bond->getPacketsPerLink();
  525. }
  526. nlohmann::json pa = nlohmann::json::array();
  527. for(unsigned int i=0;i<peer->pathCount;++i) {
  528. int64_t lastSend = peer->paths[i].lastSend;
  529. int64_t lastReceive = peer->paths[i].lastReceive;
  530. nlohmann::json j;
  531. j["address"] = reinterpret_cast<const InetAddress *>(&(peer->paths[i].address))->toString(tmp);
  532. j["lastSend"] = (lastSend < 0) ? 0 : lastSend;
  533. j["lastReceive"] = (lastReceive < 0) ? 0 : lastReceive;
  534. j["trustedPathId"] = peer->paths[i].trustedPathId;
  535. j["active"] = (bool)(peer->paths[i].expired == 0);
  536. j["expired"] = (bool)(peer->paths[i].expired != 0);
  537. j["preferred"] = (bool)(peer->paths[i].preferred != 0);
  538. j["localSocket"] = peer->paths[i].localSocket;
  539. if (bond && peer->isBonded) {
  540. uint64_t now = OSUtils::now();
  541. j["ifname"] = std::string(peer->paths[i].ifname);
  542. j["latencyMean"] = peer->paths[i].latencyMean;
  543. j["latencyVariance"] = peer->paths[i].latencyVariance;
  544. j["packetLossRatio"] = peer->paths[i].packetLossRatio;
  545. j["packetErrorRatio"] = peer->paths[i].packetErrorRatio;
  546. j["assignedFlowCount"] = peer->paths[i].assignedFlowCount;
  547. j["lastInAge"] = (now - lastReceive);
  548. j["lastOutAge"] = (now - lastSend);
  549. j["bonded"] = peer->paths[i].bonded;
  550. j["eligible"] = peer->paths[i].eligible;
  551. j["givenLinkSpeed"] = peer->paths[i].linkSpeed;
  552. j["relativeQuality"] = peer->paths[i].relativeQuality;
  553. }
  554. pa.push_back(j);
  555. }
  556. pj["paths"] = pa;
  557. }
  558. static void _moonToJson(nlohmann::json &mj,const World &world)
  559. {
  560. char tmp[4096];
  561. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",world.id());
  562. mj["id"] = tmp;
  563. mj["timestamp"] = world.timestamp();
  564. mj["signature"] = Utils::hex(world.signature().data,ZT_C25519_SIGNATURE_LEN,tmp);
  565. mj["updatesMustBeSignedBy"] = Utils::hex(world.updatesMustBeSignedBy().data,ZT_C25519_PUBLIC_KEY_LEN,tmp);
  566. nlohmann::json ra = nlohmann::json::array();
  567. for(std::vector<World::Root>::const_iterator r(world.roots().begin());r!=world.roots().end();++r) {
  568. nlohmann::json rj;
  569. rj["identity"] = r->identity.toString(false,tmp);
  570. nlohmann::json eps = nlohmann::json::array();
  571. for(std::vector<InetAddress>::const_iterator a(r->stableEndpoints.begin());a!=r->stableEndpoints.end();++a)
  572. eps.push_back(a->toString(tmp));
  573. rj["stableEndpoints"] = eps;
  574. ra.push_back(rj);
  575. }
  576. mj["roots"] = ra;
  577. mj["waiting"] = false;
  578. }
  579. class OneServiceImpl;
  580. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
  581. static void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData);
  582. static void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len);
  583. static int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen);
  584. 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);
  585. 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);
  586. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr);
  587. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result);
  588. 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);
  589. static int ShttpOnMessageBegin(http_parser *parser);
  590. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  591. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  592. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  593. #else
  594. static int ShttpOnStatus(http_parser *parser);
  595. #endif
  596. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  597. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  598. static int ShttpOnHeadersComplete(http_parser *parser);
  599. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  600. static int ShttpOnMessageComplete(http_parser *parser);
  601. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 1)
  602. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  603. ShttpOnMessageBegin,
  604. ShttpOnUrl,
  605. ShttpOnStatus,
  606. ShttpOnHeaderField,
  607. ShttpOnValue,
  608. ShttpOnHeadersComplete,
  609. ShttpOnBody,
  610. ShttpOnMessageComplete
  611. };
  612. #else
  613. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  614. ShttpOnMessageBegin,
  615. ShttpOnUrl,
  616. ShttpOnHeaderField,
  617. ShttpOnValue,
  618. ShttpOnHeadersComplete,
  619. ShttpOnBody,
  620. ShttpOnMessageComplete
  621. };
  622. #endif
  623. /**
  624. * A TCP connection and related state and buffers
  625. */
  626. struct TcpConnection
  627. {
  628. enum {
  629. TCP_UNCATEGORIZED_INCOMING, // uncategorized incoming connection
  630. TCP_HTTP_INCOMING,
  631. TCP_HTTP_OUTGOING,
  632. TCP_TUNNEL_OUTGOING // TUNNELED mode proxy outbound connection
  633. } type;
  634. OneServiceImpl *parent;
  635. PhySocket *sock;
  636. InetAddress remoteAddr;
  637. uint64_t lastReceive;
  638. // Used for inbound HTTP connections
  639. http_parser parser;
  640. unsigned long messageSize;
  641. std::string currentHeaderField;
  642. std::string currentHeaderValue;
  643. std::string url;
  644. std::string status;
  645. std::map< std::string,std::string > headers;
  646. std::string readq;
  647. std::string writeq;
  648. Mutex writeq_m;
  649. };
  650. struct OneServiceIncomingPacket
  651. {
  652. uint64_t now;
  653. int64_t sock;
  654. struct sockaddr_storage from;
  655. unsigned int size;
  656. uint8_t data[ZT_MAX_MTU];
  657. };
  658. class OneServiceImpl : public OneService
  659. {
  660. public:
  661. // begin member variables --------------------------------------------------
  662. const std::string _homePath;
  663. std::string _authToken;
  664. std::string _metricsToken;
  665. std::string _controllerDbPath;
  666. const std::string _networksPath;
  667. const std::string _moonsPath;
  668. EmbeddedNetworkController *_controller;
  669. Phy<OneServiceImpl *> _phy;
  670. Node *_node;
  671. SoftwareUpdater *_updater;
  672. bool _updateAutoApply;
  673. httplib::Server _controlPlane;
  674. std::thread _serverThread;
  675. bool _serverThreadRunning;
  676. bool _allowTcpFallbackRelay;
  677. bool _forceTcpRelay;
  678. bool _allowSecondaryPort;
  679. unsigned int _primaryPort;
  680. unsigned int _secondaryPort;
  681. unsigned int _tertiaryPort;
  682. volatile unsigned int _udpPortPickerCounter;
  683. // Local configuration and memo-ized information from it
  684. json _localConfig;
  685. Hashtable< uint64_t,std::vector<InetAddress> > _v4Hints;
  686. Hashtable< uint64_t,std::vector<InetAddress> > _v6Hints;
  687. Hashtable< uint64_t,std::vector<InetAddress> > _v4Blacklists;
  688. Hashtable< uint64_t,std::vector<InetAddress> > _v6Blacklists;
  689. std::vector< InetAddress > _globalV4Blacklist;
  690. std::vector< InetAddress > _globalV6Blacklist;
  691. std::vector< InetAddress > _allowManagementFrom;
  692. std::vector< std::string > _interfacePrefixBlacklist;
  693. Mutex _localConfig_m;
  694. std::vector<InetAddress> explicitBind;
  695. /*
  696. * To attempt to handle NAT/gateway craziness we use three local UDP ports:
  697. *
  698. * [0] is the normal/default port, usually 9993
  699. * [1] is a port derived from our ZeroTier address
  700. * [2] is a port computed from the normal/default for use with uPnP/NAT-PMP mappings
  701. *
  702. * [2] exists because on some gateways trying to do regular NAT-t interferes
  703. * destructively with uPnP port mapping behavior in very weird buggy ways.
  704. * It's only used if uPnP/NAT-PMP is enabled in this build.
  705. */
  706. unsigned int _ports[3];
  707. Binder _binder;
  708. // Time we last received a packet from a global address
  709. uint64_t _lastDirectReceiveFromGlobal;
  710. #ifdef ZT_TCP_FALLBACK_RELAY
  711. InetAddress _fallbackRelayAddress;
  712. uint64_t _lastSendToGlobalV4;
  713. #endif
  714. // Last potential sleep/wake event
  715. uint64_t _lastRestart;
  716. // Deadline for the next background task service function
  717. volatile int64_t _nextBackgroundTaskDeadline;
  718. std::map<uint64_t,NetworkState> _nets;
  719. Mutex _nets_m;
  720. // Active TCP/IP connections
  721. std::vector< TcpConnection * > _tcpConnections;
  722. Mutex _tcpConnections_m;
  723. TcpConnection *_tcpFallbackTunnel;
  724. // Termination status information
  725. ReasonForTermination _termReason;
  726. std::string _fatalErrorMessage;
  727. Mutex _termReason_m;
  728. // uPnP/NAT-PMP port mapper if enabled
  729. bool _portMappingEnabled; // local.conf settings
  730. #ifdef ZT_USE_MINIUPNPC
  731. PortMapper *_portMapper;
  732. #endif
  733. // HashiCorp Vault Settings
  734. #if ZT_VAULT_SUPPORT
  735. bool _vaultEnabled;
  736. std::string _vaultURL;
  737. std::string _vaultToken;
  738. std::string _vaultPath; // defaults to cubbyhole/zerotier/identity.secret for per-access key storage
  739. #endif
  740. // Set to false to force service to stop
  741. volatile bool _run;
  742. Mutex _run_m;
  743. RedisConfig *_rc;
  744. std::string _ssoRedirectURL;
  745. // end member variables ----------------------------------------------------
  746. OneServiceImpl(const char *hp,unsigned int port) :
  747. _homePath((hp) ? hp : ".")
  748. ,_controllerDbPath(_homePath + ZT_PATH_SEPARATOR_S "controller.d")
  749. ,_networksPath(_homePath + ZT_PATH_SEPARATOR_S "networks.d")
  750. ,_moonsPath(_homePath + ZT_PATH_SEPARATOR_S "moons.d")
  751. ,_controller((EmbeddedNetworkController *)0)
  752. ,_phy(this,false,true)
  753. ,_node((Node *)0)
  754. ,_updater((SoftwareUpdater *)0)
  755. ,_updateAutoApply(false)
  756. ,_controlPlane()
  757. ,_serverThread()
  758. ,_serverThreadRunning(false)
  759. ,_forceTcpRelay(false)
  760. ,_primaryPort(port)
  761. ,_udpPortPickerCounter(0)
  762. ,_lastDirectReceiveFromGlobal(0)
  763. #ifdef ZT_TCP_FALLBACK_RELAY
  764. , _fallbackRelayAddress(ZT_TCP_FALLBACK_RELAY)
  765. ,_lastSendToGlobalV4(0)
  766. #endif
  767. ,_lastRestart(0)
  768. ,_nextBackgroundTaskDeadline(0)
  769. ,_tcpFallbackTunnel((TcpConnection *)0)
  770. ,_termReason(ONE_STILL_RUNNING)
  771. ,_portMappingEnabled(true)
  772. #ifdef ZT_USE_MINIUPNPC
  773. ,_portMapper((PortMapper *)0)
  774. #endif
  775. #ifdef ZT_VAULT_SUPPORT
  776. ,_vaultEnabled(false)
  777. ,_vaultURL()
  778. ,_vaultToken()
  779. ,_vaultPath("cubbyhole/zerotier")
  780. #endif
  781. ,_run(true)
  782. ,_rc(NULL)
  783. ,_ssoRedirectURL()
  784. {
  785. _ports[0] = 0;
  786. _ports[1] = 0;
  787. _ports[2] = 0;
  788. prometheus::simpleapi::saver.set_registry(prometheus::simpleapi::registry_ptr);
  789. prometheus::simpleapi::saver.set_delay(std::chrono::seconds(5));
  790. prometheus::simpleapi::saver.set_out_file(_homePath + ZT_PATH_SEPARATOR + "metrics.prom");
  791. #if ZT_VAULT_SUPPORT
  792. curl_global_init(CURL_GLOBAL_DEFAULT);
  793. #endif
  794. }
  795. virtual ~OneServiceImpl()
  796. {
  797. #ifdef __WINDOWS__
  798. WinFWHelper::removeICMPRules();
  799. #endif
  800. _binder.closeAll(_phy);
  801. #if ZT_VAULT_SUPPORT
  802. curl_global_cleanup();
  803. #endif
  804. _controlPlane.stop();
  805. if (_serverThreadRunning) {
  806. _serverThread.join();
  807. }
  808. #ifdef ZT_USE_MINIUPNPC
  809. delete _portMapper;
  810. #endif
  811. delete _controller;
  812. delete _rc;
  813. }
  814. virtual ReasonForTermination run()
  815. {
  816. try {
  817. {
  818. const std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S "authtoken.secret");
  819. if (!OSUtils::readFile(authTokenPath.c_str(),_authToken)) {
  820. unsigned char foo[24];
  821. Utils::getSecureRandom(foo,sizeof(foo));
  822. _authToken = "";
  823. for(unsigned int i=0;i<sizeof(foo);++i)
  824. _authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  825. if (!OSUtils::writeFile(authTokenPath.c_str(),_authToken)) {
  826. Mutex::Lock _l(_termReason_m);
  827. _termReason = ONE_UNRECOVERABLE_ERROR;
  828. _fatalErrorMessage = "authtoken.secret could not be written";
  829. return _termReason;
  830. } else {
  831. OSUtils::lockDownFile(authTokenPath.c_str(),false);
  832. }
  833. }
  834. _authToken = _trimString(_authToken);
  835. }
  836. {
  837. const std::string metricsTokenPath(_homePath + ZT_PATH_SEPARATOR_S "metricstoken.secret");
  838. if (!OSUtils::readFile(metricsTokenPath.c_str(),_metricsToken)) {
  839. unsigned char foo[24];
  840. Utils::getSecureRandom(foo,sizeof(foo));
  841. _metricsToken = "";
  842. for(unsigned int i=0;i<sizeof(foo);++i)
  843. _metricsToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  844. if (!OSUtils::writeFile(metricsTokenPath.c_str(),_metricsToken)) {
  845. Mutex::Lock _l(_termReason_m);
  846. _termReason = ONE_UNRECOVERABLE_ERROR;
  847. _fatalErrorMessage = "metricstoken.secret could not be written";
  848. return _termReason;
  849. } else {
  850. OSUtils::lockDownFile(metricsTokenPath.c_str(),false);
  851. }
  852. }
  853. _metricsToken = _trimString(_metricsToken);
  854. }
  855. {
  856. struct ZT_Node_Callbacks cb;
  857. cb.version = 0;
  858. cb.stateGetFunction = SnodeStateGetFunction;
  859. cb.statePutFunction = SnodeStatePutFunction;
  860. cb.wirePacketSendFunction = SnodeWirePacketSendFunction;
  861. cb.virtualNetworkFrameFunction = SnodeVirtualNetworkFrameFunction;
  862. cb.virtualNetworkConfigFunction = SnodeVirtualNetworkConfigFunction;
  863. cb.eventCallback = SnodeEventCallback;
  864. cb.pathCheckFunction = SnodePathCheckFunction;
  865. cb.pathLookupFunction = SnodePathLookupFunction;
  866. _node = new Node(this,(void *)0,&cb,OSUtils::now());
  867. }
  868. // local.conf
  869. readLocalSettings();
  870. applyLocalConfig();
  871. // Save original port number to show it if bind error
  872. const int _configuredPort = _primaryPort;
  873. // Make sure we can use the primary port, and hunt for one if configured to do so
  874. const int portTrials = (_primaryPort == 0) ? 256 : 1; // if port is 0, pick random
  875. for(int k=0;k<portTrials;++k) {
  876. if (_primaryPort == 0) {
  877. unsigned int randp = 0;
  878. Utils::getSecureRandom(&randp,sizeof(randp));
  879. _primaryPort = 20000 + (randp % 45500);
  880. }
  881. if (_trialBind(_primaryPort)) {
  882. _ports[0] = _primaryPort;
  883. } else {
  884. _primaryPort = 0;
  885. }
  886. }
  887. if (_ports[0] == 0) {
  888. Mutex::Lock _l(_termReason_m);
  889. _termReason = ONE_UNRECOVERABLE_ERROR;
  890. _fatalErrorMessage = std::string("cannot bind to local control interface port ")+std::to_string(_configuredPort);
  891. return _termReason;
  892. }
  893. // Save primary port to a file so CLIs and GUIs can learn it easily
  894. char portstr[64];
  895. OSUtils::ztsnprintf(portstr,sizeof(portstr),"%u",_ports[0]);
  896. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S "zerotier-one.port").c_str(),std::string(portstr));
  897. // Attempt to bind to a secondary port.
  898. // This exists because there are buggy NATs out there that fail if more
  899. // than one device behind the same NAT tries to use the same internal
  900. // private address port number. Buggy NATs are a running theme.
  901. //
  902. // This used to pick the secondary port based on the node ID until we
  903. // discovered another problem: buggy routers and malicious traffic
  904. // "detection". A lot of routers have such things built in these days
  905. // and mis-detect ZeroTier traffic as malicious and block it resulting
  906. // in a node that appears to be in a coma. Secondary ports are now
  907. // randomized on startup.
  908. if (_allowSecondaryPort) {
  909. if (_secondaryPort) {
  910. _ports[1] = _secondaryPort;
  911. } else {
  912. _ports[1] = _secondaryPort = _getRandomPort();
  913. }
  914. }
  915. #ifdef ZT_USE_MINIUPNPC
  916. if (_portMappingEnabled) {
  917. // If we're running uPnP/NAT-PMP, bind a *third* port for that. We can't
  918. // use the other two ports for that because some NATs do really funky
  919. // stuff with ports that are explicitly mapped that breaks things.
  920. if (_tertiaryPort) {
  921. _ports[2] = _tertiaryPort;
  922. } else {
  923. _ports[2] = _tertiaryPort = _getRandomPort();
  924. }
  925. if (_ports[2]) {
  926. char uniqueName[64];
  927. OSUtils::ztsnprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]);
  928. _portMapper = new PortMapper(_ports[2],uniqueName);
  929. }
  930. }
  931. #endif
  932. // Delete legacy iddb.d if present (cleanup)
  933. OSUtils::rmDashRf((_homePath + ZT_PATH_SEPARATOR_S "iddb.d").c_str());
  934. // Network controller is now enabled by default for desktop and server
  935. _controller = new EmbeddedNetworkController(_node,_homePath.c_str(),_controllerDbPath.c_str(),_ports[0], _rc);
  936. if (!_ssoRedirectURL.empty()) {
  937. _controller->setSSORedirectURL(_ssoRedirectURL);
  938. }
  939. _node->setNetconfMaster((void *)_controller);
  940. startHTTPControlPlane();
  941. // Join existing networks in networks.d
  942. {
  943. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S "networks.d").c_str()));
  944. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  945. std::size_t dot = f->find_last_of('.');
  946. if ((dot == 16)&&(f->substr(16) == ".conf"))
  947. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()),(void *)0,(void *)0);
  948. }
  949. }
  950. // Orbit existing moons in moons.d
  951. {
  952. std::vector<std::string> moonsDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S "moons.d").c_str()));
  953. for(std::vector<std::string>::iterator f(moonsDotD.begin());f!=moonsDotD.end();++f) {
  954. std::size_t dot = f->find_last_of('.');
  955. if ((dot == 16)&&(f->substr(16) == ".moon"))
  956. _node->orbit((void *)0,Utils::hexStrToU64(f->substr(0,dot).c_str()),0);
  957. }
  958. }
  959. // Main I/O loop
  960. _nextBackgroundTaskDeadline = 0;
  961. int64_t clockShouldBe = OSUtils::now();
  962. _lastRestart = clockShouldBe;
  963. int64_t lastTapMulticastGroupCheck = 0;
  964. int64_t lastBindRefresh = 0;
  965. int64_t lastUpdateCheck = clockShouldBe;
  966. int64_t lastCleanedPeersDb = 0;
  967. 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
  968. int64_t lastLocalConfFileCheck = OSUtils::now();
  969. int64_t lastOnline = lastLocalConfFileCheck;
  970. for(;;) {
  971. _run_m.lock();
  972. if (!_run) {
  973. _run_m.unlock();
  974. _termReason_m.lock();
  975. _termReason = ONE_NORMAL_TERMINATION;
  976. _termReason_m.unlock();
  977. break;
  978. } else {
  979. _run_m.unlock();
  980. }
  981. const int64_t now = OSUtils::now();
  982. // Attempt to detect sleep/wake events by detecting delay overruns
  983. bool restarted = false;
  984. if ((now > clockShouldBe)&&((now - clockShouldBe) > 10000)) {
  985. _lastRestart = now;
  986. restarted = true;
  987. }
  988. // Check for updates (if enabled)
  989. if ((_updater)&&((now - lastUpdateCheck) > 10000)) {
  990. lastUpdateCheck = now;
  991. if (_updater->check(now) && _updateAutoApply)
  992. _updater->apply();
  993. }
  994. // Reload local.conf if anything changed recently
  995. if ((now - lastLocalConfFileCheck) >= ZT_LOCAL_CONF_FILE_CHECK_INTERVAL) {
  996. lastLocalConfFileCheck = now;
  997. struct stat result;
  998. if(stat((_homePath + ZT_PATH_SEPARATOR_S "local.conf").c_str(), &result)==0) {
  999. int64_t mod_time = result.st_mtime * 1000;
  1000. if ((now - mod_time) <= ZT_LOCAL_CONF_FILE_CHECK_INTERVAL) {
  1001. readLocalSettings();
  1002. applyLocalConfig();
  1003. }
  1004. }
  1005. }
  1006. // If secondary port is not configured to a constant value and we've been offline for a while,
  1007. // bind a new secondary port. This is a workaround for a "coma" issue caused by buggy NATs that stop
  1008. // working on one port after a while.
  1009. if (_node->online()) {
  1010. lastOnline = now;
  1011. } else if ((_secondaryPort == 0)&&((now - lastOnline) > ZT_PATH_HEARTBEAT_PERIOD)) {
  1012. _secondaryPort = _getRandomPort();
  1013. lastBindRefresh = 0;
  1014. }
  1015. // Refresh bindings in case device's interfaces have changed, and also sync routes to update any shadow routes (e.g. shadow default)
  1016. if (((now - lastBindRefresh) >= (_node->bondController()->inUse() ? ZT_BINDER_REFRESH_PERIOD / 4 : ZT_BINDER_REFRESH_PERIOD))||(restarted)) {
  1017. lastBindRefresh = now;
  1018. unsigned int p[3];
  1019. unsigned int pc = 0;
  1020. for(int i=0;i<3;++i) {
  1021. if (_ports[i])
  1022. p[pc++] = _ports[i];
  1023. }
  1024. if (!_forceTcpRelay) {
  1025. // Only bother binding UDP ports if we aren't forcing TCP-relay mode
  1026. _binder.refresh(_phy,p,pc,explicitBind,*this);
  1027. }
  1028. {
  1029. Mutex::Lock _l(_nets_m);
  1030. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n) {
  1031. if (n->second.tap())
  1032. syncManagedStuff(n->second,false,true,false);
  1033. }
  1034. }
  1035. }
  1036. // Run background task processor in core if it's time to do so
  1037. int64_t dl = _nextBackgroundTaskDeadline;
  1038. if (dl <= now) {
  1039. _node->processBackgroundTasks((void *)0,now,&_nextBackgroundTaskDeadline);
  1040. dl = _nextBackgroundTaskDeadline;
  1041. }
  1042. // Close TCP fallback tunnel if we have direct UDP
  1043. if (!_forceTcpRelay && (_tcpFallbackTunnel) && ((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2))) {
  1044. _phy.close(_tcpFallbackTunnel->sock);
  1045. }
  1046. // Sync multicast group memberships
  1047. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  1048. lastTapMulticastGroupCheck = now;
  1049. std::vector< std::pair< uint64_t,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> > > > mgChanges;
  1050. {
  1051. Mutex::Lock _l(_nets_m);
  1052. mgChanges.reserve(_nets.size() + 1);
  1053. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1054. if (n->second.tap()) {
  1055. 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> >()));
  1056. n->second.tap()->scanMulticastGroups(mgChanges.back().second.first,mgChanges.back().second.second);
  1057. }
  1058. }
  1059. }
  1060. for(std::vector< std::pair< uint64_t,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> > > >::iterator c(mgChanges.begin());c!=mgChanges.end();++c) {
  1061. for(std::vector<MulticastGroup>::iterator m(c->second.first.begin());m!=c->second.first.end();++m)
  1062. _node->multicastSubscribe((void *)0,c->first,m->mac().toInt(),m->adi());
  1063. for(std::vector<MulticastGroup>::iterator m(c->second.second.begin());m!=c->second.second.end();++m)
  1064. _node->multicastUnsubscribe(c->first,m->mac().toInt(),m->adi());
  1065. }
  1066. }
  1067. // Sync information about physical network interfaces
  1068. if ((now - lastLocalInterfaceAddressCheck) >= (_node->bondController()->inUse() ? ZT_LOCAL_INTERFACE_CHECK_INTERVAL / 8 : ZT_LOCAL_INTERFACE_CHECK_INTERVAL)) {
  1069. lastLocalInterfaceAddressCheck = now;
  1070. _node->clearLocalInterfaceAddresses();
  1071. #ifdef ZT_USE_MINIUPNPC
  1072. if (_portMapper) {
  1073. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  1074. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  1075. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  1076. }
  1077. #endif
  1078. std::vector<InetAddress> boundAddrs(_binder.allBoundLocalInterfaceAddresses());
  1079. for(std::vector<InetAddress>::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i) {
  1080. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*i)));
  1081. }
  1082. }
  1083. // Clean peers.d periodically
  1084. if ((now - lastCleanedPeersDb) >= 3600000) {
  1085. lastCleanedPeersDb = now;
  1086. OSUtils::cleanDirectory((_homePath + ZT_PATH_SEPARATOR_S "peers.d").c_str(),now - 2592000000LL); // delete older than 30 days
  1087. }
  1088. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 500;
  1089. clockShouldBe = now + (int64_t)delay;
  1090. _phy.poll(delay);
  1091. }
  1092. } catch (std::exception &e) {
  1093. Mutex::Lock _l(_termReason_m);
  1094. _termReason = ONE_UNRECOVERABLE_ERROR;
  1095. _fatalErrorMessage = std::string("unexpected exception in main thread: ")+e.what();
  1096. } catch (int e) {
  1097. Mutex::Lock _l(_termReason_m);
  1098. _termReason = ONE_UNRECOVERABLE_ERROR;
  1099. switch (e) {
  1100. case ZT_EXCEPTION_OUT_OF_BOUNDS: {
  1101. _fatalErrorMessage = "out of bounds exception";
  1102. break;
  1103. }
  1104. case ZT_EXCEPTION_OUT_OF_MEMORY: {
  1105. _fatalErrorMessage = "out of memory";
  1106. break;
  1107. }
  1108. case ZT_EXCEPTION_PRIVATE_KEY_REQUIRED: {
  1109. _fatalErrorMessage = "private key required";
  1110. break;
  1111. }
  1112. case ZT_EXCEPTION_INVALID_ARGUMENT: {
  1113. _fatalErrorMessage = "invalid argument";
  1114. break;
  1115. }
  1116. case ZT_EXCEPTION_INVALID_IDENTITY: {
  1117. _fatalErrorMessage = "invalid identity loaded from disk. Please remove identity.public and identity.secret from " + _homePath + " and try again";
  1118. break;
  1119. }
  1120. case ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE: {
  1121. _fatalErrorMessage = "invalid serialized data: invalid type";
  1122. break;
  1123. }
  1124. case ZT_EXCEPTION_INVALID_SERIALIZED_DATA_OVERFLOW: {
  1125. _fatalErrorMessage = "invalid serialized data: overflow";
  1126. break;
  1127. }
  1128. case ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN: {
  1129. _fatalErrorMessage = "invalid serialized data: invalid cryptographic token";
  1130. break;
  1131. }
  1132. case ZT_EXCEPTION_INVALID_SERIALIZED_DATA_BAD_ENCODING: {
  1133. _fatalErrorMessage = "invalid serialized data: bad encoding";
  1134. break;
  1135. }
  1136. default: {
  1137. _fatalErrorMessage = "unexpected exception code: " + std::to_string(e);
  1138. break;
  1139. }
  1140. }
  1141. } catch ( ... ) {
  1142. Mutex::Lock _l(_termReason_m);
  1143. _termReason = ONE_UNRECOVERABLE_ERROR;
  1144. _fatalErrorMessage = "unexpected exception in main thread: unknown exception";
  1145. }
  1146. try {
  1147. Mutex::Lock _l(_tcpConnections_m);
  1148. while (!_tcpConnections.empty())
  1149. _phy.close((*_tcpConnections.begin())->sock);
  1150. } catch ( ... ) {}
  1151. {
  1152. Mutex::Lock _l(_nets_m);
  1153. _nets.clear();
  1154. }
  1155. delete _updater;
  1156. _updater = (SoftwareUpdater *)0;
  1157. delete _node;
  1158. _node = (Node *)0;
  1159. return _termReason;
  1160. }
  1161. void readLocalSettings()
  1162. {
  1163. // Read local configuration
  1164. std::map<InetAddress,ZT_PhysicalPathConfiguration> ppc;
  1165. // LEGACY: support old "trustedpaths" flat file
  1166. FILE *trustpaths = fopen((_homePath + ZT_PATH_SEPARATOR_S "trustedpaths").c_str(),"r");
  1167. if (trustpaths) {
  1168. fprintf(stderr,"WARNING: 'trustedpaths' flat file format is deprecated in favor of path definitions in local.conf" ZT_EOL_S);
  1169. char buf[1024];
  1170. while (fgets(buf,sizeof(buf),trustpaths)) {
  1171. int fno = 0;
  1172. char *saveptr = (char *)0;
  1173. uint64_t trustedPathId = 0;
  1174. InetAddress trustedPathNetwork;
  1175. for(char *f=Utils::stok(buf,"=\r\n \t",&saveptr);(f);f=Utils::stok((char *)0,"=\r\n \t",&saveptr)) {
  1176. if (fno == 0) {
  1177. trustedPathId = Utils::hexStrToU64(f);
  1178. } else if (fno == 1) {
  1179. trustedPathNetwork = InetAddress(f);
  1180. } else break;
  1181. ++fno;
  1182. }
  1183. if ( (trustedPathId != 0) && ((trustedPathNetwork.ss_family == AF_INET)||(trustedPathNetwork.ss_family == AF_INET6)) && (trustedPathNetwork.netmaskBits() > 0) ) {
  1184. ppc[trustedPathNetwork].trustedPathId = trustedPathId;
  1185. ppc[trustedPathNetwork].mtu = 0; // use default
  1186. }
  1187. }
  1188. fclose(trustpaths);
  1189. }
  1190. // Read local config file
  1191. Mutex::Lock _l2(_localConfig_m);
  1192. std::string lcbuf;
  1193. if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S "local.conf").c_str(),lcbuf)) {
  1194. if (lcbuf.length() > 0) {
  1195. try {
  1196. _localConfig = OSUtils::jsonParse(lcbuf);
  1197. if (!_localConfig.is_object()) {
  1198. fprintf(stderr,"ERROR: unable to parse local.conf (root element is not a JSON object)" ZT_EOL_S);
  1199. exit(1);
  1200. }
  1201. } catch ( ... ) {
  1202. fprintf(stderr,"ERROR: unable to parse local.conf (invalid JSON)" ZT_EOL_S);
  1203. exit(1);
  1204. }
  1205. }
  1206. }
  1207. // Make a copy so lookups don't modify in place;
  1208. json lc(_localConfig);
  1209. // Get any trusted paths in local.conf (we'll parse the rest of physical[] elsewhere)
  1210. json &physical = lc["physical"];
  1211. if (physical.is_object()) {
  1212. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  1213. InetAddress net(OSUtils::jsonString(phy.key(),"").c_str());
  1214. if (net) {
  1215. if (phy.value().is_object()) {
  1216. uint64_t tpid;
  1217. if ((tpid = OSUtils::jsonInt(phy.value()["trustedPathId"],0ULL)) != 0ULL) {
  1218. if ((net.ss_family == AF_INET)||(net.ss_family == AF_INET6))
  1219. ppc[net].trustedPathId = tpid;
  1220. }
  1221. ppc[net].mtu = (int)OSUtils::jsonInt(phy.value()["mtu"],0ULL); // 0 means use default
  1222. }
  1223. }
  1224. }
  1225. }
  1226. json &settings = lc["settings"];
  1227. if (settings.is_object()) {
  1228. // Allow controller DB path to be put somewhere else
  1229. const std::string cdbp(OSUtils::jsonString(settings["controllerDbPath"],""));
  1230. if (cdbp.length() > 0)
  1231. _controllerDbPath = cdbp;
  1232. _ssoRedirectURL = OSUtils::jsonString(settings["ssoRedirectURL"], "");
  1233. #ifdef ZT_CONTROLLER_USE_LIBPQ
  1234. // TODO: Redis config
  1235. json &redis = settings["redis"];
  1236. if (redis.is_object() && _rc == NULL) {
  1237. _rc = new RedisConfig;
  1238. _rc->hostname = OSUtils::jsonString(redis["hostname"],"");
  1239. _rc->port = OSUtils::jsonInt(redis["port"],0);
  1240. _rc->password = OSUtils::jsonString(redis["password"],"");
  1241. _rc->clusterMode = OSUtils::jsonBool(redis["clusterMode"], false);
  1242. }
  1243. #endif
  1244. // Bind to wildcard instead of to specific interfaces (disables full tunnel capability)
  1245. json &bind = settings["bind"];
  1246. if (bind.is_array()) {
  1247. for(unsigned long i=0;i<bind.size();++i) {
  1248. const std::string ips(OSUtils::jsonString(bind[i],""));
  1249. if (ips.length() > 0) {
  1250. InetAddress ip(ips.c_str());
  1251. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6))
  1252. explicitBind.push_back(ip);
  1253. }
  1254. }
  1255. }
  1256. }
  1257. // Set trusted paths if there are any
  1258. if (!ppc.empty()) {
  1259. for(std::map<InetAddress,ZT_PhysicalPathConfiguration>::iterator i(ppc.begin());i!=ppc.end();++i)
  1260. _node->setPhysicalPathConfiguration(reinterpret_cast<const struct sockaddr_storage *>(&(i->first)),&(i->second));
  1261. }
  1262. }
  1263. virtual ReasonForTermination reasonForTermination() const
  1264. {
  1265. Mutex::Lock _l(_termReason_m);
  1266. return _termReason;
  1267. }
  1268. virtual std::string fatalErrorMessage() const
  1269. {
  1270. Mutex::Lock _l(_termReason_m);
  1271. return _fatalErrorMessage;
  1272. }
  1273. virtual std::string portDeviceName(uint64_t nwid) const
  1274. {
  1275. Mutex::Lock _l(_nets_m);
  1276. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  1277. if ((n != _nets.end())&&(n->second.tap()))
  1278. return n->second.tap()->deviceName();
  1279. else return std::string();
  1280. }
  1281. #ifdef ZT_SDK
  1282. virtual std::string givenHomePath()
  1283. {
  1284. return _homePath;
  1285. }
  1286. void getRoutes(uint64_t nwid, void *routeArray, unsigned int *numRoutes)
  1287. {
  1288. Mutex::Lock _l(_nets_m);
  1289. NetworkState &n = _nets[nwid];
  1290. *numRoutes = *numRoutes < n.config().routeCount ? *numRoutes : n.config().routeCount;
  1291. for(unsigned int i=0; i<*numRoutes; i++) {
  1292. ZT_VirtualNetworkRoute *vnr = (ZT_VirtualNetworkRoute*)routeArray;
  1293. memcpy(&vnr[i], &(n.config().routes[i]), sizeof(ZT_VirtualNetworkRoute));
  1294. }
  1295. }
  1296. virtual Node *getNode()
  1297. {
  1298. return _node;
  1299. }
  1300. #endif // ZT_SDK
  1301. virtual void terminate()
  1302. {
  1303. _run_m.lock();
  1304. _run = false;
  1305. _run_m.unlock();
  1306. _phy.whack();
  1307. }
  1308. virtual bool getNetworkSettings(const uint64_t nwid,NetworkSettings &settings) const
  1309. {
  1310. Mutex::Lock _l(_nets_m);
  1311. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  1312. if (n == _nets.end())
  1313. return false;
  1314. settings = n->second.settings();
  1315. return true;
  1316. }
  1317. virtual bool setNetworkSettings(const uint64_t nwid,const NetworkSettings &settings)
  1318. {
  1319. char nlcpath[4096];
  1320. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_networksPath.c_str(),nwid);
  1321. FILE *out = fopen(nlcpath,"w");
  1322. if (out) {
  1323. fprintf(out,"allowManaged=%d\n",(int)settings.allowManaged);
  1324. fprintf(out,"allowGlobal=%d\n",(int)settings.allowGlobal);
  1325. fprintf(out,"allowDefault=%d\n",(int)settings.allowDefault);
  1326. fprintf(out,"allowDNS=%d\n",(int)settings.allowDNS);
  1327. fclose(out);
  1328. }
  1329. return true;
  1330. }
  1331. // Internal HTTP Control Plane
  1332. void startHTTPControlPlane() {
  1333. std::vector<std::string> noAuthEndpoints { "/sso", "/health" };
  1334. auto setContent = [=] (const httplib::Request &req, httplib::Response &res, std::string content) {
  1335. if (req.has_param("jsonp")) {
  1336. if (content.length() > 0) {
  1337. res.set_content(req.get_param_value("jsonp") + "(" + content + ");", "application/javascript");
  1338. } else {
  1339. res.set_content(req.get_param_value("jsonp") + "(null);", "application/javascript");
  1340. }
  1341. } else {
  1342. if (content.length() > 0) {
  1343. res.set_content(content, "application/json");
  1344. } else {
  1345. res.set_content("{}", "application/json");
  1346. }
  1347. }
  1348. };
  1349. auto authCheck = [=] (const httplib::Request &req, httplib::Response &res) {
  1350. if (req.path == "/metrics") {
  1351. if (req.has_header("x-zt1-auth")) {
  1352. std::string token = req.get_header_value("x-zt1-auth");
  1353. if (token == _metricsToken || token == _authToken) {
  1354. return httplib::Server::HandlerResponse::Unhandled;
  1355. }
  1356. } else if (req.has_param("auth")) {
  1357. std::string token = req.get_param_value("auth");
  1358. if (token == _metricsToken || token == _authToken) {
  1359. return httplib::Server::HandlerResponse::Unhandled;
  1360. }
  1361. } else if (req.has_header("authorization")) {
  1362. std::string auth = req.get_header_value("authorization");
  1363. if (bearerTokenValid(auth, _metricsToken) || bearerTokenValid(auth, _authToken)) {
  1364. return httplib::Server::HandlerResponse::Unhandled;
  1365. }
  1366. }
  1367. setContent(req, res, "{}");
  1368. res.status = 401;
  1369. return httplib::Server::HandlerResponse::Handled;
  1370. } else {
  1371. std::string r = req.remote_addr;
  1372. InetAddress remoteAddr(r.c_str());
  1373. bool ipAllowed = false;
  1374. bool isAuth = false;
  1375. // If localhost, allow
  1376. if (remoteAddr.ipScope() == InetAddress::IP_SCOPE_LOOPBACK) {
  1377. ipAllowed = true;
  1378. }
  1379. if (!ipAllowed) {
  1380. for (auto i = _allowManagementFrom.begin(); i != _allowManagementFrom.end(); ++i) {
  1381. if (i->containsAddress(remoteAddr)) {
  1382. ipAllowed = true;
  1383. break;
  1384. }
  1385. }
  1386. }
  1387. if (ipAllowed) {
  1388. // auto-pass endpoints in `noAuthEndpoints`. No auth token required
  1389. if (std::find(noAuthEndpoints.begin(), noAuthEndpoints.end(), req.path) != noAuthEndpoints.end()) {
  1390. isAuth = true;
  1391. }
  1392. if (!isAuth) {
  1393. // check auth token
  1394. if (req.has_header("x-zt1-auth")) {
  1395. std::string token = req.get_header_value("x-zt1-auth");
  1396. if (token == _authToken) {
  1397. isAuth = true;
  1398. }
  1399. } else if (req.has_param("auth")) {
  1400. std::string token = req.get_param_value("auth");
  1401. if (token == _authToken) {
  1402. isAuth = true;
  1403. }
  1404. } else if (req.has_header("authorization")) {
  1405. std::string auth = req.get_header_value("authorization");
  1406. isAuth = bearerTokenValid(auth, _authToken);
  1407. }
  1408. }
  1409. }
  1410. if (ipAllowed && isAuth) {
  1411. return httplib::Server::HandlerResponse::Unhandled;
  1412. }
  1413. setContent(req, res, "{}");
  1414. res.status = 401;
  1415. return httplib::Server::HandlerResponse::Handled;
  1416. }
  1417. };
  1418. _controlPlane.Get("/bond/show/([0-9a-fA-F]{10})", [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1419. if (!_node->bondController()->inUse()) {
  1420. setContent(req, res, "");
  1421. res.status = 400;
  1422. return;
  1423. }
  1424. ZT_PeerList *pl = _node->peers();
  1425. if (pl) {
  1426. auto id = req.matches[1];
  1427. auto out = json::object();
  1428. uint64_t wantp = Utils::hexStrToU64(id.str().c_str());
  1429. for(unsigned long i=0;i<pl->peerCount;++i) {
  1430. if (pl->peers[i].address == wantp) {
  1431. SharedPtr<Bond> bond = _node->bondController()->getBondByPeerId(wantp);
  1432. if (bond) {
  1433. _peerToJson(out,&(pl->peers[i]),bond,(_tcpFallbackTunnel != (TcpConnection *)0));
  1434. setContent(req, res, out.dump());
  1435. } else {
  1436. setContent(req, res, "");
  1437. res.status = 400;
  1438. }
  1439. }
  1440. }
  1441. }
  1442. _node->freeQueryResult((void *)pl);
  1443. });
  1444. auto bondRotate = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1445. if (!_node->bondController()->inUse()) {
  1446. setContent(req, res, "");
  1447. res.status = 400;
  1448. return;
  1449. }
  1450. auto bondID = req.matches[1];
  1451. uint64_t id = Utils::hexStrToU64(bondID.str().c_str());
  1452. SharedPtr<Bond> bond = _node->bondController()->getBondByPeerId(id);
  1453. if (bond) {
  1454. if (bond->abForciblyRotateLink()) {
  1455. res.status = 200;
  1456. } else {
  1457. res.status = 400;
  1458. }
  1459. } else {
  1460. fprintf(stderr, "unable to find bond to peer %llx\n", (unsigned long long)id);
  1461. res.status = 400;
  1462. }
  1463. setContent(req, res, "{}");
  1464. };
  1465. _controlPlane.Post("/bond/rotate/([0-9a-fA-F]{10})", bondRotate);
  1466. _controlPlane.Put("/bond/rotate/([0-9a-fA-F]{10})", bondRotate);
  1467. auto setMtu = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1468. if (!_node->bondController()->inUse()) {
  1469. setContent(req, res, "");
  1470. res.status = 400;
  1471. return;
  1472. }
  1473. uint16_t mtu = atoi(req.matches[1].str().c_str());
  1474. res.status = _node->bondController()->setAllMtuByTuple(mtu, req.matches[2].str().c_str(), req.matches[3].str().c_str()) ? 200 : 400;
  1475. setContent(req, res, "{}");
  1476. };
  1477. _controlPlane.Post("/bond/setmtu/([0-9]{3,5})/([a-zA-Z0-9_]{1,16})/([0-9a-fA-F\\.\\:]{1,39})", setMtu);
  1478. _controlPlane.Put("/bond/setmtu/([0-9]{3,5})/([a-zA-Z0-9_]{1,16})/([0-9a-fA-F\\.\\:]{1,39})", setMtu);
  1479. _controlPlane.Get("/config", [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1480. std::string config;
  1481. {
  1482. Mutex::Lock lc(_localConfig_m);
  1483. config = _localConfig.dump();
  1484. }
  1485. if (config == "null") {
  1486. config = "{}";
  1487. }
  1488. setContent(req, res, config);
  1489. });
  1490. auto configPost = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1491. json j(OSUtils::jsonParse(req.body));
  1492. if (j.is_object()) {
  1493. Mutex::Lock lcl(_localConfig_m);
  1494. json lc(_localConfig);
  1495. for(json::const_iterator s(j.begin()); s != j.end(); ++s) {
  1496. lc["settings"][s.key()] = s.value();
  1497. }
  1498. std::string lcStr = OSUtils::jsonDump(lc, 4);
  1499. if (OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S "local.conf").c_str(), lcStr)) {
  1500. _localConfig = lc;
  1501. }
  1502. }
  1503. setContent(req, res, "{}");
  1504. };
  1505. _controlPlane.Post("/config/settings", configPost);
  1506. _controlPlane.Put("/config/settings", configPost);
  1507. _controlPlane.Get("/health", [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1508. json out = json::object();
  1509. char tmp[256];
  1510. ZT_NodeStatus status;
  1511. _node->status(&status);
  1512. out["online"] = (bool)(status.online != 0);
  1513. out["versionMajor"] = ZEROTIER_ONE_VERSION_MAJOR;
  1514. out["versionMinor"] = ZEROTIER_ONE_VERSION_MINOR;
  1515. out["versionRev"] = ZEROTIER_ONE_VERSION_REVISION;
  1516. out["versionBuild"] = ZEROTIER_ONE_VERSION_BUILD;
  1517. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%d.%d.%d",ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  1518. out["version"] = tmp;
  1519. out["clock"] = OSUtils::now();
  1520. setContent(req, res, out.dump());
  1521. });
  1522. _controlPlane.Get("/moon", [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1523. std::vector<World> moons(_node->moons());
  1524. auto out = json::array();
  1525. for (auto i = moons.begin(); i != moons.end(); ++i) {
  1526. json mj;
  1527. _moonToJson(mj, *i);
  1528. out.push_back(mj);
  1529. }
  1530. setContent(req, res, out.dump());
  1531. });
  1532. _controlPlane.Get("/moon/([0-9a-fA-F]{10})", [&, setContent](const httplib::Request &req, httplib::Response &res){
  1533. std::vector<World> moons(_node->moons());
  1534. auto input = req.matches[1];
  1535. auto out = json::object();
  1536. const uint64_t id = Utils::hexStrToU64(input.str().c_str());
  1537. for (auto i = moons.begin(); i != moons.end(); ++i) {
  1538. if (i->id() == id) {
  1539. _moonToJson(out, *i);
  1540. break;
  1541. }
  1542. }
  1543. setContent(req, res, out.dump());
  1544. });
  1545. auto moonPost = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1546. auto input = req.matches[1];
  1547. uint64_t seed = 0;
  1548. try {
  1549. json j(OSUtils::jsonParse(req.body));
  1550. if (j.is_object()) {
  1551. seed = Utils::hexStrToU64(OSUtils::jsonString(j["seed"],"0").c_str());
  1552. }
  1553. } catch ( ... ) {
  1554. // discard invalid JSON
  1555. }
  1556. std::vector<World> moons(_node->moons());
  1557. const uint64_t id = Utils::hexStrToU64(input.str().c_str());
  1558. bool found = false;
  1559. auto out = json::object();
  1560. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  1561. if (m->id() == id) {
  1562. _moonToJson(out,*m);
  1563. found = true;
  1564. break;
  1565. }
  1566. }
  1567. if (!found && seed != 0) {
  1568. char tmp[64];
  1569. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",id);
  1570. out["id"] = tmp;
  1571. out["roots"] = json::array();
  1572. out["timestamp"] = 0;
  1573. out["signature"] = json();
  1574. out["updatesMustBeSignedBy"] = json();
  1575. out["waiting"] = true;
  1576. _node->orbit((void *)0,id,seed);
  1577. }
  1578. setContent(req, res, out.dump());
  1579. };
  1580. _controlPlane.Post("/moon/([0-9a-fA-F]{10})", moonPost);
  1581. _controlPlane.Put("/moon/([0-9a-fA-F]{10})", moonPost);
  1582. _controlPlane.Delete("/moon/([0-9a-fA-F]{10})", [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1583. auto input = req.matches[1];
  1584. uint64_t id = Utils::hexStrToU64(input.str().c_str());
  1585. auto out = json::object();
  1586. _node->deorbit((void*)0,id);
  1587. out["result"] = true;
  1588. setContent(req, res, out.dump());
  1589. });
  1590. _controlPlane.Get("/network", [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1591. Mutex::Lock _l(_nets_m);
  1592. auto out = json::array();
  1593. for (auto it = _nets.begin(); it != _nets.end(); ++it) {
  1594. NetworkState &ns = it->second;
  1595. json nj;
  1596. _networkToJson(nj, ns);
  1597. out.push_back(nj);
  1598. }
  1599. setContent(req, res, out.dump());
  1600. });
  1601. _controlPlane.Get("/network/([0-9a-fA-F]{16})", [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1602. Mutex::Lock _l(_nets_m);
  1603. auto input = req.matches[1];
  1604. const uint64_t nwid = Utils::hexStrToU64(input.str().c_str());
  1605. if (_nets.find(nwid) != _nets.end()) {
  1606. auto out = json::object();
  1607. NetworkState &ns = _nets[nwid];
  1608. _networkToJson(out, ns);
  1609. setContent(req, res, out.dump());
  1610. return;
  1611. }
  1612. setContent(req, res, "");
  1613. res.status = 404;
  1614. });
  1615. auto networkPost = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1616. auto input = req.matches[1];
  1617. uint64_t wantnw = Utils::hexStrToU64(input.str().c_str());
  1618. _node->join(wantnw, (void*)0, (void*)0);
  1619. auto out = json::object();
  1620. Mutex::Lock l(_nets_m);
  1621. bool allowDefault = false;
  1622. if (!_nets.empty()) {
  1623. NetworkState &ns = _nets[wantnw];
  1624. try {
  1625. json j(OSUtils::jsonParse(req.body));
  1626. json &allowManaged = j["allowManaged"];
  1627. if (allowManaged.is_boolean()) {
  1628. ns.setAllowManaged((bool)allowManaged);
  1629. }
  1630. json& allowGlobal = j["allowGlobal"];
  1631. if (allowGlobal.is_boolean()) {
  1632. ns.setAllowGlobal((bool)allowGlobal);
  1633. }
  1634. json& _allowDefault = j["allowDefault"];
  1635. if (_allowDefault.is_boolean()) {
  1636. allowDefault = _allowDefault;
  1637. ns.setAllowDefault((bool)allowDefault);
  1638. }
  1639. json& allowDNS = j["allowDNS"];
  1640. if (allowDNS.is_boolean()) {
  1641. ns.setAllowDNS((bool)allowDNS);
  1642. }
  1643. } catch (...) {
  1644. // discard invalid JSON
  1645. }
  1646. setNetworkSettings(wantnw, ns.settings());
  1647. if (ns.tap()) {
  1648. syncManagedStuff(ns,true,true,true);
  1649. }
  1650. _networkToJson(out, ns);
  1651. }
  1652. #ifdef __FreeBSD__
  1653. if(!!allowDefault){
  1654. res.status = 400;
  1655. setContent(req, res, "Allow Default does not work properly on FreeBSD. See #580");
  1656. } else {
  1657. setContent(req, res, out.dump());
  1658. }
  1659. #else
  1660. setContent(req, res, out.dump());
  1661. #endif
  1662. };
  1663. _controlPlane.Post("/network/([0-9a-fA-F]{16})", networkPost);
  1664. _controlPlane.Put("/network/([0-9a-fA-F]){16}", networkPost);
  1665. _controlPlane.Delete("/network/([0-9a-fA-F]{16})", [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1666. auto input = req.matches[1];
  1667. auto out = json::object();
  1668. ZT_VirtualNetworkList *nws = _node->networks();
  1669. uint64_t wantnw = Utils::hexStrToU64(input.str().c_str());
  1670. for(unsigned long i=0; i < nws->networkCount; ++i) {
  1671. if (nws->networks[i].nwid == wantnw) {
  1672. _node->leave(wantnw, (void**)0, (void*)0);
  1673. out["result"] = true;
  1674. }
  1675. }
  1676. _node->freeQueryResult((void*)nws);
  1677. setContent(req, res, out.dump());
  1678. });
  1679. _controlPlane.Get("/peer", [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1680. ZT_PeerList *pl = _node->peers();
  1681. auto out = nlohmann::json::array();
  1682. for(unsigned long i=0;i<pl->peerCount;++i) {
  1683. nlohmann::json pj;
  1684. SharedPtr<Bond> bond = SharedPtr<Bond>();
  1685. if (pl->peers[i].isBonded) {
  1686. const uint64_t id = pl->peers[i].address;
  1687. bond = _node->bondController()->getBondByPeerId(id);
  1688. }
  1689. _peerToJson(pj,&(pl->peers[i]),bond,(_tcpFallbackTunnel != (TcpConnection *)0));
  1690. out.push_back(pj);
  1691. }
  1692. _node->freeQueryResult((void*)pl);
  1693. setContent(req, res, out.dump());
  1694. });
  1695. _controlPlane.Get("/peer/([0-9a-fA-F]{10})", [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1696. ZT_PeerList *pl = _node->peers();
  1697. auto input = req.matches[1];
  1698. uint64_t wantp = Utils::hexStrToU64(input.str().c_str());
  1699. auto out = json::object();
  1700. for(unsigned long i=0;i<pl->peerCount;++i) {
  1701. if (pl->peers[i].address == wantp) {
  1702. SharedPtr<Bond> bond = SharedPtr<Bond>();
  1703. if (pl->peers[i].isBonded) {
  1704. bond = _node->bondController()->getBondByPeerId(wantp);
  1705. }
  1706. _peerToJson(out,&(pl->peers[i]),bond,(_tcpFallbackTunnel != (TcpConnection *)0));
  1707. break;
  1708. }
  1709. }
  1710. _node->freeQueryResult((void*)pl);
  1711. setContent(req, res, out.dump());
  1712. });
  1713. _controlPlane.Get("/status", [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1714. ZT_NodeStatus status;
  1715. _node->status(&status);
  1716. auto out = json::object();
  1717. char tmp[256] = {};
  1718. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.10llx",status.address);
  1719. out["address"] = tmp;
  1720. out["publicIdentity"] = status.publicIdentity;
  1721. out["online"] = (bool)(status.online != 0);
  1722. out["tcpFallbackActive"] = (_tcpFallbackTunnel != (TcpConnection *)0);
  1723. out["versionMajor"] = ZEROTIER_ONE_VERSION_MAJOR;
  1724. out["versionMinor"] = ZEROTIER_ONE_VERSION_MINOR;
  1725. out["versionRev"] = ZEROTIER_ONE_VERSION_REVISION;
  1726. out["versionBuild"] = ZEROTIER_ONE_VERSION_BUILD;
  1727. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%d.%d.%d",ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  1728. out["version"] = tmp;
  1729. out["clock"] = OSUtils::now();
  1730. {
  1731. Mutex::Lock _l(_localConfig_m);
  1732. out["config"] = _localConfig;
  1733. }
  1734. json &settings = out["config"]["settings"];
  1735. settings["allowTcpFallbackRelay"] = OSUtils::jsonBool(settings["allowTcpFallbackRelay"],_allowTcpFallbackRelay);
  1736. settings["forceTcpRelay"] = OSUtils::jsonBool(settings["forceTcpRelay"],_forceTcpRelay);
  1737. settings["primaryPort"] = OSUtils::jsonInt(settings["primaryPort"],(uint64_t)_primaryPort) & 0xffff;
  1738. settings["secondaryPort"] = OSUtils::jsonInt(settings["secondaryPort"],(uint64_t)_secondaryPort) & 0xffff;
  1739. settings["tertiaryPort"] = OSUtils::jsonInt(settings["tertiaryPort"],(uint64_t)_tertiaryPort) & 0xffff;
  1740. // Enumerate all local address/port pairs that this node is listening on
  1741. std::vector<InetAddress> boundAddrs(_binder.allBoundLocalInterfaceAddresses());
  1742. auto boundAddrArray = json::array();
  1743. for (int i = 0; i < boundAddrs.size(); i++) {
  1744. char ipBuf[64] = { 0 };
  1745. boundAddrs[i].toString(ipBuf);
  1746. boundAddrArray.push_back(ipBuf);
  1747. }
  1748. settings["listeningOn"] = boundAddrArray;
  1749. // Enumerate all external address/port pairs that are reported for this node
  1750. std::vector<InetAddress> surfaceAddrs = _node->SurfaceAddresses();
  1751. auto surfaceAddrArray = json::array();
  1752. for (int i = 0; i < surfaceAddrs.size(); i++) {
  1753. char ipBuf[64] = { 0 };
  1754. surfaceAddrs[i].toString(ipBuf);
  1755. surfaceAddrArray.push_back(ipBuf);
  1756. }
  1757. settings["surfaceAddresses"] = surfaceAddrArray;
  1758. #ifdef ZT_USE_MINIUPNPC
  1759. settings["portMappingEnabled"] = OSUtils::jsonBool(settings["portMappingEnabled"],true);
  1760. #else
  1761. settings["portMappingEnabled"] = false; // not supported in build
  1762. #endif
  1763. #ifndef ZT_SDK
  1764. settings["softwareUpdate"] = OSUtils::jsonString(settings["softwareUpdate"],ZT_SOFTWARE_UPDATE_DEFAULT);
  1765. settings["softwareUpdateChannel"] = OSUtils::jsonString(settings["softwareUpdateChannel"],ZT_SOFTWARE_UPDATE_DEFAULT_CHANNEL);
  1766. #endif
  1767. const World planet(_node->planet());
  1768. out["planetWorldId"] = planet.id();
  1769. out["planetWorldTimestamp"] = planet.timestamp();
  1770. setContent(req, res, out.dump());
  1771. });
  1772. #if ZT_SSO_ENABLED
  1773. _controlPlane.Get("/sso", [this](const httplib::Request &req, httplib::Response &res) {
  1774. std::string htmlTemplatePath = _homePath + ZT_PATH_SEPARATOR + "sso-auth.template.html";
  1775. std::string htmlTemplate;
  1776. if (!OSUtils::readFile(htmlTemplatePath.c_str(), htmlTemplate)) {
  1777. htmlTemplate = ssoResponseTemplate;
  1778. }
  1779. std::string responseContentType = "text/html";
  1780. std::string responseBody = "";
  1781. json outData;
  1782. if (req.has_param("error")) {
  1783. std::string error = req.get_param_value("error");
  1784. std::string desc = req.get_param_value("error_description");
  1785. json data;
  1786. outData["isError"] = true;
  1787. outData["messageText"] = (std::string("ERROR ") + error + std::string(": ") + desc);
  1788. responseBody = inja::render(htmlTemplate, outData);
  1789. res.set_content(responseBody, responseContentType);
  1790. res.status = 500;
  1791. return;
  1792. }
  1793. // SSO redirect handling
  1794. std::string state = req.get_param_value("state");
  1795. char* nwid = zeroidc::zeroidc_network_id_from_state(state.c_str());
  1796. outData["networkId"] = std::string(nwid);
  1797. const uint64_t id = Utils::hexStrToU64(nwid);
  1798. zeroidc::free_cstr(nwid);
  1799. Mutex::Lock l(_nets_m);
  1800. if (_nets.find(id) != _nets.end()) {
  1801. NetworkState& ns = _nets[id];
  1802. std::string code = req.get_param_value("code");
  1803. char *ret = ns.doTokenExchange(code.c_str());
  1804. json ssoResult = json::parse(ret);
  1805. if (ssoResult.is_object()) {
  1806. if (ssoResult.contains("errorMessage")) {
  1807. outData["isError"] = true;
  1808. outData["messageText"] = ssoResult["errorMessage"];
  1809. responseBody = inja::render(htmlTemplate, outData);
  1810. res.set_content(responseBody, responseContentType);
  1811. res.status = 500;
  1812. } else {
  1813. outData["isError"] = false;
  1814. outData["messageText"] = "Authentication Successful. You may now access the network.";
  1815. responseBody = inja::render(htmlTemplate, outData);
  1816. res.set_content(responseBody, responseContentType);
  1817. }
  1818. } else {
  1819. // not an object? We got a problem
  1820. outData["isError"] = true;
  1821. outData["messageText"] = "ERROR: Unkown SSO response. Please contact your administrator.";
  1822. responseBody = inja::render(htmlTemplate, outData);
  1823. res.set_content(responseBody, responseContentType);
  1824. res.status = 500;
  1825. }
  1826. zeroidc::free_cstr(ret);
  1827. }
  1828. });
  1829. #endif
  1830. _controlPlane.Get("/metrics", [this](const httplib::Request &req, httplib::Response &res) {
  1831. std::string statspath = _homePath + ZT_PATH_SEPARATOR + "metrics.prom";
  1832. std::string metrics;
  1833. if (OSUtils::readFile(statspath.c_str(), metrics)) {
  1834. res.set_content(metrics, "text/plain");
  1835. } else {
  1836. res.set_content("{}", "application/json");
  1837. res.status = 500;
  1838. }
  1839. });
  1840. _controlPlane.set_exception_handler([&, setContent](const httplib::Request &req, httplib::Response &res, std::exception_ptr ep) {
  1841. char buf[1024];
  1842. auto fmt = "{\"error\": %d, \"description\": \"%s\"}";
  1843. try {
  1844. std::rethrow_exception(ep);
  1845. } catch (std::exception &e) {
  1846. snprintf(buf, sizeof(buf), fmt, 500, e.what());
  1847. } catch (...) {
  1848. snprintf(buf, sizeof(buf), fmt, 500, "Unknown Exception");
  1849. }
  1850. setContent(req, res, buf);
  1851. res.status = 500;
  1852. });
  1853. if (_controller) {
  1854. _controller->configureHTTPControlPlane(_controlPlane, setContent);
  1855. }
  1856. _controlPlane.set_pre_routing_handler(authCheck);
  1857. #if ZT_DEBUG==1
  1858. _controlPlane.set_logger([](const httplib::Request &req, const httplib::Response &res) {
  1859. fprintf(stderr, "%s", http_log(req, res).c_str());
  1860. });
  1861. #endif
  1862. if (_primaryPort==0) {
  1863. fprintf(stderr, "unable to determine local control port");
  1864. exit(-1);
  1865. }
  1866. if(!_controlPlane.bind_to_port("0.0.0.0", _primaryPort)) {
  1867. fprintf(stderr, "Error binding control plane to port %d\n", _primaryPort);
  1868. exit(-1);
  1869. }
  1870. _serverThread = std::thread([&] {
  1871. _serverThreadRunning = true;
  1872. fprintf(stderr, "Starting Control Plane...\n");
  1873. if(!_controlPlane.listen_after_bind()) {
  1874. fprintf(stderr, "Error on listen_after_bind()\n");
  1875. }
  1876. fprintf(stderr, "Control Plane Stopped\n");
  1877. _serverThreadRunning = false;
  1878. });
  1879. }
  1880. // Must be called after _localConfig is read or modified
  1881. void applyLocalConfig()
  1882. {
  1883. Mutex::Lock _l(_localConfig_m);
  1884. json lc(_localConfig);
  1885. _v4Hints.clear();
  1886. _v6Hints.clear();
  1887. _v4Blacklists.clear();
  1888. _v6Blacklists.clear();
  1889. json &virt = lc["virtual"];
  1890. if (virt.is_object()) {
  1891. for(json::iterator v(virt.begin());v!=virt.end();++v) {
  1892. const std::string nstr = v.key();
  1893. if ((nstr.length() == ZT_ADDRESS_LENGTH_HEX)&&(v.value().is_object())) {
  1894. const Address ztaddr(Utils::hexStrToU64(nstr.c_str()));
  1895. if (ztaddr) {
  1896. const uint64_t ztaddr2 = ztaddr.toInt();
  1897. std::vector<InetAddress> &v4h = _v4Hints[ztaddr2];
  1898. std::vector<InetAddress> &v6h = _v6Hints[ztaddr2];
  1899. std::vector<InetAddress> &v4b = _v4Blacklists[ztaddr2];
  1900. std::vector<InetAddress> &v6b = _v6Blacklists[ztaddr2];
  1901. json &tryAddrs = v.value()["try"];
  1902. if (tryAddrs.is_array()) {
  1903. for(unsigned long i=0;i<tryAddrs.size();++i) {
  1904. const InetAddress ip(OSUtils::jsonString(tryAddrs[i],"").c_str());
  1905. if (ip.ss_family == AF_INET)
  1906. v4h.push_back(ip);
  1907. else if (ip.ss_family == AF_INET6)
  1908. v6h.push_back(ip);
  1909. }
  1910. }
  1911. json &blAddrs = v.value()["blacklist"];
  1912. if (blAddrs.is_array()) {
  1913. for(unsigned long i=0;i<blAddrs.size();++i) {
  1914. const InetAddress ip(OSUtils::jsonString(blAddrs[i],"").c_str());
  1915. if (ip.ss_family == AF_INET)
  1916. v4b.push_back(ip);
  1917. else if (ip.ss_family == AF_INET6)
  1918. v6b.push_back(ip);
  1919. }
  1920. }
  1921. if (v4h.empty()) _v4Hints.erase(ztaddr2);
  1922. if (v6h.empty()) _v6Hints.erase(ztaddr2);
  1923. if (v4b.empty()) _v4Blacklists.erase(ztaddr2);
  1924. if (v6b.empty()) _v6Blacklists.erase(ztaddr2);
  1925. }
  1926. }
  1927. }
  1928. }
  1929. _globalV4Blacklist.clear();
  1930. _globalV6Blacklist.clear();
  1931. json &physical = lc["physical"];
  1932. if (physical.is_object()) {
  1933. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  1934. const InetAddress net(OSUtils::jsonString(phy.key(),"").c_str());
  1935. if ((net)&&(net.netmaskBits() > 0)) {
  1936. if (phy.value().is_object()) {
  1937. if (OSUtils::jsonBool(phy.value()["blacklist"],false)) {
  1938. if (net.ss_family == AF_INET)
  1939. _globalV4Blacklist.push_back(net);
  1940. else if (net.ss_family == AF_INET6)
  1941. _globalV6Blacklist.push_back(net);
  1942. }
  1943. }
  1944. }
  1945. }
  1946. }
  1947. _allowManagementFrom.clear();
  1948. _interfacePrefixBlacklist.clear();
  1949. json &settings = lc["settings"];
  1950. if (!_node->bondController()->inUse()) {
  1951. _node->bondController()->setBinder(&_binder);
  1952. // defaultBondingPolicy
  1953. std::string defaultBondingPolicyStr(OSUtils::jsonString(settings["defaultBondingPolicy"],""));
  1954. int defaultBondingPolicy = _node->bondController()->getPolicyCodeByStr(defaultBondingPolicyStr);
  1955. _node->bondController()->setBondingLayerDefaultPolicy(defaultBondingPolicy);
  1956. _node->bondController()->setBondingLayerDefaultPolicyStr(defaultBondingPolicyStr); // Used if custom policy
  1957. // Custom Policies
  1958. json &customBondingPolicies = settings["policies"];
  1959. for (json::iterator policyItr = customBondingPolicies.begin(); policyItr != customBondingPolicies.end();++policyItr) {
  1960. // Custom Policy
  1961. std::string customPolicyStr(policyItr.key());
  1962. json &customPolicy = policyItr.value();
  1963. std::string basePolicyStr(OSUtils::jsonString(customPolicy["basePolicy"],""));
  1964. if (basePolicyStr.empty()) {
  1965. fprintf(stderr, "error: no base policy was specified for custom policy (%s)\n", customPolicyStr.c_str());
  1966. }
  1967. int basePolicyCode = _node->bondController()->getPolicyCodeByStr(basePolicyStr);
  1968. if (basePolicyCode == ZT_BOND_POLICY_NONE) {
  1969. fprintf(stderr, "error: custom policy (%s) is invalid, unknown base policy (%s).\n",
  1970. customPolicyStr.c_str(), basePolicyStr.c_str());
  1971. continue;
  1972. } if (_node->bondController()->getPolicyCodeByStr(customPolicyStr) != ZT_BOND_POLICY_NONE) {
  1973. fprintf(stderr, "error: custom policy (%s) will be ignored, cannot use standard policy names for custom policies.\n",
  1974. customPolicyStr.c_str());
  1975. continue;
  1976. }
  1977. // New bond, used as a copy template for new instances
  1978. SharedPtr<Bond> newTemplateBond = new Bond(NULL, basePolicyStr, customPolicyStr, SharedPtr<Peer>());
  1979. newTemplateBond->setPolicy(basePolicyCode);
  1980. // Custom link quality spec
  1981. json &linkQualitySpec = customPolicy["linkQuality"];
  1982. if (linkQualitySpec.size() == ZT_QOS_PARAMETER_SIZE) {
  1983. float weights[ZT_QOS_PARAMETER_SIZE] = {};
  1984. weights[ZT_QOS_LAT_MAX_IDX] = (float)OSUtils::jsonDouble(linkQualitySpec["lat_max"],0.0);
  1985. weights[ZT_QOS_PDV_MAX_IDX] = (float)OSUtils::jsonDouble(linkQualitySpec["pdv_max"],0.0);
  1986. weights[ZT_QOS_PLR_MAX_IDX] = (float)OSUtils::jsonDouble(linkQualitySpec["plr_max"],0.0);
  1987. weights[ZT_QOS_PER_MAX_IDX] = (float)OSUtils::jsonDouble(linkQualitySpec["per_max"],0.0);
  1988. weights[ZT_QOS_LAT_WEIGHT_IDX] = (float)OSUtils::jsonDouble(linkQualitySpec["lat_weight"],0.0);
  1989. weights[ZT_QOS_PDV_WEIGHT_IDX] = (float)OSUtils::jsonDouble(linkQualitySpec["pdv_weight"],0.0);
  1990. weights[ZT_QOS_PLR_WEIGHT_IDX] = (float)OSUtils::jsonDouble(linkQualitySpec["plr_weight"],0.0);
  1991. weights[ZT_QOS_PER_WEIGHT_IDX] = (float)OSUtils::jsonDouble(linkQualitySpec["per_weight"],0.0);
  1992. newTemplateBond->setUserLinkQualitySpec(weights,ZT_QOS_PARAMETER_SIZE);
  1993. }
  1994. // Bond-specific properties
  1995. newTemplateBond->setUpDelay(OSUtils::jsonInt(customPolicy["upDelay"],-1));
  1996. newTemplateBond->setDownDelay(OSUtils::jsonInt(customPolicy["downDelay"],-1));
  1997. newTemplateBond->setFailoverInterval(OSUtils::jsonInt(customPolicy["failoverInterval"],ZT_BOND_FAILOVER_DEFAULT_INTERVAL));
  1998. newTemplateBond->setPacketsPerLink(OSUtils::jsonInt(customPolicy["packetsPerLink"],-1));
  1999. // Policy-Specific link set
  2000. json &links = customPolicy["links"];
  2001. for (json::iterator linkItr = links.begin(); linkItr != links.end();++linkItr) {
  2002. std::string linkNameStr(linkItr.key());
  2003. json &link = linkItr.value();
  2004. bool enabled = OSUtils::jsonInt(link["enabled"],true);
  2005. uint32_t capacity = OSUtils::jsonInt(link["capacity"],0);
  2006. uint8_t ipvPref = OSUtils::jsonInt(link["ipvPref"],0);
  2007. uint16_t mtu = OSUtils::jsonInt(link["mtu"],0);
  2008. std::string failoverToStr(OSUtils::jsonString(link["failoverTo"],""));
  2009. // Mode
  2010. std::string linkModeStr(OSUtils::jsonString(link["mode"],"spare"));
  2011. uint8_t linkMode = ZT_BOND_SLAVE_MODE_SPARE;
  2012. if (linkModeStr == "primary") { linkMode = ZT_BOND_SLAVE_MODE_PRIMARY; }
  2013. if (linkModeStr == "spare") { linkMode = ZT_BOND_SLAVE_MODE_SPARE; }
  2014. // ipvPref
  2015. if ((ipvPref != 0) && (ipvPref != 4) && (ipvPref != 6) && (ipvPref != 46) && (ipvPref != 64)) {
  2016. fprintf(stderr, "error: invalid ipvPref value (%d), link disabled.\n", ipvPref);
  2017. enabled = false;
  2018. }
  2019. if (linkMode == ZT_BOND_SLAVE_MODE_SPARE && failoverToStr.length()) {
  2020. fprintf(stderr, "error: cannot specify failover links for spares, link disabled.\n");
  2021. failoverToStr = "";
  2022. enabled = false;
  2023. }
  2024. _node->bondController()->addCustomLink(customPolicyStr, new Link(linkNameStr,ipvPref,mtu,capacity,enabled,linkMode,failoverToStr));
  2025. }
  2026. std::string linkSelectMethodStr(OSUtils::jsonString(customPolicy["activeReselect"],"optimize"));
  2027. if (linkSelectMethodStr == "always") {
  2028. newTemplateBond->setLinkSelectMethod(ZT_BOND_RESELECTION_POLICY_ALWAYS);
  2029. }
  2030. if (linkSelectMethodStr == "better") {
  2031. newTemplateBond->setLinkSelectMethod(ZT_BOND_RESELECTION_POLICY_BETTER);
  2032. }
  2033. if (linkSelectMethodStr == "failure") {
  2034. newTemplateBond->setLinkSelectMethod(ZT_BOND_RESELECTION_POLICY_FAILURE);
  2035. }
  2036. if (linkSelectMethodStr == "optimize") {
  2037. newTemplateBond->setLinkSelectMethod(ZT_BOND_RESELECTION_POLICY_OPTIMIZE);
  2038. }
  2039. if (newTemplateBond->getLinkSelectMethod() < 0 || newTemplateBond->getLinkSelectMethod() > 3) {
  2040. fprintf(stderr, "warning: invalid value (%s) for linkSelectMethod, assuming mode: always\n", linkSelectMethodStr.c_str());
  2041. }
  2042. if (!_node->bondController()->addCustomPolicy(newTemplateBond)) {
  2043. fprintf(stderr, "error: a custom policy of this name (%s) already exists.\n", customPolicyStr.c_str());
  2044. }
  2045. }
  2046. // Peer-specific bonding
  2047. json &peerSpecificBonds = settings["peerSpecificBonds"];
  2048. for (json::iterator peerItr = peerSpecificBonds.begin(); peerItr != peerSpecificBonds.end();++peerItr) {
  2049. _node->bondController()->assignBondingPolicyToPeer(std::stoull(peerItr.key(),0,16), peerItr.value());
  2050. }
  2051. // Check settings
  2052. if (defaultBondingPolicyStr.length() && !defaultBondingPolicy && !_node->bondController()->inUse()) {
  2053. fprintf(stderr, "error: unknown policy (%s) specified by defaultBondingPolicy, bond disabled.\n", defaultBondingPolicyStr.c_str());
  2054. }
  2055. }
  2056. // bondingPolicy cannot be used with allowTcpFallbackRelay
  2057. _allowTcpFallbackRelay = OSUtils::jsonBool(settings["allowTcpFallbackRelay"],true);
  2058. _forceTcpRelay = OSUtils::jsonBool(settings["forceTcpRelay"],false);
  2059. #ifdef ZT_TCP_FALLBACK_RELAY
  2060. _fallbackRelayAddress = InetAddress(OSUtils::jsonString(settings["tcpFallbackRelay"], ZT_TCP_FALLBACK_RELAY).c_str());
  2061. #endif
  2062. _primaryPort = (unsigned int)OSUtils::jsonInt(settings["primaryPort"],(uint64_t)_primaryPort) & 0xffff;
  2063. _allowSecondaryPort = OSUtils::jsonBool(settings["allowSecondaryPort"],true);
  2064. _secondaryPort = (unsigned int)OSUtils::jsonInt(settings["secondaryPort"],0);
  2065. _tertiaryPort = (unsigned int)OSUtils::jsonInt(settings["tertiaryPort"],0);
  2066. if (_secondaryPort != 0 || _tertiaryPort != 0) {
  2067. fprintf(stderr,"WARNING: using manually-specified secondary and/or tertiary ports. This can cause NAT issues." ZT_EOL_S);
  2068. }
  2069. _portMappingEnabled = OSUtils::jsonBool(settings["portMappingEnabled"],true);
  2070. _node->setLowBandwidthMode(OSUtils::jsonBool(settings["lowBandwidthMode"],false));
  2071. #ifndef ZT_SDK
  2072. const std::string up(OSUtils::jsonString(settings["softwareUpdate"],ZT_SOFTWARE_UPDATE_DEFAULT));
  2073. const bool udist = OSUtils::jsonBool(settings["softwareUpdateDist"],false);
  2074. if (((up == "apply")||(up == "download"))||(udist)) {
  2075. if (!_updater)
  2076. _updater = new SoftwareUpdater(*_node,_homePath);
  2077. _updateAutoApply = (up == "apply");
  2078. _updater->setUpdateDistribution(udist);
  2079. _updater->setChannel(OSUtils::jsonString(settings["softwareUpdateChannel"],ZT_SOFTWARE_UPDATE_DEFAULT_CHANNEL));
  2080. } else {
  2081. delete _updater;
  2082. _updater = (SoftwareUpdater *)0;
  2083. _updateAutoApply = false;
  2084. }
  2085. #endif
  2086. json &ignoreIfs = settings["interfacePrefixBlacklist"];
  2087. if (ignoreIfs.is_array()) {
  2088. for(unsigned long i=0;i<ignoreIfs.size();++i) {
  2089. const std::string tmp(OSUtils::jsonString(ignoreIfs[i],""));
  2090. if (tmp.length() > 0)
  2091. _interfacePrefixBlacklist.push_back(tmp);
  2092. }
  2093. }
  2094. json &amf = settings["allowManagementFrom"];
  2095. if (amf.is_array()) {
  2096. for(unsigned long i=0;i<amf.size();++i) {
  2097. const InetAddress nw(OSUtils::jsonString(amf[i],"").c_str());
  2098. if (nw)
  2099. _allowManagementFrom.push_back(nw);
  2100. }
  2101. }
  2102. }
  2103. #if ZT_VAULT_SUPPORT
  2104. json &vault = settings["vault"];
  2105. if (vault.is_object()) {
  2106. const std::string url(OSUtils::jsonString(vault["vaultURL"], "").c_str());
  2107. if (!url.empty()) {
  2108. _vaultURL = url;
  2109. }
  2110. const std::string token(OSUtils::jsonString(vault["vaultToken"], "").c_str());
  2111. if (!token.empty()) {
  2112. _vaultToken = token;
  2113. }
  2114. const std::string path(OSUtils::jsonString(vault["vaultPath"], "").c_str());
  2115. if (!path.empty()) {
  2116. _vaultPath = path;
  2117. }
  2118. }
  2119. // also check environment variables for values. Environment variables
  2120. // will override local.conf variables
  2121. const std::string envURL(getenv("VAULT_ADDR"));
  2122. if (!envURL.empty()) {
  2123. _vaultURL = envURL;
  2124. }
  2125. const std::string envToken(getenv("VAULT_TOKEN"));
  2126. if (!envToken.empty()) {
  2127. _vaultToken = envToken;
  2128. }
  2129. const std::string envPath(getenv("VAULT_PATH"));
  2130. if (!envPath.empty()) {
  2131. _vaultPath = envPath;
  2132. }
  2133. if (!_vaultURL.empty() && !_vaultToken.empty()) {
  2134. _vaultEnabled = true;
  2135. }
  2136. #endif
  2137. // Checks if a managed IP or route target is allowed
  2138. bool checkIfManagedIsAllowed(const NetworkState &n,const InetAddress &target)
  2139. {
  2140. if (!n.allowManaged())
  2141. return false;
  2142. if (!n.allowManagedWhitelist().empty()) {
  2143. bool allowed = false;
  2144. for (InetAddress addr : n.allowManagedWhitelist()) {
  2145. if (addr.containsAddress(target) && addr.netmaskBits() <= target.netmaskBits()) {
  2146. allowed = true;
  2147. break;
  2148. }
  2149. }
  2150. if (!allowed) return false;
  2151. }
  2152. if (target.isDefaultRoute())
  2153. return n.allowDefault();
  2154. switch(target.ipScope()) {
  2155. case InetAddress::IP_SCOPE_NONE:
  2156. case InetAddress::IP_SCOPE_MULTICAST:
  2157. case InetAddress::IP_SCOPE_LOOPBACK:
  2158. case InetAddress::IP_SCOPE_LINK_LOCAL:
  2159. return false;
  2160. case InetAddress::IP_SCOPE_GLOBAL:
  2161. return n.allowGlobal();
  2162. default:
  2163. return true;
  2164. }
  2165. }
  2166. // Match only an IP from a vector of IPs -- used in syncManagedStuff()
  2167. inline bool matchIpOnly(const std::set<InetAddress> &ips,const InetAddress &ip) const
  2168. {
  2169. for(std::set<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  2170. if (i->ipsEqual(ip))
  2171. return true;
  2172. }
  2173. return false;
  2174. }
  2175. // Apply or update managed IPs for a configured network (be sure n.tap exists)
  2176. void syncManagedStuff(NetworkState &n,bool syncIps,bool syncRoutes, bool syncDns)
  2177. {
  2178. char ipbuf[64];
  2179. // assumes _nets_m is locked
  2180. if (syncIps) {
  2181. std::vector<InetAddress> newManagedIps;
  2182. newManagedIps.reserve(n.config().assignedAddressCount);
  2183. #ifdef __APPLE__
  2184. std::vector<InetAddress> newManagedIps2;
  2185. newManagedIps2.reserve(n.config().assignedAddressCount);
  2186. #endif
  2187. for(unsigned int i=0;i<n.config().assignedAddressCount;++i) {
  2188. const InetAddress *ii = reinterpret_cast<const InetAddress *>(&(n.config().assignedAddresses[i]));
  2189. if (checkIfManagedIsAllowed(n,*ii))
  2190. newManagedIps.push_back(*ii);
  2191. }
  2192. std::sort(newManagedIps.begin(),newManagedIps.end());
  2193. newManagedIps.erase(std::unique(newManagedIps.begin(),newManagedIps.end()),newManagedIps.end());
  2194. for(std::vector<InetAddress>::iterator ip(n.managedIps().begin());ip!=n.managedIps().end();++ip) {
  2195. if (std::find(newManagedIps.begin(),newManagedIps.end(),*ip) == newManagedIps.end()) {
  2196. if (!n.tap()->removeIp(*ip))
  2197. fprintf(stderr,"ERROR: unable to remove ip address %s" ZT_EOL_S, ip->toString(ipbuf));
  2198. #ifdef __WINDOWS__
  2199. WinFWHelper::removeICMPRule(*ip, n.config().nwid);
  2200. #endif
  2201. }
  2202. }
  2203. for(std::vector<InetAddress>::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) {
  2204. #ifdef __APPLE__
  2205. // We can't add multiple addresses to an interface on macOs unless we futz with the netmask.
  2206. // see `man ifconfig`, alias section
  2207. // "If the address is on the same subnet as the first network address for this interface, a non-conflicting netmask must be given. Usually 0xffffffff is most appropriate."
  2208. auto same_subnet = [ip](InetAddress i){
  2209. return ip->network() == i.network();
  2210. };
  2211. #endif
  2212. if (std::find(n.managedIps().begin(),n.managedIps().end(),*ip) == n.managedIps().end()) {
  2213. #ifdef __APPLE__
  2214. // if same subnet as a previously added address
  2215. if (
  2216. std::find_if(n.managedIps().begin(),n.managedIps().end(), same_subnet) != n.managedIps().end() ||
  2217. std::find_if(newManagedIps2.begin(),newManagedIps2.end(), same_subnet) != newManagedIps2.end()
  2218. ) {
  2219. if (ip->isV4()) {
  2220. ip->setPort(32);
  2221. } else {
  2222. ip->setPort(128);
  2223. }
  2224. } else {
  2225. newManagedIps2.push_back(*ip);
  2226. }
  2227. #endif
  2228. if (! n.tap()->addIp(*ip)) {
  2229. fprintf(stderr, "ERROR: unable to add ip address %s" ZT_EOL_S, ip->toString(ipbuf));
  2230. }
  2231. else {
  2232. #ifdef __WINDOWS__
  2233. WinFWHelper::newICMPRule(*ip, n.config().nwid);
  2234. #endif
  2235. }
  2236. }
  2237. }
  2238. #ifdef __APPLE__
  2239. if (!MacDNSHelper::addIps6(n.config().nwid, n.config().mac, n.tap()->deviceName().c_str(), newManagedIps)) {
  2240. fprintf(stderr, "ERROR: unable to add v6 addresses to system configuration" ZT_EOL_S);
  2241. }
  2242. if (!MacDNSHelper::addIps4(n.config().nwid, n.config().mac, n.tap()->deviceName().c_str(), newManagedIps)) {
  2243. fprintf(stderr, "ERROR: unable to add v4 addresses to system configuration" ZT_EOL_S);
  2244. }
  2245. #endif
  2246. n.setManagedIps(newManagedIps);
  2247. }
  2248. if (syncRoutes) {
  2249. // Get tap device name (use LUID in hex on Windows) and IP addresses.
  2250. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  2251. char tapdevbuf[64];
  2252. OSUtils::ztsnprintf(tapdevbuf,sizeof(tapdevbuf),"%.16llx",(unsigned long long)((WindowsEthernetTap *)(n.tap().get()))->luid().Value);
  2253. std::string tapdev(tapdevbuf);
  2254. #else
  2255. std::string tapdev(n.tap()->deviceName());
  2256. #endif
  2257. std::vector<InetAddress> tapIps(n.tap()->ips());
  2258. std::set<InetAddress> myIps(tapIps.begin(), tapIps.end());
  2259. for(unsigned int i=0;i<n.config().assignedAddressCount;++i)
  2260. myIps.insert(InetAddress(n.config().assignedAddresses[i]));
  2261. std::set<InetAddress> haveRouteTargets;
  2262. for(unsigned int i=0;i<n.config().routeCount;++i) {
  2263. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config().routes[i].target));
  2264. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config().routes[i].via));
  2265. // Make sure we are allowed to set this managed route, and that 'via' is not our IP. The latter
  2266. // avoids setting routes via the router on the router.
  2267. if ( (!checkIfManagedIsAllowed(n,*target)) || ((via->ss_family == target->ss_family)&&(matchIpOnly(myIps,*via))) )
  2268. continue;
  2269. // Find an IP on the interface that can be a source IP, abort if no IPs assigned.
  2270. const InetAddress *src = nullptr;
  2271. unsigned int mostMatchingPrefixBits = 0;
  2272. for(std::set<InetAddress>::const_iterator i(myIps.begin());i!=myIps.end();++i) {
  2273. const unsigned int matchingPrefixBits = i->matchingPrefixBits(*target);
  2274. if (matchingPrefixBits >= mostMatchingPrefixBits && ((target->isV4() && i->isV4()) || (target->isV6() && i->isV6()))) {
  2275. mostMatchingPrefixBits = matchingPrefixBits;
  2276. src = &(*i);
  2277. }
  2278. }
  2279. if (!src)
  2280. continue;
  2281. // Ignore routes implied by local managed IPs since adding the IP adds the route.
  2282. // Apple on the other hand seems to need this at least on some versions.
  2283. #ifndef __APPLE__
  2284. bool haveRoute = false;
  2285. for(std::vector<InetAddress>::iterator ip(n.managedIps().begin());ip!=n.managedIps().end();++ip) {
  2286. if ((target->netmaskBits() == ip->netmaskBits())&&(target->containsAddress(*ip))) {
  2287. haveRoute = true;
  2288. break;
  2289. }
  2290. }
  2291. if (haveRoute)
  2292. continue;
  2293. #endif
  2294. haveRouteTargets.insert(*target);
  2295. #ifndef ZT_SDK
  2296. SharedPtr<ManagedRoute> &mr = n.managedRoutes()[*target];
  2297. if (!mr)
  2298. mr.set(new ManagedRoute(*target, *via, *src, tapdev.c_str()));
  2299. #endif
  2300. }
  2301. for(std::map< InetAddress, SharedPtr<ManagedRoute> >::iterator r(n.managedRoutes().begin());r!=n.managedRoutes().end();) {
  2302. if (haveRouteTargets.find(r->first) == haveRouteTargets.end())
  2303. n.managedRoutes().erase(r++);
  2304. else ++r;
  2305. }
  2306. // Sync device-local managed routes first, then indirect results. That way
  2307. // we don't get destination unreachable for routes that are via things
  2308. // that do not yet have routes in the system.
  2309. for(std::map< InetAddress, SharedPtr<ManagedRoute> >::iterator r(n.managedRoutes().begin());r!=n.managedRoutes().end();++r) {
  2310. if (!r->second->via())
  2311. r->second->sync();
  2312. }
  2313. for(std::map< InetAddress, SharedPtr<ManagedRoute> >::iterator r(n.managedRoutes().begin());r!=n.managedRoutes().end();++r) {
  2314. if (r->second->via() && (!r->second->target().isDefaultRoute() || _node->online())) {
  2315. r->second->sync();
  2316. }
  2317. }
  2318. }
  2319. if (syncDns) {
  2320. if (n.allowDNS()) {
  2321. if (strlen(n.config().dns.domain) != 0) {
  2322. std::vector<InetAddress> servers;
  2323. for (int j = 0; j < ZT_MAX_DNS_SERVERS; ++j) {
  2324. InetAddress a(n.config().dns.server_addr[j]);
  2325. if (a.isV4() || a.isV6()) {
  2326. servers.push_back(a);
  2327. }
  2328. }
  2329. n.tap()->setDns(n.config().dns.domain, servers);
  2330. }
  2331. } else {
  2332. #ifdef __APPLE__
  2333. MacDNSHelper::removeDNS(n.config().nwid);
  2334. #elif defined(__WINDOWS__)
  2335. WinDNSHelper::removeDNS(n.config().nwid);
  2336. #endif
  2337. }
  2338. }
  2339. }
  2340. // =========================================================================
  2341. // Handlers for Node and Phy<> callbacks
  2342. // =========================================================================
  2343. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  2344. {
  2345. if (_forceTcpRelay) {
  2346. return;
  2347. }
  2348. Metrics::udp_recv += len;
  2349. const uint64_t now = OSUtils::now();
  2350. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  2351. _lastDirectReceiveFromGlobal = now;
  2352. }
  2353. const ZT_ResultCode rc = _node->processWirePacket(nullptr,now,reinterpret_cast<int64_t>(sock),reinterpret_cast<const struct sockaddr_storage *>(from),data,len,&_nextBackgroundTaskDeadline);
  2354. if (ZT_ResultCode_isFatal(rc)) {
  2355. char tmp[256];
  2356. OSUtils::ztsnprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  2357. Mutex::Lock _l(_termReason_m);
  2358. _termReason = ONE_UNRECOVERABLE_ERROR;
  2359. _fatalErrorMessage = tmp;
  2360. this->terminate();
  2361. }
  2362. }
  2363. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  2364. {
  2365. if (!success) {
  2366. phyOnTcpClose(sock,uptr);
  2367. return;
  2368. }
  2369. TcpConnection *const tc = reinterpret_cast<TcpConnection *>(*uptr);
  2370. if (!tc) { // sanity check
  2371. _phy.close(sock,true);
  2372. return;
  2373. }
  2374. tc->sock = sock;
  2375. if (tc->type == TcpConnection::TCP_TUNNEL_OUTGOING) {
  2376. if (_tcpFallbackTunnel)
  2377. _phy.close(_tcpFallbackTunnel->sock);
  2378. _tcpFallbackTunnel = tc;
  2379. _phy.streamSend(sock,ZT_TCP_TUNNEL_HELLO,sizeof(ZT_TCP_TUNNEL_HELLO));
  2380. } else {
  2381. _phy.close(sock,true);
  2382. }
  2383. }
  2384. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  2385. {
  2386. if (!from) {
  2387. _phy.close(sockN,false);
  2388. return;
  2389. } else {
  2390. #ifdef ZT_SDK
  2391. // Immediately close new local connections. The intention is to prevent the backplane from being accessed when operating as libzt
  2392. if (!allowHttpBackplaneManagement && ((InetAddress*)from)->ipScope() == InetAddress::IP_SCOPE_LOOPBACK) {
  2393. _phy.close(sockN,false);
  2394. return;
  2395. }
  2396. #endif
  2397. TcpConnection *tc = new TcpConnection();
  2398. {
  2399. Mutex::Lock _l(_tcpConnections_m);
  2400. _tcpConnections.push_back(tc);
  2401. }
  2402. tc->type = TcpConnection::TCP_UNCATEGORIZED_INCOMING;
  2403. tc->parent = this;
  2404. tc->sock = sockN;
  2405. tc->remoteAddr = from;
  2406. tc->lastReceive = OSUtils::now();
  2407. http_parser_init(&(tc->parser),HTTP_REQUEST);
  2408. tc->parser.data = (void *)tc;
  2409. tc->messageSize = 0;
  2410. *uptrN = (void *)tc;
  2411. }
  2412. }
  2413. void phyOnTcpClose(PhySocket *sock,void **uptr)
  2414. {
  2415. TcpConnection *tc = (TcpConnection *)*uptr;
  2416. if (tc) {
  2417. if (tc == _tcpFallbackTunnel) {
  2418. _tcpFallbackTunnel = (TcpConnection *)0;
  2419. }
  2420. {
  2421. Mutex::Lock _l(_tcpConnections_m);
  2422. _tcpConnections.erase(std::remove(_tcpConnections.begin(),_tcpConnections.end(),tc),_tcpConnections.end());
  2423. }
  2424. delete tc;
  2425. }
  2426. }
  2427. void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  2428. {
  2429. try {
  2430. if (!len) return; // sanity check, should never happen
  2431. Metrics::tcp_recv += len;
  2432. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  2433. tc->lastReceive = OSUtils::now();
  2434. switch(tc->type) {
  2435. case TcpConnection::TCP_UNCATEGORIZED_INCOMING:
  2436. return;
  2437. case TcpConnection::TCP_HTTP_INCOMING:
  2438. case TcpConnection::TCP_HTTP_OUTGOING:
  2439. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  2440. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK))
  2441. _phy.close(sock);
  2442. return;
  2443. case TcpConnection::TCP_TUNNEL_OUTGOING:
  2444. tc->readq.append((const char *)data,len);
  2445. while (tc->readq.length() >= 5) {
  2446. const char *data = tc->readq.data();
  2447. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  2448. if (tc->readq.length() >= (mlen + 5)) {
  2449. InetAddress from;
  2450. unsigned long plen = mlen; // payload length, modified if there's an IP header
  2451. data += 5; // skip forward past pseudo-TLS junk and mlen
  2452. if (plen == 4) {
  2453. // Hello message, which isn't sent by proxy and would be ignored by client
  2454. } else if (plen) {
  2455. // Messages should contain IPv4 or IPv6 source IP address data
  2456. switch(data[0]) {
  2457. case 4: // IPv4
  2458. if (plen >= 7) {
  2459. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  2460. data += 7; // type + 4 byte IP + 2 byte port
  2461. plen -= 7;
  2462. } else {
  2463. _phy.close(sock);
  2464. return;
  2465. }
  2466. break;
  2467. case 6: // IPv6
  2468. if (plen >= 19) {
  2469. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  2470. data += 19; // type + 16 byte IP + 2 byte port
  2471. plen -= 19;
  2472. } else {
  2473. _phy.close(sock);
  2474. return;
  2475. }
  2476. break;
  2477. case 0: // none/omitted
  2478. ++data;
  2479. --plen;
  2480. break;
  2481. default: // invalid address type
  2482. _phy.close(sock);
  2483. return;
  2484. }
  2485. if (from) {
  2486. InetAddress fakeTcpLocalInterfaceAddress((uint32_t)0xffffffff,0xffff);
  2487. const ZT_ResultCode rc = _node->processWirePacket(
  2488. (void *)0,
  2489. OSUtils::now(),
  2490. -1,
  2491. reinterpret_cast<struct sockaddr_storage *>(&from),
  2492. data,
  2493. plen,
  2494. &_nextBackgroundTaskDeadline);
  2495. if (ZT_ResultCode_isFatal(rc)) {
  2496. char tmp[256];
  2497. OSUtils::ztsnprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  2498. Mutex::Lock _l(_termReason_m);
  2499. _termReason = ONE_UNRECOVERABLE_ERROR;
  2500. _fatalErrorMessage = tmp;
  2501. this->terminate();
  2502. _phy.close(sock);
  2503. return;
  2504. }
  2505. }
  2506. }
  2507. if (tc->readq.length() > (mlen + 5))
  2508. tc->readq.erase(tc->readq.begin(),tc->readq.begin() + (mlen + 5));
  2509. else tc->readq.clear();
  2510. } else break;
  2511. }
  2512. return;
  2513. }
  2514. } catch ( ... ) {
  2515. _phy.close(sock);
  2516. }
  2517. }
  2518. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  2519. {
  2520. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  2521. bool closeit = false;
  2522. {
  2523. Mutex::Lock _l(tc->writeq_m);
  2524. if (tc->writeq.length() > 0) {
  2525. long sent = (long)_phy.streamSend(sock,tc->writeq.data(),(unsigned long)tc->writeq.length(),true);
  2526. Metrics::tcp_send += sent;
  2527. if (sent > 0) {
  2528. if ((unsigned long)sent >= (unsigned long)tc->writeq.length()) {
  2529. tc->writeq.clear();
  2530. _phy.setNotifyWritable(sock,false);
  2531. if (tc->type == TcpConnection::TCP_HTTP_INCOMING)
  2532. closeit = true; // HTTP keep alive not supported
  2533. } else {
  2534. tc->writeq.erase(tc->writeq.begin(),tc->writeq.begin() + sent);
  2535. }
  2536. }
  2537. } else {
  2538. _phy.setNotifyWritable(sock,false);
  2539. }
  2540. }
  2541. if (closeit)
  2542. _phy.close(sock);
  2543. }
  2544. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  2545. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  2546. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  2547. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  2548. inline void phyOnUnixWritable(PhySocket *sock,void **uptr) {}
  2549. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  2550. {
  2551. Mutex::Lock _l(_nets_m);
  2552. NetworkState &n = _nets[nwid];
  2553. n.setWebPort(_primaryPort);
  2554. switch (op) {
  2555. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  2556. if (!n.tap()) {
  2557. try {
  2558. char friendlyName[128];
  2559. OSUtils::ztsnprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  2560. n.setTap(EthernetTap::newInstance(
  2561. nullptr,
  2562. _homePath.c_str(),
  2563. MAC(nwc->mac),
  2564. nwc->mtu,
  2565. (unsigned int)ZT_IF_METRIC,
  2566. nwid,
  2567. friendlyName,
  2568. StapFrameHandler,
  2569. (void *)this));
  2570. *nuptr = (void *)&n;
  2571. char nlcpath[256];
  2572. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  2573. std::string nlcbuf;
  2574. if (OSUtils::readFile(nlcpath,nlcbuf)) {
  2575. Dictionary<4096> nc;
  2576. nc.load(nlcbuf.c_str());
  2577. Buffer<1024> allowManaged;
  2578. if (nc.get("allowManaged", allowManaged) && allowManaged.size() > 0) {
  2579. std::string addresses (allowManaged.begin(), allowManaged.size());
  2580. if (allowManaged.size() <= 5) { // untidy parsing for backward compatibility
  2581. if (allowManaged[0] == '1' || allowManaged[0] == 't' || allowManaged[0] == 'T') {
  2582. n.setAllowManaged(true);
  2583. } else {
  2584. n.setAllowManaged(false);
  2585. }
  2586. } else {
  2587. // this should be a list of IP addresses
  2588. n.setAllowManaged(true);
  2589. size_t pos = 0;
  2590. while (true) {
  2591. size_t nextPos = addresses.find(',', pos);
  2592. std::string address = addresses.substr(pos, (nextPos == std::string::npos ? addresses.size() : nextPos) - pos);
  2593. n.addToAllowManagedWhiteList(InetAddress(address.c_str()));
  2594. if (nextPos == std::string::npos) break;
  2595. pos = nextPos + 1;
  2596. }
  2597. }
  2598. } else {
  2599. n.setAllowManaged(true);
  2600. }
  2601. n.setAllowGlobal(nc.getB("allowGlobal", false));
  2602. n.setAllowDefault(nc.getB("allowDefault", false));
  2603. n.setAllowDNS(nc.getB("allowDNS", false));
  2604. }
  2605. } catch (std::exception &exc) {
  2606. #ifdef __WINDOWS__
  2607. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  2608. if (tapFailLog) {
  2609. fprintf(tapFailLog,"%.16llx: %s" ZT_EOL_S,(unsigned long long)nwid,exc.what());
  2610. fclose(tapFailLog);
  2611. }
  2612. #else
  2613. fprintf(stderr,"ERROR: unable to configure virtual network port: %s" ZT_EOL_S,exc.what());
  2614. #endif
  2615. _nets.erase(nwid);
  2616. return -999;
  2617. } catch ( ... ) {
  2618. return -999; // tap init failed
  2619. }
  2620. }
  2621. // After setting up tap, fall through to CONFIG_UPDATE since we also want to do this...
  2622. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  2623. n.setConfig(nwc);
  2624. if (n.tap()) { // sanity check
  2625. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  2626. // wait for up to 5 seconds for the WindowsEthernetTap to actually be initialized
  2627. //
  2628. // without WindowsEthernetTap::isInitialized() returning true, the won't actually
  2629. // be online yet and setting managed routes on it will fail.
  2630. const int MAX_SLEEP_COUNT = 500;
  2631. for (int i = 0; !((WindowsEthernetTap *)(n.tap().get()))->isInitialized() && i < MAX_SLEEP_COUNT; i++) {
  2632. Sleep(10);
  2633. }
  2634. #endif
  2635. syncManagedStuff(n,true,true,true);
  2636. n.tap()->setMtu(nwc->mtu);
  2637. } else {
  2638. _nets.erase(nwid);
  2639. return -999; // tap init failed
  2640. }
  2641. break;
  2642. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  2643. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  2644. if (n.tap()) { // sanity check
  2645. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  2646. std::string winInstanceId(((WindowsEthernetTap *)(n.tap().get()))->instanceId());
  2647. #endif
  2648. *nuptr = (void *)0;
  2649. n.tap().reset();
  2650. _nets.erase(nwid);
  2651. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  2652. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY) && (winInstanceId.length() > 0)) {
  2653. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  2654. WinFWHelper::removeICMPRules(nwid);
  2655. }
  2656. #endif
  2657. if (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY) {
  2658. char nlcpath[256];
  2659. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  2660. OSUtils::rm(nlcpath);
  2661. }
  2662. } else {
  2663. _nets.erase(nwid);
  2664. }
  2665. break;
  2666. }
  2667. return 0;
  2668. }
  2669. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  2670. {
  2671. switch(event) {
  2672. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  2673. Mutex::Lock _l(_termReason_m);
  2674. _termReason = ONE_IDENTITY_COLLISION;
  2675. _fatalErrorMessage = "identity/address collision";
  2676. this->terminate();
  2677. } break;
  2678. case ZT_EVENT_TRACE: {
  2679. if (metaData) {
  2680. ::fprintf(stderr,"%s" ZT_EOL_S,(const char *)metaData);
  2681. ::fflush(stderr);
  2682. }
  2683. } break;
  2684. case ZT_EVENT_USER_MESSAGE: {
  2685. const ZT_UserMessage *um = reinterpret_cast<const ZT_UserMessage *>(metaData);
  2686. if ((um->typeId == ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE)&&(_updater)) {
  2687. _updater->handleSoftwareUpdateUserMessage(um->origin,um->data,um->length);
  2688. }
  2689. } break;
  2690. case ZT_EVENT_REMOTE_TRACE: {
  2691. const ZT_RemoteTrace *rt = reinterpret_cast<const ZT_RemoteTrace *>(metaData);
  2692. if ((rt)&&(rt->len > 0)&&(rt->len <= ZT_MAX_REMOTE_TRACE_SIZE)&&(rt->data))
  2693. _controller->handleRemoteTrace(*rt);
  2694. }
  2695. default:
  2696. break;
  2697. }
  2698. }
  2699. #if ZT_VAULT_SUPPORT
  2700. inline bool nodeVaultPutIdentity(enum ZT_StateObjectType type, const void *data, int len)
  2701. {
  2702. bool retval = false;
  2703. if (type != ZT_STATE_OBJECT_IDENTITY_PUBLIC && type != ZT_STATE_OBJECT_IDENTITY_SECRET) {
  2704. return retval;
  2705. }
  2706. CURL *curl = curl_easy_init();
  2707. if (curl) {
  2708. char token[512] = { 0 };
  2709. snprintf(token, sizeof(token), "X-Vault-Token: %s", _vaultToken.c_str());
  2710. struct curl_slist *chunk = NULL;
  2711. chunk = curl_slist_append(chunk, token);
  2712. char content_type[512] = { 0 };
  2713. snprintf(content_type, sizeof(content_type), "Content-Type: application/json");
  2714. chunk = curl_slist_append(chunk, content_type);
  2715. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
  2716. char url[2048] = { 0 };
  2717. snprintf(url, sizeof(url), "%s/v1/%s", _vaultURL.c_str(), _vaultPath.c_str());
  2718. curl_easy_setopt(curl, CURLOPT_URL, url);
  2719. json d = json::object();
  2720. if (type == ZT_STATE_OBJECT_IDENTITY_PUBLIC) {
  2721. std::string key((const char*)data, len);
  2722. d["public"] = key;
  2723. }
  2724. else if (type == ZT_STATE_OBJECT_IDENTITY_SECRET) {
  2725. std::string key((const char*)data, len);
  2726. d["secret"] = key;
  2727. }
  2728. if (!d.empty()) {
  2729. std::string post = d.dump();
  2730. if (!post.empty()) {
  2731. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post.c_str());
  2732. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, post.length());
  2733. #ifndef NDEBUG
  2734. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  2735. #endif
  2736. CURLcode res = curl_easy_perform(curl);
  2737. if (res == CURLE_OK) {
  2738. long response_code = 0;
  2739. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
  2740. if (response_code == 200 || response_code == 204) {
  2741. retval = true;
  2742. }
  2743. }
  2744. }
  2745. }
  2746. curl_easy_cleanup(curl);
  2747. curl = NULL;
  2748. curl_slist_free_all(chunk);
  2749. chunk = NULL;
  2750. }
  2751. return retval;
  2752. }
  2753. #endif
  2754. inline void nodeStatePutFunction(enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)
  2755. {
  2756. #if ZT_VAULT_SUPPORT
  2757. if (_vaultEnabled && (type == ZT_STATE_OBJECT_IDENTITY_SECRET || type == ZT_STATE_OBJECT_IDENTITY_PUBLIC)) {
  2758. if (nodeVaultPutIdentity(type, data, len)) {
  2759. // value successfully written to Vault
  2760. return;
  2761. }
  2762. // else fallback to disk
  2763. }
  2764. #endif
  2765. char p[1024];
  2766. FILE *f;
  2767. bool secure = false;
  2768. char dirname[1024];
  2769. dirname[0] = 0;
  2770. switch(type) {
  2771. case ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  2772. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str());
  2773. break;
  2774. case ZT_STATE_OBJECT_IDENTITY_SECRET:
  2775. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str());
  2776. secure = true;
  2777. break;
  2778. case ZT_STATE_OBJECT_PLANET:
  2779. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "planet",_homePath.c_str());
  2780. break;
  2781. case ZT_STATE_OBJECT_MOON:
  2782. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "moons.d",_homePath.c_str());
  2783. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.moon",dirname,(unsigned long long)id[0]);
  2784. break;
  2785. case ZT_STATE_OBJECT_NETWORK_CONFIG:
  2786. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "networks.d",_homePath.c_str());
  2787. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.conf",dirname,(unsigned long long)id[0]);
  2788. break;
  2789. case ZT_STATE_OBJECT_PEER:
  2790. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "peers.d",_homePath.c_str());
  2791. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.10llx.peer",dirname,(unsigned long long)id[0]);
  2792. break;
  2793. default:
  2794. return;
  2795. }
  2796. if ((len >= 0)&&(data)) {
  2797. // Check to see if we've already written this first. This reduces
  2798. // redundant writes and I/O overhead on most platforms and has
  2799. // little effect on others.
  2800. f = fopen(p,"rb");
  2801. if (f) {
  2802. char *const buf = (char *)malloc(len*4);
  2803. if (buf) {
  2804. long l = (long)fread(buf,1,(size_t)(len*4),f);
  2805. fclose(f);
  2806. if ((l == (long)len)&&(memcmp(data,buf,l) == 0)) {
  2807. free(buf);
  2808. return;
  2809. }
  2810. free(buf);
  2811. }
  2812. }
  2813. f = fopen(p,"wb");
  2814. if ((!f)&&(dirname[0])) { // create subdirectory if it does not exist
  2815. OSUtils::mkdir(dirname);
  2816. f = fopen(p,"wb");
  2817. }
  2818. if (f) {
  2819. if (fwrite(data,len,1,f) != 1)
  2820. fprintf(stderr,"WARNING: unable to write to file: %s (I/O error)" ZT_EOL_S,p);
  2821. fclose(f);
  2822. if (secure)
  2823. OSUtils::lockDownFile(p,false);
  2824. } else {
  2825. fprintf(stderr,"WARNING: unable to write to file: %s (unable to open)" ZT_EOL_S,p);
  2826. }
  2827. } else {
  2828. OSUtils::rm(p);
  2829. }
  2830. }
  2831. #if ZT_VAULT_SUPPORT
  2832. inline int nodeVaultGetIdentity(enum ZT_StateObjectType type, void *data, unsigned int maxlen)
  2833. {
  2834. if (type != ZT_STATE_OBJECT_IDENTITY_SECRET && type != ZT_STATE_OBJECT_IDENTITY_PUBLIC) {
  2835. return -1;
  2836. }
  2837. int ret = -1;
  2838. CURL *curl = curl_easy_init();
  2839. if (curl) {
  2840. char token[512] = { 0 };
  2841. snprintf(token, sizeof(token), "X-Vault-Token: %s", _vaultToken.c_str());
  2842. struct curl_slist *chunk = NULL;
  2843. chunk = curl_slist_append(chunk, token);
  2844. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
  2845. char url[2048] = { 0 };
  2846. snprintf(url, sizeof(url), "%s/v1/%s", _vaultURL.c_str(), _vaultPath.c_str());
  2847. curl_easy_setopt(curl, CURLOPT_URL, url);
  2848. std::string response;
  2849. std::string res_headers;
  2850. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &curlResponseWrite);
  2851. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
  2852. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &res_headers);
  2853. #ifndef NDEBUG
  2854. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  2855. #endif
  2856. CURLcode res = curl_easy_perform(curl);
  2857. if (res == CURLE_OK) {
  2858. long response_code = 0;
  2859. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
  2860. if (response_code == 200) {
  2861. try {
  2862. json payload = json::parse(response);
  2863. if (!payload["data"].is_null()) {
  2864. json &d = payload["data"];
  2865. if (type == ZT_STATE_OBJECT_IDENTITY_SECRET) {
  2866. std::string secret = OSUtils::jsonString(d["secret"],"");
  2867. if (!secret.empty()) {
  2868. ret = (int)secret.length();
  2869. memcpy(data, secret.c_str(), ret);
  2870. }
  2871. }
  2872. else if (type == ZT_STATE_OBJECT_IDENTITY_PUBLIC) {
  2873. std::string pub = OSUtils::jsonString(d["public"],"");
  2874. if (!pub.empty()) {
  2875. ret = (int)pub.length();
  2876. memcpy(data, pub.c_str(), ret);
  2877. }
  2878. }
  2879. }
  2880. }
  2881. catch (...) {
  2882. ret = -1;
  2883. }
  2884. }
  2885. }
  2886. curl_easy_cleanup(curl);
  2887. curl = NULL;
  2888. curl_slist_free_all(chunk);
  2889. chunk = NULL;
  2890. }
  2891. return ret;
  2892. }
  2893. #endif
  2894. inline int nodeStateGetFunction(enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)
  2895. {
  2896. #if ZT_VAULT_SUPPORT
  2897. if (_vaultEnabled && (type == ZT_STATE_OBJECT_IDENTITY_SECRET || type == ZT_STATE_OBJECT_IDENTITY_PUBLIC) ) {
  2898. int retval = nodeVaultGetIdentity(type, data, maxlen);
  2899. if (retval >= 0)
  2900. return retval;
  2901. // else continue file based lookup
  2902. }
  2903. #endif
  2904. char p[4096];
  2905. switch(type) {
  2906. case ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  2907. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str());
  2908. break;
  2909. case ZT_STATE_OBJECT_IDENTITY_SECRET:
  2910. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str());
  2911. break;
  2912. case ZT_STATE_OBJECT_PLANET:
  2913. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "planet",_homePath.c_str());
  2914. break;
  2915. case ZT_STATE_OBJECT_MOON:
  2916. 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]);
  2917. break;
  2918. case ZT_STATE_OBJECT_NETWORK_CONFIG:
  2919. 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]);
  2920. break;
  2921. case ZT_STATE_OBJECT_PEER:
  2922. 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]);
  2923. break;
  2924. default:
  2925. return -1;
  2926. }
  2927. FILE *f = fopen(p,"rb");
  2928. if (f) {
  2929. int n = (int)fread(data,1,maxlen,f);
  2930. fclose(f);
  2931. #if ZT_VAULT_SUPPORT
  2932. if (_vaultEnabled && (type == ZT_STATE_OBJECT_IDENTITY_SECRET || type == ZT_STATE_OBJECT_IDENTITY_PUBLIC)) {
  2933. // If we've gotten here while Vault is enabled, Vault does not know the key and it's been
  2934. // read from disk instead.
  2935. //
  2936. // We should put the value in Vault and remove the local file.
  2937. if (nodeVaultPutIdentity(type, data, n)) {
  2938. unlink(p);
  2939. }
  2940. }
  2941. #endif
  2942. if (n >= 0)
  2943. return n;
  2944. }
  2945. return -1;
  2946. }
  2947. inline int nodeWirePacketSendFunction(const int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  2948. {
  2949. #ifdef ZT_TCP_FALLBACK_RELAY
  2950. if(_allowTcpFallbackRelay) {
  2951. if (addr->ss_family == AF_INET) {
  2952. // TCP fallback tunnel support, currently IPv4 only
  2953. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  2954. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  2955. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  2956. // valid direct traffic we'll stop using it and close the socket after a while.
  2957. const int64_t now = OSUtils::now();
  2958. if (_forceTcpRelay || (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER))) {
  2959. if (_tcpFallbackTunnel) {
  2960. bool flushNow = false;
  2961. {
  2962. Mutex::Lock _l(_tcpFallbackTunnel->writeq_m);
  2963. if (_tcpFallbackTunnel->writeq.size() < (1024 * 64)) {
  2964. if (_tcpFallbackTunnel->writeq.length() == 0) {
  2965. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  2966. flushNow = true;
  2967. }
  2968. const unsigned long mlen = len + 7;
  2969. _tcpFallbackTunnel->writeq.push_back((char)0x17);
  2970. _tcpFallbackTunnel->writeq.push_back((char)0x03);
  2971. _tcpFallbackTunnel->writeq.push_back((char)0x03); // fake TLS 1.2 header
  2972. _tcpFallbackTunnel->writeq.push_back((char)((mlen >> 8) & 0xff));
  2973. _tcpFallbackTunnel->writeq.push_back((char)(mlen & 0xff));
  2974. _tcpFallbackTunnel->writeq.push_back((char)4); // IPv4
  2975. _tcpFallbackTunnel->writeq.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  2976. _tcpFallbackTunnel->writeq.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  2977. _tcpFallbackTunnel->writeq.append((const char *)data,len);
  2978. }
  2979. }
  2980. if (flushNow) {
  2981. void *tmpptr = (void *)_tcpFallbackTunnel;
  2982. phyOnTcpWritable(_tcpFallbackTunnel->sock,&tmpptr);
  2983. }
  2984. } else if (_forceTcpRelay || (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INTERVAL / 2)))) {
  2985. const InetAddress addr(_fallbackRelayAddress);
  2986. TcpConnection *tc = new TcpConnection();
  2987. {
  2988. Mutex::Lock _l(_tcpConnections_m);
  2989. _tcpConnections.push_back(tc);
  2990. }
  2991. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  2992. tc->remoteAddr = addr;
  2993. tc->lastReceive = OSUtils::now();
  2994. tc->parent = this;
  2995. tc->sock = (PhySocket *)0; // set in connect handler
  2996. tc->messageSize = 0;
  2997. bool connected = false;
  2998. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected,(void *)tc,true);
  2999. }
  3000. }
  3001. _lastSendToGlobalV4 = now;
  3002. }
  3003. }
  3004. }
  3005. if (_forceTcpRelay) {
  3006. // Shortcut here so that we don't emit any UDP packets
  3007. return 0;
  3008. }
  3009. #endif // ZT_TCP_FALLBACK_RELAY
  3010. // Even when relaying we still send via UDP. This way if UDP starts
  3011. // working we can instantly "fail forward" to it and stop using TCP
  3012. // proxy fallback, which is slow.
  3013. if ((localSocket != -1)&&(localSocket != 0)&&(_binder.isUdpSocketValid((PhySocket *)((uintptr_t)localSocket)))) {
  3014. if ((ttl)&&(addr->ss_family == AF_INET)) {
  3015. _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),ttl);
  3016. }
  3017. const bool r = _phy.udpSend((PhySocket *)((uintptr_t)localSocket),(const struct sockaddr *)addr,data,len);
  3018. if ((ttl)&&(addr->ss_family == AF_INET)) {
  3019. _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),255);
  3020. }
  3021. return ((r) ? 0 : -1);
  3022. } else {
  3023. return ((_binder.udpSendAll(_phy,addr,data,len,ttl)) ? 0 : -1);
  3024. }
  3025. }
  3026. 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)
  3027. {
  3028. NetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);
  3029. if ((!n)||(!n->tap()))
  3030. return;
  3031. n->tap()->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  3032. }
  3033. inline int nodePathCheckFunction(uint64_t ztaddr,const int64_t localSocket,const struct sockaddr_storage *remoteAddr)
  3034. {
  3035. // Make sure we're not trying to do ZeroTier-over-ZeroTier
  3036. {
  3037. Mutex::Lock _l(_nets_m);
  3038. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  3039. if (n->second.tap()) {
  3040. std::vector<InetAddress> ips(n->second.tap()->ips());
  3041. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  3042. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  3043. return 0;
  3044. }
  3045. }
  3046. }
  3047. }
  3048. }
  3049. /* Note: I do not think we need to scan for overlap with managed routes
  3050. * because of the "route forking" and interface binding that we do. This
  3051. * ensures (we hope) that ZeroTier traffic will still take the physical
  3052. * path even if its managed routes override this for other traffic. Will
  3053. * revisit if we see recursion problems. */
  3054. // Check blacklists
  3055. const Hashtable< uint64_t,std::vector<InetAddress> > *blh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  3056. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  3057. if (remoteAddr->ss_family == AF_INET) {
  3058. blh = &_v4Blacklists;
  3059. gbl = &_globalV4Blacklist;
  3060. } else if (remoteAddr->ss_family == AF_INET6) {
  3061. blh = &_v6Blacklists;
  3062. gbl = &_globalV6Blacklist;
  3063. }
  3064. if (blh) {
  3065. Mutex::Lock _l(_localConfig_m);
  3066. const std::vector<InetAddress> *l = blh->get(ztaddr);
  3067. if (l) {
  3068. for(std::vector<InetAddress>::const_iterator a(l->begin());a!=l->end();++a) {
  3069. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  3070. return 0;
  3071. }
  3072. }
  3073. }
  3074. if (gbl) {
  3075. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  3076. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  3077. return 0;
  3078. }
  3079. }
  3080. return 1;
  3081. }
  3082. inline int nodePathLookupFunction(uint64_t ztaddr, int family, struct sockaddr_storage* result)
  3083. {
  3084. const Hashtable< uint64_t, std::vector<InetAddress> >* lh = (const Hashtable< uint64_t, std::vector<InetAddress> > *)0;
  3085. if (family < 0)
  3086. lh = (_node->prng() & 1) ? &_v4Hints : &_v6Hints;
  3087. else if (family == AF_INET)
  3088. lh = &_v4Hints;
  3089. else if (family == AF_INET6)
  3090. lh = &_v6Hints;
  3091. else return 0;
  3092. const std::vector<InetAddress>* l = lh->get(ztaddr);
  3093. if ((l) && (!l->empty())) {
  3094. memcpy(result, &((*l)[(unsigned long)_node->prng() % l->size()]), sizeof(struct sockaddr_storage));
  3095. return 1;
  3096. }
  3097. else return 0;
  3098. }
  3099. inline void tapFrameHandler(uint64_t nwid, const MAC& from, const MAC& to, unsigned int etherType, unsigned int vlanId, const void* data, unsigned int len)
  3100. {
  3101. _node->processVirtualNetworkFrame((void*)0, OSUtils::now(), nwid, from.toInt(), to.toInt(), etherType, vlanId, data, len, &_nextBackgroundTaskDeadline);
  3102. }
  3103. inline void onHttpResponseFromClient(TcpConnection* tc)
  3104. {
  3105. _phy.close(tc->sock);
  3106. }
  3107. bool shouldBindInterface(const char* ifname, const InetAddress& ifaddr)
  3108. {
  3109. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  3110. if ((ifname[0] == 'l') && (ifname[1] == 'o')) return false; // loopback
  3111. if ((ifname[0] == 'z') && (ifname[1] == 't')) return false; // sanity check: zt#
  3112. if ((ifname[0] == 't') && (ifname[1] == 'u') && (ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  3113. if ((ifname[0] == 't') && (ifname[1] == 'a') && (ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  3114. #endif
  3115. #ifdef __APPLE__
  3116. if ((ifname[0] == 'f') && (ifname[1] == 'e') && (ifname[2] == 't') && (ifname[3] == 'h')) return false; // ... as is feth#
  3117. if ((ifname[0] == 'l') && (ifname[1] == 'o')) return false; // loopback
  3118. if ((ifname[0] == 'z') && (ifname[1] == 't')) return false; // sanity check: zt#
  3119. if ((ifname[0] == 't') && (ifname[1] == 'u') && (ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  3120. if ((ifname[0] == 't') && (ifname[1] == 'a') && (ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  3121. if ((ifname[0] == 'u') && (ifname[1] == 't') && (ifname[2] == 'u') && (ifname[3] == 'n')) return false; // ... as is utun#
  3122. #endif
  3123. #ifdef __FreeBSD__
  3124. if ((ifname[0] == 'l') && (ifname[1] == 'o')) return false; // loopback
  3125. if ((ifname[0] == 'z') && (ifname[1] == 't')) return false; // sanity check: zt#
  3126. #endif
  3127. {
  3128. Mutex::Lock _l(_localConfig_m);
  3129. for(std::vector<std::string>::const_iterator p(_interfacePrefixBlacklist.begin());p!=_interfacePrefixBlacklist.end();++p) {
  3130. if (!strncmp(p->c_str(),ifname,p->length()))
  3131. return false;
  3132. }
  3133. }
  3134. {
  3135. // Check global blacklists
  3136. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  3137. if (ifaddr.ss_family == AF_INET) {
  3138. gbl = &_globalV4Blacklist;
  3139. } else if (ifaddr.ss_family == AF_INET6) {
  3140. gbl = &_globalV6Blacklist;
  3141. }
  3142. if (gbl) {
  3143. Mutex::Lock _l(_localConfig_m);
  3144. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  3145. if (a->containsAddress(ifaddr))
  3146. return false;
  3147. }
  3148. }
  3149. }
  3150. {
  3151. Mutex::Lock _l(_nets_m);
  3152. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  3153. if (n->second.tap()) {
  3154. std::vector<InetAddress> ips(n->second.tap()->ips());
  3155. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  3156. if (i->ipsEqual(ifaddr))
  3157. return false;
  3158. }
  3159. #ifdef _WIN32
  3160. if (n->second.tap()->friendlyName() == ifname)
  3161. return false;
  3162. #endif
  3163. }
  3164. }
  3165. }
  3166. return true;
  3167. }
  3168. unsigned int _getRandomPort()
  3169. {
  3170. unsigned int randp = 0;
  3171. Utils::getSecureRandom(&randp,sizeof(randp));
  3172. randp = 20000 + (randp % 45500);
  3173. for(int i=0;;++i) {
  3174. if (i > 1000) {
  3175. return 0;
  3176. } else if (++randp >= 65536) {
  3177. randp = 20000;
  3178. }
  3179. if (_trialBind(randp))
  3180. break;
  3181. }
  3182. return randp;
  3183. }
  3184. bool _trialBind(unsigned int port)
  3185. {
  3186. struct sockaddr_in in4;
  3187. struct sockaddr_in6 in6;
  3188. PhySocket *tb;
  3189. memset(&in4,0,sizeof(in4));
  3190. in4.sin_family = AF_INET;
  3191. in4.sin_port = Utils::hton((uint16_t)port);
  3192. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
  3193. if (tb) {
  3194. _phy.close(tb,false);
  3195. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
  3196. if (tb) {
  3197. _phy.close(tb,false);
  3198. return true;
  3199. }
  3200. }
  3201. memset(&in6,0,sizeof(in6));
  3202. in6.sin6_family = AF_INET6;
  3203. in6.sin6_port = Utils::hton((uint16_t)port);
  3204. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
  3205. if (tb) {
  3206. _phy.close(tb,false);
  3207. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
  3208. if (tb) {
  3209. _phy.close(tb,false);
  3210. return true;
  3211. }
  3212. }
  3213. return false;
  3214. }
  3215. };
  3216. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  3217. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  3218. static void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData)
  3219. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  3220. static void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)
  3221. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeStatePutFunction(type,id,data,len); }
  3222. static int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)
  3223. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeStateGetFunction(type,id,data,maxlen); }
  3224. 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)
  3225. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localSocket,addr,data,len,ttl); }
  3226. 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)
  3227. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  3228. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr)
  3229. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(ztaddr,localSocket,remoteAddr); }
  3230. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result)
  3231. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathLookupFunction(ztaddr,family,result); }
  3232. 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)
  3233. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  3234. static int ShttpOnMessageBegin(http_parser *parser)
  3235. {
  3236. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  3237. tc->currentHeaderField = "";
  3238. tc->currentHeaderValue = "";
  3239. tc->messageSize = 0;
  3240. tc->url.clear();
  3241. tc->status.clear();
  3242. tc->headers.clear();
  3243. tc->readq.clear();
  3244. return 0;
  3245. }
  3246. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  3247. {
  3248. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  3249. tc->messageSize += (unsigned long)length;
  3250. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  3251. return -1;
  3252. tc->url.append(ptr,length);
  3253. return 0;
  3254. }
  3255. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  3256. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  3257. #else
  3258. static int ShttpOnStatus(http_parser *parser)
  3259. #endif
  3260. { return 0; }
  3261. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  3262. {
  3263. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  3264. tc->messageSize += (unsigned long)length;
  3265. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  3266. return -1;
  3267. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  3268. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  3269. tc->currentHeaderField = "";
  3270. tc->currentHeaderValue = "";
  3271. }
  3272. for(size_t i=0;i<length;++i)
  3273. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  3274. return 0;
  3275. }
  3276. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  3277. {
  3278. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  3279. tc->messageSize += (unsigned long)length;
  3280. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  3281. return -1;
  3282. tc->currentHeaderValue.append(ptr,length);
  3283. return 0;
  3284. }
  3285. static int ShttpOnHeadersComplete(http_parser *parser)
  3286. {
  3287. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  3288. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  3289. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  3290. return 0;
  3291. }
  3292. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  3293. {
  3294. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  3295. tc->messageSize += (unsigned long)length;
  3296. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  3297. return -1;
  3298. tc->readq.append(ptr,length);
  3299. return 0;
  3300. }
  3301. static int ShttpOnMessageComplete(http_parser *parser)
  3302. {
  3303. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  3304. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  3305. } else {
  3306. tc->parent->onHttpResponseFromClient(tc);
  3307. }
  3308. return 0;
  3309. }
  3310. } // anonymous namespace
  3311. std::string OneService::platformDefaultHomePath()
  3312. {
  3313. return OSUtils::platformDefaultHomePath();
  3314. }
  3315. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  3316. OneService::~OneService() {}
  3317. } // namespace ZeroTier