OneService.cpp 119 KB

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