1
0

OneService.cpp 154 KB

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