OneService.cpp 119 KB

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