OneService.cpp 150 KB

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