OneService.cpp 117 KB

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