OneService.cpp 104 KB

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