From 668c428051706e33a1d5a411a1b446ca865a4854 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Tue, 23 Jul 2013 22:46:04 -0700 Subject: Basic RPC stuff in Packet and PacketDecoder for RPC service support. --- node/PacketDecoder.hpp | 1 + 1 file changed, 1 insertion(+) (limited to 'node/PacketDecoder.hpp') diff --git a/node/PacketDecoder.hpp b/node/PacketDecoder.hpp index e595d326..82bf9aee 100644 --- a/node/PacketDecoder.hpp +++ b/node/PacketDecoder.hpp @@ -122,6 +122,7 @@ private: bool _doFRAME(const RuntimeEnvironment *_r,const SharedPtr &peer); bool _doMULTICAST_LIKE(const RuntimeEnvironment *_r,const SharedPtr &peer); bool _doMULTICAST_FRAME(const RuntimeEnvironment *_r,const SharedPtr &peer); + bool _doRPC(const RuntimeEnvironment *_r,const SharedPtr &peer); uint64_t _receiveTime; Demarc::Port _localPort; -- cgit v1.2.3 From b0a83093ce698390a4e2d266ba1c63ee241cd7ad Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Sat, 27 Jul 2013 13:36:27 -0400 Subject: Back out of RPC... blech. Have a better idea. --- node/Constants.hpp | 5 -- node/Network.hpp | 8 -- node/Node.cpp | 22 ----- node/Packet.cpp | 1 - node/Packet.hpp | 21 +---- node/PacketDecoder.cpp | 6 -- node/PacketDecoder.hpp | 1 - node/RPC.cpp | 212 -------------------------------------------- node/RPC.hpp | 196 ---------------------------------------- node/RuntimeEnvironment.hpp | 5 +- objects.mk | 1 - 11 files changed, 2 insertions(+), 476 deletions(-) delete mode 100644 node/RPC.cpp delete mode 100644 node/RPC.hpp (limited to 'node/PacketDecoder.hpp') diff --git a/node/Constants.hpp b/node/Constants.hpp index 9f856948..b8dc9ebf 100644 --- a/node/Constants.hpp +++ b/node/Constants.hpp @@ -324,9 +324,4 @@ error_no_ZT_ARCH_defined; */ #define ZT_RENDEZVOUS_NAT_T_DELAY 500 -/** - * Timeout for remote RPC calls - */ -#define ZT_RPC_TIMEOUT 10000 - #endif diff --git a/node/Network.hpp b/node/Network.hpp index 8429cf84..a95ae869 100644 --- a/node/Network.hpp +++ b/node/Network.hpp @@ -50,14 +50,6 @@ class NodeConfig; /** * Local membership to a network - * - * Networks configure themselves via RPC by accessing the function - * com.zerotier.one.Network.bootstrap at any supernode. This returns - * a series of key/value pairs that includes the IP address - * information for this node on the network and -- for closed - * networks -- a URL to retreive the network's membership list. - * A SHA-256 hash is also included to verify the return from this - * URL query. */ class Network : NonCopyable { diff --git a/node/Node.cpp b/node/Node.cpp index b5c23ed9..08b08fc1 100644 --- a/node/Node.cpp +++ b/node/Node.cpp @@ -68,7 +68,6 @@ #include "Mutex.hpp" #include "Multicaster.hpp" #include "CMWC4096.hpp" -#include "RPC.hpp" #include "../version.h" @@ -211,7 +210,6 @@ Node::~Node() { _NodeImpl *impl = (_NodeImpl *)_impl; - delete impl->renv.rpc; delete impl->renv.sysEnv; delete impl->renv.topology; delete impl->renv.sw; @@ -317,7 +315,6 @@ Node::ReasonForTermination Node::run() _r->sw = new Switch(_r); _r->topology = new Topology(_r,(_r->homePath + ZT_PATH_SEPARATOR_S + "peer.db").c_str()); _r->sysEnv = new SysEnv(_r); - _r->rpc = new RPC(_r); // TODO: make configurable bool boundPort = false; @@ -341,25 +338,6 @@ Node::ReasonForTermination Node::run() return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unknown exception during initialization"); } - try { - std::map pluginsd(Utils::listDirectory((_r->homePath + ZT_PATH_SEPARATOR_S + "plugins.d").c_str())); - for(std::map::iterator ppath(pluginsd.begin());ppath!=pluginsd.end();++ppath) { - if (!ppath->second) { - try { - std::string funcName(ppath->first.substr(0,ppath->first.rfind('.'))); - LOG("loading plugins.d/%s as RPC function %s",ppath->first.c_str(),funcName.c_str()); - _r->rpc->loadLocal(funcName.c_str(),(_r->homePath + ZT_PATH_SEPARATOR_S + "plugins.d" + ZT_PATH_SEPARATOR_S + ppath->first).c_str()); - } catch (std::exception &exc) { - LOG("failed to load plugin plugins.d/%s: %s",ppath->first.c_str(),exc.what()); - } catch ( ... ) { - LOG("failed to load plugin plugins.d/%s: (unknown exception)",ppath->first.c_str()); - } - } - } - } catch ( ... ) { - TRACE("unknown exception attempting to enumerate and load plugins"); - } - try { uint64_t lastPingCheck = 0; uint64_t lastTopologyClean = Utils::now(); // don't need to do this immediately diff --git a/node/Packet.cpp b/node/Packet.cpp index bce80bf1..d12f396d 100644 --- a/node/Packet.cpp +++ b/node/Packet.cpp @@ -42,7 +42,6 @@ const char *Packet::verbString(Verb v) case VERB_FRAME: return "FRAME"; case VERB_MULTICAST_FRAME: return "MULTICAST_FRAME"; case VERB_MULTICAST_LIKE: return "MULTICAST_LIKE"; - case VERB_RPC: return "RPC"; } return "(unknown)"; } diff --git a/node/Packet.hpp b/node/Packet.hpp index 8b06d1a5..5ccfae45 100644 --- a/node/Packet.hpp +++ b/node/Packet.hpp @@ -463,26 +463,7 @@ public: * * No OK or ERROR is generated. */ - VERB_MULTICAST_FRAME = 9, - - /* Call a plugin via RPC: - * <[2] length of function name> - * <[...] function name> - * [<[2] length of argument>] - * [<[...] argument>] - * [... additional length/argument pairs ...] - * - * This generates ERROR_NOT_FOUND if the specified function was not - * found. Otherwise it generates an OK message. The OK message has - * the same format as the request, except arguments are replaced - * by results. - * - * This can be used to implement simple RPC. No retransmission or - * other guarantees are made, so it behaves like UDP-based RPC - * protocols. Plugins are typically run by supernodes and are used - * to implement network lookup and other services. - */ - VERB_RPC = 10 + VERB_MULTICAST_FRAME = 9 }; /** diff --git a/node/PacketDecoder.cpp b/node/PacketDecoder.cpp index e081fa8e..810e30a7 100644 --- a/node/PacketDecoder.cpp +++ b/node/PacketDecoder.cpp @@ -102,8 +102,6 @@ bool PacketDecoder::tryDecode(const RuntimeEnvironment *_r) return _doMULTICAST_LIKE(_r,peer); case Packet::VERB_MULTICAST_FRAME: return _doMULTICAST_FRAME(_r,peer); - case Packet::VERB_RPC: - return _doRPC(_r,peer); default: // This might be something from a new or old version of the protocol. // Technically it passed HMAC so the packet is still valid, but we @@ -540,8 +538,4 @@ bool PacketDecoder::_doMULTICAST_FRAME(const RuntimeEnvironment *_r,const Shared return true; } -bool PacketDecoder::_doRPC(const RuntimeEnvironment *_r,const SharedPtr &peer) -{ -} - } // namespace ZeroTier diff --git a/node/PacketDecoder.hpp b/node/PacketDecoder.hpp index 82bf9aee..e595d326 100644 --- a/node/PacketDecoder.hpp +++ b/node/PacketDecoder.hpp @@ -122,7 +122,6 @@ private: bool _doFRAME(const RuntimeEnvironment *_r,const SharedPtr &peer); bool _doMULTICAST_LIKE(const RuntimeEnvironment *_r,const SharedPtr &peer); bool _doMULTICAST_FRAME(const RuntimeEnvironment *_r,const SharedPtr &peer); - bool _doRPC(const RuntimeEnvironment *_r,const SharedPtr &peer); uint64_t _receiveTime; Demarc::Port _localPort; diff --git a/node/RPC.cpp b/node/RPC.cpp deleted file mode 100644 index 5a9cd719..00000000 --- a/node/RPC.cpp +++ /dev/null @@ -1,212 +0,0 @@ -/* - * ZeroTier One - Global Peer to Peer Ethernet - * Copyright (C) 2012-2013 ZeroTier Networks LLC - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - * -- - * - * ZeroTier may be used and distributed under the terms of the GPLv3, which - * are available at: http://www.gnu.org/licenses/gpl-3.0.html - * - * If you would like to embed ZeroTier into a commercial application or - * redistribute it in a modified binary form, please contact ZeroTier Networks - * LLC. Start here: http://www.zerotier.com/ - */ - -#ifndef __WINDOWS__ -#include -#endif - -#include "Utils.hpp" -#include "RuntimeEnvironment.hpp" -#include "RPC.hpp" -#include "Switch.hpp" -#include "Topology.hpp" - -namespace ZeroTier { - -#ifndef __WINDOWS__ - -RPC::LocalService::LocalService(const char *dllPath) - throw(std::invalid_argument) : - _handle((void *)0), - _init((void *)0), - _do((void *)0), - _free((void *)0), - _destroy((void *)0) -{ - _handle = dlopen(dllPath,RTLD_LAZY|RTLD_LOCAL); - if (!_handle) - throw std::invalid_argument("Unable to load DLL: dlopen() failed"); - - _init = dlsym(_handle,"ZeroTierPluginInit"); - if (!_init) { - dlclose(_handle); - throw std::invalid_argument("Unable to resolve symbol ZeroTierPluginInit in DLL"); - } - _do = dlsym(_handle,"ZeroTierPluginDo"); - if (!_do) { - dlclose(_handle); - throw std::invalid_argument("Unable to resolve symbol ZeroTierPluginDo in DLL"); - } - _free = dlsym(_handle,"ZeroTierPluginFree"); - if (!_free) { - dlclose(_handle); - throw std::invalid_argument("Unable to resolve symbol ZeroTierPluginFree in DLL"); - } - _destroy = dlsym(_handle,"ZeroTierPluginDestroy"); - if (!_destroy) { - dlclose(_handle); - throw std::invalid_argument("Unable to resolve symbol ZeroTierPluginDestroy in DLL"); - } - - if (((int (*)())_init)() < 0) { - dlclose(_handle); - throw std::invalid_argument("ZeroTierPluginInit() returned error"); - } -} - -RPC::LocalService::~LocalService() -{ - if (_handle) { - if (_destroy) - ((void (*)())_destroy)(); - dlclose(_handle); - } -} - -std::pair< int,std::vector > RPC::LocalService::operator()(const std::vector &args) -{ - unsigned int alengths[4096]; - const void *argptrs[4096]; - const unsigned int *rlengths = (const unsigned int *)0; - const void **resultptrs = (const void **)0; - std::vector results; - - if (args.size() > 4096) - throw std::runtime_error("args[] too long"); - - for(unsigned int i=0;i >(rcount,results); -} - -#endif // __WINDOWS__ - -RPC::RPC(const RuntimeEnvironment *renv) : - _r(renv) -{ -} - -RPC::~RPC() -{ - for(std::map::iterator co(_remoteCallsOutstanding.begin());co!=_remoteCallsOutstanding.end();++co) { - if (co->second.handler) - co->second.handler(co->second.arg,co->first,co->second.peer,ZT_RPC_ERROR_CANCELLED,std::vector()); - } - -#ifndef __WINDOWS__ - for(std::map::iterator s(_rpcServices.begin());s!=_rpcServices.end();++s) - delete s->second; -#endif -} - -std::pair< int,std::vector > RPC::callLocal(const std::string &name,const std::vector &args) -{ -#ifdef __WINDOWS__ - return std::pair< int,std::vector >(ZT_RPC_ERROR_NOT_FOUND,std::vector()); -#else - Mutex::Lock _l(_rpcServices_m); - std::map::iterator s(_rpcServices.find(name)); - if (s == _rpcServices.end()) - return std::pair< int,std::vector >(ZT_RPC_ERROR_NOT_FOUND,std::vector()); - return ((*(s->second))(args)); -#endif -} - -void RPC::loadLocal(const char *name,const char *path) - throw(std::invalid_argument) -{ -#ifdef __WINDOWS__ - throw std::invalid_argument("RPC plugins not supported on Windows (yet?)"); -#else - LocalService *s = new LocalService(path); - Mutex::Lock _l(_rpcServices_m); - _rpcServices[std::string(name)] = s; -#endif -} - -uint64_t RPC::callRemote( - const Address &peer, - const std::string &name, - const std::vector &args, - void (*handler)(void *,uint64_t,const Address &,int,const std::vector &), - void *arg) - throw(std::invalid_argument,std::out_of_range) -{ - Packet outp(peer,_r->identity.address(),Packet::VERB_RPC); - - if (name.length() > 0xffff) - throw std::invalid_argument("function name too long"); - outp.append((uint16_t)name.length()); - outp.append(name); - for(std::vector::const_iterator a(args.begin());a!=args.end();++a) { - if (a->length() > 0xffff) - throw std::invalid_argument("argument too long"); - outp.append((uint16_t)a->length()); - outp.append(*a); - } - outp.compress(); - - uint64_t id = outp.packetId(); - - { - Mutex::Lock _l(_remoteCallsOutstanding_m); - RemoteCallOutstanding &rc = _remoteCallsOutstanding[id]; - rc.callTime = Utils::now(); - rc.peer = peer; - rc.handler = handler; - rc.arg = arg; - } - - _r->sw->send(outp,true); - - return id; -} - -void RPC::clean() -{ - Mutex::Lock _l(_remoteCallsOutstanding_m); - uint64_t now = Utils::now(); - for(std::map::iterator co(_remoteCallsOutstanding.begin());co!=_remoteCallsOutstanding.end();) { - if ((now - co->second.callTime) >= ZT_RPC_TIMEOUT) { - if (co->second.handler) - co->second.handler(co->second.arg,co->first,co->second.peer,ZT_RPC_ERROR_EXPIRED_NO_RESPONSE,std::vector()); - _remoteCallsOutstanding.erase(co++); - } else ++co; - } -} - -} // namespace ZeroTier diff --git a/node/RPC.hpp b/node/RPC.hpp deleted file mode 100644 index 669bf5ae..00000000 --- a/node/RPC.hpp +++ /dev/null @@ -1,196 +0,0 @@ -/* - * ZeroTier One - Global Peer to Peer Ethernet - * Copyright (C) 2012-2013 ZeroTier Networks LLC - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - * -- - * - * ZeroTier may be used and distributed under the terms of the GPLv3, which - * are available at: http://www.gnu.org/licenses/gpl-3.0.html - * - * If you would like to embed ZeroTier into a commercial application or - * redistribute it in a modified binary form, please contact ZeroTier Networks - * LLC. Start here: http://www.zerotier.com/ - */ - -#ifndef _ZT_RPC_HPP -#define _ZT_RPC_HPP - -#include - -#include -#include -#include -#include - -#include "Constants.hpp" -#include "NonCopyable.hpp" -#include "Mutex.hpp" -#include "Address.hpp" - -namespace ZeroTier { - -class RuntimeEnvironment; - -/** - * Peer or method not found - */ -#define ZT_RPC_ERROR_NOT_FOUND -1 - -/** - * A runtime error occurred - */ -#define ZT_RPC_ERROR_RUNTIME -2 - -/** - * Call was expired without response from target - */ -#define ZT_RPC_ERROR_EXPIRED_NO_RESPONSE -3 - -/** - * Call was cancelled (or RPC is shutting down) - */ -#define ZT_RPC_ERROR_CANCELLED -4 - -/** - * RPC request and result handler - */ -class RPC : NonCopyable -{ -public: -#ifndef __WINDOWS__ - /** - * A local service accessible by RPC, non-Windows only for now - * - * Each service DLL must export these functions: - * - * int ZeroTierPluginInit(); - * int ZeroTierPluginDo(unsigned int,const unsigned int *,const void **,const unsigned int **,const void ***); - * void ZeroTierPluginFree(int,const unsigned int *,const void **); - * void ZeroTierPluginDestroy(); - * - * Init is called on library load, Destroy on unload. Do() may - * be called from multiple threads concurrently, so any locking - * is the responsibility of the library. These must have C - * function signatures (extern "C" in C++). - * - * Do's arguments are: the number of paramters, the size of each parameter in bytes, - * and each parameter's contents. The last two arguments are result parameters. The - * first result parameter must be set to an array of integers describing the size of - * each result. The second is set to an array of pointers to actual results. The number - * of results (size of both arrays) is returned. If Do() returns zero or negative, - * these result paremeters are not used by the caller and don't need to be set. - * - * After the caller is done with Do()'s results, it calls ZeroTierPluginFree() to - * free them. This may also be called concurrently. Free() takes the number of - * results, the array of result sizes, and the result array. - */ - class LocalService : NonCopyable - { - public: - /** - * @param dllPath Path to DLL/shared object - * @throws std::invalid_argument Unable to properly load or resolve symbol(s) in DLL - */ - LocalService(const char *dllPath) - throw(std::invalid_argument); - - ~LocalService(); - - /** - * Call the DLL, return result - * - * @param args Input arguments - * @return Results from DLL - * @throws std::runtime_error Error calling DLL - */ - std::pair< int,std::vector > operator()(const std::vector &args); - - private: - void *_handle; - void *_init; - void *_do; - void *_free; - void *_destroy; - }; -#endif - - RPC(const RuntimeEnvironment *renv); - ~RPC(); - - /** - * Used by PacketDecoder to call local RPC methods - * - * @param name Name of locally loaded method to call - * @param args Arguments to method - * @return Return value of method, and results (negative first item and empty vector means error) - */ - std::pair< int,std::vector > callLocal(const std::string &name,const std::vector &args); - - /** - * Load a plugin - * - * @param name Name of RPC function - * @param path Path to plugin DLL - * @throws std::invalid_argument Unable to properly load or resolve symbol(s) in DLL - */ - void loadLocal(const char *name,const char *path) - throw(std::invalid_argument); - - /** - * Call a remote service - * - * @param peer Peer to call on - * @param name Name of remote function - * @param args Arguments to remote function - * @param handler Handler to call on result - * @param arg First argument to handler - * @return Call ID (packet ID of sent packet) - */ - uint64_t callRemote( - const Address &peer, - const std::string &name, - const std::vector &args, - void (*handler)(void *,uint64_t,const Address &,int,const std::vector &), - void *arg) - throw(std::invalid_argument,std::out_of_range); - - /** - * Periodically called to clean up, such as by expiring remote calls - */ - void clean(); - -private: - const RuntimeEnvironment *_r; - -#ifndef __WINDOWS__ - std::map _rpcServices; - Mutex _rpcServices_m; -#endif - - struct RemoteCallOutstanding - { - uint64_t callTime; - Address peer; - void (*handler)(void *,uint64_t,const Address &,int,const std::vector &); - void *arg; - }; - std::map _remoteCallsOutstanding; - Mutex _remoteCallsOutstanding_m; -}; - -} // namespace ZeroTier - -#endif diff --git a/node/RuntimeEnvironment.hpp b/node/RuntimeEnvironment.hpp index 35c2de3f..7797e651 100644 --- a/node/RuntimeEnvironment.hpp +++ b/node/RuntimeEnvironment.hpp @@ -42,7 +42,6 @@ class Topology; class SysEnv; class Multicaster; class CMWC4096; -class RPC; /** * Holds global state for an instance of ZeroTier::Node @@ -67,8 +66,7 @@ public: multicaster((Multicaster *)0), sw((Switch *)0), topology((Topology *)0), - sysEnv((SysEnv *)0), - rpc((RPC *)0) + sysEnv((SysEnv *)0) { } @@ -90,7 +88,6 @@ public: Switch *sw; Topology *topology; SysEnv *sysEnv; - RPC *rpc; }; } // namespace ZeroTier diff --git a/objects.mk b/objects.mk index d7811a2e..f5b88719 100644 --- a/objects.mk +++ b/objects.mk @@ -21,7 +21,6 @@ OBJS=\ node/PacketDecoder.o \ node/Pack.o \ node/Peer.o \ - node/RPC.o \ node/Salsa20.o \ node/Switch.o \ node/SysEnv.o \ -- cgit v1.2.3 From a53cfc909638ea9eeb2bd477cee20d106f79bf6d Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Mon, 29 Jul 2013 13:56:20 -0400 Subject: Network membership certificate work in progress... does not build yet. --- Makefile.linux | 2 +- Makefile.mac | 2 +- node/Address.hpp | 34 ++++++- node/Dictionary.hpp | 73 +++++++++++++- node/Identity.cpp | 6 +- node/Network.cpp | 87 +++++++++++++++- node/Network.hpp | 262 ++++++++++++++++++++++++++++++++++++++++--------- node/NodeConfig.cpp | 2 +- node/Packet.cpp | 3 +- node/Packet.hpp | 49 +++++++-- node/PacketDecoder.cpp | 18 ++++ node/PacketDecoder.hpp | 3 + 12 files changed, 467 insertions(+), 74 deletions(-) (limited to 'node/PacketDecoder.hpp') diff --git a/Makefile.linux b/Makefile.linux index 9cb86305..bc77db4e 100644 --- a/Makefile.linux +++ b/Makefile.linux @@ -20,7 +20,7 @@ CXXFLAGS=$(CFLAGS) -fno-rtti # separate binaries for the RedHat and Debian universes to distribute via # auto-update. This way we get one Linux binary for all systems of a given # architecture. -LIBS=ext/bin/libcrypto/linux-$(ARCH)/libcrypto.a -ldl +LIBS=ext/bin/libcrypto/linux-$(ARCH)/libcrypto.a -lm include objects.mk diff --git a/Makefile.mac b/Makefile.mac index d3e3c27a..d47d18cc 100644 --- a/Makefile.mac +++ b/Makefile.mac @@ -13,7 +13,7 @@ STRIP=strip #STRIP=echo CXXFLAGS=$(CFLAGS) -fno-rtti -LIBS=-lcrypto -ldl +LIBS=-lcrypto -lm include objects.mk diff --git a/node/Address.hpp b/node/Address.hpp index 0e3f7b8e..8573a268 100644 --- a/node/Address.hpp +++ b/node/Address.hpp @@ -64,13 +64,28 @@ public: { } + Address(const char *s) + throw() + { + unsigned char foo[ZT_ADDRESS_LENGTH]; + setTo(foo,Utils::unhex(s,foo,ZT_ADDRESS_LENGTH)); + } + + Address(const std::string &s) + throw() + { + unsigned char foo[ZT_ADDRESS_LENGTH]; + setTo(foo,Utils::unhex(s.c_str(),foo,ZT_ADDRESS_LENGTH)); + } + /** * @param bits Raw address -- 5 bytes, big-endian byte order + * @param len Length of array */ - Address(const void *bits) + Address(const void *bits,unsigned int len) throw() { - setTo(bits); + setTo(bits,len); } inline Address &operator=(const Address &a) @@ -89,10 +104,15 @@ public: /** * @param bits Raw address -- 5 bytes, big-endian byte order + * @param len Length of array */ - inline void setTo(const void *bits) + inline void setTo(const void *bits,unsigned int len) throw() { + if (len < ZT_ADDRESS_LENGTH) { + _a = 0; + return; + } const unsigned char *b = (const unsigned char *)bits; uint64_t a = ((uint64_t)*b++) << 32; a |= ((uint64_t)*b++) << 24; @@ -104,10 +124,13 @@ public: /** * @param bits Buffer to hold 5-byte address in big-endian byte order + * @param len Length of array */ - inline void copyTo(void *bits) const + inline void copyTo(void *bits,unsigned int len) const throw() { + if (len < ZT_ADDRESS_LENGTH) + return; unsigned char *b = (unsigned char *)bits; *(b++) = (unsigned char)((_a >> 32) & 0xff); *(b++) = (unsigned char)((_a >> 24) & 0xff); @@ -164,7 +187,8 @@ public: throw() { MAC m; - copyTo(m.data); + m.data[0] = ZT_MAC_FIRST_OCTET; + copyTo(m.data + 1,ZT_ADDRESS_LENGTH); return m; } diff --git a/node/Dictionary.hpp b/node/Dictionary.hpp index fff600eb..f706168f 100644 --- a/node/Dictionary.hpp +++ b/node/Dictionary.hpp @@ -30,6 +30,7 @@ #include #include +#include #include "Constants.hpp" namespace ZeroTier { @@ -38,11 +39,76 @@ namespace ZeroTier { * Simple key/value dictionary with string serialization * * The serialization format is a flat key=value with backslash escape. - * It does not support comments or other syntactic complexities. + * It does not support comments or other syntactic complexities. It is + * human-readable if the keys and values in the dictionary are also + * human-readable. Otherwise it might contain unprintable characters. */ class Dictionary : public std::map { public: + Dictionary() + { + } + + /** + * @param s String-serialized dictionary + */ + Dictionary(const char *s) + { + fromString(s); + } + + /** + * @param s String-serialized dictionary + */ + Dictionary(const std::string &s) + { + fromString(s.c_str()); + } + + /** + * Get a key, throwing an exception if it is not present + * + * @param key Key to look up + * @return Reference to value + * @throws std::invalid_argument Key not found + */ + inline const std::string &get(const std::string &key) const + throw(std::invalid_argument) + { + const_iterator e(find(key)); + if (e == end()) + throw std::invalid_argument(std::string("missing required field: ")+key); + return e->second; + } + + /** + * Get a key, returning a default if not present + * + * @param key Key to look up + * @param dfl Default if not present + * @return Value or default + */ + inline const std::string &get(const std::string &key,const std::string &dfl) const + { + const_iterator e(find(key)); + if (e == end()) + return dfl; + return e->second; + } + + /** + * @param key Key to check + * @return True if dictionary contains key + */ + inline bool contains(const std::string &key) const + { + return (find(key) != end()); + } + + /** + * @return String-serialized dictionary + */ inline std::string toString() const { std::string s; @@ -57,6 +123,11 @@ public: return s; } + /** + * Clear and initialize from a string + * + * @param s String-serialized dictionary + */ inline void fromString(const char *s) { clear(); diff --git a/node/Identity.cpp b/node/Identity.cpp index a7ef403d..fdfdcd99 100644 --- a/node/Identity.cpp +++ b/node/Identity.cpp @@ -58,7 +58,7 @@ void Identity::generate() // invalid. Of course, deep verification of address/key relationship is // required to cover the more elaborate address claim jump attempt case. unsigned char atmp[ZT_ADDRESS_LENGTH]; - _address.copyTo(atmp); + _address.copyTo(atmp,ZT_ADDRESS_LENGTH); SHA256_CTX sha; unsigned char dig[32]; unsigned char idtype = IDENTITY_TYPE_NIST_P_521,zero = 0; @@ -76,7 +76,7 @@ void Identity::generate() bool Identity::locallyValidate(bool doAddressDerivationCheck) const { unsigned char atmp[ZT_ADDRESS_LENGTH]; - _address.copyTo(atmp); + _address.copyTo(atmp,ZT_ADDRESS_LENGTH); SHA256_CTX sha; unsigned char dig[32]; unsigned char idtype = IDENTITY_TYPE_NIST_P_521,zero = 0; @@ -222,7 +222,7 @@ Address Identity::deriveAddress(const void *keyBytes,unsigned int keyLen) delete [] ram; - return Address(dig); // first 5 bytes of dig[] + return Address(dig,ZT_ADDRESS_LENGTH); // first 5 bytes of dig[] } std::string Identity::encrypt(const Identity &to,const void *data,unsigned int len) const diff --git a/node/Network.cpp b/node/Network.cpp index f34e07e0..34a9a85b 100644 --- a/node/Network.cpp +++ b/node/Network.cpp @@ -25,19 +25,90 @@ * LLC. Start here: http://www.zerotier.com/ */ +#include +#include + +#include + +#include "RuntimeEnvironment.hpp" +#include "NodeConfig.hpp" #include "Network.hpp" #include "Switch.hpp" namespace ZeroTier { +void Network::Certificate::sign(const Identity &with) +{ + unsigned char dig[32]; + SHA256_CTX sha; + SHA256_Init(&sha); + unsigned char zero = 0; + for(const_iterator i(begin());i!=end();++i) { + if (i->first != "sig") { + SHA256_Update(&sha,&zero,1); + SHA256_Update(&sha,(const unsigned char *)i->first.data(),i->first.length()); + SHA256_Update(&sha,&zero,1); + SHA256_Update(&sha,(const unsigned char *)i->second.data(),i->second.length()); + SHA256_Update(&sha,&zero,1); + } + } + SHA256_Final(dig,&sha); + (*this)["sig"] = with.sign(dig); +} + +static const std::string _DELTA_PREFIX("~"); +bool Network::Certificate::qualifyMembership(const Network::Certificate &mc) const +{ + // Note: optimization probably needed here, probably via some kind of + // memoization / dynamic programming. + + for(const_iterator myField(begin());myField!=end();++myField) { + if (!((myField->first.length() > 1)&&(myField->first[0] == '~'))) { // ~fields are max delta range specs + // If they lack the same field, comparison fails. + const_iterator theirField(mc.find(myField->first)); + if (theirField == mc.end()) + return false; + + const_iterator deltaField(find(_DELTA_PREFIX + myField->first)); + if (deltaField == end()) { + // If there is no delta, compare for equality (e.g. node, nwid) + if (myField->second != theirField->second) + return false; + } else { + // Otherwise compare range with max delta. Presence of a dot in delta + // indicates a floating point comparison. Otherwise an integer + // comparison occurs. + if (deltaField->second.find('.') != std::string::npos) { + double my = strtod(myField->second.c_str(),(char **)0); + double their = strtod(theirField->second.c_str(),(char **)0); + double delta = strtod(deltaField->second.c_str(),(char **)0); + if (fabs(my - their) > delta) + return false; + } else { + int64_t my = strtoll(myField->second.c_str(),(char **)0,10); + int64_t their = strtoll(theirField->second.c_str(),(char **)0,10); + int64_t delta = strtoll(deltaField->second.c_str(),(char **)0,10); + if (my > their) { + if ((my - their) > delta) + return false; + } else { + if ((their - my) > delta) + return false; + } + } + } + } + } + + return true; +} + Network::Network(const RuntimeEnvironment *renv,uint64_t id) throw(std::runtime_error) : _r(renv), - _id(id), _tap(renv,renv->identity.address().toMAC(),ZT_IF_MTU,&_CBhandleTapData,this), - _members(), - _open(false), - _lock() + _id(id), + _isOpen(false) { } @@ -45,6 +116,14 @@ Network::~Network() { } +void Network::setConfiguration(const Network::Config &conf) +{ +} + +void Network::requestConfiguration() +{ +} + void Network::_CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data) { const RuntimeEnvironment *_r = ((Network *)arg)->_r; diff --git a/node/Network.hpp b/node/Network.hpp index 6263aa9b..359e2ce5 100644 --- a/node/Network.hpp +++ b/node/Network.hpp @@ -30,28 +30,37 @@ #include #include +#include #include #include + +#include "Constants.hpp" +#include "Utils.hpp" #include "EthernetTap.hpp" #include "Address.hpp" #include "Mutex.hpp" -#include "InetAddress.hpp" -#include "Constants.hpp" #include "SharedPtr.hpp" #include "AtomicCounter.hpp" -#include "RuntimeEnvironment.hpp" #include "MulticastGroup.hpp" #include "NonCopyable.hpp" #include "MAC.hpp" +#include "Dictionary.hpp" +#include "Identity.hpp" +#include "InetAddress.hpp" namespace ZeroTier { +class RuntimeEnvironment; class NodeConfig; /** * A virtual LAN * - * Networks can be open or closed. + * Networks can be open or closed. Each network has an ID whose most + * significant 40 bits are the ZeroTier address of the node that should + * be contacted for network configuration. The least significant 24 + * bits are arbitrary, allowing up to 2^24 networks per managing + * node. * * Open networks do not track membership. Anyone is allowed to communicate * over them. @@ -69,7 +78,183 @@ class Network : NonCopyable friend class SharedPtr; friend class NodeConfig; +public: + /** + * A certificate of network membership + */ + class Certificate : private Dictionary + { + public: + Certificate() + { + } + + Certificate(const char *s) : + Dictionary(s) + { + } + + Certificate(const std::string &s) : + Dictionary(s) + { + } + + /** + * @return Read-only underlying dictionary + */ + inline const Dictionary &dictionary() const { return *this; } + + inline void setNetworkId(uint64_t id) + { + char buf[32]; + sprintf(buf,"%llu",id); + (*this)["nwid"] = buf; + } + + inline uint64_t networkId() const + throw(std::invalid_argument) + { + return strtoull(get("nwid").c_str(),(char **)0,10); + } + + inline void setPeerAddress(Address &a) + { + (*this)["peer"] = a.toString(); + } + + inline Address peerAddress() const + throw(std::invalid_argument) + { + return Address(get("peer")); + } + + /** + * Set the timestamp and max-delta + * + * @param ts Timestamp in ms since epoch + * @param maxDelta Maximum difference between two peers on the same network + */ + inline void setTimestamp(uint64_t ts,uint64_t maxDelta) + { + char foo[32]; + sprintf(foo,"%llu",ts); + (*this)["ts"] = foo; + sprintf(foo,"%llu",maxDelta); + (*this)["~ts"] = foo; + } + + /** + * Set or update the sig field to contain a signature + * + * @param with Signing identity -- the identity of this network's controller + */ + void sign(const Identity &with); + + /** + * Check if another peer is indeed a current member of this network + * + * Fields with companion ~fields are compared with the defined maximum + * delta in this certificate. Fields without ~fields are compared for + * equality. + * + * This does not verify the certificate's signature! The signature + * must be verified first. + * + * @param mc Peer membership certificate + * @return True if mc's membership in this network is current + */ + bool qualifyMembership(const Certificate &mc) const; + }; + + /** + * A network configuration for a given node + */ + class Config : private Dictionary + { + public: + Config() + { + } + + Config(const char *s) : + Dictionary(s) + { + } + + Config(const std::string &s) : + Dictionary(s) + { + } + + /** + * @return Certificate of membership for this network, or empty cert if none + */ + inline Certificate certificateOfMembership() const + { + return Certificate(get("com","")); + } + + /** + * @return True if this is an open non-access-controlled network + */ + inline bool isOpen() const + { + return (get("isOpen","0") == "1"); + } + + /** + * @return All static addresses / netmasks, IPv4 or IPv6 + */ + inline std::set staticAddresses() const + { + std::set sa; + std::vector ips(Utils::split(get("ipv4Static","").c_str(),",","","")); + for(std::vector::const_iterator i(ips.begin());i!=ips.end();++i) + sa.insert(InetAddress(*i)); + ips = Utils::split(get("ipv6Static","").c_str(),",","",""); + for(std::vector::const_iterator i(ips.begin());i!=ips.end();++i) + sa.insert(InetAddress(*i)); + return sa; + } + + /** + * Set static IPv4 and IPv6 addresses + * + * This sets the ipv4Static and ipv6Static fields to comma-delimited + * lists of assignments. The port field in InetAddress must be the + * number of bits in the netmask. + * + * @param begin Start of container or array of addresses (InetAddress) + * @param end End of container or array of addresses (InetAddress) + * @tparam I Type of container or array + */ + template + inline void setStaticInetAddresses(const I &begin,const I &end) + { + std::string v4; + std::string v6; + for(I i(begin);i!=end;++i) { + if (i->isV4()) { + if (v4.length()) + v4.push_back(','); + v4.append(i->toString()); + } else if (i->isV6()) { + if (v6.length()) + v6.push_back(','); + v6.append(i->toString()); + } + } + if (v4.length()) + (*this)["ipv4Static"] = v4; + else erase("ipv4Static"); + if (v6.length()) + (*this)["ipv6Static"] = v6; + else erase("ipv6Static"); + } + }; + private: + // Only NodeConfig can create, only SharedPtr can delete Network(const RuntimeEnvironment *renv,uint64_t id) throw(std::runtime_error); @@ -87,56 +272,22 @@ public: inline EthernetTap &tap() throw() { return _tap; } /** - * Get this network's members - * - * If this is an open network, membership isn't relevant and this doesn't - * mean much. If it's a closed network, frames will only be exchanged to/from - * members. - * - * @return Members of this network + * @return Address of network's controlling node */ - inline std::set
members() const - { - Mutex::Lock _l(_lock); - return _members; - } - - /** - * @param addr Address to check - * @return True if address is a member - */ - inline bool isMember(const Address &addr) const - throw() - { - Mutex::Lock _l(_lock); - return (_members.count(addr) > 0); - } - - /** - * Shortcut to check open() and then isMember() - * - * @param addr Address to check - * @return True if network is open or if address is a member - */ - inline bool isAllowed(const Address &addr) const - throw() - { - Mutex::Lock _l(_lock); - return ((_open)||(_members.count(addr) > 0)); - } + inline Address controller() throw() { return Address(_id >> 24); } /** * @return True if network is open (no membership required) */ - inline bool open() const + inline bool isOpen() const throw() { Mutex::Lock _l(_lock); - return _open; + return _isOpen; } /** - * Update internal multicast group set and return true if changed + * Update multicast groups for this network's tap * * @return True if internal multicast group set has changed */ @@ -147,7 +298,7 @@ public: } /** - * @return Latest set of multicast groups + * @return Latest set of multicast groups for this network's tap */ inline std::set multicastGroups() const { @@ -155,15 +306,32 @@ public: return _multicastGroups; } + /** + * Set or update this network's configuration + * + * This is called by PacketDecoder when an update comes over the wire, or + * internally when an old config is reloaded from disk. + * + * @param conf Configuration in key/value dictionary form + */ + void setConfiguration(const Config &conf); + + /** + * Causes this network to request an updated configuration from its master node now + */ + void requestConfiguration(); + private: static void _CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data); const RuntimeEnvironment *_r; - uint64_t _id; + EthernetTap _tap; - std::set
_members; std::set _multicastGroups; - bool _open; + + uint64_t _id; + bool _isOpen; + Mutex _lock; AtomicCounter __refCount; diff --git a/node/NodeConfig.cpp b/node/NodeConfig.cpp index 1a84b6b7..214c06b7 100644 --- a/node/NodeConfig.cpp +++ b/node/NodeConfig.cpp @@ -126,7 +126,7 @@ std::vector NodeConfig::execute(const char *command) _P("200 listnetworks %llu %s %s", nw->first, nw->second->tap().deviceName().c_str(), - (nw->second->open() ? "public" : "private")); + (nw->second->isOpen() ? "public" : "private")); } } else if (cmd[0] == "join") { _P("404 join Not implemented yet."); diff --git a/node/Packet.cpp b/node/Packet.cpp index 4728609d..d3c0a3af 100644 --- a/node/Packet.cpp +++ b/node/Packet.cpp @@ -43,6 +43,8 @@ const char *Packet::verbString(Verb v) case VERB_MULTICAST_FRAME: return "MULTICAST_FRAME"; case VERB_MULTICAST_LIKE: return "MULTICAST_LIKE"; case VERB_NETWORK_PERMISSION_CERTIFICATE: return "NETWORK_PERMISSION_CERTIFICATE"; + case VERB_NETWORK_CONFIG_REQUEST: return "NETWORK_CONFIG_REQUEST"; + case VERB_NETWORK_CONFIG_REFRESH: return "NETWORK_CONFIG_REFRESH"; } return "(unknown)"; } @@ -59,7 +61,6 @@ const char *Packet::errorString(ErrorCode e) case ERROR_IDENTITY_INVALID: return "IDENTITY_INVALID"; case ERROR_UNSUPPORTED_OPERATION: return "UNSUPPORTED_OPERATION"; case ERROR_NO_NETWORK_CERTIFICATE_ON_FILE: return "NO_NETWORK_CERTIFICATE_ON_FILE"; - case ERROR_OBJECT_EXPIRED: return "OBJECT_EXPIRED"; } return "(unknown)"; } diff --git a/node/Packet.hpp b/node/Packet.hpp index 86d94e1d..2f88ac37 100644 --- a/node/Packet.hpp +++ b/node/Packet.hpp @@ -287,7 +287,7 @@ public: * * @return Destination ZT address */ - inline Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH)); } + inline Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); } /** * @return True if fragment is of a valid length @@ -468,8 +468,9 @@ public: /* Network permission certificate: * <[8] 64-bit network ID> * <[1] flags (currently unused, must be 0)> - * <[8] certificate timestamp> - * <[8] 16-bit length of signature> + * <[2] 16-bit length of qualifying fields> + * <[...] string-serialized dictionary of qualifying fields> + * <[2] 16-bit length of signature> * <[...] ECDSA signature of my binary serialized identity and timestamp> * * This message is used to send ahead of time a certificate proving @@ -478,7 +479,38 @@ public: * OK is generated on acceptance. ERROR is returned on failure. In both * cases the payload is the network ID. */ - VERB_NETWORK_PERMISSION_CERTIFICATE = 10 + VERB_NETWORK_PERMISSION_CERTIFICATE = 10, + + /* Network configuration request: + * <[8] 64-bit network ID> + * + * This message requests network configuration from a node capable of + * providing it. Such nodes run the netconf service, which must be + * installed into the ZeroTier home directory. + * + * OK response payload: + * <[8] 64-bit network ID> + * <[...] network configuration dictionary> + * + * OK returns a Dictionary (string serialized) containing the network's + * configuration and IP address assignment information for the querying + * node. + * + * ERROR may be NOT_FOUND if no such network is known, or + * UNSUPPORTED_OPERATION if the netconf service isn't available. The + * payload will be the network ID. + */ + VERB_NETWORK_CONFIG_REQUEST = 11, + + /* Network configuration refresh request: + * <[8] 64-bit network ID> + * + * This message can be sent by the network configuration master node + * to request that nodes refresh their network configuration. + * + * It is only a hint and does not presently elicit a response. + */ + VERB_NETWORK_CONFIG_REFRESH = 12 }; /** @@ -508,10 +540,7 @@ public: ERROR_UNSUPPORTED_OPERATION = 6, /* Message to private network rejected -- no unexpired certificate on file */ - ERROR_NO_NETWORK_CERTIFICATE_ON_FILE = 7, - - /* Object is expired (e.g. network certificate) */ - ERROR_OBJECT_EXPIRED = 8 + ERROR_NO_NETWORK_CERTIFICATE_ON_FILE = 7 }; /** @@ -624,14 +653,14 @@ public: * * @return Destination ZT address */ - inline Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH)); } + inline Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); } /** * Get this packet's source * * @return Source ZT address */ - inline Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH)); } + inline Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); } /** * @return True if packet is of valid length diff --git a/node/PacketDecoder.cpp b/node/PacketDecoder.cpp index 810e30a7..cd9985c3 100644 --- a/node/PacketDecoder.cpp +++ b/node/PacketDecoder.cpp @@ -102,6 +102,12 @@ bool PacketDecoder::tryDecode(const RuntimeEnvironment *_r) return _doMULTICAST_LIKE(_r,peer); case Packet::VERB_MULTICAST_FRAME: return _doMULTICAST_FRAME(_r,peer); + case Packet::VERB_NETWORK_PERMISSION_CERTIFICATE: + return _doNETWORK_PERMISSION_CERTIFICATE(_r,peer); + case Packet::VERB_NETWORK_CONFIG_REQUEST: + return _doNETWORK_CONFIG_REQUEST(_r,peer); + case Packet::VERB_NETWORK_CONFIG_REFRESH: + return _doNETWORK_CONFIG_REFRESH(_r,peer); default: // This might be something from a new or old version of the protocol. // Technically it passed HMAC so the packet is still valid, but we @@ -538,4 +544,16 @@ bool PacketDecoder::_doMULTICAST_FRAME(const RuntimeEnvironment *_r,const Shared return true; } +bool PacketDecoder::_doNETWORK_PERMISSION_CERTIFICATE(const RuntimeEnvironment *_r,const SharedPtr &peer) +{ +} + +bool PacketDecoder::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *_r,const SharedPtr &peer) +{ +} + +bool PacketDecoder::_doNETWORK_CONFIG_REFRESH(const RuntimeEnvironment *_r,const SharedPtr &peer) +{ +} + } // namespace ZeroTier diff --git a/node/PacketDecoder.hpp b/node/PacketDecoder.hpp index e595d326..1cd1dca7 100644 --- a/node/PacketDecoder.hpp +++ b/node/PacketDecoder.hpp @@ -122,6 +122,9 @@ private: bool _doFRAME(const RuntimeEnvironment *_r,const SharedPtr &peer); bool _doMULTICAST_LIKE(const RuntimeEnvironment *_r,const SharedPtr &peer); bool _doMULTICAST_FRAME(const RuntimeEnvironment *_r,const SharedPtr &peer); + bool _doNETWORK_PERMISSION_CERTIFICATE(const RuntimeEnvironment *_r,const SharedPtr &peer); + bool _doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *_r,const SharedPtr &peer); + bool _doNETWORK_CONFIG_REFRESH(const RuntimeEnvironment *_r,const SharedPtr &peer); uint64_t _receiveTime; Demarc::Port _localPort; -- cgit v1.2.3 From 439e602d5a5712d1b33fb19d558d0e9fdf784703 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Mon, 29 Jul 2013 16:18:29 -0400 Subject: Fix a bunch of errors due to minor method signature changes, still a work in progress. --- node/Identity.hpp | 2 +- node/Network.cpp | 18 +++++++----------- node/Network.hpp | 32 +++++++++++++++++++++++++++----- node/Packet.cpp | 5 +++-- node/Packet.hpp | 22 +++++++++++----------- node/PacketDecoder.cpp | 16 ++++++++-------- node/PacketDecoder.hpp | 2 +- 7 files changed, 58 insertions(+), 39 deletions(-) (limited to 'node/PacketDecoder.hpp') diff --git a/node/Identity.hpp b/node/Identity.hpp index e5a11d6a..a9f78c8a 100644 --- a/node/Identity.hpp +++ b/node/Identity.hpp @@ -340,7 +340,7 @@ public: unsigned int p = startAt; - _address = b.field(p,ZT_ADDRESS_LENGTH); + _address.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); p += ZT_ADDRESS_LENGTH; if (b[p++] != IDENTITY_TYPE_NIST_P_521) diff --git a/node/Network.cpp b/node/Network.cpp index 34a9a85b..696426e4 100644 --- a/node/Network.cpp +++ b/node/Network.cpp @@ -37,23 +37,19 @@ namespace ZeroTier { -void Network::Certificate::sign(const Identity &with) +void Network::Certificate::_shaForSignature(unsigned char *dig) const { - unsigned char dig[32]; SHA256_CTX sha; SHA256_Init(&sha); unsigned char zero = 0; for(const_iterator i(begin());i!=end();++i) { - if (i->first != "sig") { - SHA256_Update(&sha,&zero,1); - SHA256_Update(&sha,(const unsigned char *)i->first.data(),i->first.length()); - SHA256_Update(&sha,&zero,1); - SHA256_Update(&sha,(const unsigned char *)i->second.data(),i->second.length()); - SHA256_Update(&sha,&zero,1); - } + SHA256_Update(&sha,&zero,1); + SHA256_Update(&sha,(const unsigned char *)i->first.data(),i->first.length()); + SHA256_Update(&sha,&zero,1); + SHA256_Update(&sha,(const unsigned char *)i->second.data(),i->second.length()); + SHA256_Update(&sha,&zero,1); } SHA256_Final(dig,&sha); - (*this)["sig"] = with.sign(dig); } static const std::string _DELTA_PREFIX("~"); @@ -71,7 +67,7 @@ bool Network::Certificate::qualifyMembership(const Network::Certificate &mc) con const_iterator deltaField(find(_DELTA_PREFIX + myField->first)); if (deltaField == end()) { - // If there is no delta, compare for equality (e.g. node, nwid) + // If there is no delta, compare on simple equality if (myField->second != theirField->second) return false; } else { diff --git a/node/Network.hpp b/node/Network.hpp index 359e2ce5..c13f00a4 100644 --- a/node/Network.hpp +++ b/node/Network.hpp @@ -129,7 +129,7 @@ public: } /** - * Set the timestamp and max-delta + * Set the timestamp and timestamp max-delta * * @param ts Timestamp in ms since epoch * @param maxDelta Maximum difference between two peers on the same network @@ -144,11 +144,31 @@ public: } /** - * Set or update the sig field to contain a signature + * Sign this certificate * * @param with Signing identity -- the identity of this network's controller + * @return Signature or empty string on failure */ - void sign(const Identity &with); + inline std::string sign(const Identity &with) const + { + unsigned char dig[32]; + _shaForSignature(dig); + return with.sign(dig); + } + + /** + * Verify this certificate's signature + * + * @param with Signing identity -- the identity of this network's controller + * @param sig Signature + * @param siglen Length of signature in bytes + */ + inline bool verify(const Identity &with,const void *sig,unsigned int siglen) const + { + unsigned char dig[32]; + _shaForSignature(dig); + return with.verifySignature(dig,sig,siglen); + } /** * Check if another peer is indeed a current member of this network @@ -157,13 +177,15 @@ public: * delta in this certificate. Fields without ~fields are compared for * equality. * - * This does not verify the certificate's signature! The signature - * must be verified first. + * This does not verify the certificate's signature! * * @param mc Peer membership certificate * @return True if mc's membership in this network is current */ bool qualifyMembership(const Certificate &mc) const; + + private: + void _shaForSignature(unsigned char *dig) const; }; /** diff --git a/node/Packet.cpp b/node/Packet.cpp index d3c0a3af..0aae1e2d 100644 --- a/node/Packet.cpp +++ b/node/Packet.cpp @@ -42,7 +42,7 @@ const char *Packet::verbString(Verb v) case VERB_FRAME: return "FRAME"; case VERB_MULTICAST_FRAME: return "MULTICAST_FRAME"; case VERB_MULTICAST_LIKE: return "MULTICAST_LIKE"; - case VERB_NETWORK_PERMISSION_CERTIFICATE: return "NETWORK_PERMISSION_CERTIFICATE"; + case VERB_NETWORK_MEMBERSHIP_CERTIFICATE: return "NETWORK_MEMBERSHIP_CERTIFICATE"; case VERB_NETWORK_CONFIG_REQUEST: return "NETWORK_CONFIG_REQUEST"; case VERB_NETWORK_CONFIG_REFRESH: return "NETWORK_CONFIG_REFRESH"; } @@ -60,7 +60,8 @@ const char *Packet::errorString(ErrorCode e) case ERROR_IDENTITY_COLLISION: return "IDENTITY_COLLISION"; case ERROR_IDENTITY_INVALID: return "IDENTITY_INVALID"; case ERROR_UNSUPPORTED_OPERATION: return "UNSUPPORTED_OPERATION"; - case ERROR_NO_NETWORK_CERTIFICATE_ON_FILE: return "NO_NETWORK_CERTIFICATE_ON_FILE"; + case ERROR_NO_MEMBER_CERTIFICATE_ON_FILE: return "NO_MEMBER_CERTIFICATE_ON_FILE"; + case ERROR_MEMBER_CERTIFICATE_UNQUALIFIED: return "MEMBER_CERTIFICATE_UNQUALIFIED"; } return "(unknown)"; } diff --git a/node/Packet.hpp b/node/Packet.hpp index 2f88ac37..85ccb466 100644 --- a/node/Packet.hpp +++ b/node/Packet.hpp @@ -465,21 +465,17 @@ public: */ VERB_MULTICAST_FRAME = 9, - /* Network permission certificate: + /* Network member certificate for sending peer: * <[8] 64-bit network ID> - * <[1] flags (currently unused, must be 0)> - * <[2] 16-bit length of qualifying fields> - * <[...] string-serialized dictionary of qualifying fields> + * <[2] 16-bit length of certificate> + * <[...] string-serialized certificate dictionary> * <[2] 16-bit length of signature> - * <[...] ECDSA signature of my binary serialized identity and timestamp> - * - * This message is used to send ahead of time a certificate proving - * this node has permission to communicate on a private network. + * <[...] ECDSA signature of certificate> * * OK is generated on acceptance. ERROR is returned on failure. In both * cases the payload is the network ID. */ - VERB_NETWORK_PERMISSION_CERTIFICATE = 10, + VERB_NETWORK_MEMBERSHIP_CERTIFICATE = 10, /* Network configuration request: * <[8] 64-bit network ID> @@ -506,7 +502,8 @@ public: * <[8] 64-bit network ID> * * This message can be sent by the network configuration master node - * to request that nodes refresh their network configuration. + * to request that nodes refresh their network configuration. It can + * thus be used to "push" updates. * * It is only a hint and does not presently elicit a response. */ @@ -540,7 +537,10 @@ public: ERROR_UNSUPPORTED_OPERATION = 6, /* Message to private network rejected -- no unexpired certificate on file */ - ERROR_NO_NETWORK_CERTIFICATE_ON_FILE = 7 + ERROR_NO_MEMBER_CERTIFICATE_ON_FILE = 7, + + /* Membership certificate no longer qualified for membership in network */ + ERROR_MEMBER_CERTIFICATE_UNQUALIFIED = 8 }; /** diff --git a/node/PacketDecoder.cpp b/node/PacketDecoder.cpp index cd9985c3..0353625c 100644 --- a/node/PacketDecoder.cpp +++ b/node/PacketDecoder.cpp @@ -102,8 +102,8 @@ bool PacketDecoder::tryDecode(const RuntimeEnvironment *_r) return _doMULTICAST_LIKE(_r,peer); case Packet::VERB_MULTICAST_FRAME: return _doMULTICAST_FRAME(_r,peer); - case Packet::VERB_NETWORK_PERMISSION_CERTIFICATE: - return _doNETWORK_PERMISSION_CERTIFICATE(_r,peer); + case Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE: + return _doNETWORK_MEMBERSHIP_CERTIFICATE(_r,peer); case Packet::VERB_NETWORK_CONFIG_REQUEST: return _doNETWORK_CONFIG_REQUEST(_r,peer); case Packet::VERB_NETWORK_CONFIG_REFRESH: @@ -311,7 +311,7 @@ bool PacketDecoder::_doOK(const RuntimeEnvironment *_r,const SharedPtr &pe bool PacketDecoder::_doWHOIS(const RuntimeEnvironment *_r,const SharedPtr &peer) { if (payloadLength() == ZT_ADDRESS_LENGTH) { - SharedPtr p(_r->topology->getPeer(Address(payload()))); + SharedPtr p(_r->topology->getPeer(Address(payload(),ZT_ADDRESS_LENGTH))); if (p) { Packet outp(source(),_r->identity.address(),Packet::VERB_OK); outp.append((unsigned char)Packet::VERB_WHOIS); @@ -320,7 +320,7 @@ bool PacketDecoder::_doWHOIS(const RuntimeEnvironment *_r,const SharedPtr outp.encrypt(peer->cryptKey()); outp.hmacSet(peer->macKey()); _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1); - TRACE("sent WHOIS response to %s for %s",source().toString().c_str(),Address(payload()).toString().c_str()); + TRACE("sent WHOIS response to %s for %s",source().toString().c_str(),Address(payload(),ZT_ADDRESS_LENGTH).toString().c_str()); } else { Packet outp(source(),_r->identity.address(),Packet::VERB_ERROR); outp.append((unsigned char)Packet::VERB_WHOIS); @@ -330,7 +330,7 @@ bool PacketDecoder::_doWHOIS(const RuntimeEnvironment *_r,const SharedPtr outp.encrypt(peer->cryptKey()); outp.hmacSet(peer->macKey()); _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1); - TRACE("sent WHOIS ERROR to %s for %s (not found)",source().toString().c_str(),Address(payload()).toString().c_str()); + TRACE("sent WHOIS ERROR to %s for %s (not found)",source().toString().c_str(),Address(payload(),ZT_ADDRESS_LENGTH).toString().c_str()); } } else { TRACE("dropped WHOIS from %s(%s): missing or invalid address",source().toString().c_str(),_remoteAddress.toString().c_str()); @@ -341,7 +341,7 @@ bool PacketDecoder::_doWHOIS(const RuntimeEnvironment *_r,const SharedPtr bool PacketDecoder::_doRENDEZVOUS(const RuntimeEnvironment *_r,const SharedPtr &peer) { try { - Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH)); + Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); SharedPtr withPeer(_r->topology->getPeer(with)); if (withPeer) { unsigned int port = at(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT); @@ -439,7 +439,7 @@ bool PacketDecoder::_doMULTICAST_FRAME(const RuntimeEnvironment *_r,const Shared if (network->isAllowed(source())) { if (size() > ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PAYLOAD) { - Address originalSubmitterAddress(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SUBMITTER_ADDRESS,ZT_ADDRESS_LENGTH)); + Address originalSubmitterAddress(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SUBMITTER_ADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); MAC fromMac(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC,6)); MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DESTINATION_MAC,6)),at(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ADI)); unsigned int hops = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME_IDX_HOP_COUNT]; @@ -544,7 +544,7 @@ bool PacketDecoder::_doMULTICAST_FRAME(const RuntimeEnvironment *_r,const Shared return true; } -bool PacketDecoder::_doNETWORK_PERMISSION_CERTIFICATE(const RuntimeEnvironment *_r,const SharedPtr &peer) +bool PacketDecoder::_doNETWORK_MEMBERSHIP_CERTIFICATE(const RuntimeEnvironment *_r,const SharedPtr &peer) { } diff --git a/node/PacketDecoder.hpp b/node/PacketDecoder.hpp index 1cd1dca7..51408ba5 100644 --- a/node/PacketDecoder.hpp +++ b/node/PacketDecoder.hpp @@ -122,7 +122,7 @@ private: bool _doFRAME(const RuntimeEnvironment *_r,const SharedPtr &peer); bool _doMULTICAST_LIKE(const RuntimeEnvironment *_r,const SharedPtr &peer); bool _doMULTICAST_FRAME(const RuntimeEnvironment *_r,const SharedPtr &peer); - bool _doNETWORK_PERMISSION_CERTIFICATE(const RuntimeEnvironment *_r,const SharedPtr &peer); + bool _doNETWORK_MEMBERSHIP_CERTIFICATE(const RuntimeEnvironment *_r,const SharedPtr &peer); bool _doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *_r,const SharedPtr &peer); bool _doNETWORK_CONFIG_REFRESH(const RuntimeEnvironment *_r,const SharedPtr &peer); -- cgit v1.2.3