OneService.cpp 90 KB

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