OneService.cpp 119 KB

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