OneService.cpp 119 KB

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