OneService.cpp 149 KB

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