OneService.cpp 87 KB

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