NodeConfig.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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((std::string(ZT_IPC_ENDPOINT_BASE) + renv->identity.address().toString()).c_str(),&_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. std::vector<Path> pp(p->paths());
  144. std::string pathsStr;
  145. for(std::vector<Path>::const_iterator ppp(pp.begin());ppp!=pp.end();++ppp) {
  146. if (pathsStr.length())
  147. pathsStr.push_back(',');
  148. pathsStr.append(ppp->toString());
  149. }
  150. ipcc->printf("200 listpeers %s %s %u %s"ZT_EOL_S,
  151. p->address().toString().c_str(),
  152. ((pathsStr.length() > 0) ? pathsStr.c_str() : "-"),
  153. p->latency(),
  154. p->remoteVersion().c_str());
  155. }
  156. IpcConnection *ipcc;
  157. uint64_t now;
  158. };
  159. void NodeConfig::_doCommand(IpcConnection *ipcc,const char *commandLine)
  160. {
  161. if ((!commandLine)||(!commandLine[0]))
  162. return;
  163. std::vector<std::string> r;
  164. std::vector<std::string> cmd(Utils::split(commandLine,"\r\n \t","\\","'"));
  165. if ((cmd.empty())||(cmd[0] == "help")) {
  166. ipcc->printf("200 help help"ZT_EOL_S);
  167. ipcc->printf("200 help auth <token>"ZT_EOL_S);
  168. ipcc->printf("200 help info"ZT_EOL_S);
  169. ipcc->printf("200 help listpeers"ZT_EOL_S);
  170. ipcc->printf("200 help listnetworks"ZT_EOL_S);
  171. ipcc->printf("200 help join <network ID>"ZT_EOL_S);
  172. ipcc->printf("200 help leave <network ID>"ZT_EOL_S);
  173. ipcc->printf("200 help terminate [<reason>]"ZT_EOL_S);
  174. ipcc->printf("200 help updatecheck"ZT_EOL_S);
  175. } else if (cmd[0] == "auth") {
  176. if ((cmd.size() > 1)&&(_authToken == cmd[1])) {
  177. Mutex::Lock _l(_connections_m);
  178. _connections[ipcc] = true;
  179. ipcc->printf("200 auth OK"ZT_EOL_S);
  180. } else ipcc->printf("403 auth failed"ZT_EOL_S);
  181. } else {
  182. {
  183. Mutex::Lock _l(_connections_m);
  184. if (!_connections[ipcc]) {
  185. ipcc->printf("403 %s unauthorized"ZT_EOL_S"."ZT_EOL_S,cmd[0].c_str());
  186. return;
  187. }
  188. }
  189. if (cmd[0] == "info") {
  190. // We are online if at least one supernode has spoken to us since the last time our
  191. // network environment changed and also less than ZT_PEER_LINK_ACTIVITY_TIMEOUT ago.
  192. bool isOnline = false;
  193. uint64_t now = Utils::now();
  194. uint64_t since = _r->timeOfLastResynchronize;
  195. std::vector< SharedPtr<Peer> > snp(_r->topology->supernodePeers());
  196. for(std::vector< SharedPtr<Peer> >::const_iterator sn(snp.begin());sn!=snp.end();++sn) {
  197. uint64_t lastRec = (*sn)->lastDirectReceive();
  198. if ((lastRec)&&(lastRec > since)&&((now - lastRec) < ZT_PEER_PATH_ACTIVITY_TIMEOUT)) {
  199. isOnline = true;
  200. break;
  201. }
  202. }
  203. ipcc->printf("200 info %s %s %s"ZT_EOL_S,_r->identity.address().toString().c_str(),(isOnline ? "ONLINE" : "OFFLINE"),Node::versionString());
  204. } else if (cmd[0] == "listpeers") {
  205. ipcc->printf("200 listpeers <ztaddr> <paths> <latency> <version>"ZT_EOL_S);
  206. _r->topology->eachPeer(_DumpPeerStatistics(ipcc));
  207. } else if (cmd[0] == "listnetworks") {
  208. Mutex::Lock _l(_networks_m);
  209. ipcc->printf("200 listnetworks <nwid> <name> <status> <config age> <type> <dev> <ips>"ZT_EOL_S);
  210. for(std::map< uint64_t,SharedPtr<Network> >::const_iterator nw(_networks.begin());nw!=_networks.end();++nw) {
  211. std::string tmp;
  212. std::set<InetAddress> ips(nw->second->ips());
  213. for(std::set<InetAddress>::iterator i(ips.begin());i!=ips.end();++i) {
  214. if (tmp.length())
  215. tmp.push_back(',');
  216. tmp.append(i->toString());
  217. }
  218. SharedPtr<NetworkConfig> nconf(nw->second->config2());
  219. long long age = (nconf) ? ((long long)Utils::now() - (long long)nconf->timestamp()) : (long long)0;
  220. if (age < 0)
  221. age = 0;
  222. age /= 1000;
  223. std::string dn(nw->second->tapDeviceName());
  224. ipcc->printf("200 listnetworks %.16llx %s %s %lld %s %s %s"ZT_EOL_S,
  225. (unsigned long long)nw->first,
  226. ((nconf) ? nconf->name().c_str() : "?"),
  227. Network::statusString(nw->second->status()),
  228. age,
  229. ((nconf) ? (nconf->isOpen() ? "public" : "private") : "?"),
  230. (dn.length() > 0) ? dn.c_str() : "?",
  231. ((tmp.length() > 0) ? tmp.c_str() : "-"));
  232. }
  233. } else if (cmd[0] == "join") {
  234. if (cmd.size() > 1) {
  235. uint64_t nwid = Utils::hexStrToU64(cmd[1].c_str());
  236. if (nwid > 0) {
  237. Mutex::Lock _l(_networks_m);
  238. if (_networks.count(nwid)) {
  239. ipcc->printf("409 already a member of %.16llx"ZT_EOL_S,(unsigned long long)nwid);
  240. } else {
  241. try {
  242. SharedPtr<Network> nw(Network::newInstance(_r,this,nwid));
  243. _networks[nwid] = nw;
  244. ipcc->printf("200 join %.16llx OK"ZT_EOL_S,(unsigned long long)nwid);
  245. } catch (std::exception &exc) {
  246. ipcc->printf("500 join %.16llx ERROR: %s"ZT_EOL_S,(unsigned long long)nwid,exc.what());
  247. } catch ( ... ) {
  248. ipcc->printf("500 join %.16llx ERROR: (unknown exception)"ZT_EOL_S,(unsigned long long)nwid);
  249. }
  250. }
  251. } else {
  252. ipcc->printf("400 join requires a network ID (>0) in hexadecimal format"ZT_EOL_S);
  253. }
  254. } else {
  255. ipcc->printf("400 join requires a network ID (>0) in hexadecimal format"ZT_EOL_S);
  256. }
  257. } else if (cmd[0] == "leave") {
  258. if (cmd.size() > 1) {
  259. Mutex::Lock _l(_networks_m);
  260. uint64_t nwid = Utils::hexStrToU64(cmd[1].c_str());
  261. std::map< uint64_t,SharedPtr<Network> >::iterator nw(_networks.find(nwid));
  262. if (nw == _networks.end()) {
  263. ipcc->printf("404 leave %.16llx ERROR: not a member of that network"ZT_EOL_S,(unsigned long long)nwid);
  264. } else {
  265. nw->second->destroyOnDelete();
  266. _networks.erase(nw);
  267. }
  268. } else {
  269. ipcc->printf("400 leave requires a network ID (>0) in hexadecimal format"ZT_EOL_S);
  270. }
  271. } else if (cmd[0] == "terminate") {
  272. if (cmd.size() > 1)
  273. _r->node->terminate(Node::NODE_NORMAL_TERMINATION,cmd[1].c_str());
  274. else _r->node->terminate(Node::NODE_NORMAL_TERMINATION,"terminate via IPC command");
  275. } else if (cmd[0] == "updatecheck") {
  276. if (_r->updater) {
  277. ipcc->printf("200 checking for software updates now at: %s"ZT_EOL_S,ZT_DEFAULTS.updateLatestNfoURL.c_str());
  278. _r->updater->checkNow();
  279. } else {
  280. ipcc->printf("500 software updates are not enabled"ZT_EOL_S);
  281. }
  282. } else {
  283. ipcc->printf("404 %s No such command. Use 'help' for help."ZT_EOL_S,cmd[0].c_str());
  284. }
  285. }
  286. ipcc->printf("."ZT_EOL_S); // blank line ends response
  287. }
  288. void NodeConfig::_readLocalConfig()
  289. {
  290. // assumes _localConfig_m is locked
  291. std::string localDotConf(_r->homePath + ZT_PATH_SEPARATOR_S + "local.conf");
  292. std::string buf;
  293. if (Utils::readFile(localDotConf.c_str(),buf))
  294. _localConfig.fromString(buf.c_str());
  295. }
  296. void NodeConfig::_writeLocalConfig()
  297. {
  298. // assumes _localConfig_m is locked
  299. Utils::writeFile(((_r->homePath + ZT_PATH_SEPARATOR_S + "local.conf")).c_str(),_localConfig.toString());
  300. }
  301. } // namespace ZeroTier