OneService.cpp 97 KB

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