OneService.cpp 120 KB

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