OneService.cpp 147 KB

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