OneService.cpp 120 KB

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