OneService.cpp 133 KB

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