OneService.cpp 131 KB

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