OneService.cpp 153 KB

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