OneService.cpp 148 KB

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