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