OneService.cpp 138 KB

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