NodeConfig.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <string.h>
  29. #include <stdlib.h>
  30. #include <stdint.h>
  31. #include <memory>
  32. #include <string>
  33. #include <map>
  34. #include <set>
  35. #include "Constants.hpp"
  36. #include "NodeConfig.hpp"
  37. #include "RuntimeEnvironment.hpp"
  38. #include "Defaults.hpp"
  39. #include "Utils.hpp"
  40. #include "Logger.hpp"
  41. #include "Topology.hpp"
  42. #include "Packet.hpp"
  43. #include "InetAddress.hpp"
  44. #include "Peer.hpp"
  45. #include "Node.hpp"
  46. #include "SoftwareUpdater.hpp"
  47. namespace ZeroTier {
  48. NodeConfig::NodeConfig(const RuntimeEnvironment *renv,const char *authToken) :
  49. _r(renv),
  50. _ipcListener(ZT_IPC_ENDPOINT,&_CBcommandHandler,this),
  51. _authToken(authToken)
  52. {
  53. {
  54. Mutex::Lock _l(_localConfig_m);
  55. _readLocalConfig();
  56. }
  57. std::string networksFolder(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d");
  58. std::map<std::string,bool> networksDotD(Utils::listDirectory(networksFolder.c_str()));
  59. std::vector<uint64_t> configuredNets;
  60. for(std::map<std::string,bool>::iterator d(networksDotD.begin());d!=networksDotD.end();++d) {
  61. if (!d->second) {
  62. std::string::size_type dot = d->first.rfind(".conf");
  63. if (dot != std::string::npos) {
  64. uint64_t nwid = Utils::hexStrToU64(d->first.substr(0,dot).c_str());
  65. if ((nwid > 0)&&(std::find(configuredNets.begin(),configuredNets.end(),nwid) == configuredNets.end()))
  66. configuredNets.push_back(nwid);
  67. }
  68. }
  69. }
  70. for(std::vector<uint64_t>::iterator n(configuredNets.begin());n!=configuredNets.end();++n) {
  71. try {
  72. _networks[*n] = Network::newInstance(_r,this,*n);
  73. } catch (std::exception &exc) {
  74. LOG("unable to create network %.16llx: %s",(unsigned long long)*n,exc.what());
  75. } catch ( ... ) {
  76. LOG("unable to create network %.16llx: (unknown exception)",(unsigned long long)*n);
  77. }
  78. }
  79. }
  80. NodeConfig::~NodeConfig()
  81. {
  82. _writeLocalConfig();
  83. // Close any open IPC connections
  84. Mutex::Lock _l(_connections_m);
  85. for(std::map< IpcConnection *,bool >::iterator c(_connections.begin());c!=_connections.end();++c)
  86. delete c->first;
  87. _connections.clear();
  88. }
  89. void NodeConfig::putLocalConfig(const std::string &key,const char *value)
  90. {
  91. Mutex::Lock _l(_localConfig_m);
  92. _localConfig[key] = value;
  93. _writeLocalConfig();
  94. }
  95. void NodeConfig::putLocalConfig(const std::string &key,const std::string &value)
  96. {
  97. Mutex::Lock _l(_localConfig_m);
  98. _localConfig[key] = value;
  99. _writeLocalConfig();
  100. }
  101. std::string NodeConfig::getLocalConfig(const std::string &key) const
  102. {
  103. Mutex::Lock _l(_localConfig_m);
  104. Dictionary::const_iterator i(_localConfig.find(key));
  105. if (i == _localConfig.end())
  106. return std::string();
  107. return i->second;
  108. }
  109. void NodeConfig::clean()
  110. {
  111. Mutex::Lock _l(_networks_m);
  112. for(std::map< uint64_t,SharedPtr<Network> >::const_iterator n(_networks.begin());n!=_networks.end();++n)
  113. n->second->clean();
  114. }
  115. void NodeConfig::_CBcommandHandler(void *arg,IpcConnection *ipcc,IpcConnection::EventType event,const char *commandLine)
  116. {
  117. switch(event) {
  118. case IpcConnection::IPC_EVENT_COMMAND:
  119. ((NodeConfig *)arg)->_doCommand(ipcc,commandLine);
  120. break;
  121. case IpcConnection::IPC_EVENT_NEW_CONNECTION: {
  122. Mutex::Lock _l(((NodeConfig *)arg)->_connections_m);
  123. ((NodeConfig *)arg)->_connections[ipcc] = false; // not yet authenticated
  124. } break;
  125. case IpcConnection::IPC_EVENT_CONNECTION_CLOSED: {
  126. Mutex::Lock _l(((NodeConfig *)arg)->_connections_m);
  127. ((NodeConfig *)arg)->_connections.erase(ipcc);
  128. delete ipcc;
  129. } break;
  130. }
  131. }
  132. // Used with Topology::eachPeer to dump peer stats
  133. class _DumpPeerStatistics
  134. {
  135. public:
  136. _DumpPeerStatistics(IpcConnection *i) :
  137. ipcc(i),
  138. now(Utils::now())
  139. {
  140. }
  141. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  142. {
  143. InetAddress v4(p->ipv4ActivePath(now));
  144. InetAddress v6(p->ipv6ActivePath(now));
  145. if ((v4)||(v6)) {
  146. ipcc->printf("200 listpeers %s %s %s %u %s"ZT_EOL_S,
  147. p->address().toString().c_str(),
  148. ((v4) ? v4.toString().c_str() : "-"),
  149. ((v6) ? v6.toString().c_str() : "-"),
  150. p->latency(),
  151. p->remoteVersion().c_str());
  152. } else {
  153. ipcc->printf("200 listpeers %s - - - %s"ZT_EOL_S,
  154. p->address().toString().c_str(),
  155. p->remoteVersion().c_str());
  156. }
  157. }
  158. IpcConnection *ipcc;
  159. uint64_t now;
  160. };
  161. void NodeConfig::_doCommand(IpcConnection *ipcc,const char *commandLine)
  162. {
  163. if (!commandLine)
  164. return; // sanity check
  165. std::vector<std::string> r;
  166. std::vector<std::string> cmd(Utils::split(commandLine,"\r\n \t","\\","'"));
  167. if ((cmd.empty())||(cmd[0] == "help")) {
  168. ipcc->printf("200 help help"ZT_EOL_S);
  169. ipcc->printf("200 auth token"ZT_EOL_S);
  170. ipcc->printf("200 help info"ZT_EOL_S);
  171. ipcc->printf("200 help listpeers"ZT_EOL_S);
  172. ipcc->printf("200 help listnetworks"ZT_EOL_S);
  173. ipcc->printf("200 help join <network ID>"ZT_EOL_S);
  174. ipcc->printf("200 help leave <network ID>"ZT_EOL_S);
  175. ipcc->printf("200 help terminate [<reason>]"ZT_EOL_S);
  176. ipcc->printf("200 help updatecheck"ZT_EOL_S);
  177. } else if (cmd[0] == "auth") {
  178. if ((cmd.size() > 1)&&(_authToken == cmd[1])) {
  179. Mutex::Lock _l(_connections_m);
  180. _connections[ipcc] = true;
  181. ipcc->printf("200 OK"ZT_EOL_S);
  182. } else ipcc->printf("403 auth failed"ZT_EOL_S);
  183. } else {
  184. {
  185. Mutex::Lock _l(_connections_m);
  186. if (!_connections[ipcc]) {
  187. ipcc->printf("403 not authorized"ZT_EOL_S""ZT_EOL_S);
  188. return;
  189. }
  190. }
  191. if (cmd[0] == "info") {
  192. // We are online if at least one supernode has spoken to us since the last time our
  193. // network environment changed and also less than ZT_PEER_LINK_ACTIVITY_TIMEOUT ago.
  194. bool isOnline = false;
  195. uint64_t now = Utils::now();
  196. uint64_t since = _r->timeOfLastNetworkEnvironmentChange;
  197. std::vector< SharedPtr<Peer> > snp(_r->topology->supernodePeers());
  198. for(std::vector< SharedPtr<Peer> >::const_iterator sn(snp.begin());sn!=snp.end();++sn) {
  199. uint64_t lastRec = (*sn)->lastDirectReceive();
  200. if ((lastRec)&&(lastRec > since)&&((now - lastRec) < ZT_PEER_LINK_ACTIVITY_TIMEOUT)) {
  201. isOnline = true;
  202. break;
  203. }
  204. }
  205. ipcc->printf("200 info %s %s %s"ZT_EOL_S,_r->identity.address().toString().c_str(),(isOnline ? "ONLINE" : "OFFLINE"),Node::versionString());
  206. } else if (cmd[0] == "listpeers") {
  207. ipcc->printf("200 listpeers <ztaddr> <ipv4> <ipv6> <latency> <version>"ZT_EOL_S);
  208. _r->topology->eachPeer(_DumpPeerStatistics(ipcc));
  209. } else if (cmd[0] == "listnetworks") {
  210. Mutex::Lock _l(_networks_m);
  211. ipcc->printf("200 listnetworks <nwid> <name> <status> <config age> <type> <dev> <ips>"ZT_EOL_S);
  212. for(std::map< uint64_t,SharedPtr<Network> >::const_iterator nw(_networks.begin());nw!=_networks.end();++nw) {
  213. std::string tmp;
  214. std::set<InetAddress> ips(nw->second->ips());
  215. for(std::set<InetAddress>::iterator i(ips.begin());i!=ips.end();++i) {
  216. if (tmp.length())
  217. tmp.push_back(',');
  218. tmp.append(i->toString());
  219. }
  220. SharedPtr<NetworkConfig> nconf(nw->second->config2());
  221. long long age = (nconf) ? ((long long)Utils::now() - (long long)nconf->timestamp()) : (long long)0;
  222. if (age < 0)
  223. age = 0;
  224. age /= 1000;
  225. std::string dn(nw->second->tapDeviceName());
  226. ipcc->printf("200 listnetworks %.16llx %s %s %lld %s %s %s"ZT_EOL_S,
  227. (unsigned long long)nw->first,
  228. ((nconf) ? nconf->name().c_str() : "?"),
  229. Network::statusString(nw->second->status()),
  230. age,
  231. ((nconf) ? (nconf->isOpen() ? "public" : "private") : "?"),
  232. (dn.length() > 0) ? dn.c_str() : "?",
  233. ((tmp.length() > 0) ? tmp.c_str() : "-"));
  234. }
  235. } else if (cmd[0] == "join") {
  236. if (cmd.size() > 1) {
  237. uint64_t nwid = Utils::hexStrToU64(cmd[1].c_str());
  238. if (nwid > 0) {
  239. Mutex::Lock _l(_networks_m);
  240. if (_networks.count(nwid)) {
  241. ipcc->printf("409 already a member of %.16llx"ZT_EOL_S,(unsigned long long)nwid);
  242. } else {
  243. try {
  244. SharedPtr<Network> nw(Network::newInstance(_r,this,nwid));
  245. _networks[nwid] = nw;
  246. ipcc->printf("200 join %.16llx OK"ZT_EOL_S,(unsigned long long)nwid);
  247. } catch (std::exception &exc) {
  248. ipcc->printf("500 join %.16llx ERROR: %s"ZT_EOL_S,(unsigned long long)nwid,exc.what());
  249. } catch ( ... ) {
  250. ipcc->printf("500 join %.16llx ERROR: (unknown exception)"ZT_EOL_S,(unsigned long long)nwid);
  251. }
  252. }
  253. } else {
  254. ipcc->printf("400 join requires a network ID (>0) in hexadecimal format"ZT_EOL_S);
  255. }
  256. } else {
  257. ipcc->printf("400 join requires a network ID (>0) in hexadecimal format"ZT_EOL_S);
  258. }
  259. } else if (cmd[0] == "leave") {
  260. if (cmd.size() > 1) {
  261. Mutex::Lock _l(_networks_m);
  262. uint64_t nwid = Utils::hexStrToU64(cmd[1].c_str());
  263. std::map< uint64_t,SharedPtr<Network> >::iterator nw(_networks.find(nwid));
  264. if (nw == _networks.end()) {
  265. ipcc->printf("404 leave %.16llx ERROR: not a member of that network"ZT_EOL_S,(unsigned long long)nwid);
  266. } else {
  267. nw->second->destroyOnDelete();
  268. _networks.erase(nw);
  269. }
  270. } else {
  271. ipcc->printf("400 leave requires a network ID (>0) in hexadecimal format"ZT_EOL_S);
  272. }
  273. } else if (cmd[0] == "terminate") {
  274. if (cmd.size() > 1)
  275. _r->node->terminate(Node::NODE_NORMAL_TERMINATION,cmd[1].c_str());
  276. else _r->node->terminate(Node::NODE_NORMAL_TERMINATION,"terminate via IPC command");
  277. } else if (cmd[0] == "updatecheck") {
  278. if (_r->updater) {
  279. ipcc->printf("200 checking for software updates now at: %s"ZT_EOL_S,ZT_DEFAULTS.updateLatestNfoURL.c_str());
  280. _r->updater->checkNow();
  281. } else {
  282. ipcc->printf("500 software updates are not enabled"ZT_EOL_S);
  283. }
  284. } else {
  285. ipcc->printf("404 %s No such command. Use 'help' for help."ZT_EOL_S,cmd[0].c_str());
  286. }
  287. }
  288. ipcc->printf(ZT_EOL_S); // blank line ends response
  289. }
  290. void NodeConfig::_readLocalConfig()
  291. {
  292. // assumes _localConfig_m is locked
  293. std::string localDotConf(_r->homePath + ZT_PATH_SEPARATOR_S + "local.conf");
  294. std::string buf;
  295. if (Utils::readFile(localDotConf.c_str(),buf))
  296. _localConfig.fromString(buf.c_str());
  297. }
  298. void NodeConfig::_writeLocalConfig()
  299. {
  300. // assumes _localConfig_m is locked
  301. Utils::writeFile(((_r->homePath + ZT_PATH_SEPARATOR_S + "local.conf")).c_str(),_localConfig.toString());
  302. }
  303. } // namespace ZeroTier