OneService.cpp 138 KB

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