OneService.cpp 147 KB

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