OneService.cpp 110 KB

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