OneService.cpp 120 KB

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