OneService.cpp 113 KB

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