OneService.cpp 90 KB

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