OneService.cpp 118 KB

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