OneService.cpp 120 KB

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