OneService.cpp 87 KB

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