OneService.cpp 88 KB

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