2
0

OneService.cpp 117 KB

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