OneService.cpp 137 KB

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