OneService.cpp 121 KB

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