From 9cf734b74a750b8af0c628809c16be57eef1ff21 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 25 Jul 2013 13:24:39 -0400 Subject: Sane-ify Address, get rid of goofy union thingy. --- node/Identity.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'node/Identity.cpp') diff --git a/node/Identity.cpp b/node/Identity.cpp index f16947a0..a7ef403d 100644 --- a/node/Identity.cpp +++ b/node/Identity.cpp @@ -57,11 +57,13 @@ void Identity::generate() // the address of an identity will be detected as its signature will be // 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); SHA256_CTX sha; unsigned char dig[32]; unsigned char idtype = IDENTITY_TYPE_NIST_P_521,zero = 0; SHA256_Init(&sha); - SHA256_Update(&sha,_address.data(),ZT_ADDRESS_LENGTH); + SHA256_Update(&sha,atmp,ZT_ADDRESS_LENGTH); SHA256_Update(&sha,&zero,1); SHA256_Update(&sha,&idtype,1); SHA256_Update(&sha,&zero,1); @@ -73,11 +75,13 @@ void Identity::generate() bool Identity::locallyValidate(bool doAddressDerivationCheck) const { + unsigned char atmp[ZT_ADDRESS_LENGTH]; + _address.copyTo(atmp); SHA256_CTX sha; unsigned char dig[32]; unsigned char idtype = IDENTITY_TYPE_NIST_P_521,zero = 0; SHA256_Init(&sha); - SHA256_Update(&sha,_address.data(),ZT_ADDRESS_LENGTH); + SHA256_Update(&sha,atmp,ZT_ADDRESS_LENGTH); SHA256_Update(&sha,&zero,1); SHA256_Update(&sha,&idtype,1); SHA256_Update(&sha,&zero,1); -- 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/Identity.cpp') 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 f260c2839c73afa9898547398e1911c585904132 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Wed, 31 Jul 2013 17:24:59 -0400 Subject: Local service plugin stuff... work in progress. --- netconf-plugin/Makefile | 0 netconf-plugin/netconf.cpp | 127 ++++++++++++++++++++++++++++++ node/Identity.cpp | 2 +- node/Service.cpp | 192 +++++++++++++++++++++++++++++++++++++++++++++ node/Service.hpp | 125 +++++++++++++++++++++++++++++ objects.mk | 1 + 6 files changed, 446 insertions(+), 1 deletion(-) create mode 100644 netconf-plugin/Makefile create mode 100644 netconf-plugin/netconf.cpp create mode 100644 node/Service.cpp create mode 100644 node/Service.hpp (limited to 'node/Identity.cpp') diff --git a/netconf-plugin/Makefile b/netconf-plugin/Makefile new file mode 100644 index 00000000..e69de29b diff --git a/netconf-plugin/netconf.cpp b/netconf-plugin/netconf.cpp new file mode 100644 index 00000000..57d3653b --- /dev/null +++ b/netconf-plugin/netconf.cpp @@ -0,0 +1,127 @@ +/* + * 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/ + */ + +/* + * This is the netconf service. It's currently used only by netconf nodes that + * are run by ZeroTier itself. There is nothing to prevent you from running + * your own if you wanted to create your own networks outside our system. + * + * That being said, we'd like to charge for private networks to support + * ZeroTier One and future development efforts. So while this software is + * open source and we're not going to stop you from sidestepping this, we + * do ask -- honor system here -- that you pay for private networks if you + * are going to use them for any commercial purpose such as a business VPN + * alternative. + * + * This will at the moment only build on Linux and requires the mysql++ + * library, which is available here: + * + * http://tangentsoft.net/mysql++/ + * + * (Packages are available for CentOS via EPEL and for any Debian distro.) + * + * This program must be built and installed in the services.d subfolder of + * the ZeroTier One home folder of the node designated to act as a master + * for networks. Doing so will enable the NETWORK_CONFIG_REQUEST protocol + * verb. + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include "../node/Dictionary.hpp" + +using namespace ZeroTier; +using namespace mysqlpp; + +static Connection *dbCon = (Connection *)0; + +static void connectOrReconnect() +{ + if (dbCon) + delete dbCon; + dbCon = new Connection(mysqlDatabase,mysqlHost,mysqlUser,mysqlPassword,(unsigned int)strtol(mysqlPort,(char **)0,10)); + if (dbCon->connected()) + break; + else { + fprintf(stderr,"Unable to connect to database server.\n"); + usleep(1000); + } +} + +int main(int argc,char **argv) +{ + char mysqlHost[64],mysqlPort[64],mysqlDatabase[64],mysqlUser[64],mysqlPassword[64]; + + { + char *ee = getenv("ZT_NETCONF_MYSQL_HOST"); + if (!ee) { + fprintf(stderr,"Missing environment variable: ZT_NETCONF_MYSQL_HOST\n"); + return -1; + } + strcpy(mysqlHost,ee); + ee = getenv("ZT_NETCONF_MYSQL_PORT"); + if (ee == null) + strcpy(mysqlPort,"3306"); + else strcpy(mysqlPort,ee); + ee = getenv("ZT_NETCONF_MYSQL_DATABASE"); + if (!ee) { + fprintf(stderr,"Missing environment variable: ZT_NETCONF_MYSQL_DATABASE\n"); + return -1; + } + strcpy(mysqlDatabase,ee); + ee = getenv("ZT_NETCONF_MYSQL_USER"); + if (!ee) { + fprintf(stderr,"Missing environment variable: ZT_NETCONF_MYSQL_USER\n"); + return -1; + } + strcpy(mysqlUser,ee); + ee = getenv("ZT_NETCONF_MYSQL_PASSWORD"); + if (!ee) { + fprintf(stderr,"Missing environment variable: ZT_NETCONF_MYSQL_PASSWORD\n"); + return -1; + } + strcpy(mysqlPassword,ee); + } + + connectOrReconnect(); + for(;;) { + if (!dbCon->connected()) + connectOrReconnect(); + } +} diff --git a/node/Identity.cpp b/node/Identity.cpp index fdfdcd99..e9cbef3d 100644 --- a/node/Identity.cpp +++ b/node/Identity.cpp @@ -123,7 +123,7 @@ bool Identity::fromString(const char *str) std::string b(Utils::unhex(fields[0])); if (b.length() != ZT_ADDRESS_LENGTH) return false; - _address = b.data(); + _address.setTo(b.data(),ZT_ADDRESS_LENGTH); b = Utils::base64Decode(fields[2]); if ((!b.length())||(b.length() > ZT_EC_MAX_BYTES)) diff --git a/node/Service.cpp b/node/Service.cpp new file mode 100644 index 00000000..e0d06792 --- /dev/null +++ b/node/Service.cpp @@ -0,0 +1,192 @@ +/* + * 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/ + */ + +#include "Constants.hpp" + +#ifndef __WINDOWS__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Service.hpp" +#include "RuntimeEnvironment.hpp" +#include "Utils.hpp" +#include "Logger.hpp" + +namespace ZeroTier { + +Service::Service(const RuntimeEnvironment *renv,const char *name,const char *path,void (*handler)(void *,Service &,const Dictionary &),void *arg) : + _r(renv), + _path(path), + _name(name), + _arg(arg), + _handler(handler), + _pid(-1), + _childStdin(0), + _childStdout(0), + _childStderr(0), + _run(true) +{ + start(); +} + +Service::~Service() +{ + _run = false; + long pid = _pid; + if (pid > 0) { + int st = 0; + ::kill(pid,SIGTERM); + for(int i=0;i<20;++i) { + if (waitpid(pid,&st,WNOHANG) == pid) { + pid = 0; + break; + } + Thread::sleep(100); + } + if (pid > 0) { + ::kill(pid,SIGKILL); + waitpid(pid,&st,0); + } + } + join(); +} + +bool Service::send(const Dictionary &msg) +{ + if (_childStdin <= 0) + return false; + + std::string mser = msg.toString(); + if (mser.length() > ZT_SERVICE_MAX_MESSAGE_SIZE) + return false; + + // This can technically block. We'll fix this if it ends up being a + // problem. + uint32_t len = Utils::hton((uint32_t)mser.length()); + if (write(_childStdin,&len,4) != 4) + return false; + if ((int)write(_childStdin,mser.data(),mser.length()) != (int)mser.length()) + return false; + + return true; +} + +void Service::main() + throw() +{ + fd_set readfds,writefds,exceptfds; + struct timeval tv; + + while (_run) { + if (_pid <= 0) { + LOG("launching service %s...",_name.c_str()); + + int in[2],out[2],err[2]; + pipe(in); + pipe(out); + pipe(err); + + long pid = fork(); + if (pid < 0) { + LOG("service %s terminating: could not fork!",_name.c_str()); + return; + } else if (pid) { + close(in[1]); + close(out[0]); + close(err[0]); + Thread::sleep(500); // give child time to start + _childStdin = in[1]; + _childStdout = out[0]; + _childStderr = err[0]; + } else { + dup2(in[0],STDIN_FILENO); + dup2(out[1],STDOUT_FILENO); + dup2(err[1],STDERR_FILENO); + execl(_path.c_str(),_path.c_str(),_r->homePath.c_str(),(const char *)0); + exit(-1); + } + } else { + int st = 0; + if (waitpid(_pid,&st,WNOHANG) == _pid) { + if (_childStdin > 0) close(_childStdin); + _childStdin = 0; + if (_childStdout > 0) close(_childStdout); + if (_childStderr > 0) close(_childStderr); + _pid = 0; + + if (!_run) + return; + + LOG("service %s exited with exit code: %d, delaying 1s to attempt relaunch",_name.c_str(),st); + + Thread::sleep(1000); // wait to relaunch + continue; + } + } + + FD_ZERO(&readfds); + FD_ZERO(&writefds); + FD_ZERO(&exceptfds); + + FD_SET(_childStdout,&readfds); + FD_SET(_childStderr,&readfds); + + tv.tv_sec = 1; + tv.tv_usec = 0; + select(std::max(_childStdout,_childStderr)+1,&readfds,&writefds,&exceptfds,&tv); + + if (!_run) { + if (_childStdin > 0) close(_childStdin); + _childStdin = 0; + if (_childStdout > 0) close(_childStdout); + if (_childStderr > 0) close(_childStderr); + return; + } + + if ((_childStderr > 0)&&(FD_ISSET(_childStderr,&readfds))) { + } + + if ((_childStdout > 0)&&(FD_ISSET(_childStdout,&readfds))) { + } + } +} + +} // namespace ZeroTier + +#endif // __WINDOWS__ + diff --git a/node/Service.hpp b/node/Service.hpp new file mode 100644 index 00000000..8b9407e7 --- /dev/null +++ b/node/Service.hpp @@ -0,0 +1,125 @@ +/* + * 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_SERVICE_HPP +#define _ZT_SERVICE_HPP + +#include +#include + +#include "Constants.hpp" +#include "Dictionary.hpp" +#include "Thread.hpp" +#include "Mutex.hpp" + +/** + * Maximum size of a service message in bytes (sanity limit) + */ +#define ZT_SERVICE_MAX_MESSAGE_SIZE 131072 + +namespace ZeroTier { + +class RuntimeEnvironment; + +#ifndef __WINDOWS__ +/** + * A subprocess that communicates with the host via a simple protocol + * + * This is currently only supported on *nix systems, and is used to implement + * special plugins that are used by supernodes and network configuration + * master nodes. Users will probably have no use for it. + * + * The simple binary protocol consists of a bidirectional stream of string- + * serialized Dictionaries prefixed by a 32-bit message length. Input + * messages are sent to the subprocess via its stdin, and output is read + * from its stdout. Messages printed by the subprocess on its stderr are + * logged via the standard Logger instance. If the subprocess dies, an + * attempt is made to restart it every second. + */ +class Service : protected Thread +{ +public: + /** + * Create and launch a new service + * + * @param renv Runtime environment + * @param name Name of service + * @param path Path to service binary + * @param handler Handler function to call when service generates output + * @param arg First argument to service + */ + Service(const RuntimeEnvironment *renv,const char *name,const char *path,void (*handler)(void *,Service &,const Dictionary &),void *arg); + + virtual ~Service(); + + /** + * Send a message to service subprocess + * + * @param msg Message in key/value dictionary form + * @return True if message was sent + */ + bool send(const Dictionary &msg); + + /** + * @return Name of service + */ + inline const char *name() const + throw() + { + return _name.c_str(); + } + + /** + * @return True if subprocess is running + */ + inline bool running() const + throw() + { + return (_pid > 0); + } + +protected: + virtual void main() + throw(); + +private: + const RuntimeEnvironment *_r; + std::string _path; + std::string _name; + void *_arg; + void (*_handler)(void *,Service &,const Dictionary &); + long _pid; + int _childStdin; + int _childStdout; + int _childStderr; + volatile bool _run; +}; +#endif // __WINDOWS__ + +} // namespace ZeroTier + +#endif diff --git a/objects.mk b/objects.mk index 4d828923..be5cdc4e 100644 --- a/objects.mk +++ b/objects.mk @@ -18,6 +18,7 @@ OBJS=\ node/PacketDecoder.o \ node/Peer.o \ node/Salsa20.o \ + node/Service.o \ node/Switch.o \ node/SysEnv.o \ node/Thread.o \ -- cgit v1.2.3