OneService.cpp 152 KB

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