OneService.cpp 119 KB

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