OneService.cpp 121 KB

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