OneService.cpp 138 KB

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