OneService.cpp 135 KB

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