OneService.cpp 117 KB

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