2
0

NodeConfig.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. /*
  85. Mutex::Lock _l(_connections_m);
  86. for(std::map< IpcConnection *,bool >::iterator c(_connections.begin());c!=_connections.end();++c)
  87. delete c->first;
  88. _connections.clear();
  89. */
  90. }
  91. void NodeConfig::putLocalConfig(const std::string &key,const char *value)
  92. {
  93. Mutex::Lock _l(_localConfig_m);
  94. _localConfig[key] = value;
  95. _writeLocalConfig();
  96. }
  97. void NodeConfig::putLocalConfig(const std::string &key,const std::string &value)
  98. {
  99. Mutex::Lock _l(_localConfig_m);
  100. _localConfig[key] = value;
  101. _writeLocalConfig();
  102. }
  103. std::string NodeConfig::getLocalConfig(const std::string &key) const
  104. {
  105. Mutex::Lock _l(_localConfig_m);
  106. Dictionary::const_iterator i(_localConfig.find(key));
  107. if (i == _localConfig.end())
  108. return std::string();
  109. return i->second;
  110. }
  111. void NodeConfig::clean()
  112. {
  113. Mutex::Lock _l(_networks_m);
  114. for(std::map< uint64_t,SharedPtr<Network> >::const_iterator n(_networks.begin());n!=_networks.end();++n)
  115. n->second->clean();
  116. }
  117. /*
  118. void NodeConfig::_CBcommandHandler(void *arg,IpcConnection *ipcc,IpcConnection::EventType event,const char *commandLine)
  119. {
  120. switch(event) {
  121. case IpcConnection::IPC_EVENT_COMMAND:
  122. ((NodeConfig *)arg)->_doCommand(ipcc,commandLine);
  123. break;
  124. case IpcConnection::IPC_EVENT_NEW_CONNECTION: {
  125. Mutex::Lock _l(((NodeConfig *)arg)->_connections_m);
  126. ((NodeConfig *)arg)->_connections[ipcc] = false; // not yet authenticated
  127. } break;
  128. case IpcConnection::IPC_EVENT_CONNECTION_CLOSED: {
  129. Mutex::Lock _l(((NodeConfig *)arg)->_connections_m);
  130. ((NodeConfig *)arg)->_connections.erase(ipcc);
  131. delete ipcc;
  132. } break;
  133. }
  134. }
  135. // Used with Topology::eachPeer to dump peer stats
  136. class _DumpPeerStatistics
  137. {
  138. public:
  139. _DumpPeerStatistics(IpcConnection *i) :
  140. ipcc(i),
  141. now(Utils::now())
  142. {
  143. }
  144. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  145. {
  146. std::vector<Path> pp(p->paths());
  147. std::string pathsStr;
  148. for(std::vector<Path>::const_iterator ppp(pp.begin());ppp!=pp.end();++ppp) {
  149. if (pathsStr.length())
  150. pathsStr.push_back(',');
  151. pathsStr.append(ppp->toString());
  152. }
  153. ipcc->printf("200 listpeers %s %s %u %s"ZT_EOL_S,
  154. p->address().toString().c_str(),
  155. ((pathsStr.length() > 0) ? pathsStr.c_str() : "-"),
  156. p->latency(),
  157. p->remoteVersion().c_str());
  158. }
  159. IpcConnection *ipcc;
  160. uint64_t now;
  161. };
  162. void NodeConfig::_doCommand(IpcConnection *ipcc,const char *commandLine)
  163. {
  164. if ((!commandLine)||(!commandLine[0]))
  165. return;
  166. std::vector<std::string> r;
  167. std::vector<std::string> cmd(Utils::split(commandLine,"\r\n \t","\\","'"));
  168. if ((cmd.empty())||(cmd[0] == "help")) {
  169. ipcc->printf("200 help help"ZT_EOL_S);
  170. ipcc->printf("200 help auth <token>"ZT_EOL_S);
  171. ipcc->printf("200 help info"ZT_EOL_S);
  172. ipcc->printf("200 help listpeers"ZT_EOL_S);
  173. ipcc->printf("200 help listnetworks"ZT_EOL_S);
  174. ipcc->printf("200 help join <network ID>"ZT_EOL_S);
  175. ipcc->printf("200 help leave <network ID>"ZT_EOL_S);
  176. ipcc->printf("200 help terminate [<reason>]"ZT_EOL_S);
  177. ipcc->printf("200 help updatecheck"ZT_EOL_S);
  178. } else if (cmd[0] == "auth") {
  179. if ((cmd.size() > 1)&&(_authToken == cmd[1])) {
  180. Mutex::Lock _l(_connections_m);
  181. _connections[ipcc] = true;
  182. ipcc->printf("200 auth OK"ZT_EOL_S);
  183. } else ipcc->printf("403 auth failed"ZT_EOL_S);
  184. } else {
  185. {
  186. Mutex::Lock _l(_connections_m);
  187. if (!_connections[ipcc]) {
  188. ipcc->printf("403 %s unauthorized"ZT_EOL_S"."ZT_EOL_S,cmd[0].c_str());
  189. return;
  190. }
  191. }
  192. if (cmd[0] == "info") {
  193. // We are online if at least one supernode has spoken to us since the last time our
  194. // network environment changed and also less than ZT_PEER_LINK_ACTIVITY_TIMEOUT ago.
  195. bool isOnline = false;
  196. uint64_t now = Utils::now();
  197. uint64_t since = _r->timeOfLastResynchronize;
  198. std::vector< SharedPtr<Peer> > snp(_r->topology->supernodePeers());
  199. for(std::vector< SharedPtr<Peer> >::const_iterator sn(snp.begin());sn!=snp.end();++sn) {
  200. uint64_t lastRec = (*sn)->lastDirectReceive();
  201. if ((lastRec)&&(lastRec > since)&&((now - lastRec) < ZT_PEER_PATH_ACTIVITY_TIMEOUT)) {
  202. isOnline = true;
  203. break;
  204. }
  205. }
  206. ipcc->printf("200 info %s %s %s"ZT_EOL_S,_r->identity.address().toString().c_str(),(isOnline ? "ONLINE" : "OFFLINE"),Node::versionString());
  207. } else if (cmd[0] == "listpeers") {
  208. ipcc->printf("200 listpeers <ztaddr> <paths> <latency> <version>"ZT_EOL_S);
  209. _r->topology->eachPeer(_DumpPeerStatistics(ipcc));
  210. } else if (cmd[0] == "listnetworks") {
  211. Mutex::Lock _l(_networks_m);
  212. ipcc->printf("200 listnetworks <nwid> <name> <mac> <status> <config age> <type> <dev> <ips>"ZT_EOL_S);
  213. for(std::map< uint64_t,SharedPtr<Network> >::const_iterator nw(_networks.begin());nw!=_networks.end();++nw) {
  214. std::string tmp;
  215. std::set<InetAddress> ips(nw->second->ips());
  216. for(std::set<InetAddress>::iterator i(ips.begin());i!=ips.end();++i) {
  217. if (tmp.length())
  218. tmp.push_back(',');
  219. tmp.append(i->toString());
  220. }
  221. SharedPtr<NetworkConfig> nconf(nw->second->config2());
  222. long long age = (nconf) ? ((long long)Utils::now() - (long long)nconf->timestamp()) : (long long)0;
  223. if (age < 0)
  224. age = 0;
  225. age /= 1000;
  226. std::string dn(nw->second->tapDeviceName());
  227. ipcc->printf("200 listnetworks %.16llx %s %s %s %lld %s %s %s"ZT_EOL_S,
  228. (unsigned long long)nw->first,
  229. ((nconf) ? nconf->name().c_str() : "?"),
  230. nw->second->mac().toString().c_str(),
  231. Network::statusString(nw->second->status()),
  232. age,
  233. ((nconf) ? (nconf->isPublic() ? "public" : "private") : "?"),
  234. (dn.length() > 0) ? dn.c_str() : "?",
  235. ((tmp.length() > 0) ? tmp.c_str() : "-"));
  236. }
  237. } else if (cmd[0] == "join") {
  238. if (cmd.size() > 1) {
  239. uint64_t nwid = Utils::hexStrToU64(cmd[1].c_str());
  240. if (nwid > 0) {
  241. Mutex::Lock _l(_networks_m);
  242. if (_networks.count(nwid)) {
  243. ipcc->printf("409 already a member of %.16llx"ZT_EOL_S,(unsigned long long)nwid);
  244. } else {
  245. try {
  246. SharedPtr<Network> nw(Network::newInstance(_r,this,nwid));
  247. _networks[nwid] = nw;
  248. ipcc->printf("200 join %.16llx OK"ZT_EOL_S,(unsigned long long)nwid);
  249. } catch (std::exception &exc) {
  250. ipcc->printf("500 join %.16llx ERROR: %s"ZT_EOL_S,(unsigned long long)nwid,exc.what());
  251. } catch ( ... ) {
  252. ipcc->printf("500 join %.16llx ERROR: (unknown exception)"ZT_EOL_S,(unsigned long long)nwid);
  253. }
  254. }
  255. } else {
  256. ipcc->printf("400 join requires a network ID (>0) in hexadecimal format"ZT_EOL_S);
  257. }
  258. } else {
  259. ipcc->printf("400 join requires a network ID (>0) in hexadecimal format"ZT_EOL_S);
  260. }
  261. } else if (cmd[0] == "leave") {
  262. if (cmd.size() > 1) {
  263. Mutex::Lock _l(_networks_m);
  264. uint64_t nwid = Utils::hexStrToU64(cmd[1].c_str());
  265. std::map< uint64_t,SharedPtr<Network> >::iterator nw(_networks.find(nwid));
  266. if (nw == _networks.end()) {
  267. ipcc->printf("404 leave %.16llx ERROR: not a member of that network"ZT_EOL_S,(unsigned long long)nwid);
  268. } else {
  269. nw->second->destroy();
  270. _networks.erase(nw);
  271. }
  272. } else {
  273. ipcc->printf("400 leave requires a network ID (>0) in hexadecimal format"ZT_EOL_S);
  274. }
  275. } else if (cmd[0] == "terminate") {
  276. if (cmd.size() > 1)
  277. _r->node->terminate(Node::NODE_NORMAL_TERMINATION,cmd[1].c_str());
  278. else _r->node->terminate(Node::NODE_NORMAL_TERMINATION,"terminate via IPC command");
  279. } else if (cmd[0] == "updatecheck") {
  280. if (_r->updater) {
  281. ipcc->printf("200 checking for software updates now at: %s"ZT_EOL_S,ZT_DEFAULTS.updateLatestNfoURL.c_str());
  282. _r->updater->checkNow();
  283. } else {
  284. ipcc->printf("500 software updates are not enabled"ZT_EOL_S);
  285. }
  286. } else {
  287. ipcc->printf("404 %s No such command. Use 'help' for help."ZT_EOL_S,cmd[0].c_str());
  288. }
  289. }
  290. ipcc->printf("."ZT_EOL_S); // blank line ends response
  291. }
  292. */
  293. void NodeConfig::_readLocalConfig()
  294. {
  295. // assumes _localConfig_m is locked
  296. std::string localDotConf(_r->homePath + ZT_PATH_SEPARATOR_S + "local.conf");
  297. std::string buf;
  298. if (Utils::readFile(localDotConf.c_str(),buf))
  299. _localConfig.fromString(buf.c_str());
  300. }
  301. void NodeConfig::_writeLocalConfig()
  302. {
  303. // assumes _localConfig_m is locked
  304. Utils::writeFile(((_r->homePath + ZT_PATH_SEPARATOR_S + "local.conf")).c_str(),_localConfig.toString());
  305. }
  306. } // namespace ZeroTier