OneService.cpp 121 KB

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