OneService.cpp 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549
  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. /*
  1430. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  1431. if ((target->netmaskBits() == ip->netmaskBits())&&(target->containsAddress(*ip))) {
  1432. haveRoute = true;
  1433. break;
  1434. }
  1435. }
  1436. */
  1437. if (haveRoute)
  1438. continue;
  1439. // If we've already applied this route, just sync it and continue
  1440. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();++mr) {
  1441. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (tapdev == (*mr)->device()) ) ) {
  1442. haveRoute = true;
  1443. (*mr)->sync();
  1444. break;
  1445. }
  1446. }
  1447. if (haveRoute)
  1448. continue;
  1449. // Add and apply new routes
  1450. n.managedRoutes.push_back(SharedPtr<ManagedRoute>(new ManagedRoute(*target,*via,tapdev)));
  1451. if (!n.managedRoutes.back()->sync())
  1452. n.managedRoutes.pop_back();
  1453. }
  1454. }
  1455. }
  1456. // =========================================================================
  1457. // Handlers for Node and Phy<> callbacks
  1458. // =========================================================================
  1459. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  1460. {
  1461. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  1462. _lastDirectReceiveFromGlobal = OSUtils::now();
  1463. const ZT_ResultCode rc = _node->processWirePacket(
  1464. (void *)0,
  1465. OSUtils::now(),
  1466. reinterpret_cast<int64_t>(sock),
  1467. reinterpret_cast<const struct sockaddr_storage *>(from), // Phy<> uses sockaddr_storage, so it'll always be that big
  1468. data,
  1469. len,
  1470. &_nextBackgroundTaskDeadline);
  1471. if (ZT_ResultCode_isFatal(rc)) {
  1472. char tmp[256];
  1473. OSUtils::ztsnprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1474. Mutex::Lock _l(_termReason_m);
  1475. _termReason = ONE_UNRECOVERABLE_ERROR;
  1476. _fatalErrorMessage = tmp;
  1477. this->terminate();
  1478. }
  1479. }
  1480. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  1481. {
  1482. if (!success) {
  1483. phyOnTcpClose(sock,uptr);
  1484. return;
  1485. }
  1486. TcpConnection *const tc = reinterpret_cast<TcpConnection *>(*uptr);
  1487. if (!tc) { // sanity check
  1488. _phy.close(sock,true);
  1489. return;
  1490. }
  1491. tc->sock = sock;
  1492. if (tc->type == TcpConnection::TCP_TUNNEL_OUTGOING) {
  1493. if (_tcpFallbackTunnel)
  1494. _phy.close(_tcpFallbackTunnel->sock);
  1495. _tcpFallbackTunnel = tc;
  1496. _phy.streamSend(sock,ZT_TCP_TUNNEL_HELLO,sizeof(ZT_TCP_TUNNEL_HELLO));
  1497. } else {
  1498. _phy.close(sock,true);
  1499. }
  1500. }
  1501. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  1502. {
  1503. if (!from) {
  1504. _phy.close(sockN,false);
  1505. return;
  1506. } else {
  1507. TcpConnection *tc = new TcpConnection();
  1508. {
  1509. Mutex::Lock _l(_tcpConnections_m);
  1510. _tcpConnections.push_back(tc);
  1511. }
  1512. tc->type = TcpConnection::TCP_UNCATEGORIZED_INCOMING;
  1513. tc->parent = this;
  1514. tc->sock = sockN;
  1515. tc->remoteAddr = from;
  1516. tc->lastReceive = OSUtils::now();
  1517. http_parser_init(&(tc->parser),HTTP_REQUEST);
  1518. tc->parser.data = (void *)tc;
  1519. tc->messageSize = 0;
  1520. *uptrN = (void *)tc;
  1521. }
  1522. }
  1523. void phyOnTcpClose(PhySocket *sock,void **uptr)
  1524. {
  1525. TcpConnection *tc = (TcpConnection *)*uptr;
  1526. if (tc) {
  1527. if (tc == _tcpFallbackTunnel) {
  1528. _tcpFallbackTunnel = (TcpConnection *)0;
  1529. }
  1530. {
  1531. Mutex::Lock _l(_tcpConnections_m);
  1532. _tcpConnections.erase(std::remove(_tcpConnections.begin(),_tcpConnections.end(),tc),_tcpConnections.end());
  1533. }
  1534. delete tc;
  1535. }
  1536. }
  1537. void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  1538. {
  1539. try {
  1540. if (!len) return; // sanity check, should never happen
  1541. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1542. tc->lastReceive = OSUtils::now();
  1543. switch(tc->type) {
  1544. case TcpConnection::TCP_UNCATEGORIZED_INCOMING:
  1545. switch(reinterpret_cast<uint8_t *>(data)[0]) {
  1546. // HTTP: GET, PUT, POST, HEAD, DELETE
  1547. case 'G':
  1548. case 'P':
  1549. case 'D':
  1550. case 'H': {
  1551. // This is only allowed from IPs permitted to access the management
  1552. // backplane, which is just 127.0.0.1/::1 unless otherwise configured.
  1553. bool allow;
  1554. {
  1555. Mutex::Lock _l(_localConfig_m);
  1556. if (_allowManagementFrom.size() == 0) {
  1557. allow = (tc->remoteAddr.ipScope() == InetAddress::IP_SCOPE_LOOPBACK);
  1558. } else {
  1559. allow = false;
  1560. for(std::vector<InetAddress>::const_iterator i(_allowManagementFrom.begin());i!=_allowManagementFrom.end();++i) {
  1561. if (i->containsAddress(tc->remoteAddr)) {
  1562. allow = true;
  1563. break;
  1564. }
  1565. }
  1566. }
  1567. }
  1568. if (allow) {
  1569. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  1570. phyOnTcpData(sock,uptr,data,len);
  1571. } else {
  1572. _phy.close(sock);
  1573. }
  1574. } break;
  1575. // Drop unknown protocols
  1576. default:
  1577. _phy.close(sock);
  1578. break;
  1579. }
  1580. return;
  1581. case TcpConnection::TCP_HTTP_INCOMING:
  1582. case TcpConnection::TCP_HTTP_OUTGOING:
  1583. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  1584. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK))
  1585. _phy.close(sock);
  1586. return;
  1587. case TcpConnection::TCP_TUNNEL_OUTGOING:
  1588. tc->readq.append((const char *)data,len);
  1589. while (tc->readq.length() >= 5) {
  1590. const char *data = tc->readq.data();
  1591. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  1592. if (tc->readq.length() >= (mlen + 5)) {
  1593. InetAddress from;
  1594. unsigned long plen = mlen; // payload length, modified if there's an IP header
  1595. data += 5; // skip forward past pseudo-TLS junk and mlen
  1596. if (plen == 4) {
  1597. // Hello message, which isn't sent by proxy and would be ignored by client
  1598. } else if (plen) {
  1599. // Messages should contain IPv4 or IPv6 source IP address data
  1600. switch(data[0]) {
  1601. case 4: // IPv4
  1602. if (plen >= 7) {
  1603. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  1604. data += 7; // type + 4 byte IP + 2 byte port
  1605. plen -= 7;
  1606. } else {
  1607. _phy.close(sock);
  1608. return;
  1609. }
  1610. break;
  1611. case 6: // IPv6
  1612. if (plen >= 19) {
  1613. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  1614. data += 19; // type + 16 byte IP + 2 byte port
  1615. plen -= 19;
  1616. } else {
  1617. _phy.close(sock);
  1618. return;
  1619. }
  1620. break;
  1621. case 0: // none/omitted
  1622. ++data;
  1623. --plen;
  1624. break;
  1625. default: // invalid address type
  1626. _phy.close(sock);
  1627. return;
  1628. }
  1629. if (from) {
  1630. InetAddress fakeTcpLocalInterfaceAddress((uint32_t)0xffffffff,0xffff);
  1631. const ZT_ResultCode rc = _node->processWirePacket(
  1632. (void *)0,
  1633. OSUtils::now(),
  1634. -1,
  1635. reinterpret_cast<struct sockaddr_storage *>(&from),
  1636. data,
  1637. plen,
  1638. &_nextBackgroundTaskDeadline);
  1639. if (ZT_ResultCode_isFatal(rc)) {
  1640. char tmp[256];
  1641. OSUtils::ztsnprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1642. Mutex::Lock _l(_termReason_m);
  1643. _termReason = ONE_UNRECOVERABLE_ERROR;
  1644. _fatalErrorMessage = tmp;
  1645. this->terminate();
  1646. _phy.close(sock);
  1647. return;
  1648. }
  1649. }
  1650. }
  1651. if (tc->readq.length() > (mlen + 5))
  1652. tc->readq.erase(tc->readq.begin(),tc->readq.begin() + (mlen + 5));
  1653. else tc->readq.clear();
  1654. } else break;
  1655. }
  1656. return;
  1657. }
  1658. } catch ( ... ) {
  1659. _phy.close(sock);
  1660. }
  1661. }
  1662. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  1663. {
  1664. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1665. bool closeit = false;
  1666. {
  1667. Mutex::Lock _l(tc->writeq_m);
  1668. if (tc->writeq.length() > 0) {
  1669. long sent = (long)_phy.streamSend(sock,tc->writeq.data(),(unsigned long)tc->writeq.length(),true);
  1670. if (sent > 0) {
  1671. if ((unsigned long)sent >= (unsigned long)tc->writeq.length()) {
  1672. tc->writeq.clear();
  1673. _phy.setNotifyWritable(sock,false);
  1674. if (tc->type == TcpConnection::TCP_HTTP_INCOMING)
  1675. closeit = true; // HTTP keep alive not supported
  1676. } else {
  1677. tc->writeq.erase(tc->writeq.begin(),tc->writeq.begin() + sent);
  1678. }
  1679. }
  1680. } else {
  1681. _phy.setNotifyWritable(sock,false);
  1682. }
  1683. }
  1684. if (closeit)
  1685. _phy.close(sock);
  1686. }
  1687. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  1688. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  1689. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  1690. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  1691. inline void phyOnUnixWritable(PhySocket *sock,void **uptr,bool lwip_invoked) {}
  1692. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  1693. {
  1694. Mutex::Lock _l(_nets_m);
  1695. NetworkState &n = _nets[nwid];
  1696. switch(op) {
  1697. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  1698. if (!n.tap) {
  1699. try {
  1700. char friendlyName[128];
  1701. OSUtils::ztsnprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  1702. n.tap = new EthernetTap(
  1703. _homePath.c_str(),
  1704. MAC(nwc->mac),
  1705. nwc->mtu,
  1706. (unsigned int)ZT_IF_METRIC,
  1707. nwid,
  1708. friendlyName,
  1709. StapFrameHandler,
  1710. (void *)this);
  1711. *nuptr = (void *)&n;
  1712. char nlcpath[256];
  1713. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1714. std::string nlcbuf;
  1715. if (OSUtils::readFile(nlcpath,nlcbuf)) {
  1716. Dictionary<4096> nc;
  1717. nc.load(nlcbuf.c_str());
  1718. Buffer<1024> allowManaged;
  1719. if (nc.get("allowManaged", allowManaged) && allowManaged.size() != 0) {
  1720. std::string addresses (allowManaged.begin(), allowManaged.size());
  1721. if (allowManaged.size() <= 5) { // untidy parsing for backward compatibility
  1722. if (allowManaged[0] == '1' || allowManaged[0] == 't' || allowManaged[0] == 'T') {
  1723. n.settings.allowManaged = true;
  1724. } else {
  1725. n.settings.allowManaged = false;
  1726. }
  1727. } else {
  1728. // this should be a list of IP addresses
  1729. n.settings.allowManaged = true;
  1730. size_t pos = 0;
  1731. while (true) {
  1732. size_t nextPos = addresses.find(',', pos);
  1733. std::string address = addresses.substr(pos, (nextPos == std::string::npos ? addresses.size() : nextPos) - pos);
  1734. n.settings.allowManagedWhitelist.push_back(InetAddress(address.c_str()));
  1735. if (nextPos == std::string::npos) break;
  1736. pos = nextPos + 1;
  1737. }
  1738. }
  1739. } else {
  1740. n.settings.allowManaged = true;
  1741. }
  1742. n.settings.allowGlobal = nc.getB("allowGlobal", false);
  1743. n.settings.allowDefault = nc.getB("allowDefault", false);
  1744. }
  1745. } catch (std::exception &exc) {
  1746. #ifdef __WINDOWS__
  1747. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1748. if (tapFailLog) {
  1749. fprintf(tapFailLog,"%.16llx: %s" ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1750. fclose(tapFailLog);
  1751. }
  1752. #else
  1753. fprintf(stderr,"ERROR: unable to configure virtual network port: %s" ZT_EOL_S,exc.what());
  1754. #endif
  1755. _nets.erase(nwid);
  1756. return -999;
  1757. } catch ( ... ) {
  1758. return -999; // tap init failed
  1759. }
  1760. }
  1761. // After setting up tap, fall through to CONFIG_UPDATE since we also want to do this...
  1762. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1763. ZT_FAST_MEMCPY(&(n.config),nwc,sizeof(ZT_VirtualNetworkConfig));
  1764. if (n.tap) { // sanity check
  1765. #ifdef __WINDOWS__
  1766. // wait for up to 5 seconds for the WindowsEthernetTap to actually be initialized
  1767. //
  1768. // without WindowsEthernetTap::isInitialized() returning true, the won't actually
  1769. // be online yet and setting managed routes on it will fail.
  1770. const int MAX_SLEEP_COUNT = 500;
  1771. for (int i = 0; !n.tap->isInitialized() && i < MAX_SLEEP_COUNT; i++) {
  1772. Sleep(10);
  1773. }
  1774. #endif
  1775. syncManagedStuff(n,true,true);
  1776. n.tap->setMtu(nwc->mtu);
  1777. } else {
  1778. _nets.erase(nwid);
  1779. return -999; // tap init failed
  1780. }
  1781. break;
  1782. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1783. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1784. if (n.tap) { // sanity check
  1785. #ifdef __WINDOWS__
  1786. std::string winInstanceId(n.tap->instanceId());
  1787. #endif
  1788. *nuptr = (void *)0;
  1789. delete n.tap;
  1790. _nets.erase(nwid);
  1791. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1792. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1793. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1794. #endif
  1795. if (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY) {
  1796. char nlcpath[256];
  1797. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1798. OSUtils::rm(nlcpath);
  1799. }
  1800. } else {
  1801. _nets.erase(nwid);
  1802. }
  1803. break;
  1804. }
  1805. return 0;
  1806. }
  1807. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1808. {
  1809. switch(event) {
  1810. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  1811. Mutex::Lock _l(_termReason_m);
  1812. _termReason = ONE_IDENTITY_COLLISION;
  1813. _fatalErrorMessage = "identity/address collision";
  1814. this->terminate();
  1815. } break;
  1816. case ZT_EVENT_TRACE: {
  1817. if (metaData) {
  1818. ::fprintf(stderr,"%s" ZT_EOL_S,(const char *)metaData);
  1819. ::fflush(stderr);
  1820. }
  1821. } break;
  1822. case ZT_EVENT_USER_MESSAGE: {
  1823. const ZT_UserMessage *um = reinterpret_cast<const ZT_UserMessage *>(metaData);
  1824. if ((um->typeId == ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE)&&(_updater)) {
  1825. _updater->handleSoftwareUpdateUserMessage(um->origin,um->data,um->length);
  1826. }
  1827. } break;
  1828. case ZT_EVENT_REMOTE_TRACE: {
  1829. const ZT_RemoteTrace *rt = reinterpret_cast<const ZT_RemoteTrace *>(metaData);
  1830. if ((rt)&&(rt->len > 0)&&(rt->len <= ZT_MAX_REMOTE_TRACE_SIZE)&&(rt->data))
  1831. _controller->handleRemoteTrace(*rt);
  1832. }
  1833. default:
  1834. break;
  1835. }
  1836. }
  1837. inline void nodeStatePutFunction(enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)
  1838. {
  1839. char p[1024];
  1840. FILE *f;
  1841. bool secure = false;
  1842. char dirname[1024];
  1843. dirname[0] = 0;
  1844. switch(type) {
  1845. case ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  1846. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str());
  1847. break;
  1848. case ZT_STATE_OBJECT_IDENTITY_SECRET:
  1849. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str());
  1850. secure = true;
  1851. break;
  1852. case ZT_STATE_OBJECT_PLANET:
  1853. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "planet",_homePath.c_str());
  1854. break;
  1855. case ZT_STATE_OBJECT_MOON:
  1856. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "moons.d",_homePath.c_str());
  1857. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.moon",dirname,(unsigned long long)id[0]);
  1858. break;
  1859. case ZT_STATE_OBJECT_NETWORK_CONFIG:
  1860. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "networks.d",_homePath.c_str());
  1861. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.conf",dirname,(unsigned long long)id[0]);
  1862. secure = true;
  1863. break;
  1864. case ZT_STATE_OBJECT_PEER:
  1865. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "peers.d",_homePath.c_str());
  1866. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.10llx.peer",dirname,(unsigned long long)id[0]);
  1867. break;
  1868. default:
  1869. return;
  1870. }
  1871. if (len >= 0) {
  1872. // Check to see if we've already written this first. This reduces
  1873. // redundant writes and I/O overhead on most platforms and has
  1874. // little effect on others.
  1875. f = fopen(p,"r");
  1876. if (f) {
  1877. char buf[65535];
  1878. long l = (long)fread(buf,1,sizeof(buf),f);
  1879. fclose(f);
  1880. if ((l == (long)len)&&(memcmp(data,buf,l) == 0))
  1881. return;
  1882. }
  1883. f = fopen(p,"w");
  1884. if ((!f)&&(dirname[0])) { // create subdirectory if it does not exist
  1885. OSUtils::mkdir(dirname);
  1886. f = fopen(p,"w");
  1887. }
  1888. if (f) {
  1889. if (fwrite(data,len,1,f) != 1)
  1890. fprintf(stderr,"WARNING: unable to write to file: %s (I/O error)" ZT_EOL_S,p);
  1891. fclose(f);
  1892. if (secure)
  1893. OSUtils::lockDownFile(p,false);
  1894. } else {
  1895. fprintf(stderr,"WARNING: unable to write to file: %s (unable to open)" ZT_EOL_S,p);
  1896. }
  1897. } else {
  1898. OSUtils::rm(p);
  1899. }
  1900. }
  1901. inline int nodeStateGetFunction(enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)
  1902. {
  1903. char p[4096];
  1904. switch(type) {
  1905. case ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  1906. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str());
  1907. break;
  1908. case ZT_STATE_OBJECT_IDENTITY_SECRET:
  1909. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str());
  1910. break;
  1911. case ZT_STATE_OBJECT_PLANET:
  1912. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "planet",_homePath.c_str());
  1913. break;
  1914. case ZT_STATE_OBJECT_MOON:
  1915. 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);
  1916. break;
  1917. case ZT_STATE_OBJECT_NETWORK_CONFIG:
  1918. 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);
  1919. break;
  1920. case ZT_STATE_OBJECT_PEER:
  1921. 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]);
  1922. break;
  1923. default:
  1924. return -1;
  1925. }
  1926. FILE *f = fopen(p,"r");
  1927. if (f) {
  1928. int n = (int)fread(data,1,maxlen,f);
  1929. fclose(f);
  1930. if (n >= 0)
  1931. return n;
  1932. }
  1933. return -1;
  1934. }
  1935. inline int nodeWirePacketSendFunction(const int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1936. {
  1937. #ifdef ZT_TCP_FALLBACK_RELAY
  1938. if (addr->ss_family == AF_INET) {
  1939. // TCP fallback tunnel support, currently IPv4 only
  1940. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  1941. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  1942. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  1943. // valid direct traffic we'll stop using it and close the socket after a while.
  1944. const int64_t now = OSUtils::now();
  1945. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  1946. if (_tcpFallbackTunnel) {
  1947. bool flushNow = false;
  1948. {
  1949. Mutex::Lock _l(_tcpFallbackTunnel->writeq_m);
  1950. if (_tcpFallbackTunnel->writeq.size() < (1024 * 64)) {
  1951. if (_tcpFallbackTunnel->writeq.length() == 0) {
  1952. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  1953. flushNow = true;
  1954. }
  1955. const unsigned long mlen = len + 7;
  1956. _tcpFallbackTunnel->writeq.push_back((char)0x17);
  1957. _tcpFallbackTunnel->writeq.push_back((char)0x03);
  1958. _tcpFallbackTunnel->writeq.push_back((char)0x03); // fake TLS 1.2 header
  1959. _tcpFallbackTunnel->writeq.push_back((char)((mlen >> 8) & 0xff));
  1960. _tcpFallbackTunnel->writeq.push_back((char)(mlen & 0xff));
  1961. _tcpFallbackTunnel->writeq.push_back((char)4); // IPv4
  1962. _tcpFallbackTunnel->writeq.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  1963. _tcpFallbackTunnel->writeq.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  1964. _tcpFallbackTunnel->writeq.append((const char *)data,len);
  1965. }
  1966. }
  1967. if (flushNow) {
  1968. void *tmpptr = (void *)_tcpFallbackTunnel;
  1969. phyOnTcpWritable(_tcpFallbackTunnel->sock,&tmpptr);
  1970. }
  1971. } else if (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INVERVAL / 2))) {
  1972. const InetAddress addr(ZT_TCP_FALLBACK_RELAY);
  1973. TcpConnection *tc = new TcpConnection();
  1974. {
  1975. Mutex::Lock _l(_tcpConnections_m);
  1976. _tcpConnections.push_back(tc);
  1977. }
  1978. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  1979. tc->remoteAddr = addr;
  1980. tc->lastReceive = OSUtils::now();
  1981. tc->parent = this;
  1982. tc->sock = (PhySocket *)0; // set in connect handler
  1983. tc->messageSize = 0;
  1984. bool connected = false;
  1985. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected,(void *)tc,true);
  1986. }
  1987. }
  1988. _lastSendToGlobalV4 = now;
  1989. }
  1990. }
  1991. // Even when relaying we still send via UDP. This way if UDP starts
  1992. // working we can instantly "fail forward" to it and stop using TCP
  1993. // proxy fallback, which is slow.
  1994. #endif // ZT_TCP_FALLBACK_RELAY
  1995. if ((localSocket != -1)&&(localSocket != 0)&&(_binder.isUdpSocketValid((PhySocket *)((uintptr_t)localSocket)))) {
  1996. if ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),ttl);
  1997. const bool r = _phy.udpSend((PhySocket *)((uintptr_t)localSocket),(const struct sockaddr *)addr,data,len);
  1998. if ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),255);
  1999. return ((r) ? 0 : -1);
  2000. } else {
  2001. return ((_binder.udpSendAll(_phy,addr,data,len,ttl)) ? 0 : -1);
  2002. }
  2003. }
  2004. 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)
  2005. {
  2006. NetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);
  2007. if ((!n)||(!n->tap))
  2008. return;
  2009. n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  2010. }
  2011. inline int nodePathCheckFunction(uint64_t ztaddr,const int64_t localSocket,const struct sockaddr_storage *remoteAddr)
  2012. {
  2013. // Make sure we're not trying to do ZeroTier-over-ZeroTier
  2014. {
  2015. Mutex::Lock _l(_nets_m);
  2016. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  2017. if (n->second.tap) {
  2018. std::vector<InetAddress> ips(n->second.tap->ips());
  2019. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  2020. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  2021. return 0;
  2022. }
  2023. }
  2024. }
  2025. }
  2026. }
  2027. /* Note: I do not think we need to scan for overlap with managed routes
  2028. * because of the "route forking" and interface binding that we do. This
  2029. * ensures (we hope) that ZeroTier traffic will still take the physical
  2030. * path even if its managed routes override this for other traffic. Will
  2031. * revisit if we see recursion problems. */
  2032. // Check blacklists
  2033. const Hashtable< uint64_t,std::vector<InetAddress> > *blh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  2034. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  2035. if (remoteAddr->ss_family == AF_INET) {
  2036. blh = &_v4Blacklists;
  2037. gbl = &_globalV4Blacklist;
  2038. } else if (remoteAddr->ss_family == AF_INET6) {
  2039. blh = &_v6Blacklists;
  2040. gbl = &_globalV6Blacklist;
  2041. }
  2042. if (blh) {
  2043. Mutex::Lock _l(_localConfig_m);
  2044. const std::vector<InetAddress> *l = blh->get(ztaddr);
  2045. if (l) {
  2046. for(std::vector<InetAddress>::const_iterator a(l->begin());a!=l->end();++a) {
  2047. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  2048. return 0;
  2049. }
  2050. }
  2051. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  2052. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  2053. return 0;
  2054. }
  2055. }
  2056. return 1;
  2057. }
  2058. inline int nodePathLookupFunction(uint64_t ztaddr,int family,struct sockaddr_storage *result)
  2059. {
  2060. const Hashtable< uint64_t,std::vector<InetAddress> > *lh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  2061. if (family < 0)
  2062. lh = (_node->prng() & 1) ? &_v4Hints : &_v6Hints;
  2063. else if (family == AF_INET)
  2064. lh = &_v4Hints;
  2065. else if (family == AF_INET6)
  2066. lh = &_v6Hints;
  2067. else return 0;
  2068. const std::vector<InetAddress> *l = lh->get(ztaddr);
  2069. if ((l)&&(l->size() > 0)) {
  2070. ZT_FAST_MEMCPY(result,&((*l)[(unsigned long)_node->prng() % l->size()]),sizeof(struct sockaddr_storage));
  2071. return 1;
  2072. } else return 0;
  2073. }
  2074. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  2075. {
  2076. _node->processVirtualNetworkFrame((void *)0,OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  2077. }
  2078. inline void onHttpRequestToServer(TcpConnection *tc)
  2079. {
  2080. char tmpn[4096];
  2081. std::string data;
  2082. std::string contentType("text/plain"); // default if not changed in handleRequest()
  2083. unsigned int scode = 404;
  2084. // Note that we check allowed IP ranges when HTTP connections are first detected in
  2085. // phyOnTcpData(). If we made it here the source IP is okay.
  2086. try {
  2087. scode = handleControlPlaneHttpRequest(tc->remoteAddr,tc->parser.method,tc->url,tc->headers,tc->readq,data,contentType);
  2088. } catch (std::exception &exc) {
  2089. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: %s" ZT_EOL_S,exc.what());
  2090. scode = 500;
  2091. } catch ( ... ) {
  2092. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: unknown exception" ZT_EOL_S);
  2093. scode = 500;
  2094. }
  2095. const char *scodestr;
  2096. switch(scode) {
  2097. case 200: scodestr = "OK"; break;
  2098. case 400: scodestr = "Bad Request"; break;
  2099. case 401: scodestr = "Unauthorized"; break;
  2100. case 403: scodestr = "Forbidden"; break;
  2101. case 404: scodestr = "Not Found"; break;
  2102. case 500: scodestr = "Internal Server Error"; break;
  2103. case 501: scodestr = "Not Implemented"; break;
  2104. case 503: scodestr = "Service Unavailable"; break;
  2105. default: scodestr = "Error"; break;
  2106. }
  2107. 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",
  2108. scode,
  2109. scodestr,
  2110. contentType.c_str(),
  2111. (unsigned long)data.length());
  2112. {
  2113. Mutex::Lock _l(tc->writeq_m);
  2114. tc->writeq = tmpn;
  2115. if (tc->parser.method != HTTP_HEAD)
  2116. tc->writeq.append(data);
  2117. }
  2118. _phy.setNotifyWritable(tc->sock,true);
  2119. }
  2120. inline void onHttpResponseFromClient(TcpConnection *tc)
  2121. {
  2122. _phy.close(tc->sock);
  2123. }
  2124. bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
  2125. {
  2126. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  2127. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  2128. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  2129. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  2130. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  2131. #endif
  2132. #ifdef __APPLE__
  2133. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  2134. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  2135. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  2136. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  2137. if ((ifname[0] == 'u')&&(ifname[1] == 't')&&(ifname[2] == 'u')&&(ifname[3] == 'n')) return false; // ... as is utun#
  2138. #endif
  2139. {
  2140. Mutex::Lock _l(_localConfig_m);
  2141. for(std::vector<std::string>::const_iterator p(_interfacePrefixBlacklist.begin());p!=_interfacePrefixBlacklist.end();++p) {
  2142. if (!strncmp(p->c_str(),ifname,p->length()))
  2143. return false;
  2144. }
  2145. }
  2146. {
  2147. Mutex::Lock _l(_nets_m);
  2148. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  2149. if (n->second.tap) {
  2150. std::vector<InetAddress> ips(n->second.tap->ips());
  2151. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  2152. if (i->ipsEqual(ifaddr))
  2153. return false;
  2154. }
  2155. }
  2156. }
  2157. }
  2158. return true;
  2159. }
  2160. bool _trialBind(unsigned int port)
  2161. {
  2162. struct sockaddr_in in4;
  2163. struct sockaddr_in6 in6;
  2164. PhySocket *tb;
  2165. memset(&in4,0,sizeof(in4));
  2166. in4.sin_family = AF_INET;
  2167. in4.sin_port = Utils::hton((uint16_t)port);
  2168. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
  2169. if (tb) {
  2170. _phy.close(tb,false);
  2171. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
  2172. if (tb) {
  2173. _phy.close(tb,false);
  2174. return true;
  2175. }
  2176. }
  2177. memset(&in6,0,sizeof(in6));
  2178. in6.sin6_family = AF_INET6;
  2179. in6.sin6_port = Utils::hton((uint16_t)port);
  2180. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
  2181. if (tb) {
  2182. _phy.close(tb,false);
  2183. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
  2184. if (tb) {
  2185. _phy.close(tb,false);
  2186. return true;
  2187. }
  2188. }
  2189. return false;
  2190. }
  2191. };
  2192. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  2193. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  2194. static void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData)
  2195. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  2196. static void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)
  2197. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeStatePutFunction(type,id,data,len); }
  2198. static int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)
  2199. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeStateGetFunction(type,id,data,maxlen); }
  2200. 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)
  2201. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localSocket,addr,data,len,ttl); }
  2202. 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)
  2203. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  2204. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr)
  2205. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(ztaddr,localSocket,remoteAddr); }
  2206. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result)
  2207. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathLookupFunction(ztaddr,family,result); }
  2208. 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)
  2209. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  2210. static int ShttpOnMessageBegin(http_parser *parser)
  2211. {
  2212. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2213. tc->currentHeaderField = "";
  2214. tc->currentHeaderValue = "";
  2215. tc->messageSize = 0;
  2216. tc->url.clear();
  2217. tc->status.clear();
  2218. tc->headers.clear();
  2219. tc->readq.clear();
  2220. return 0;
  2221. }
  2222. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  2223. {
  2224. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2225. tc->messageSize += (unsigned long)length;
  2226. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2227. return -1;
  2228. tc->url.append(ptr,length);
  2229. return 0;
  2230. }
  2231. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  2232. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  2233. #else
  2234. static int ShttpOnStatus(http_parser *parser)
  2235. #endif
  2236. { return 0; }
  2237. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  2238. {
  2239. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2240. tc->messageSize += (unsigned long)length;
  2241. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2242. return -1;
  2243. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  2244. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  2245. tc->currentHeaderField = "";
  2246. tc->currentHeaderValue = "";
  2247. }
  2248. for(size_t i=0;i<length;++i)
  2249. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  2250. return 0;
  2251. }
  2252. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  2253. {
  2254. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2255. tc->messageSize += (unsigned long)length;
  2256. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2257. return -1;
  2258. tc->currentHeaderValue.append(ptr,length);
  2259. return 0;
  2260. }
  2261. static int ShttpOnHeadersComplete(http_parser *parser)
  2262. {
  2263. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2264. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  2265. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  2266. return 0;
  2267. }
  2268. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  2269. {
  2270. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2271. tc->messageSize += (unsigned long)length;
  2272. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2273. return -1;
  2274. tc->readq.append(ptr,length);
  2275. return 0;
  2276. }
  2277. static int ShttpOnMessageComplete(http_parser *parser)
  2278. {
  2279. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2280. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  2281. tc->parent->onHttpRequestToServer(tc);
  2282. } else {
  2283. tc->parent->onHttpResponseFromClient(tc);
  2284. }
  2285. return 0;
  2286. }
  2287. } // anonymous namespace
  2288. std::string OneService::platformDefaultHomePath()
  2289. {
  2290. return OSUtils::platformDefaultHomePath();
  2291. }
  2292. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  2293. OneService::~OneService() {}
  2294. } // namespace ZeroTier