OneService.cpp 127 KB

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