OneService.cpp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040
  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 "../osdep/Phy.hpp"
  38. #include "../osdep/Thread.hpp"
  39. #include "../osdep/OSUtils.hpp"
  40. #include "../osdep/Http.hpp"
  41. #include "../osdep/BackgroundResolver.hpp"
  42. #include "../osdep/PortMapper.hpp"
  43. #include "../osdep/Binder.hpp"
  44. #include "../osdep/ManagedRoute.hpp"
  45. #include "OneService.hpp"
  46. #include "ControlPlane.hpp"
  47. #include "ClusterGeoIpService.hpp"
  48. #include "ClusterDefinition.hpp"
  49. #include "SoftwareUpdater.hpp"
  50. #ifdef ZT_USE_SYSTEM_HTTP_PARSER
  51. #include <http_parser.h>
  52. #else
  53. #include "../ext/http-parser/http_parser.h"
  54. #endif
  55. #include "../ext/json/json.hpp"
  56. using json = nlohmann::json;
  57. /**
  58. * Uncomment to enable UDP breakage switch
  59. *
  60. * If this is defined, the presence of a file called /tmp/ZT_BREAK_UDP
  61. * will cause direct UDP TX/RX to stop working. This can be used to
  62. * test TCP tunneling fallback and other robustness features. Deleting
  63. * this file will cause it to start working again.
  64. */
  65. //#define ZT_BREAK_UDP
  66. #include "../controller/EmbeddedNetworkController.hpp"
  67. #ifdef __WINDOWS__
  68. #include <WinSock2.h>
  69. #include <Windows.h>
  70. #include <ShlObj.h>
  71. #include <netioapi.h>
  72. #include <iphlpapi.h>
  73. #else
  74. #include <sys/types.h>
  75. #include <sys/socket.h>
  76. #include <sys/wait.h>
  77. #include <unistd.h>
  78. #include <ifaddrs.h>
  79. #endif
  80. // Include the right tap device driver for this platform -- add new platforms here
  81. #ifdef ZT_SERVICE_NETCON
  82. // In network containers builds, use the virtual netcon endpoint instead of a tun/tap port driver
  83. #include "../netcon/NetconEthernetTap.hpp"
  84. namespace ZeroTier { typedef NetconEthernetTap EthernetTap; }
  85. #else // not ZT_SERVICE_NETCON so pick a tap driver
  86. #ifdef __APPLE__
  87. #include "../osdep/OSXEthernetTap.hpp"
  88. namespace ZeroTier { typedef OSXEthernetTap EthernetTap; }
  89. #endif // __APPLE__
  90. #ifdef __LINUX__
  91. #include "../osdep/LinuxEthernetTap.hpp"
  92. namespace ZeroTier { typedef LinuxEthernetTap EthernetTap; }
  93. #endif // __LINUX__
  94. #ifdef __WINDOWS__
  95. #include "../osdep/WindowsEthernetTap.hpp"
  96. namespace ZeroTier { typedef WindowsEthernetTap EthernetTap; }
  97. #endif // __WINDOWS__
  98. #ifdef __FreeBSD__
  99. #include "../osdep/BSDEthernetTap.hpp"
  100. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  101. #endif // __FreeBSD__
  102. #ifdef __OpenBSD__
  103. #include "../osdep/BSDEthernetTap.hpp"
  104. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  105. #endif // __OpenBSD__
  106. #endif // ZT_SERVICE_NETCON
  107. // Sanity limits for HTTP
  108. #define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 64)
  109. #define ZT_MAX_HTTP_CONNECTIONS 64
  110. // Interface metric for ZeroTier taps -- this ensures that if we are on WiFi and also
  111. // bridged via ZeroTier to the same LAN traffic will (if the OS is sane) prefer WiFi.
  112. #define ZT_IF_METRIC 5000
  113. // How often to check for new multicast subscriptions on a tap device
  114. #define ZT_TAP_CHECK_MULTICAST_INTERVAL 5000
  115. // Path under ZT1 home for controller database if controller is enabled
  116. #define ZT_CONTROLLER_DB_PATH "controller.d"
  117. // TCP fallback relay host -- geo-distributed using Amazon Route53 geo-aware DNS
  118. #define ZT_TCP_FALLBACK_RELAY "tcp-fallback.zerotier.com"
  119. #define ZT_TCP_FALLBACK_RELAY_PORT 443
  120. // Frequency at which we re-resolve the TCP fallback relay
  121. #define ZT_TCP_FALLBACK_RERESOLVE_DELAY 86400000
  122. // Attempt to engage TCP fallback after this many ms of no reply to packets sent to global-scope IPs
  123. #define ZT_TCP_FALLBACK_AFTER 60000
  124. // How often to check for local interface addresses
  125. #define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 60000
  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. class OneServiceImpl;
  147. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
  148. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData);
  149. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize);
  150. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure);
  151. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl);
  152. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  153. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr);
  154. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,int family,struct sockaddr_storage *result);
  155. #ifdef ZT_ENABLE_CLUSTER
  156. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len);
  157. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z);
  158. #endif
  159. static void StapFrameHandler(void *uptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  160. static int ShttpOnMessageBegin(http_parser *parser);
  161. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  162. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  163. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  164. #else
  165. static int ShttpOnStatus(http_parser *parser);
  166. #endif
  167. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  168. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  169. static int ShttpOnHeadersComplete(http_parser *parser);
  170. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  171. static int ShttpOnMessageComplete(http_parser *parser);
  172. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 1)
  173. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  174. ShttpOnMessageBegin,
  175. ShttpOnUrl,
  176. ShttpOnStatus,
  177. ShttpOnHeaderField,
  178. ShttpOnValue,
  179. ShttpOnHeadersComplete,
  180. ShttpOnBody,
  181. ShttpOnMessageComplete
  182. };
  183. #else
  184. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  185. ShttpOnMessageBegin,
  186. ShttpOnUrl,
  187. ShttpOnHeaderField,
  188. ShttpOnValue,
  189. ShttpOnHeadersComplete,
  190. ShttpOnBody,
  191. ShttpOnMessageComplete
  192. };
  193. #endif
  194. struct TcpConnection
  195. {
  196. enum {
  197. TCP_HTTP_INCOMING,
  198. TCP_HTTP_OUTGOING, // not currently used
  199. TCP_TUNNEL_OUTGOING // fale-SSL outgoing tunnel -- HTTP-related fields are not used
  200. } type;
  201. bool shouldKeepAlive;
  202. OneServiceImpl *parent;
  203. PhySocket *sock;
  204. InetAddress from;
  205. http_parser parser;
  206. unsigned long messageSize;
  207. uint64_t lastActivity;
  208. std::string currentHeaderField;
  209. std::string currentHeaderValue;
  210. std::string url;
  211. std::string status;
  212. std::map< std::string,std::string > headers;
  213. std::string body;
  214. std::string writeBuf;
  215. Mutex writeBuf_m;
  216. };
  217. // Used to pseudo-randomize local source port picking
  218. static volatile unsigned int _udpPortPickerCounter = 0;
  219. class OneServiceImpl : public OneService
  220. {
  221. public:
  222. // begin member variables --------------------------------------------------
  223. const std::string _homePath;
  224. BackgroundResolver _tcpFallbackResolver;
  225. EmbeddedNetworkController *_controller;
  226. Phy<OneServiceImpl *> _phy;
  227. Node *_node;
  228. SoftwareUpdater *_updater;
  229. bool _updateAutoApply;
  230. unsigned int _primaryPort;
  231. // Local configuration and memo-ized static path definitions
  232. json _localConfig;
  233. Hashtable< uint64_t,std::vector<InetAddress> > _v4Hints;
  234. Hashtable< uint64_t,std::vector<InetAddress> > _v6Hints;
  235. Hashtable< uint64_t,std::vector<InetAddress> > _v4Blacklists;
  236. Hashtable< uint64_t,std::vector<InetAddress> > _v6Blacklists;
  237. std::vector< InetAddress > _globalV4Blacklist;
  238. std::vector< InetAddress > _globalV6Blacklist;
  239. std::vector< InetAddress > _allowManagementFrom;
  240. std::vector< std::string > _interfacePrefixBlacklist;
  241. Mutex _localConfig_m;
  242. /*
  243. * To attempt to handle NAT/gateway craziness we use three local UDP ports:
  244. *
  245. * [0] is the normal/default port, usually 9993
  246. * [1] is a port dervied from our ZeroTier address
  247. * [2] is a port computed from the normal/default for use with uPnP/NAT-PMP mappings
  248. *
  249. * [2] exists because on some gateways trying to do regular NAT-t interferes
  250. * destructively with uPnP port mapping behavior in very weird buggy ways.
  251. * It's only used if uPnP/NAT-PMP is enabled in this build.
  252. */
  253. Binder _bindings[3];
  254. unsigned int _ports[3];
  255. uint16_t _portsBE[3]; // ports in big-endian network byte order as in sockaddr
  256. // Sockets for JSON API -- bound only to V4 and V6 localhost
  257. PhySocket *_v4TcpControlSocket;
  258. PhySocket *_v6TcpControlSocket;
  259. // JSON API handler
  260. ControlPlane *_controlPlane;
  261. // Time we last received a packet from a global address
  262. uint64_t _lastDirectReceiveFromGlobal;
  263. #ifdef ZT_TCP_FALLBACK_RELAY
  264. uint64_t _lastSendToGlobalV4;
  265. #endif
  266. // Last potential sleep/wake event
  267. uint64_t _lastRestart;
  268. // Deadline for the next background task service function
  269. volatile uint64_t _nextBackgroundTaskDeadline;
  270. // Configured networks
  271. struct NetworkState
  272. {
  273. NetworkState() :
  274. tap((EthernetTap *)0)
  275. {
  276. // Real defaults are in network 'up' code in network event handler
  277. settings.allowManaged = true;
  278. settings.allowGlobal = false;
  279. settings.allowDefault = false;
  280. }
  281. EthernetTap *tap;
  282. ZT_VirtualNetworkConfig config; // memcpy() of raw config from core
  283. std::vector<InetAddress> managedIps;
  284. std::list< SharedPtr<ManagedRoute> > managedRoutes;
  285. NetworkSettings settings;
  286. };
  287. std::map<uint64_t,NetworkState> _nets;
  288. Mutex _nets_m;
  289. // Active TCP/IP connections
  290. std::set< TcpConnection * > _tcpConnections; // no mutex for this since it's done in the main loop thread only
  291. TcpConnection *_tcpFallbackTunnel;
  292. // Termination status information
  293. ReasonForTermination _termReason;
  294. std::string _fatalErrorMessage;
  295. Mutex _termReason_m;
  296. // uPnP/NAT-PMP port mapper if enabled
  297. bool _portMappingEnabled; // local.conf settings
  298. #ifdef ZT_USE_MINIUPNPC
  299. PortMapper *_portMapper;
  300. #endif
  301. // Cluster management instance if enabled
  302. #ifdef ZT_ENABLE_CLUSTER
  303. PhySocket *_clusterMessageSocket;
  304. ClusterDefinition *_clusterDefinition;
  305. unsigned int _clusterMemberId;
  306. #endif
  307. // Set to false to force service to stop
  308. volatile bool _run;
  309. Mutex _run_m;
  310. // end member variables ----------------------------------------------------
  311. OneServiceImpl(const char *hp,unsigned int port) :
  312. _homePath((hp) ? hp : ".")
  313. ,_tcpFallbackResolver(ZT_TCP_FALLBACK_RELAY)
  314. ,_controller((EmbeddedNetworkController *)0)
  315. ,_phy(this,false,true)
  316. ,_node((Node *)0)
  317. ,_updater((SoftwareUpdater *)0)
  318. ,_updateAutoApply(false)
  319. ,_primaryPort(port)
  320. ,_controlPlane((ControlPlane *)0)
  321. ,_lastDirectReceiveFromGlobal(0)
  322. #ifdef ZT_TCP_FALLBACK_RELAY
  323. ,_lastSendToGlobalV4(0)
  324. #endif
  325. ,_lastRestart(0)
  326. ,_nextBackgroundTaskDeadline(0)
  327. ,_tcpFallbackTunnel((TcpConnection *)0)
  328. ,_termReason(ONE_STILL_RUNNING)
  329. ,_portMappingEnabled(true)
  330. #ifdef ZT_USE_MINIUPNPC
  331. ,_portMapper((PortMapper *)0)
  332. #endif
  333. #ifdef ZT_ENABLE_CLUSTER
  334. ,_clusterMessageSocket((PhySocket *)0)
  335. ,_clusterDefinition((ClusterDefinition *)0)
  336. ,_clusterMemberId(0)
  337. #endif
  338. ,_run(true)
  339. {
  340. _ports[0] = 0;
  341. _ports[1] = 0;
  342. _ports[2] = 0;
  343. }
  344. virtual ~OneServiceImpl()
  345. {
  346. for(int i=0;i<3;++i)
  347. _bindings[i].closeAll(_phy);
  348. _phy.close(_v4TcpControlSocket);
  349. _phy.close(_v6TcpControlSocket);
  350. #ifdef ZT_ENABLE_CLUSTER
  351. _phy.close(_clusterMessageSocket);
  352. #endif
  353. #ifdef ZT_USE_MINIUPNPC
  354. delete _portMapper;
  355. #endif
  356. delete _controller;
  357. #ifdef ZT_ENABLE_CLUSTER
  358. delete _clusterDefinition;
  359. #endif
  360. }
  361. virtual ReasonForTermination run()
  362. {
  363. try {
  364. std::string authToken;
  365. {
  366. std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  367. if (!OSUtils::readFile(authTokenPath.c_str(),authToken)) {
  368. unsigned char foo[24];
  369. Utils::getSecureRandom(foo,sizeof(foo));
  370. authToken = "";
  371. for(unsigned int i=0;i<sizeof(foo);++i)
  372. authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  373. if (!OSUtils::writeFile(authTokenPath.c_str(),authToken)) {
  374. Mutex::Lock _l(_termReason_m);
  375. _termReason = ONE_UNRECOVERABLE_ERROR;
  376. _fatalErrorMessage = "authtoken.secret could not be written";
  377. return _termReason;
  378. } else {
  379. OSUtils::lockDownFile(authTokenPath.c_str(),false);
  380. }
  381. }
  382. }
  383. authToken = _trimString(authToken);
  384. // Clean up any legacy files if present
  385. OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S + "peers.save").c_str());
  386. {
  387. struct ZT_Node_Callbacks cb;
  388. cb.version = 0;
  389. cb.dataStoreGetFunction = SnodeDataStoreGetFunction;
  390. cb.dataStorePutFunction = SnodeDataStorePutFunction;
  391. cb.wirePacketSendFunction = SnodeWirePacketSendFunction;
  392. cb.virtualNetworkFrameFunction = SnodeVirtualNetworkFrameFunction;
  393. cb.virtualNetworkConfigFunction = SnodeVirtualNetworkConfigFunction;
  394. cb.eventCallback = SnodeEventCallback;
  395. cb.pathCheckFunction = SnodePathCheckFunction;
  396. cb.pathLookupFunction = SnodePathLookupFunction;
  397. _node = new Node(this,&cb,OSUtils::now());
  398. }
  399. // Read local configuration
  400. {
  401. uint64_t trustedPathIds[ZT_MAX_TRUSTED_PATHS];
  402. InetAddress trustedPathNetworks[ZT_MAX_TRUSTED_PATHS];
  403. unsigned int trustedPathCount = 0;
  404. // Old style "trustedpaths" flat file -- will eventually go away
  405. FILE *trustpaths = fopen((_homePath + ZT_PATH_SEPARATOR_S + "trustedpaths").c_str(),"r");
  406. if (trustpaths) {
  407. char buf[1024];
  408. while ((fgets(buf,sizeof(buf),trustpaths))&&(trustedPathCount < ZT_MAX_TRUSTED_PATHS)) {
  409. int fno = 0;
  410. char *saveptr = (char *)0;
  411. uint64_t trustedPathId = 0;
  412. InetAddress trustedPathNetwork;
  413. for(char *f=Utils::stok(buf,"=\r\n \t",&saveptr);(f);f=Utils::stok((char *)0,"=\r\n \t",&saveptr)) {
  414. if (fno == 0) {
  415. trustedPathId = Utils::hexStrToU64(f);
  416. } else if (fno == 1) {
  417. trustedPathNetwork = InetAddress(f);
  418. } else break;
  419. ++fno;
  420. }
  421. if ( (trustedPathId != 0) && ((trustedPathNetwork.ss_family == AF_INET)||(trustedPathNetwork.ss_family == AF_INET6)) && (trustedPathNetwork.ipScope() != InetAddress::IP_SCOPE_GLOBAL) && (trustedPathNetwork.netmaskBits() > 0) ) {
  422. trustedPathIds[trustedPathCount] = trustedPathId;
  423. trustedPathNetworks[trustedPathCount] = trustedPathNetwork;
  424. ++trustedPathCount;
  425. }
  426. }
  427. fclose(trustpaths);
  428. }
  429. // Read local config file
  430. Mutex::Lock _l2(_localConfig_m);
  431. std::string lcbuf;
  432. if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S + "local.conf").c_str(),lcbuf)) {
  433. try {
  434. _localConfig = OSUtils::jsonParse(lcbuf);
  435. if (!_localConfig.is_object()) {
  436. fprintf(stderr,"WARNING: unable to parse local.conf (root element is not a JSON object)" ZT_EOL_S);
  437. }
  438. } catch ( ... ) {
  439. fprintf(stderr,"WARNING: unable to parse local.conf (invalid JSON)" ZT_EOL_S);
  440. }
  441. }
  442. // Get any trusted paths in local.conf (we'll parse the rest of physical[] elsewhere)
  443. json &physical = _localConfig["physical"];
  444. if (physical.is_object()) {
  445. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  446. InetAddress net(OSUtils::jsonString(phy.key(),""));
  447. if (net) {
  448. if (phy.value().is_object()) {
  449. uint64_t tpid;
  450. if ((tpid = OSUtils::jsonInt(phy.value()["trustedPathId"],0ULL)) != 0ULL) {
  451. 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) ) {
  452. trustedPathIds[trustedPathCount] = tpid;
  453. trustedPathNetworks[trustedPathCount] = net;
  454. ++trustedPathCount;
  455. }
  456. }
  457. }
  458. }
  459. }
  460. }
  461. // Set trusted paths if there are any
  462. if (trustedPathCount)
  463. _node->setTrustedPaths(reinterpret_cast<const struct sockaddr_storage *>(trustedPathNetworks),trustedPathIds,trustedPathCount);
  464. }
  465. applyLocalConfig();
  466. // Bind TCP control socket
  467. const int portTrials = (_primaryPort == 0) ? 256 : 1; // if port is 0, pick random
  468. for(int k=0;k<portTrials;++k) {
  469. if (_primaryPort == 0) {
  470. unsigned int randp = 0;
  471. Utils::getSecureRandom(&randp,sizeof(randp));
  472. _primaryPort = 20000 + (randp % 45500);
  473. }
  474. if (_trialBind(_primaryPort)) {
  475. struct sockaddr_in in4;
  476. memset(&in4,0,sizeof(in4));
  477. in4.sin_family = AF_INET;
  478. 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
  479. in4.sin_port = Utils::hton((uint16_t)_primaryPort);
  480. _v4TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
  481. struct sockaddr_in6 in6;
  482. memset((void *)&in6,0,sizeof(in6));
  483. in6.sin6_family = AF_INET6;
  484. in6.sin6_port = in4.sin_port;
  485. if (_allowManagementFrom.size() == 0)
  486. in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
  487. _v6TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
  488. // We must bind one of IPv4 or IPv6 -- support either failing to support hosts that
  489. // have only IPv4 or only IPv6 stacks.
  490. if ((_v4TcpControlSocket)||(_v6TcpControlSocket)) {
  491. _ports[0] = _primaryPort;
  492. break;
  493. } else {
  494. if (_v4TcpControlSocket)
  495. _phy.close(_v4TcpControlSocket,false);
  496. if (_v6TcpControlSocket)
  497. _phy.close(_v6TcpControlSocket,false);
  498. _primaryPort = 0;
  499. }
  500. } else {
  501. _primaryPort = 0;
  502. }
  503. }
  504. if (_ports[0] == 0) {
  505. Mutex::Lock _l(_termReason_m);
  506. _termReason = ONE_UNRECOVERABLE_ERROR;
  507. _fatalErrorMessage = "cannot bind to local control interface port";
  508. return _termReason;
  509. }
  510. // Write file containing primary port to be read by CLIs, etc.
  511. char portstr[64];
  512. Utils::snprintf(portstr,sizeof(portstr),"%u",_ports[0]);
  513. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),std::string(portstr));
  514. // Attempt to bind to a secondary port chosen from our ZeroTier address.
  515. // This exists because there are buggy NATs out there that fail if more
  516. // than one device behind the same NAT tries to use the same internal
  517. // private address port number.
  518. _ports[1] = 20000 + ((unsigned int)_node->address() % 45500);
  519. for(int i=0;;++i) {
  520. if (i > 1000) {
  521. _ports[1] = 0;
  522. break;
  523. } else if (++_ports[1] >= 65536) {
  524. _ports[1] = 20000;
  525. }
  526. if (_trialBind(_ports[1]))
  527. break;
  528. }
  529. #ifdef ZT_USE_MINIUPNPC
  530. if (_portMappingEnabled) {
  531. // If we're running uPnP/NAT-PMP, bind a *third* port for that. We can't
  532. // use the other two ports for that because some NATs do really funky
  533. // stuff with ports that are explicitly mapped that breaks things.
  534. if (_ports[1]) {
  535. _ports[2] = _ports[1];
  536. for(int i=0;;++i) {
  537. if (i > 1000) {
  538. _ports[2] = 0;
  539. break;
  540. } else if (++_ports[2] >= 65536) {
  541. _ports[2] = 20000;
  542. }
  543. if (_trialBind(_ports[2]))
  544. break;
  545. }
  546. if (_ports[2]) {
  547. char uniqueName[64];
  548. Utils::snprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]);
  549. _portMapper = new PortMapper(_ports[2],uniqueName);
  550. }
  551. }
  552. }
  553. #endif
  554. // Populate ports in big-endian format for quick compare
  555. for(int i=0;i<3;++i)
  556. _portsBE[i] = Utils::hton((uint16_t)_ports[i]);
  557. // Check for legacy controller.db and terminate if present to prevent nasty surprises for DIY controller folks
  558. if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S "controller.db").c_str())) {
  559. Mutex::Lock _l(_termReason_m);
  560. _termReason = ONE_UNRECOVERABLE_ERROR;
  561. _fatalErrorMessage = "controller.db is present in our home path! run migrate-sqlite to migrate to new controller.d format.";
  562. return _termReason;
  563. }
  564. _controller = new EmbeddedNetworkController(_node,(_homePath + ZT_PATH_SEPARATOR_S ZT_CONTROLLER_DB_PATH).c_str(),(FILE *)0);
  565. _node->setNetconfMaster((void *)_controller);
  566. #ifdef ZT_ENABLE_CLUSTER
  567. if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str())) {
  568. _clusterDefinition = new ClusterDefinition(_node->address(),(_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str());
  569. if (_clusterDefinition->size() > 0) {
  570. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  571. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  572. PhySocket *cs = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&(m->clusterEndpoint)));
  573. if (cs) {
  574. if (_clusterMessageSocket) {
  575. _phy.close(_clusterMessageSocket,false);
  576. _phy.close(cs,false);
  577. Mutex::Lock _l(_termReason_m);
  578. _termReason = ONE_UNRECOVERABLE_ERROR;
  579. _fatalErrorMessage = "cluster: can't determine my cluster member ID: able to bind more than one cluster message socket IP/port!";
  580. return _termReason;
  581. }
  582. _clusterMessageSocket = cs;
  583. _clusterMemberId = m->id;
  584. }
  585. }
  586. if (!_clusterMessageSocket) {
  587. Mutex::Lock _l(_termReason_m);
  588. _termReason = ONE_UNRECOVERABLE_ERROR;
  589. _fatalErrorMessage = "cluster: can't determine my cluster member ID: unable to bind to any cluster message socket IP/port.";
  590. return _termReason;
  591. }
  592. const ClusterDefinition::MemberDefinition &me = (*_clusterDefinition)[_clusterMemberId];
  593. InetAddress endpoints[255];
  594. unsigned int numEndpoints = 0;
  595. for(std::vector<InetAddress>::const_iterator i(me.zeroTierEndpoints.begin());i!=me.zeroTierEndpoints.end();++i)
  596. endpoints[numEndpoints++] = *i;
  597. 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) {
  598. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  599. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  600. if (m->id != _clusterMemberId)
  601. _node->clusterAddMember(m->id);
  602. }
  603. }
  604. } else {
  605. delete _clusterDefinition;
  606. _clusterDefinition = (ClusterDefinition *)0;
  607. }
  608. }
  609. #endif
  610. _controlPlane = new ControlPlane(this,_node,(_homePath + ZT_PATH_SEPARATOR_S + "ui").c_str());
  611. _controlPlane->addAuthToken(authToken.c_str());
  612. _controlPlane->setController(_controller);
  613. { // Remember networks from previous session
  614. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S + "networks.d").c_str()));
  615. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  616. std::size_t dot = f->find_last_of('.');
  617. if ((dot == 16)&&(f->substr(16) == ".conf"))
  618. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()),(void *)0);
  619. }
  620. }
  621. _nextBackgroundTaskDeadline = 0;
  622. uint64_t clockShouldBe = OSUtils::now();
  623. _lastRestart = clockShouldBe;
  624. uint64_t lastTapMulticastGroupCheck = 0;
  625. uint64_t lastTcpFallbackResolve = 0;
  626. uint64_t lastBindRefresh = 0;
  627. uint64_t lastUpdateCheck = clockShouldBe;
  628. 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
  629. for(;;) {
  630. _run_m.lock();
  631. if (!_run) {
  632. _run_m.unlock();
  633. _termReason_m.lock();
  634. _termReason = ONE_NORMAL_TERMINATION;
  635. _termReason_m.unlock();
  636. break;
  637. } else {
  638. _run_m.unlock();
  639. }
  640. const uint64_t now = OSUtils::now();
  641. // Attempt to detect sleep/wake events by detecting delay overruns
  642. bool restarted = false;
  643. if ((now > clockShouldBe)&&((now - clockShouldBe) > 10000)) {
  644. _lastRestart = now;
  645. restarted = true;
  646. }
  647. // Check for updates (if enabled)
  648. if ((_updater)&&((now - lastUpdateCheck) > 10000)) {
  649. lastUpdateCheck = now;
  650. if (_updater->check(now) && _updateAutoApply)
  651. _updater->apply();
  652. }
  653. // Refresh bindings in case device's interfaces have changed, and also sync routes to update any shadow routes (e.g. shadow default)
  654. if (((now - lastBindRefresh) >= ZT_BINDER_REFRESH_PERIOD)||(restarted)) {
  655. lastBindRefresh = now;
  656. for(int i=0;i<3;++i) {
  657. if (_ports[i]) {
  658. _bindings[i].refresh(_phy,_ports[i],*this);
  659. }
  660. }
  661. {
  662. Mutex::Lock _l(_nets_m);
  663. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n) {
  664. if (n->second.tap)
  665. syncManagedStuff(n->second,false,true);
  666. }
  667. }
  668. }
  669. uint64_t dl = _nextBackgroundTaskDeadline;
  670. if (dl <= now) {
  671. _node->processBackgroundTasks(now,&_nextBackgroundTaskDeadline);
  672. dl = _nextBackgroundTaskDeadline;
  673. }
  674. if ((now - lastTcpFallbackResolve) >= ZT_TCP_FALLBACK_RERESOLVE_DELAY) {
  675. lastTcpFallbackResolve = now;
  676. _tcpFallbackResolver.resolveNow();
  677. }
  678. if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2)))
  679. _phy.close(_tcpFallbackTunnel->sock);
  680. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  681. lastTapMulticastGroupCheck = now;
  682. Mutex::Lock _l(_nets_m);
  683. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  684. if (n->second.tap) {
  685. std::vector<MulticastGroup> added,removed;
  686. n->second.tap->scanMulticastGroups(added,removed);
  687. for(std::vector<MulticastGroup>::iterator m(added.begin());m!=added.end();++m)
  688. _node->multicastSubscribe(n->first,m->mac().toInt(),m->adi());
  689. for(std::vector<MulticastGroup>::iterator m(removed.begin());m!=removed.end();++m)
  690. _node->multicastUnsubscribe(n->first,m->mac().toInt(),m->adi());
  691. }
  692. }
  693. }
  694. if ((now - lastLocalInterfaceAddressCheck) >= ZT_LOCAL_INTERFACE_CHECK_INTERVAL) {
  695. lastLocalInterfaceAddressCheck = now;
  696. _node->clearLocalInterfaceAddresses();
  697. #ifdef ZT_USE_MINIUPNPC
  698. if (_portMapper) {
  699. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  700. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  701. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  702. }
  703. #endif
  704. std::vector<InetAddress> boundAddrs(_bindings[0].allBoundLocalInterfaceAddresses());
  705. for(std::vector<InetAddress>::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i)
  706. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*i)));
  707. }
  708. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  709. clockShouldBe = now + (uint64_t)delay;
  710. _phy.poll(delay);
  711. }
  712. } catch (std::exception &exc) {
  713. Mutex::Lock _l(_termReason_m);
  714. _termReason = ONE_UNRECOVERABLE_ERROR;
  715. _fatalErrorMessage = exc.what();
  716. } catch ( ... ) {
  717. Mutex::Lock _l(_termReason_m);
  718. _termReason = ONE_UNRECOVERABLE_ERROR;
  719. _fatalErrorMessage = "unexpected exception in main thread";
  720. }
  721. try {
  722. while (!_tcpConnections.empty())
  723. _phy.close((*_tcpConnections.begin())->sock);
  724. } catch ( ... ) {}
  725. {
  726. Mutex::Lock _l(_nets_m);
  727. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n)
  728. delete n->second.tap;
  729. _nets.clear();
  730. }
  731. delete _controlPlane;
  732. _controlPlane = (ControlPlane *)0;
  733. delete _updater;
  734. _updater = (SoftwareUpdater *)0;
  735. delete _node;
  736. _node = (Node *)0;
  737. return _termReason;
  738. }
  739. virtual ReasonForTermination reasonForTermination() const
  740. {
  741. Mutex::Lock _l(_termReason_m);
  742. return _termReason;
  743. }
  744. virtual std::string fatalErrorMessage() const
  745. {
  746. Mutex::Lock _l(_termReason_m);
  747. return _fatalErrorMessage;
  748. }
  749. virtual std::string portDeviceName(uint64_t nwid) const
  750. {
  751. Mutex::Lock _l(_nets_m);
  752. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  753. if ((n != _nets.end())&&(n->second.tap))
  754. return n->second.tap->deviceName();
  755. else return std::string();
  756. }
  757. virtual bool tcpFallbackActive() const
  758. {
  759. return (_tcpFallbackTunnel != (TcpConnection *)0);
  760. }
  761. virtual void terminate()
  762. {
  763. _run_m.lock();
  764. _run = false;
  765. _run_m.unlock();
  766. _phy.whack();
  767. }
  768. virtual bool getNetworkSettings(const uint64_t nwid,NetworkSettings &settings) const
  769. {
  770. Mutex::Lock _l(_nets_m);
  771. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  772. if (n == _nets.end())
  773. return false;
  774. memcpy(&settings,&(n->second.settings),sizeof(NetworkSettings));
  775. return true;
  776. }
  777. virtual bool setNetworkSettings(const uint64_t nwid,const NetworkSettings &settings)
  778. {
  779. Mutex::Lock _l(_nets_m);
  780. std::map<uint64_t,NetworkState>::iterator n(_nets.find(nwid));
  781. if (n == _nets.end())
  782. return false;
  783. memcpy(&(n->second.settings),&settings,sizeof(NetworkSettings));
  784. char nlcpath[256];
  785. Utils::snprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  786. FILE *out = fopen(nlcpath,"w");
  787. if (out) {
  788. fprintf(out,"allowManaged=%d\n",(int)n->second.settings.allowManaged);
  789. fprintf(out,"allowGlobal=%d\n",(int)n->second.settings.allowGlobal);
  790. fprintf(out,"allowDefault=%d\n",(int)n->second.settings.allowDefault);
  791. fclose(out);
  792. }
  793. if (n->second.tap)
  794. syncManagedStuff(n->second,true,true);
  795. return true;
  796. }
  797. // Internal implementation methods -----------------------------------------
  798. // Must be called after _localConfig is read or modified
  799. void applyLocalConfig()
  800. {
  801. Mutex::Lock _l(_localConfig_m);
  802. _v4Hints.clear();
  803. _v6Hints.clear();
  804. _v4Blacklists.clear();
  805. _v6Blacklists.clear();
  806. json &virt = _localConfig["virtual"];
  807. if (virt.is_object()) {
  808. for(json::iterator v(virt.begin());v!=virt.end();++v) {
  809. const std::string nstr = v.key();
  810. if ((nstr.length() == ZT_ADDRESS_LENGTH_HEX)&&(v.value().is_object())) {
  811. const Address ztaddr(nstr.c_str());
  812. if (ztaddr) {
  813. const std::string rstr(OSUtils::jsonString(v.value()["role"],""));
  814. _node->setRole(ztaddr.toInt(),((rstr == "upstream")||(rstr == "UPSTREAM")) ? ZT_PEER_ROLE_UPSTREAM : ZT_PEER_ROLE_LEAF);
  815. const uint64_t ztaddr2 = ztaddr.toInt();
  816. std::vector<InetAddress> &v4h = _v4Hints[ztaddr2];
  817. std::vector<InetAddress> &v6h = _v6Hints[ztaddr2];
  818. std::vector<InetAddress> &v4b = _v4Blacklists[ztaddr2];
  819. std::vector<InetAddress> &v6b = _v6Blacklists[ztaddr2];
  820. json &tryAddrs = v.value()["try"];
  821. if (tryAddrs.is_array()) {
  822. for(unsigned long i=0;i<tryAddrs.size();++i) {
  823. const InetAddress ip(OSUtils::jsonString(tryAddrs[i],""));
  824. if (ip.ss_family == AF_INET)
  825. v4h.push_back(ip);
  826. else if (ip.ss_family == AF_INET6)
  827. v6h.push_back(ip);
  828. }
  829. }
  830. json &blAddrs = v.value()["blacklist"];
  831. if (blAddrs.is_array()) {
  832. for(unsigned long i=0;i<blAddrs.size();++i) {
  833. const InetAddress ip(OSUtils::jsonString(tryAddrs[i],""));
  834. if (ip.ss_family == AF_INET)
  835. v4b.push_back(ip);
  836. else if (ip.ss_family == AF_INET6)
  837. v6b.push_back(ip);
  838. }
  839. }
  840. if (v4h.empty()) _v4Hints.erase(ztaddr2);
  841. if (v6h.empty()) _v6Hints.erase(ztaddr2);
  842. if (v4b.empty()) _v4Blacklists.erase(ztaddr2);
  843. if (v6b.empty()) _v6Blacklists.erase(ztaddr2);
  844. }
  845. }
  846. }
  847. }
  848. _globalV4Blacklist.clear();
  849. _globalV6Blacklist.clear();
  850. json &physical = _localConfig["physical"];
  851. if (physical.is_object()) {
  852. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  853. const InetAddress net(OSUtils::jsonString(phy.key(),""));
  854. if ((net)&&(net.netmaskBits() > 0)) {
  855. if (phy.value().is_object()) {
  856. if (OSUtils::jsonBool(phy.value()["blacklist"],false)) {
  857. if (net.ss_family == AF_INET)
  858. _globalV4Blacklist.push_back(net);
  859. else if (net.ss_family == AF_INET6)
  860. _globalV6Blacklist.push_back(net);
  861. }
  862. }
  863. }
  864. }
  865. }
  866. _allowManagementFrom.clear();
  867. _interfacePrefixBlacklist.clear();
  868. json &settings = _localConfig["settings"];
  869. if (settings.is_object()) {
  870. _portMappingEnabled = OSUtils::jsonBool(settings["portMappingEnabled"],true);
  871. const std::string rp(OSUtils::jsonString(settings["relayPolicy"],""));
  872. if ((rp == "always")||(rp == "ALWAYS"))
  873. _node->setRelayPolicy(ZT_RELAY_POLICY_ALWAYS);
  874. else if ((rp == "never")||(rp == "NEVER"))
  875. _node->setRelayPolicy(ZT_RELAY_POLICY_NEVER);
  876. else _node->setRelayPolicy(ZT_RELAY_POLICY_TRUSTED);
  877. const std::string up(OSUtils::jsonString(settings["softwareUpdate"],ZT_SOFTWARE_UPDATE_DEFAULT));
  878. const bool udist = OSUtils::jsonBool(settings["softwareUpdateDist"],false);
  879. if (((up == "apply")||(up == "download"))||(udist)) {
  880. if (!_updater)
  881. _updater = new SoftwareUpdater(*_node,_homePath);
  882. _updateAutoApply = (up == "apply");
  883. _updater->setUpdateDistribution(udist);
  884. _updater->setChannel(OSUtils::jsonString(settings["softwareUpdateChannel"],ZT_SOFTWARE_UPDATE_DEFAULT_CHANNEL));
  885. } else {
  886. delete _updater;
  887. _updater = (SoftwareUpdater *)0;
  888. _updateAutoApply = false;
  889. }
  890. json &ignoreIfs = settings["interfacePrefixBlacklist"];
  891. if (ignoreIfs.is_array()) {
  892. for(unsigned long i=0;i<ignoreIfs.size();++i) {
  893. const std::string tmp(OSUtils::jsonString(ignoreIfs[i],""));
  894. if (tmp.length() > 0)
  895. _interfacePrefixBlacklist.push_back(tmp);
  896. }
  897. }
  898. json &amf = settings["allowManagementFrom"];
  899. if (amf.is_array()) {
  900. for(unsigned long i=0;i<amf.size();++i) {
  901. const InetAddress nw(OSUtils::jsonString(amf[i],""));
  902. if (nw)
  903. _allowManagementFrom.push_back(nw);
  904. }
  905. }
  906. }
  907. }
  908. // Checks if a managed IP or route target is allowed
  909. bool checkIfManagedIsAllowed(const NetworkState &n,const InetAddress &target)
  910. {
  911. if (!n.settings.allowManaged)
  912. return false;
  913. if (target.isDefaultRoute())
  914. return n.settings.allowDefault;
  915. switch(target.ipScope()) {
  916. case InetAddress::IP_SCOPE_NONE:
  917. case InetAddress::IP_SCOPE_MULTICAST:
  918. case InetAddress::IP_SCOPE_LOOPBACK:
  919. case InetAddress::IP_SCOPE_LINK_LOCAL:
  920. return false;
  921. case InetAddress::IP_SCOPE_GLOBAL:
  922. return n.settings.allowGlobal;
  923. default:
  924. return true;
  925. }
  926. }
  927. // Match only an IP from a vector of IPs -- used in syncManagedStuff()
  928. bool matchIpOnly(const std::vector<InetAddress> &ips,const InetAddress &ip) const
  929. {
  930. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  931. if (i->ipsEqual(ip))
  932. return true;
  933. }
  934. return false;
  935. }
  936. // Apply or update managed IPs for a configured network (be sure n.tap exists)
  937. void syncManagedStuff(NetworkState &n,bool syncIps,bool syncRoutes)
  938. {
  939. // assumes _nets_m is locked
  940. if (syncIps) {
  941. std::vector<InetAddress> newManagedIps;
  942. newManagedIps.reserve(n.config.assignedAddressCount);
  943. for(unsigned int i=0;i<n.config.assignedAddressCount;++i) {
  944. const InetAddress *ii = reinterpret_cast<const InetAddress *>(&(n.config.assignedAddresses[i]));
  945. if (checkIfManagedIsAllowed(n,*ii))
  946. newManagedIps.push_back(*ii);
  947. }
  948. std::sort(newManagedIps.begin(),newManagedIps.end());
  949. newManagedIps.erase(std::unique(newManagedIps.begin(),newManagedIps.end()),newManagedIps.end());
  950. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  951. if (std::find(newManagedIps.begin(),newManagedIps.end(),*ip) == newManagedIps.end()) {
  952. if (!n.tap->removeIp(*ip))
  953. fprintf(stderr,"ERROR: unable to remove ip address %s" ZT_EOL_S, ip->toString().c_str());
  954. }
  955. }
  956. for(std::vector<InetAddress>::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) {
  957. if (std::find(n.managedIps.begin(),n.managedIps.end(),*ip) == n.managedIps.end()) {
  958. if (!n.tap->addIp(*ip))
  959. fprintf(stderr,"ERROR: unable to add ip address %s" ZT_EOL_S, ip->toString().c_str());
  960. }
  961. }
  962. n.managedIps.swap(newManagedIps);
  963. }
  964. if (syncRoutes) {
  965. char tapdev[64];
  966. #ifdef __WINDOWS__
  967. Utils::snprintf(tapdev,sizeof(tapdev),"%.16llx",(unsigned long long)n.tap->luid().Value);
  968. #else
  969. Utils::scopy(tapdev,sizeof(tapdev),n.tap->deviceName().c_str());
  970. #endif
  971. std::vector<InetAddress> myIps(n.tap->ips());
  972. // Nuke applied routes that are no longer in n.config.routes[] and/or are not allowed
  973. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();) {
  974. bool haveRoute = false;
  975. if ( (checkIfManagedIsAllowed(n,(*mr)->target())) && (((*mr)->via().ss_family != (*mr)->target().ss_family)||(!matchIpOnly(myIps,(*mr)->via()))) ) {
  976. for(unsigned int i=0;i<n.config.routeCount;++i) {
  977. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  978. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  979. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (tapdev == (*mr)->device()) ) ) {
  980. haveRoute = true;
  981. break;
  982. }
  983. }
  984. }
  985. if (haveRoute) {
  986. ++mr;
  987. } else {
  988. n.managedRoutes.erase(mr++);
  989. }
  990. }
  991. // Apply routes in n.config.routes[] that we haven't applied yet, and sync those we have in case shadow routes need to change
  992. for(unsigned int i=0;i<n.config.routeCount;++i) {
  993. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  994. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  995. if ( (!checkIfManagedIsAllowed(n,*target)) || ((via->ss_family == target->ss_family)&&(matchIpOnly(myIps,*via))) )
  996. continue;
  997. bool haveRoute = false;
  998. // Ignore routes implied by local managed IPs since adding the IP adds the route
  999. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  1000. if ((target->netmaskBits() == ip->netmaskBits())&&(target->containsAddress(*ip))) {
  1001. haveRoute = true;
  1002. break;
  1003. }
  1004. }
  1005. if (haveRoute)
  1006. continue;
  1007. // If we've already applied this route, just sync it and continue
  1008. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();++mr) {
  1009. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (tapdev == (*mr)->device()) ) ) {
  1010. haveRoute = true;
  1011. (*mr)->sync();
  1012. break;
  1013. }
  1014. }
  1015. if (haveRoute)
  1016. continue;
  1017. // Add and apply new routes
  1018. n.managedRoutes.push_back(SharedPtr<ManagedRoute>(new ManagedRoute(*target,*via,tapdev)));
  1019. if (!n.managedRoutes.back()->sync())
  1020. n.managedRoutes.pop_back();
  1021. }
  1022. }
  1023. }
  1024. // Handlers for Node and Phy<> callbacks -----------------------------------
  1025. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  1026. {
  1027. #ifdef ZT_ENABLE_CLUSTER
  1028. if (sock == _clusterMessageSocket) {
  1029. _lastDirectReceiveFromGlobal = OSUtils::now();
  1030. _node->clusterHandleIncomingMessage(data,len);
  1031. return;
  1032. }
  1033. #endif
  1034. #ifdef ZT_BREAK_UDP
  1035. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  1036. return;
  1037. #endif
  1038. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  1039. _lastDirectReceiveFromGlobal = OSUtils::now();
  1040. const ZT_ResultCode rc = _node->processWirePacket(
  1041. OSUtils::now(),
  1042. reinterpret_cast<const struct sockaddr_storage *>(localAddr),
  1043. (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
  1044. data,
  1045. len,
  1046. &_nextBackgroundTaskDeadline);
  1047. if (ZT_ResultCode_isFatal(rc)) {
  1048. char tmp[256];
  1049. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1050. Mutex::Lock _l(_termReason_m);
  1051. _termReason = ONE_UNRECOVERABLE_ERROR;
  1052. _fatalErrorMessage = tmp;
  1053. this->terminate();
  1054. }
  1055. }
  1056. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  1057. {
  1058. if (!success)
  1059. return;
  1060. // Outgoing TCP connections are always TCP fallback tunnel connections.
  1061. TcpConnection *tc = new TcpConnection();
  1062. _tcpConnections.insert(tc);
  1063. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  1064. tc->shouldKeepAlive = true;
  1065. tc->parent = this;
  1066. tc->sock = sock;
  1067. // from and parser are not used
  1068. tc->messageSize = 0; // unused
  1069. tc->lastActivity = OSUtils::now();
  1070. // HTTP stuff is not used
  1071. tc->writeBuf = "";
  1072. *uptr = (void *)tc;
  1073. // Send "hello" message
  1074. tc->writeBuf.push_back((char)0x17);
  1075. tc->writeBuf.push_back((char)0x03);
  1076. tc->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1077. tc->writeBuf.push_back((char)0x00);
  1078. tc->writeBuf.push_back((char)0x04); // mlen == 4
  1079. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MAJOR);
  1080. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MINOR);
  1081. tc->writeBuf.push_back((char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff));
  1082. tc->writeBuf.push_back((char)(ZEROTIER_ONE_VERSION_REVISION & 0xff));
  1083. _phy.setNotifyWritable(sock,true);
  1084. _tcpFallbackTunnel = tc;
  1085. }
  1086. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  1087. {
  1088. if (!from) {
  1089. _phy.close(sockN,false);
  1090. return;
  1091. } else {
  1092. TcpConnection *tc = new TcpConnection();
  1093. _tcpConnections.insert(tc);
  1094. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  1095. tc->shouldKeepAlive = true;
  1096. tc->parent = this;
  1097. tc->sock = sockN;
  1098. tc->from = from;
  1099. http_parser_init(&(tc->parser),HTTP_REQUEST);
  1100. tc->parser.data = (void *)tc;
  1101. tc->messageSize = 0;
  1102. tc->lastActivity = OSUtils::now();
  1103. tc->currentHeaderField = "";
  1104. tc->currentHeaderValue = "";
  1105. tc->url = "";
  1106. tc->status = "";
  1107. tc->headers.clear();
  1108. tc->body = "";
  1109. tc->writeBuf = "";
  1110. *uptrN = (void *)tc;
  1111. }
  1112. }
  1113. inline void phyOnTcpClose(PhySocket *sock,void **uptr)
  1114. {
  1115. TcpConnection *tc = (TcpConnection *)*uptr;
  1116. if (tc) {
  1117. if (tc == _tcpFallbackTunnel)
  1118. _tcpFallbackTunnel = (TcpConnection *)0;
  1119. _tcpConnections.erase(tc);
  1120. delete tc;
  1121. }
  1122. }
  1123. inline void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  1124. {
  1125. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1126. switch(tc->type) {
  1127. case TcpConnection::TCP_HTTP_INCOMING:
  1128. case TcpConnection::TCP_HTTP_OUTGOING:
  1129. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  1130. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK)) {
  1131. _phy.close(sock);
  1132. return;
  1133. }
  1134. break;
  1135. case TcpConnection::TCP_TUNNEL_OUTGOING:
  1136. tc->body.append((const char *)data,len);
  1137. while (tc->body.length() >= 5) {
  1138. const char *data = tc->body.data();
  1139. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  1140. if (tc->body.length() >= (mlen + 5)) {
  1141. InetAddress from;
  1142. unsigned long plen = mlen; // payload length, modified if there's an IP header
  1143. data += 5; // skip forward past pseudo-TLS junk and mlen
  1144. if (plen == 4) {
  1145. // Hello message, which isn't sent by proxy and would be ignored by client
  1146. } else if (plen) {
  1147. // Messages should contain IPv4 or IPv6 source IP address data
  1148. switch(data[0]) {
  1149. case 4: // IPv4
  1150. if (plen >= 7) {
  1151. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  1152. data += 7; // type + 4 byte IP + 2 byte port
  1153. plen -= 7;
  1154. } else {
  1155. _phy.close(sock);
  1156. return;
  1157. }
  1158. break;
  1159. case 6: // IPv6
  1160. if (plen >= 19) {
  1161. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  1162. data += 19; // type + 16 byte IP + 2 byte port
  1163. plen -= 19;
  1164. } else {
  1165. _phy.close(sock);
  1166. return;
  1167. }
  1168. break;
  1169. case 0: // none/omitted
  1170. ++data;
  1171. --plen;
  1172. break;
  1173. default: // invalid address type
  1174. _phy.close(sock);
  1175. return;
  1176. }
  1177. if (from) {
  1178. InetAddress fakeTcpLocalInterfaceAddress((uint32_t)0xffffffff,0xffff);
  1179. const ZT_ResultCode rc = _node->processWirePacket(
  1180. OSUtils::now(),
  1181. reinterpret_cast<struct sockaddr_storage *>(&fakeTcpLocalInterfaceAddress),
  1182. reinterpret_cast<struct sockaddr_storage *>(&from),
  1183. data,
  1184. plen,
  1185. &_nextBackgroundTaskDeadline);
  1186. if (ZT_ResultCode_isFatal(rc)) {
  1187. char tmp[256];
  1188. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1189. Mutex::Lock _l(_termReason_m);
  1190. _termReason = ONE_UNRECOVERABLE_ERROR;
  1191. _fatalErrorMessage = tmp;
  1192. this->terminate();
  1193. _phy.close(sock);
  1194. return;
  1195. }
  1196. }
  1197. }
  1198. if (tc->body.length() > (mlen + 5))
  1199. tc->body = tc->body.substr(mlen + 5);
  1200. else tc->body = "";
  1201. } else break;
  1202. }
  1203. break;
  1204. }
  1205. }
  1206. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  1207. {
  1208. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1209. Mutex::Lock _l(tc->writeBuf_m);
  1210. if (tc->writeBuf.length() > 0) {
  1211. long sent = (long)_phy.streamSend(sock,tc->writeBuf.data(),(unsigned long)tc->writeBuf.length(),true);
  1212. if (sent > 0) {
  1213. tc->lastActivity = OSUtils::now();
  1214. if ((unsigned long)sent >= (unsigned long)tc->writeBuf.length()) {
  1215. tc->writeBuf = "";
  1216. _phy.setNotifyWritable(sock,false);
  1217. if (!tc->shouldKeepAlive)
  1218. _phy.close(sock); // will call close handler to delete from _tcpConnections
  1219. } else {
  1220. tc->writeBuf = tc->writeBuf.substr(sent);
  1221. }
  1222. }
  1223. } else {
  1224. _phy.setNotifyWritable(sock,false);
  1225. }
  1226. }
  1227. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  1228. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  1229. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  1230. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  1231. inline void phyOnUnixWritable(PhySocket *sock,void **uptr,bool lwip_invoked) {}
  1232. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  1233. {
  1234. Mutex::Lock _l(_nets_m);
  1235. NetworkState &n = _nets[nwid];
  1236. switch(op) {
  1237. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  1238. if (!n.tap) {
  1239. try {
  1240. char friendlyName[128];
  1241. Utils::snprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  1242. n.tap = new EthernetTap(
  1243. _homePath.c_str(),
  1244. MAC(nwc->mac),
  1245. nwc->mtu,
  1246. (unsigned int)ZT_IF_METRIC,
  1247. nwid,
  1248. friendlyName,
  1249. StapFrameHandler,
  1250. (void *)this);
  1251. *nuptr = (void *)&n;
  1252. char nlcpath[256];
  1253. Utils::snprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1254. std::string nlcbuf;
  1255. if (OSUtils::readFile(nlcpath,nlcbuf)) {
  1256. Dictionary<4096> nc;
  1257. nc.load(nlcbuf.c_str());
  1258. n.settings.allowManaged = nc.getB("allowManaged",true);
  1259. n.settings.allowGlobal = nc.getB("allowGlobal",false);
  1260. n.settings.allowDefault = nc.getB("allowDefault",false);
  1261. }
  1262. } catch (std::exception &exc) {
  1263. #ifdef __WINDOWS__
  1264. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1265. if (tapFailLog) {
  1266. fprintf(tapFailLog,"%.16llx: %s" ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1267. fclose(tapFailLog);
  1268. }
  1269. #else
  1270. fprintf(stderr,"ERROR: unable to configure virtual network port: %s" ZT_EOL_S,exc.what());
  1271. #endif
  1272. _nets.erase(nwid);
  1273. return -999;
  1274. } catch ( ... ) {
  1275. return -999; // tap init failed
  1276. }
  1277. }
  1278. // After setting up tap, fall through to CONFIG_UPDATE since we also want to do this...
  1279. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1280. memcpy(&(n.config),nwc,sizeof(ZT_VirtualNetworkConfig));
  1281. if (n.tap) { // sanity check
  1282. #ifdef __WINDOWS__
  1283. // wait for up to 5 seconds for the WindowsEthernetTap to actually be initialized
  1284. //
  1285. // without WindowsEthernetTap::isInitialized() returning true, the won't actually
  1286. // be online yet and setting managed routes on it will fail.
  1287. const int MAX_SLEEP_COUNT = 500;
  1288. for (int i = 0; !n.tap->isInitialized() && i < MAX_SLEEP_COUNT; i++) {
  1289. Sleep(10);
  1290. }
  1291. #endif
  1292. syncManagedStuff(n,true,true);
  1293. } else {
  1294. _nets.erase(nwid);
  1295. return -999; // tap init failed
  1296. }
  1297. break;
  1298. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1299. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1300. if (n.tap) { // sanity check
  1301. #ifdef __WINDOWS__
  1302. std::string winInstanceId(n.tap->instanceId());
  1303. #endif
  1304. *nuptr = (void *)0;
  1305. delete n.tap;
  1306. _nets.erase(nwid);
  1307. #ifdef __WINDOWS__
  1308. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1309. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1310. #endif
  1311. if (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY) {
  1312. char nlcpath[256];
  1313. Utils::snprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1314. OSUtils::rm(nlcpath);
  1315. }
  1316. } else {
  1317. _nets.erase(nwid);
  1318. }
  1319. break;
  1320. }
  1321. return 0;
  1322. }
  1323. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1324. {
  1325. switch(event) {
  1326. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  1327. Mutex::Lock _l(_termReason_m);
  1328. _termReason = ONE_IDENTITY_COLLISION;
  1329. _fatalErrorMessage = "identity/address collision";
  1330. this->terminate();
  1331. } break;
  1332. case ZT_EVENT_TRACE: {
  1333. if (metaData) {
  1334. ::fprintf(stderr,"%s" ZT_EOL_S,(const char *)metaData);
  1335. ::fflush(stderr);
  1336. }
  1337. } break;
  1338. case ZT_EVENT_USER_MESSAGE: {
  1339. const ZT_UserMessage *um = reinterpret_cast<const ZT_UserMessage *>(metaData);
  1340. if ((um->typeId == ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE)&&(_updater)) {
  1341. _updater->handleSoftwareUpdateUserMessage(um->origin,um->data,um->length);
  1342. }
  1343. } break;
  1344. default:
  1345. break;
  1346. }
  1347. }
  1348. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1349. {
  1350. std::string p(_dataStorePrepPath(name));
  1351. if (!p.length())
  1352. return -2;
  1353. FILE *f = fopen(p.c_str(),"rb");
  1354. if (!f)
  1355. return -1;
  1356. if (fseek(f,0,SEEK_END) != 0) {
  1357. fclose(f);
  1358. return -2;
  1359. }
  1360. long ts = ftell(f);
  1361. if (ts < 0) {
  1362. fclose(f);
  1363. return -2;
  1364. }
  1365. *totalSize = (unsigned long)ts;
  1366. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  1367. fclose(f);
  1368. return -2;
  1369. }
  1370. long n = (long)fread(buf,1,bufSize,f);
  1371. fclose(f);
  1372. return n;
  1373. }
  1374. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  1375. {
  1376. std::string p(_dataStorePrepPath(name));
  1377. if (!p.length())
  1378. return -2;
  1379. if (!data) {
  1380. OSUtils::rm(p.c_str());
  1381. return 0;
  1382. }
  1383. FILE *f = fopen(p.c_str(),"wb");
  1384. if (!f)
  1385. return -1;
  1386. if (fwrite(data,len,1,f) == 1) {
  1387. fclose(f);
  1388. if (secure)
  1389. OSUtils::lockDownFile(p.c_str(),false);
  1390. return 0;
  1391. } else {
  1392. fclose(f);
  1393. OSUtils::rm(p.c_str());
  1394. return -1;
  1395. }
  1396. }
  1397. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1398. {
  1399. unsigned int fromBindingNo = 0;
  1400. if (addr->ss_family == AF_INET) {
  1401. if (reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port == 0) {
  1402. // If sender is sending from wildcard (null address), choose the secondary backup
  1403. // port 1/4 of the time. (but only for IPv4)
  1404. fromBindingNo = (++_udpPortPickerCounter & 0x4) >> 2;
  1405. if (!_ports[fromBindingNo])
  1406. fromBindingNo = 0;
  1407. } else {
  1408. const uint16_t lp = reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port;
  1409. if (lp == _portsBE[1])
  1410. fromBindingNo = 1;
  1411. else if (lp == _portsBE[2])
  1412. fromBindingNo = 2;
  1413. }
  1414. #ifdef ZT_TCP_FALLBACK_RELAY
  1415. // TCP fallback tunnel support, currently IPv4 only
  1416. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  1417. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  1418. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  1419. // valid direct traffic we'll stop using it and close the socket after a while.
  1420. const uint64_t now = OSUtils::now();
  1421. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  1422. if (_tcpFallbackTunnel) {
  1423. Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
  1424. if (!_tcpFallbackTunnel->writeBuf.length())
  1425. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  1426. unsigned long mlen = len + 7;
  1427. _tcpFallbackTunnel->writeBuf.push_back((char)0x17);
  1428. _tcpFallbackTunnel->writeBuf.push_back((char)0x03);
  1429. _tcpFallbackTunnel->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1430. _tcpFallbackTunnel->writeBuf.push_back((char)((mlen >> 8) & 0xff));
  1431. _tcpFallbackTunnel->writeBuf.push_back((char)(mlen & 0xff));
  1432. _tcpFallbackTunnel->writeBuf.push_back((char)4); // IPv4
  1433. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  1434. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  1435. _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
  1436. } else if (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INVERVAL / 2))) {
  1437. std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
  1438. if (tunnelIps.empty()) {
  1439. if (!_tcpFallbackResolver.running())
  1440. _tcpFallbackResolver.resolveNow();
  1441. } else {
  1442. bool connected = false;
  1443. InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
  1444. addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
  1445. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
  1446. }
  1447. }
  1448. }
  1449. _lastSendToGlobalV4 = now;
  1450. }
  1451. #endif // ZT_TCP_FALLBACK_RELAY
  1452. } else if (addr->ss_family == AF_INET6) {
  1453. if (reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port != 0) {
  1454. const uint16_t lp = reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port;
  1455. if (lp == _portsBE[1])
  1456. fromBindingNo = 1;
  1457. else if (lp == _portsBE[2])
  1458. fromBindingNo = 2;
  1459. }
  1460. } else {
  1461. return -1;
  1462. }
  1463. #ifdef ZT_BREAK_UDP
  1464. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  1465. return 0; // silently break UDP
  1466. #endif
  1467. return (_bindings[fromBindingNo].udpSend(_phy,*(reinterpret_cast<const InetAddress *>(localAddr)),*(reinterpret_cast<const InetAddress *>(addr)),data,len,ttl)) ? 0 : -1;
  1468. }
  1469. 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)
  1470. {
  1471. NetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);
  1472. if ((!n)||(!n->tap))
  1473. return;
  1474. n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1475. }
  1476. inline int nodePathCheckFunction(uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1477. {
  1478. // Make sure we're not trying to do ZeroTier-over-ZeroTier
  1479. {
  1480. Mutex::Lock _l(_nets_m);
  1481. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1482. if (n->second.tap) {
  1483. std::vector<InetAddress> ips(n->second.tap->ips());
  1484. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1485. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  1486. return 0;
  1487. }
  1488. }
  1489. }
  1490. }
  1491. }
  1492. /* Note: I do not think we need to scan for overlap with managed routes
  1493. * because of the "route forking" and interface binding that we do. This
  1494. * ensures (we hope) that ZeroTier traffic will still take the physical
  1495. * path even if its managed routes override this for other traffic. Will
  1496. * revisit if we see recursion problems. */
  1497. // Check blacklists
  1498. const Hashtable< uint64_t,std::vector<InetAddress> > *blh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  1499. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  1500. if (remoteAddr->ss_family == AF_INET) {
  1501. blh = &_v4Blacklists;
  1502. gbl = &_globalV4Blacklist;
  1503. } else if (remoteAddr->ss_family == AF_INET6) {
  1504. blh = &_v6Blacklists;
  1505. gbl = &_globalV6Blacklist;
  1506. }
  1507. if (blh) {
  1508. Mutex::Lock _l(_localConfig_m);
  1509. const std::vector<InetAddress> *l = blh->get(ztaddr);
  1510. if (l) {
  1511. for(std::vector<InetAddress>::const_iterator a(l->begin());a!=l->end();++a) {
  1512. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  1513. return 0;
  1514. }
  1515. }
  1516. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  1517. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  1518. return 0;
  1519. }
  1520. }
  1521. return 1;
  1522. }
  1523. inline int nodePathLookupFunction(uint64_t ztaddr,int family,struct sockaddr_storage *result)
  1524. {
  1525. const Hashtable< uint64_t,std::vector<InetAddress> > *lh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  1526. if (family < 0)
  1527. lh = (_node->prng() & 1) ? &_v4Hints : &_v6Hints;
  1528. else if (family == AF_INET)
  1529. lh = &_v4Hints;
  1530. else if (family == AF_INET6)
  1531. lh = &_v6Hints;
  1532. else return 0;
  1533. const std::vector<InetAddress> *l = lh->get(ztaddr);
  1534. if ((l)&&(l->size() > 0)) {
  1535. memcpy(result,&((*l)[(unsigned long)_node->prng() % l->size()]),sizeof(struct sockaddr_storage));
  1536. return 1;
  1537. } else return 0;
  1538. }
  1539. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1540. {
  1541. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1542. }
  1543. inline void onHttpRequestToServer(TcpConnection *tc)
  1544. {
  1545. char tmpn[256];
  1546. std::string data;
  1547. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1548. unsigned int scode = 404;
  1549. bool allow;
  1550. {
  1551. Mutex::Lock _l(_localConfig_m);
  1552. if (_allowManagementFrom.size() == 0) {
  1553. allow = (tc->from.ipScope() == InetAddress::IP_SCOPE_LOOPBACK);
  1554. } else {
  1555. allow = false;
  1556. for(std::vector<InetAddress>::const_iterator i(_allowManagementFrom.begin());i!=_allowManagementFrom.end();++i) {
  1557. if (i->containsAddress(tc->from)) {
  1558. allow = true;
  1559. break;
  1560. }
  1561. }
  1562. }
  1563. }
  1564. if (allow) {
  1565. try {
  1566. if (_controlPlane)
  1567. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  1568. else scode = 500;
  1569. } catch (std::exception &exc) {
  1570. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: %s" ZT_EOL_S,exc.what());
  1571. scode = 500;
  1572. } catch ( ... ) {
  1573. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: unknown exceptino" ZT_EOL_S);
  1574. scode = 500;
  1575. }
  1576. } else {
  1577. scode = 401;
  1578. }
  1579. const char *scodestr;
  1580. switch(scode) {
  1581. case 200: scodestr = "OK"; break;
  1582. case 400: scodestr = "Bad Request"; break;
  1583. case 401: scodestr = "Unauthorized"; break;
  1584. case 403: scodestr = "Forbidden"; break;
  1585. case 404: scodestr = "Not Found"; break;
  1586. case 500: scodestr = "Internal Server Error"; break;
  1587. case 501: scodestr = "Not Implemented"; break;
  1588. case 503: scodestr = "Service Unavailable"; break;
  1589. default: scodestr = "Error"; break;
  1590. }
  1591. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  1592. {
  1593. Mutex::Lock _l(tc->writeBuf_m);
  1594. tc->writeBuf.assign(tmpn);
  1595. tc->writeBuf.append("Content-Type: ");
  1596. tc->writeBuf.append(contentType);
  1597. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  1598. tc->writeBuf.append(tmpn);
  1599. if (!tc->shouldKeepAlive)
  1600. tc->writeBuf.append("Connection: close\r\n");
  1601. tc->writeBuf.append("\r\n");
  1602. if (tc->parser.method != HTTP_HEAD)
  1603. tc->writeBuf.append(data);
  1604. }
  1605. _phy.setNotifyWritable(tc->sock,true);
  1606. }
  1607. inline void onHttpResponseFromClient(TcpConnection *tc)
  1608. {
  1609. if (!tc->shouldKeepAlive)
  1610. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConnections
  1611. }
  1612. bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
  1613. {
  1614. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  1615. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  1616. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  1617. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  1618. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  1619. #endif
  1620. #ifdef __APPLE__
  1621. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  1622. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  1623. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  1624. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  1625. if ((ifname[0] == 'u')&&(ifname[1] == 't')&&(ifname[2] == 'u')&&(ifname[3] == 'n')) return false; // ... as is utun#
  1626. #endif
  1627. {
  1628. Mutex::Lock _l(_localConfig_m);
  1629. for(std::vector<std::string>::const_iterator p(_interfacePrefixBlacklist.begin());p!=_interfacePrefixBlacklist.end();++p) {
  1630. if (!strncmp(p->c_str(),ifname,p->length()))
  1631. return false;
  1632. }
  1633. }
  1634. {
  1635. Mutex::Lock _l(_nets_m);
  1636. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1637. if (n->second.tap) {
  1638. std::vector<InetAddress> ips(n->second.tap->ips());
  1639. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1640. if (i->ipsEqual(ifaddr))
  1641. return false;
  1642. }
  1643. }
  1644. }
  1645. }
  1646. return true;
  1647. }
  1648. std::string _dataStorePrepPath(const char *name) const
  1649. {
  1650. std::string p(_homePath);
  1651. p.push_back(ZT_PATH_SEPARATOR);
  1652. char lastc = (char)0;
  1653. for(const char *n=name;(*n);++n) {
  1654. if ((*n == '.')&&(lastc == '.'))
  1655. return std::string(); // don't allow ../../ stuff as a precaution
  1656. if (*n == '/') {
  1657. OSUtils::mkdir(p.c_str());
  1658. p.push_back(ZT_PATH_SEPARATOR);
  1659. } else p.push_back(*n);
  1660. lastc = *n;
  1661. }
  1662. return p;
  1663. }
  1664. bool _trialBind(unsigned int port)
  1665. {
  1666. struct sockaddr_in in4;
  1667. struct sockaddr_in6 in6;
  1668. PhySocket *tb;
  1669. memset(&in4,0,sizeof(in4));
  1670. in4.sin_family = AF_INET;
  1671. in4.sin_port = Utils::hton((uint16_t)port);
  1672. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
  1673. if (tb) {
  1674. _phy.close(tb,false);
  1675. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
  1676. if (tb) {
  1677. _phy.close(tb,false);
  1678. return true;
  1679. }
  1680. }
  1681. memset(&in6,0,sizeof(in6));
  1682. in6.sin6_family = AF_INET6;
  1683. in6.sin6_port = Utils::hton((uint16_t)port);
  1684. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
  1685. if (tb) {
  1686. _phy.close(tb,false);
  1687. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
  1688. if (tb) {
  1689. _phy.close(tb,false);
  1690. return true;
  1691. }
  1692. }
  1693. return false;
  1694. }
  1695. };
  1696. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  1697. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  1698. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData)
  1699. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1700. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1701. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  1702. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  1703. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  1704. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1705. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localAddr,addr,data,len,ttl); }
  1706. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1707. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  1708. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1709. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(ztaddr,localAddr,remoteAddr); }
  1710. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,int family,struct sockaddr_storage *result)
  1711. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathLookupFunction(ztaddr,family,result); }
  1712. #ifdef ZT_ENABLE_CLUSTER
  1713. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len)
  1714. {
  1715. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1716. const ClusterDefinition::MemberDefinition &md = (*(impl->_clusterDefinition))[toMemberId];
  1717. if (md.clusterEndpoint)
  1718. impl->_phy.udpSend(impl->_clusterMessageSocket,reinterpret_cast<const struct sockaddr *>(&(md.clusterEndpoint)),data,len);
  1719. }
  1720. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z)
  1721. {
  1722. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1723. return (int)(impl->_clusterDefinition->geo().locate(*(reinterpret_cast<const InetAddress *>(addr)),*x,*y,*z));
  1724. }
  1725. #endif
  1726. static void StapFrameHandler(void *uptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1727. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1728. static int ShttpOnMessageBegin(http_parser *parser)
  1729. {
  1730. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1731. tc->currentHeaderField = "";
  1732. tc->currentHeaderValue = "";
  1733. tc->messageSize = 0;
  1734. tc->url = "";
  1735. tc->status = "";
  1736. tc->headers.clear();
  1737. tc->body = "";
  1738. return 0;
  1739. }
  1740. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  1741. {
  1742. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1743. tc->messageSize += (unsigned long)length;
  1744. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1745. return -1;
  1746. tc->url.append(ptr,length);
  1747. return 0;
  1748. }
  1749. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  1750. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1751. #else
  1752. static int ShttpOnStatus(http_parser *parser)
  1753. #endif
  1754. {
  1755. /*
  1756. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1757. tc->messageSize += (unsigned long)length;
  1758. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1759. return -1;
  1760. tc->status.append(ptr,length);
  1761. */
  1762. return 0;
  1763. }
  1764. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1765. {
  1766. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1767. tc->messageSize += (unsigned long)length;
  1768. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1769. return -1;
  1770. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1771. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1772. tc->currentHeaderField = "";
  1773. tc->currentHeaderValue = "";
  1774. }
  1775. for(size_t i=0;i<length;++i)
  1776. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1777. return 0;
  1778. }
  1779. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1780. {
  1781. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1782. tc->messageSize += (unsigned long)length;
  1783. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1784. return -1;
  1785. tc->currentHeaderValue.append(ptr,length);
  1786. return 0;
  1787. }
  1788. static int ShttpOnHeadersComplete(http_parser *parser)
  1789. {
  1790. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1791. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  1792. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1793. return 0;
  1794. }
  1795. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  1796. {
  1797. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1798. tc->messageSize += (unsigned long)length;
  1799. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1800. return -1;
  1801. tc->body.append(ptr,length);
  1802. return 0;
  1803. }
  1804. static int ShttpOnMessageComplete(http_parser *parser)
  1805. {
  1806. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1807. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  1808. tc->lastActivity = OSUtils::now();
  1809. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  1810. tc->parent->onHttpRequestToServer(tc);
  1811. } else {
  1812. tc->parent->onHttpResponseFromClient(tc);
  1813. }
  1814. return 0;
  1815. }
  1816. } // anonymous namespace
  1817. std::string OneService::platformDefaultHomePath()
  1818. {
  1819. return OSUtils::platformDefaultHomePath();
  1820. }
  1821. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  1822. OneService::~OneService() {}
  1823. } // namespace ZeroTier