OneService.cpp 154 KB

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