OneService.cpp 114 KB

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