OneService.cpp 148 KB

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