summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAdam Ierymenko <adam.ierymenko@gmail.com>2014-03-19 08:20:09 -0700
committerAdam Ierymenko <adam.ierymenko@gmail.com>2014-03-19 08:20:09 -0700
commitacf7d70d241c6afc1f3f13fb7b678882f1ec3ea5 (patch)
tree6fe15b9d0305f00787db610424c9aa26322f03ba
parent3be4c38946ddd38134f2093bc55950d45b1d1a6c (diff)
downloadinfinitytier-acf7d70d241c6afc1f3f13fb7b678882f1ec3ea5.tar.gz
infinitytier-acf7d70d241c6afc1f3f13fb7b678882f1ec3ea5.zip
Integrate IPC stuff into NodeConfig.
-rw-r--r--node/IpcConnection.cpp65
-rw-r--r--node/IpcConnection.hpp24
-rw-r--r--node/IpcListener.cpp7
-rw-r--r--node/IpcListener.hpp22
-rw-r--r--node/NodeConfig.cpp400
-rw-r--r--node/NodeConfig.hpp62
6 files changed, 236 insertions, 344 deletions
diff --git a/node/IpcConnection.cpp b/node/IpcConnection.cpp
index 784c651d..c6937004 100644
--- a/node/IpcConnection.cpp
+++ b/node/IpcConnection.cpp
@@ -46,11 +46,13 @@
namespace ZeroTier {
-IpcConnection::IpcConnection(const char *endpoint,void (*commandHandler)(void *,const SharedPtr<IpcConnection> &,const char *),void *arg) :
+IpcConnection::IpcConnection(const char *endpoint,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg) :
_handler(commandHandler),
_arg(arg),
_sock(0)
{
+#ifdef __WINDOWS__
+#else
struct sockaddr_un unaddr;
unaddr.sun_family = AF_UNIX;
strncpy(unaddr.sun_path,endpoint,sizeof(unaddr.sun_path));
@@ -64,11 +66,12 @@ IpcConnection::IpcConnection(const char *endpoint,void (*commandHandler)(void *,
::close(_sock);
throw std::runtime_error("IPC endpoint unreachable");
}
+#endif
Thread::start(this);
}
-IpcConnection::IpcConnection(int s,void (*commandHandler)(void *,const SharedPtr<IpcConnection> &,const char *),void *arg) :
+IpcConnection::IpcConnection(int s,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg) :
_handler(commandHandler),
_arg(arg),
_sock(s)
@@ -78,7 +81,17 @@ IpcConnection::IpcConnection(int s,void (*commandHandler)(void *,const SharedPtr
IpcConnection::~IpcConnection()
{
- this->close();
+#ifdef __WINDOWS__
+#else
+ _writeLock.lock();
+ int s = _sock;
+ _sock = 0;
+ if (s > 0) {
+ ::shutdown(s,SHUT_RDWR);
+ ::close(s);
+ }
+ _writeLock.unlock();
+#endif
}
void IpcConnection::printf(const char *format,...)
@@ -95,44 +108,56 @@ void IpcConnection::printf(const char *format,...)
va_start(ap,format);
n = (int)::vsnprintf(tmp,sizeof(tmp),format,ap);
va_end(ap);
+ if (n <= 0)
+ return;
+#ifdef __WINDOWS__
+#else
::write(_sock,tmp,n);
-}
-
-void IpcConnection::close()
-{
- Mutex::Lock _l(_writeLock);
- int s = _sock;
- _sock = 0;
- if (s > 0) {
- ::shutdown(s,SHUT_RDWR);
- ::close(s);
- }
- Thread::join(_thread);
+#endif
}
void IpcConnection::threadMain()
throw()
{
+#ifdef __WINDOWS__
+#else
char tmp[65536];
char linebuf[65536];
unsigned int lineptr = 0;
+ int s,n,i;
+ char c;
- while (_sock) {
- int n = (int)::read(_sock,tmp,sizeof(tmp));
+ for(;;) {
+ s = _sock;
+ if (s <= 0)
+ break;
+ n = (int)::read(s,tmp,sizeof(tmp));
if (n <= 0)
break;
- for(int i=0;i<n;++i) {
- char c = (linebuf[lineptr] = tmp[i]);
+ for(i=0;i<n;++i) {
+ c = (linebuf[lineptr] = tmp[i]);
if ((c == '\r')||(c == '\n')||(lineptr == (sizeof(linebuf) - 1))) {
if (lineptr) {
linebuf[lineptr] = (char)0;
- _handler(_arg,SharedPtr<IpcConnection>(this),linebuf);
+ _handler(_arg,this,IPC_EVENT_COMMAND,linebuf);
lineptr = 0;
}
} else ++lineptr;
}
}
+
+ {
+ _writeLock.lock();
+ int s = _sock;
+ _sock = 0;
+ if (s > 0)
+ ::close(s);
+ _writeLock.unlock();
+ }
+
+ _handler(_arg,this,IPC_EVENT_CONNECTION_CLOSING,(const char *)0);
+#endif
}
} // namespace ZeroTier
diff --git a/node/IpcConnection.hpp b/node/IpcConnection.hpp
index 60d34634..d1294d36 100644
--- a/node/IpcConnection.hpp
+++ b/node/IpcConnection.hpp
@@ -32,8 +32,6 @@
#include "Thread.hpp"
#include "NonCopyable.hpp"
#include "Mutex.hpp"
-#include "SharedPtr.hpp"
-#include "AtomicCounter.hpp"
namespace ZeroTier {
@@ -45,9 +43,15 @@ class IpcListener;
class IpcConnection : NonCopyable
{
friend class IpcListener;
- friend class SharedPtr<IpcConnection>;
public:
+ enum EventType
+ {
+ IPC_EVENT_COMMAND,
+ IPC_EVENT_NEW_CONNECTION,
+ IPC_EVENT_CONNECTION_CLOSED
+ };
+
/**
* Connect to an IPC endpoint
*
@@ -56,7 +60,7 @@ public:
* @param arg First argument to command handler
* @throws std::runtime_error Unable to connect
*/
- IpcConnection(const char *endpoint,void (*commandHandler)(void *,const SharedPtr<IpcConnection> &,const char *),void *arg);
+ IpcConnection(const char *endpoint,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg);
~IpcConnection();
/**
@@ -65,25 +69,17 @@ public:
*/
void printf(const char *format,...);
- /**
- * Close this connection
- */
- void close();
-
void threadMain()
throw();
private:
// Used by IpcListener to construct incoming connections
- IpcConnection(int s,void (*commandHandler)(void *,const SharedPtr<IpcConnection> &,const char *),void *arg);
+ IpcConnection(int s,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg);
- void (*_handler)(void *,const SharedPtr<IpcConnection> &,const char *);
+ void (*_handler)(void *,IpcConnection *,IpcConnection::EventType,const char *);
void *_arg;
volatile int _sock;
- Thread _thread;
Mutex _writeLock;
-
- AtomicCounter __refCount;
};
} // namespace ZeroTier
diff --git a/node/IpcListener.cpp b/node/IpcListener.cpp
index 3cc5fb23..dc5ef52a 100644
--- a/node/IpcListener.cpp
+++ b/node/IpcListener.cpp
@@ -30,10 +30,7 @@
#include <string.h>
#include <errno.h>
-#include <set>
-
#include "IpcListener.hpp"
-#include "IpcConnection.hpp"
#ifdef __WINDOWS__
#include <WinSock2.h>
@@ -46,7 +43,7 @@
namespace ZeroTier {
-IpcListener::IpcListener(const char *ep,void (*commandHandler)(void *,const SharedPtr<IpcConnection> &,const char *),void *arg) :
+IpcListener::IpcListener(const char *ep,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg) :
_endpoint(ep),
_handler(commandHandler),
_arg(arg),
@@ -127,7 +124,7 @@ void IpcListener::threadMain()
break;
}
try {
- _handler(_arg,SharedPtr<IpcConnection>(new IpcConnection(s,_handler,_arg)),(const char *)0);
+ _handler(_arg,new IpcConnection(s,_handler,_arg),Ipcconnection::IPC_EVENT_NEW_CONNECTION,(const char *)0);
} catch ( ... ) {} // handlers should not throw
}
#endif
diff --git a/node/IpcListener.hpp b/node/IpcListener.hpp
index 40beba0d..897c5451 100644
--- a/node/IpcListener.hpp
+++ b/node/IpcListener.hpp
@@ -31,7 +31,7 @@
#include "Constants.hpp"
#include "Thread.hpp"
#include "NonCopyable.hpp"
-#include "SharedPtr.hpp"
+#include "IpcConnection.hpp"
#include <string>
#include <stdexcept>
@@ -44,8 +44,6 @@
namespace ZeroTier {
-class IpcConnection;
-
/**
* IPC incoming connection listener (Unix domain sockets or named pipes on Windows)
*/
@@ -53,11 +51,25 @@ class IpcListener : NonCopyable
{
public:
/**
+ * Listen for IPC connections
+ *
+ * The supplied handler is passed on to incoming instances of IpcConnection. When
+ * a connection is first opened, it is called with IPC_EVENT_NEW_CONNECTION. The
+ * receiver must take ownership of the connection object. When a connection is
+ * closed, IPC_EVENT_CONNECTION_CLOSING is generated. At this point (or after) the
+ * receiver must delete the object. IPC_EVENT_COMMAND is generated when lines of
+ * text are read, and in this cases the last argument is not NULL. No closed event
+ * is generated in the event of manual delete if the connection is still open.
+ *
+ * Yeah, this whole callback model sort of sucks. Might rethink and replace with
+ * some kind of actor model or something if it gets too unweildy. But for now the
+ * use cases are simple enough that it's not too bad.
+ *
* @param commandHandler Function to call for each command
* @param arg First argument to pass to handler
* @throws std::runtime_error Unable to bind to endpoint
*/
- IpcListener(const char *ep,void (*commandHandler)(void *,const SharedPtr<IpcConnection> &,const char *),void *arg);
+ IpcListener(const char *ep,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg);
~IpcListener();
@@ -66,7 +78,7 @@ public:
private:
std::string _endpoint;
- void (*_handler)(void *,const SharedPtr<IpcConnection> &,const char *);
+ void (*_handler)(void *,IpcConnection *,const char *);
void *_arg;
volatile int _sock;
Thread _thread;
diff --git a/node/NodeConfig.cpp b/node/NodeConfig.cpp
index 81fd8d3d..48782efa 100644
--- a/node/NodeConfig.cpp
+++ b/node/NodeConfig.cpp
@@ -37,41 +37,27 @@
#include "Constants.hpp"
-#ifdef __WINDOWS__
-#include <WinSock2.h>
-#include <Windows.h>
-#endif
-
#include "NodeConfig.hpp"
#include "RuntimeEnvironment.hpp"
#include "Defaults.hpp"
#include "Utils.hpp"
#include "Logger.hpp"
#include "Topology.hpp"
-#include "Demarc.hpp"
#include "Packet.hpp"
#include "InetAddress.hpp"
#include "Peer.hpp"
-#include "Salsa20.hpp"
-#include "Poly1305.hpp"
-#include "SHA512.hpp"
#include "Node.hpp"
#include "SoftwareUpdater.hpp"
namespace ZeroTier {
-NodeConfig::NodeConfig(const RuntimeEnvironment *renv,const char *authToken,unsigned int controlPort) :
+NodeConfig::NodeConfig(const RuntimeEnvironment *renv,const char *authToken) :
_r(renv),
- _controlSocket(true,controlPort,false,&_CBcontrolPacketHandler,this)
+ _ipcListener(ZT_IPC_ENDPOINT,&_CBcommandHandler,this),
+ _authToken(authToken)
{
{
- unsigned int csk[64];
- SHA512::hash(csk,authToken,(unsigned int)strlen(authToken));
- memcpy(_controlSocketKey,csk,32);
- }
-
- {
- Mutex::Lock _llc(_localConfig_m);
+ Mutex::Lock _l(_localConfig_m);
_readLocalConfig();
}
@@ -103,6 +89,12 @@ NodeConfig::NodeConfig(const RuntimeEnvironment *renv,const char *authToken,unsi
NodeConfig::~NodeConfig()
{
_writeLocalConfig();
+
+ // Close any open IPC connections
+ Mutex::Lock _l(_connections_m);
+ for(std::map< IpcConnection *,bool >::iterator c(_connections.begin());c!=_connections.end();++c)
+ delete c->first;
+ _connections.clear();
}
void NodeConfig::putLocalConfig(const std::string &key,const char *value)
@@ -135,283 +127,191 @@ void NodeConfig::clean()
n->second->clean();
}
-/////////////////////////////////////////////////////////////////////////////
-// UDP localhost control bus
-
-// Macro used in execute() to push lines onto the return packet
-#undef _P
-#define _P(f,...) { r.push_back(std::string()); Utils::stdsprintf(r.back(),(f),##__VA_ARGS__); }
+void NodeConfig::_CBcommandHandler(void *arg,IpcConnection *ipcc,IpcConnection::EventType event,const char *commandLine)
+{
+ switch(event) {
+ case IpcConnection::IPC_EVENT_COMMAND:
+ ((NodeConfig *)arg)->_doCommand(ipcc,commandLine);
+ break;
+ case IpcConnection::IPC_EVENT_NEW_CONNECTION: {
+ Mutex::Lock _l(((NodeConfig *)arg)->_connections_m);
+ ((NodeConfig *)arg)->_connections[ipcc] = false; // not yet authenticated
+ } break;
+ case IpcConnection::IPC_EVENT_CONNECTION_CLOSED: {
+ Mutex::Lock _l(((NodeConfig *)arg)->_connections_m);
+ ((NodeConfig *)arg)->_connections.erase(ipcc);
+ delete ipcc;
+ } break;
+ }
+}
// Used with Topology::eachPeer to dump peer stats
class _DumpPeerStatistics
{
public:
- _DumpPeerStatistics(std::vector<std::string> &out) :
- r(out),
- _now(Utils::now())
+ _DumpPeerStatistics(IpcConnection *i) :
+ ipcc(i),
+ now(Utils::now())
{
}
-
inline void operator()(Topology &t,const SharedPtr<Peer> &p)
{
- InetAddress v4(p->ipv4ActivePath(_now));
- InetAddress v6(p->ipv6ActivePath(_now));
+ InetAddress v4(p->ipv4ActivePath(now));
+ InetAddress v6(p->ipv6ActivePath(now));
if ((v4)||(v6)) {
- _P("200 listpeers %s %s %s %u %s",
+ ipcc->printf("200 listpeers %s %s %s %u %s"ZT_EOL_S,
p->address().toString().c_str(),
((v4) ? v4.toString().c_str() : "-"),
((v6) ? v6.toString().c_str() : "-"),
p->latency(),
p->remoteVersion().c_str());
} else {
- _P("200 listpeers %s - - - %s",
+ ipcc->printf("200 listpeers %s - - - %s"ZT_EOL_S,
p->address().toString().c_str(),
p->remoteVersion().c_str());
}
}
-
-private:
- std::vector<std::string> &r;
- uint64_t _now;
+ IpcConnection *ipcc;
+ uint64_t now;
};
-std::vector<std::string> NodeConfig::execute(const char *command)
+void NodeConfig::_doCommand(IpcConnection *ipcc,const char *commandLine)
{
+ if (!commandLine)
+ return; // sanity check
std::vector<std::string> r;
- std::vector<std::string> cmd(Utils::split(command,"\r\n \t","\\","'"));
-
- /* Not coincidentally, response type codes correspond with HTTP
- * status codes. Technically a little arbitrary, but would maybe
- * make things easier if we wanted to slap some kind of web API
- * in front of this thing. */
+ std::vector<std::string> cmd(Utils::split(commandLine,"\r\n \t","\\","'"));
if ((cmd.empty())||(cmd[0] == "help")) {
- _P("200 help help");
- _P("200 help info");
- _P("200 help listpeers");
- _P("200 help listnetworks");
- _P("200 help join <network ID>");
- _P("200 help leave <network ID>");
- _P("200 help terminate [<reason>]");
- _P("200 help updatecheck");
- } else if (cmd[0] == "info") {
- // We are online if at least one supernode has spoken to us since the last time our
- // network environment changed and also less than ZT_PEER_LINK_ACTIVITY_TIMEOUT ago.
- bool isOnline = false;
- uint64_t now = Utils::now();
- uint64_t since = _r->timeOfLastNetworkEnvironmentChange;
- std::vector< SharedPtr<Peer> > snp(_r->topology->supernodePeers());
- for(std::vector< SharedPtr<Peer> >::const_iterator sn(snp.begin());sn!=snp.end();++sn) {
- uint64_t lastRec = (*sn)->lastDirectReceive();
- if ((lastRec)&&(lastRec > since)&&((now - lastRec) < ZT_PEER_LINK_ACTIVITY_TIMEOUT)) {
- isOnline = true;
- break;
+ ipcc->printf("200 help help"ZT_EOL_S);
+ ipcc->printf("200 auth token"ZT_EOL_S);
+ ipcc->printf("200 help info"ZT_EOL_S);
+ ipcc->printf("200 help listpeers"ZT_EOL_S);
+ ipcc->printf("200 help listnetworks"ZT_EOL_S);
+ ipcc->printf("200 help join <network ID>"ZT_EOL_S);
+ ipcc->printf("200 help leave <network ID>"ZT_EOL_S);
+ ipcc->printf("200 help terminate [<reason>]"ZT_EOL_S);
+ ipcc->printf("200 help updatecheck"ZT_EOL_S);
+ } else if (cmd[0] == "auth") {
+ if ((cmd.size() > 1)&&(_authToken == cmd[1])) {
+ Mutex::Lock _l(_connections_m);
+ _connections[ipcc] = true;
+ ipcc->printf("200 OK"ZT_EOL_S);
+ } else ipcc->printf("403 auth failed"ZT_EOL_S);
+ } else {
+ {
+ Mutex::Lock _l(_connections_m);
+ if (!_connections[ipcc]) {
+ ipcc->printf("403 not authorized"ZT_EOL_S""ZT_EOL_S);
+ return;
}
}
- _P("200 info %s %s %s",_r->identity.address().toString().c_str(),(isOnline ? "ONLINE" : "OFFLINE"),Node::versionString());
- } else if (cmd[0] == "listpeers") {
- _P("200 listpeers <ztaddr> <ipv4> <ipv6> <latency> <version>");
- _r->topology->eachPeer(_DumpPeerStatistics(r));
- } else if (cmd[0] == "listnetworks") {
- Mutex::Lock _l(_networks_m);
- _P("200 listnetworks <nwid> <name> <status> <config age> <type> <dev> <ips>");
- for(std::map< uint64_t,SharedPtr<Network> >::const_iterator nw(_networks.begin());nw!=_networks.end();++nw) {
- std::string tmp;
- std::set<InetAddress> ips(nw->second->ips());
- for(std::set<InetAddress>::iterator i(ips.begin());i!=ips.end();++i) {
- if (tmp.length())
- tmp.push_back(',');
- tmp.append(i->toString());
+ if (cmd[0] == "info") {
+ // We are online if at least one supernode has spoken to us since the last time our
+ // network environment changed and also less than ZT_PEER_LINK_ACTIVITY_TIMEOUT ago.
+ bool isOnline = false;
+ uint64_t now = Utils::now();
+ uint64_t since = _r->timeOfLastNetworkEnvironmentChange;
+ std::vector< SharedPtr<Peer> > snp(_r->topology->supernodePeers());
+ for(std::vector< SharedPtr<Peer> >::const_iterator sn(snp.begin());sn!=snp.end();++sn) {
+ uint64_t lastRec = (*sn)->lastDirectReceive();
+ if ((lastRec)&&(lastRec > since)&&((now - lastRec) < ZT_PEER_LINK_ACTIVITY_TIMEOUT)) {
+ isOnline = true;
+ break;
+ }
}
- SharedPtr<NetworkConfig> nconf(nw->second->config2());
-
- long long age = (nconf) ? ((long long)Utils::now() - (long long)nconf->timestamp()) : (long long)0;
- if (age < 0)
- age = 0;
- age /= 1000;
+ ipcc->printf("200 info %s %s %s"ZT_EOL_S,_r->identity.address().toString().c_str(),(isOnline ? "ONLINE" : "OFFLINE"),Node::versionString());
+ } else if (cmd[0] == "listpeers") {
+ ipcc->printf("200 listpeers <ztaddr> <ipv4> <ipv6> <latency> <version>"ZT_EOL_S);
+ _r->topology->eachPeer(_DumpPeerStatistics(ipcc));
+ } else if (cmd[0] == "listnetworks") {
+ Mutex::Lock _l(_networks_m);
+ ipcc->printf("200 listnetworks <nwid> <name> <status> <config age> <type> <dev> <ips>"ZT_EOL_S);
+ for(std::map< uint64_t,SharedPtr<Network> >::const_iterator nw(_networks.begin());nw!=_networks.end();++nw) {
+ std::string tmp;
+ std::set<InetAddress> ips(nw->second->ips());
+ for(std::set<InetAddress>::iterator i(ips.begin());i!=ips.end();++i) {
+ if (tmp.length())
+ tmp.push_back(',');
+ tmp.append(i->toString());
+ }
- std::string dn(nw->second->tapDeviceName());
- _P("200 listnetworks %.16llx %s %s %lld %s %s %s",
- (unsigned long long)nw->first,
- ((nconf) ? nconf->name().c_str() : "?"),
- Network::statusString(nw->second->status()),
- age,
- ((nconf) ? (nconf->isOpen() ? "public" : "private") : "?"),
- (dn.length() > 0) ? dn.c_str() : "?",
- ((tmp.length() > 0) ? tmp.c_str() : "-"));
- }
- } else if (cmd[0] == "join") {
- if (cmd.size() > 1) {
- uint64_t nwid = Utils::hexStrToU64(cmd[1].c_str());
- if (nwid > 0) {
+ SharedPtr<NetworkConfig> nconf(nw->second->config2());
+
+ long long age = (nconf) ? ((long long)Utils::now() - (long long)nconf->timestamp()) : (long long)0;
+ if (age < 0)
+ age = 0;
+ age /= 1000;
+
+ std::string dn(nw->second->tapDeviceName());
+ ipcc->printf("200 listnetworks %.16llx %s %s %lld %s %s %s"ZT_EOL_S,
+ (unsigned long long)nw->first,
+ ((nconf) ? nconf->name().c_str() : "?"),
+ Network::statusString(nw->second->status()),
+ age,
+ ((nconf) ? (nconf->isOpen() ? "public" : "private") : "?"),
+ (dn.length() > 0) ? dn.c_str() : "?",
+ ((tmp.length() > 0) ? tmp.c_str() : "-"));
+ }
+ } else if (cmd[0] == "join") {
+ if (cmd.size() > 1) {
+ uint64_t nwid = Utils::hexStrToU64(cmd[1].c_str());
+ if (nwid > 0) {
+ Mutex::Lock _l(_networks_m);
+ if (_networks.count(nwid)) {
+ ipcc->printf("409 already a member of %.16llx"ZT_EOL_S,(unsigned long long)nwid);
+ } else {
+ try {
+ SharedPtr<Network> nw(Network::newInstance(_r,this,nwid));
+ _networks[nwid] = nw;
+ ipcc->printf("200 join %.16llx OK"ZT_EOL_S,(unsigned long long)nwid);
+ } catch (std::exception &exc) {
+ ipcc->printf("500 join %.16llx ERROR: %s"ZT_EOL_S,(unsigned long long)nwid,exc.what());
+ } catch ( ... ) {
+ ipcc->printf("500 join %.16llx ERROR: (unknown exception)"ZT_EOL_S,(unsigned long long)nwid);
+ }
+ }
+ } else {
+ ipcc->printf("400 join requires a network ID (>0) in hexadecimal format"ZT_EOL_S);
+ }
+ } else {
+ ipcc->printf("400 join requires a network ID (>0) in hexadecimal format"ZT_EOL_S);
+ }
+ } else if (cmd[0] == "leave") {
+ if (cmd.size() > 1) {
Mutex::Lock _l(_networks_m);
- if (_networks.count(nwid)) {
- _P("409 already a member of %.16llx",(unsigned long long)nwid);
+ uint64_t nwid = Utils::hexStrToU64(cmd[1].c_str());
+ std::map< uint64_t,SharedPtr<Network> >::iterator nw(_networks.find(nwid));
+ if (nw == _networks.end()) {
+ ipcc->printf("404 leave %.16llx ERROR: not a member of that network"ZT_EOL_S,(unsigned long long)nwid);
} else {
- try {
- SharedPtr<Network> nw(Network::newInstance(_r,this,nwid));
- _networks[nwid] = nw;
- _P("200 join %.16llx OK",(unsigned long long)nwid);
- } catch (std::exception &exc) {
- _P("500 join %.16llx ERROR: %s",(unsigned long long)nwid,exc.what());
- } catch ( ... ) {
- _P("500 join %.16llx ERROR: (unknown exception)",(unsigned long long)nwid);
- }
+ nw->second->destroyOnDelete();
+ _networks.erase(nw);
}
} else {
- _P("400 join requires a network ID (>0) in hexadecimal format");
+ ipcc->printf("400 leave requires a network ID (>0) in hexadecimal format"ZT_EOL_S);
}
- } else {
- _P("400 join requires a network ID (>0) in hexadecimal format");
- }
- } else if (cmd[0] == "leave") {
- if (cmd.size() > 1) {
- Mutex::Lock _l(_networks_m);
- uint64_t nwid = Utils::hexStrToU64(cmd[1].c_str());
- std::map< uint64_t,SharedPtr<Network> >::iterator nw(_networks.find(nwid));
- if (nw == _networks.end()) {
- _P("404 leave %.16llx ERROR: not a member of that network",(unsigned long long)nwid);
+ } else if (cmd[0] == "terminate") {
+ if (cmd.size() > 1)
+ _r->node->terminate(Node::NODE_NORMAL_TERMINATION,cmd[1].c_str());
+ else _r->node->terminate(Node::NODE_NORMAL_TERMINATION,"terminate via IPC command");
+ } else if (cmd[0] == "updatecheck") {
+ if (_r->updater) {
+ ipcc->printf("200 checking for software updates now at: %s"ZT_EOL_S,ZT_DEFAULTS.updateLatestNfoURL.c_str());
+ _r->updater->checkNow();
} else {
- nw->second->destroyOnDelete();
- _networks.erase(nw);
+ ipcc->printf("500 software updates are not enabled"ZT_EOL_S);
}
} else {
- _P("400 leave requires a network ID (>0) in hexadecimal format");
- }
- } else if (cmd[0] == "terminate") {
- if (cmd.size() > 1)
- _r->node->terminate(Node::NODE_NORMAL_TERMINATION,cmd[1].c_str());
- else _r->node->terminate(Node::NODE_NORMAL_TERMINATION,(const char *)0);
- } else if (cmd[0] == "updatecheck") {
- if (_r->updater) {
- _P("200 checking for software updates now at: %s",ZT_DEFAULTS.updateLatestNfoURL.c_str());
- _r->updater->checkNow();
- } else {
- _P("500 software updates are not enabled");
+ ipcc->printf("404 %s No such command. Use 'help' for help."ZT_EOL_S,cmd[0].c_str());
}
- } else {
- _P("404 %s No such command. Use 'help' for help.",cmd[0].c_str());
}
- r.push_back(std::string()); // terminate with empty line
-
- return r;
+ ipcc->printf(ZT_EOL_S); // blank line ends response
}
-std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> > NodeConfig::encodeControlMessage(const void *key,unsigned long conversationId,const std::vector<std::string> &payload)
-{
- char poly1305tag[ZT_POLY1305_MAC_LEN];
- char iv[8];
- char keytmp[32];
- std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> > packets;
- Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> packet;
-
- packet.setSize(16); // room for poly1305 auth tag and IV
- packet.append((uint32_t)(conversationId & 0xffffffff));
-
- for(unsigned int i=0;i<payload.size();++i) {
- packet.append(payload[i]); // will throw if too big
- packet.append((unsigned char)0);
-
- if (((i + 1) >= payload.size())||((packet.size() + payload[i + 1].length() + 1) >= packet.capacity())) {
- Utils::getSecureRandom(iv,8);
- memcpy(packet.field(8,8),iv,8);
-
- Salsa20 s20(key,256,iv,ZT_PROTO_SALSA20_ROUNDS);
- s20.encrypt(packet.field(16,packet.size() - 16),packet.field(16,packet.size() - 16),packet.size() - 16);
-
- memcpy(keytmp,key,32);
- for(unsigned int i=0;i<8;++i)
- keytmp[i] ^= iv[i]; // can't reuse poly1305 keys, so mangle key with IV each time
- Poly1305::compute(poly1305tag,packet.field(16,packet.size() - 16),packet.size() - 16,keytmp);
- memcpy(packet.field(0,8),poly1305tag,8);
-
- packets.push_back(packet);
-
- packet.setSize(16); // room for poly1305 auth tag and IV
- packet.append((uint32_t)(conversationId & 0xffffffff));
- }
- }
-
- return packets;
-}
-
-bool NodeConfig::decodeControlMessagePacket(const void *key,const void *data,unsigned int len,unsigned long &conversationId,std::vector<std::string> &payload)
-{
- char poly1305tag[ZT_POLY1305_MAC_LEN];
- char keytmp[32];
- char iv[8];
-
- try {
- if (len < 20)
- return false;
-
- Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> packet(data,len);
-
- memcpy(keytmp,key,32);
- memcpy(iv,packet.field(8,8),8);
- for(unsigned int i=0;i<8;++i)
- keytmp[i] ^= iv[i];
- Poly1305::compute(poly1305tag,packet.field(16,packet.size() - 16),packet.size() - 16,keytmp);
- if (!Utils::secureEq(packet.field(0,8),poly1305tag,8))
- return false;
-
- Salsa20 s20(key,256,packet.field(8,8),ZT_PROTO_SALSA20_ROUNDS);
- s20.decrypt(packet.field(16,packet.size() - 16),packet.field(16,packet.size() - 16),packet.size() - 16);
-
- conversationId = packet.at<uint32_t>(16);
-
- const char *pl = ((const char *)packet.data()) + 20;
- unsigned int pll = packet.size() - 20;
- for(unsigned int i=0;i<pll;) {
- unsigned int eos = i;
- while ((eos < pll)&&(pl[eos]))
- ++eos;
- if (eos >= i) {
- payload.push_back(std::string(pl + i,eos - i));
- i = eos + 1;
- } else break;
- }
-
- return true;
- } catch ( ... ) {
- return false;
- }
-}
-
-void NodeConfig::_CBcontrolPacketHandler(UdpSocket *sock,void *arg,const InetAddress &remoteAddr,const void *data,unsigned int len)
-{
- NodeConfig *nc = (NodeConfig *)arg;
-#ifdef ZT_TRACE
- const RuntimeEnvironment *_r = nc->_r;
-#endif
-
- try {
- unsigned long convId = 0;
- std::vector<std::string> commands;
-
- if (!decodeControlMessagePacket(nc->_controlSocketKey,data,len,convId,commands)) {
- TRACE("control bus packet from %s failed decode, discarded",remoteAddr.toString().c_str());
- return;
- }
- TRACE("control bus packet from %s, contains %d commands",remoteAddr.toString().c_str(),(int)commands.size());
-
- for(std::vector<std::string>::iterator c(commands.begin());c!=commands.end();++c) {
- std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> > resultPackets(encodeControlMessage(nc->_controlSocketKey,convId,nc->execute(c->c_str())));
- for(std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> >::iterator p(resultPackets.begin());p!=resultPackets.end();++p)
- sock->send(remoteAddr,p->data(),p->size(),-1);
- }
- } catch (std::exception &exc) {
- TRACE("exception handling control bus packet from %s: %s",remoteAddr.toString().c_str(),exc.what());
- } catch ( ... ) {
- TRACE("exception handling control bus packet from %s: (unknown)",remoteAddr.toString().c_str());
- }
-}
-
-/////////////////////////////////////////////////////////////////////////////
-
void NodeConfig::_readLocalConfig()
{
// assumes _localConfig_m is locked
diff --git a/node/NodeConfig.hpp b/node/NodeConfig.hpp
index 4b385c12..ada135ac 100644
--- a/node/NodeConfig.hpp
+++ b/node/NodeConfig.hpp
@@ -36,10 +36,11 @@
#include <vector>
#include <stdexcept>
+#include "IpcListener.hpp"
+#include "IpcConnection.hpp"
#include "SharedPtr.hpp"
#include "Network.hpp"
#include "Utils.hpp"
-#include "UdpSocket.hpp"
#include "Buffer.hpp"
#include "Dictionary.hpp"
@@ -48,11 +49,6 @@ namespace ZeroTier {
class RuntimeEnvironment;
/**
- * Maximum size of a packet for node configuration
- */
-#define ZT_NODECONFIG_MAX_PACKET_SIZE 4096
-
-/**
* Node configuration endpoint
*/
class NodeConfig
@@ -61,10 +57,9 @@ public:
/**
* @param renv Runtime environment
* @param authToken Configuration authentication token
- * @param controlPort Control port for local control packet I/O
- * @throws std::runtime_error Unable to bind to local control port
+ * @throws std::runtime_error Unable to initialize or listen for IPC connections
*/
- NodeConfig(const RuntimeEnvironment *renv,const char *authToken,unsigned int controlPort);
+ NodeConfig(const RuntimeEnvironment *renv,const char *authToken);
~NodeConfig();
@@ -110,7 +105,7 @@ public:
}
/**
- * Perform cleanup and possibly update saved state
+ * Perform cleanup and possibly persist saved state
*/
void clean();
@@ -125,7 +120,7 @@ public:
}
/**
- * @return Set of network tap device names
+ * @return Set of network tap device names from our virtual networks (not other taps on system)
*/
inline std::set<std::string> networkTapDeviceNames() const
{
@@ -139,52 +134,19 @@ public:
return tapDevs;
}
- /**
- * Execute a control command (called when stuff comes in via control bus)
- *
- * @param command Command and arguments separated by whitespace (must already be trimmed of CR+LF, etc.)
- * @return One or more command results (lines of output)
- */
- std::vector<std::string> execute(const char *command);
-
- /**
- * Armor payload for control bus
- *
- * Note that no single element of payload can be longer than the max packet
- * size. If this occurs out_of_range is thrown.
- *
- * @param key 32 byte key
- * @param conversationId 32-bit conversation ID (bits beyond 32 are ignored)
- * @param payload One or more strings to encode in packet
- * @return One or more transport armored packets (if payload too big)
- * @throws std::out_of_range An element of payload is too big
- */
- static std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> > encodeControlMessage(const void *key,unsigned long conversationId,const std::vector<std::string> &payload);
-
- /**
- * Decode a packet from the control bus
- *
- * Note that 'payload' is appended to. Existing data is not cleared.
- *
- * @param key 32 byte key
- * @param data Packet data
- * @param len Packet length
- * @param conversationId Result parameter filled with conversation ID on success
- * @param payload Result parameter to which results are appended
- * @return True on success, false on invalid packet or packet that failed authentication
- */
- static bool decodeControlMessagePacket(const void *key,const void *data,unsigned int len,unsigned long &conversationId,std::vector<std::string> &payload);
-
private:
- static void _CBcontrolPacketHandler(UdpSocket *sock,void *arg,const InetAddress &remoteAddr,const void *data,unsigned int len);
+ static void _CBcommandHandler(void *arg,IpcConnection *ipcc,IpcConnection::EventType event,const char *commandLine);
+ void _doCommand(IpcConnection *ipcc,const char *commandLine);
void _readLocalConfig();
void _writeLocalConfig();
const RuntimeEnvironment *_r;
- unsigned char _controlSocketKey[32];
- UdpSocket _controlSocket;
+ IpcListener _ipcListener;
+ std::string _authToken;
+ std::map< IpcConnection *,bool > _connections;
+ Mutex _connections_m;
Dictionary _localConfig; // persisted as local.conf
Mutex _localConfig_m;