OneService.cpp 90 KB

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