OneService.cpp 119 KB

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