OneService.cpp 120 KB

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