OneService.cpp 118 KB

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