OneService.cpp 142 KB

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