OneService.cpp 132 KB

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