OneService.cpp 130 KB

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