OneService.cpp 147 KB

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