OneService.cpp 120 KB

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