OneService.cpp 120 KB

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