OneService.cpp 136 KB

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