diff --git a/node/Packet.cpp b/node/Packet.cpp index 33866727a..d809d4027 100644 --- a/node/Packet.cpp +++ b/node/Packet.cpp @@ -48,8 +48,6 @@ const char *Packet::verbString(Verb v) 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"; - case VERB_FILE_INFO_REQUEST: return "FILE_INFO_REQUEST"; - case VERB_FILE_BLOCK_REQUEST: return "FILE_BLOCK_REQUEST"; } return "(unknown)"; } diff --git a/node/Packet.hpp b/node/Packet.hpp index daa9946b5..b7f52e3c0 100644 --- a/node/Packet.hpp +++ b/node/Packet.hpp @@ -615,60 +615,7 @@ public: * It does not generate an OK or ERROR message, and is treated only as * a hint to refresh now. */ - VERB_NETWORK_CONFIG_REFRESH = 12, - - /* Request information about a shared file (for software updates): - * <[1] flags, currently unused and must be 0> - * <[1] 8-bit length of filename> - * <[...] name of file being requested> - * - * OK response payload (indicates that we have and will share): - * <[1] flags, currently unused and must be 0> - * <[1] 8-bit length of filename> - * <[...] name of file being requested> - * <[64] full length SHA-512 hash of file contents> - * <[4] 32-bit length of file in bytes> - * <[5] Signing ZeroTier One identity address> - * <[2] 16-bit length of signature of filename + SHA-512 hash> - * <[...] signature of filename + SHA-512 hash> - * - * ERROR response payload: - * <[2] 16-bit length of filename> - * <[...] name of file being requested> - * - * This is used for distribution of software updates and in the future may - * be used for anything else that needs to be globally distributed. It - * is not designed for end-user use for other purposes. - * - * Support is optional. Nodes should return UNSUPPORTED_OPERATION if - * not supported or enabled. - */ - VERB_FILE_INFO_REQUEST = 13, - - /* Request a piece of a shared file - * <[16] first 16 bytes of SHA-512 of file being requested> - * <[4] 32-bit index of desired chunk> - * <[2] 16-bit length of desired chunk> - * - * OK response payload: - * <[16] first 16 bytes of SHA-512 of file being requested> - * <[4] 32-bit index of desired chunk> - * <[2] 16-bit length of desired chunk> - * <[...] the chunk> - * - * ERROR response payload: - * <[16] first 16 bytes of SHA-512 of file being requested> - * <[4] 32-bit index of desired chunk> - * <[2] 16-bit length of desired chunk> - * - * This is used for distribution of software updates and in the future may - * be used for anything else that needs to be globally distributed. It - * is not designed for end-user use for other purposes. - * - * Support is optional. Nodes should return UNSUPPORTED_OPERATION if - * not supported or enabled. - */ - VERB_FILE_BLOCK_REQUEST = 14 + VERB_NETWORK_CONFIG_REFRESH = 12 }; /** diff --git a/node/PacketDecoder.cpp b/node/PacketDecoder.cpp index 83c47b0e3..956cb642b 100644 --- a/node/PacketDecoder.cpp +++ b/node/PacketDecoder.cpp @@ -112,10 +112,6 @@ bool PacketDecoder::tryDecode(const RuntimeEnvironment *_r) return _doNETWORK_CONFIG_REQUEST(_r,peer); case Packet::VERB_NETWORK_CONFIG_REFRESH: return _doNETWORK_CONFIG_REFRESH(_r,peer); - case Packet::VERB_FILE_INFO_REQUEST: - return _doFILE_INFO_REQUEST(_r,peer); - case Packet::VERB_FILE_BLOCK_REQUEST: - return _doFILE_BLOCK_REQUEST(_r,peer); default: // This might be something from a new or old version of the protocol. // Technically it passed MAC so the packet is still valid, but we @@ -878,14 +874,4 @@ bool PacketDecoder::_doNETWORK_CONFIG_REFRESH(const RuntimeEnvironment *_r,const return true; } -bool PacketDecoder::_doFILE_INFO_REQUEST(const RuntimeEnvironment *_r,const SharedPtr &peer) -{ - return true; -} - -bool PacketDecoder::_doFILE_BLOCK_REQUEST(const RuntimeEnvironment *_r,const SharedPtr &peer) -{ - return true; -} - } // namespace ZeroTier diff --git a/node/PacketDecoder.hpp b/node/PacketDecoder.hpp index 8ec015948..cb3522ff2 100644 --- a/node/PacketDecoder.hpp +++ b/node/PacketDecoder.hpp @@ -122,8 +122,6 @@ private: 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); - bool _doFILE_INFO_REQUEST(const RuntimeEnvironment *_r,const SharedPtr &peer); - bool _doFILE_BLOCK_REQUEST(const RuntimeEnvironment *_r,const SharedPtr &peer); uint64_t _receiveTime; Demarc::Port _localPort; diff --git a/node/Updater.cpp b/node/Updater.cpp deleted file mode 100644 index aba227d8d..000000000 --- a/node/Updater.cpp +++ /dev/null @@ -1,449 +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/ - */ - -#include "Updater.hpp" -#include "RuntimeEnvironment.hpp" -#include "Logger.hpp" -#include "Defaults.hpp" -#include "Utils.hpp" -#include "Topology.hpp" -#include "Switch.hpp" -#include "SHA512.hpp" - -#include "../version.h" - -namespace ZeroTier { - -Updater::Updater(const RuntimeEnvironment *renv) : - _r(renv), - _download((_Download *)0) -{ - refreshShared(); -} - -Updater::~Updater() -{ - Mutex::Lock _l(_lock); - delete _download; -} - -void Updater::refreshShared() -{ - std::string updatesPath(_r->homePath + ZT_PATH_SEPARATOR_S + "updates.d"); - std::map ud(Utils::listDirectory(updatesPath.c_str())); - - Mutex::Lock _l(_lock); - _sharedUpdates.clear(); - for(std::map::iterator u(ud.begin());u!=ud.end();++u) { - if (u->second) - continue; // skip directories - if ((u->first.length() >= 4)&&(!strcasecmp(u->first.substr(u->first.length() - 4).c_str(),".sig"))) - continue; // skip .sig companion files - - std::string fullPath(updatesPath + ZT_PATH_SEPARATOR_S + u->first); - std::string sigPath(fullPath + ".sig"); - - std::string buf; - if (Utils::readFile(sigPath.c_str(),buf)) { - Dictionary sig(buf); - - SharedUpdate shared; - shared.fullPath = fullPath; - shared.filename = u->first; - - std::string sha512(Utils::unhex(sig.get("sha512",std::string()))); - std::string signature(Utils::unhex(sig.get("sha512_ed25519",std::string()))); - Address signedBy(sig.get("signedBy",std::string())); - if ((sha512.length() < sizeof(shared.sha512))||(signature.length() < shared.sig.size())||(!signedBy)) { - TRACE("skipped shareable update due to missing fields in companion .sig: %s",fullPath.c_str()); - continue; - } - memcpy(shared.sha512,sha512.data(),sizeof(shared.sha512)); - memcpy(shared.sig.data,signature.data(),shared.sig.size()); - shared.signedBy = signedBy; - - int64_t fs = Utils::getFileSize(fullPath.c_str()); - if (fs <= 0) { - TRACE("skipped shareable update due to unreadable, invalid, or 0-byte file: %s",fullPath.c_str()); - continue; - } - shared.size = (unsigned long)fs; - - LOG("sharing software update %s to other peers",shared.filename.c_str()); - _sharedUpdates.push_back(shared); - } else { - TRACE("skipped shareable update due to missing companion .sig: %s",fullPath.c_str()); - continue; - } - } -} - -void Updater::getUpdateIfThisIsNewer(unsigned int vMajor,unsigned int vMinor,unsigned int revision) -{ - if (!compareVersions(vMajor,vMinor,revision,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION)) - return; - - std::string updateFilename(generateUpdateFilename(vMajor,vMinor,revision)); - if (!updateFilename.length()) { - TRACE("an update to %u.%u.%u is available, but this platform or build doesn't support auto-update",vMajor,vMinor,revision); - return; - } - - std::vector< SharedPtr > peers; - _r->topology->eachPeer(Topology::CollectPeersWithActiveDirectPath(peers,Utils::now())); - - TRACE("new update available to %u.%u.%u, looking for %s from %u peers",vMajor,vMinor,revision,updateFilename.c_str(),(unsigned int)peers.size()); - - for(std::vector< SharedPtr >::iterator p(peers.begin());p!=peers.end();++p) { - Packet outp((*p)->address(),_r->identity.address(),Packet::VERB_FILE_INFO_REQUEST); - outp.append((unsigned char)0); - outp.append((uint16_t)updateFilename.length()); - outp.append(updateFilename.data(),updateFilename.length()); - _r->sw->send(outp,true); - } -} - -void Updater::retryIfNeeded() -{ - Mutex::Lock _l(_lock); - - if (_download) { - uint64_t elapsed = Utils::now() - _download->lastChunkReceivedAt; - if ((elapsed >= ZT_UPDATER_PEER_TIMEOUT)||(!_download->currentlyReceivingFrom)) { - if (_download->peersThatHave.empty()) { - // Search for more sources if we have no more possibilities queued - TRACE("all sources for %s timed out, searching for more...",_download->filename.c_str()); - _download->currentlyReceivingFrom.zero(); - - std::vector< SharedPtr > peers; - _r->topology->eachPeer(Topology::CollectPeersWithActiveDirectPath(peers,Utils::now())); - - for(std::vector< SharedPtr >::iterator p(peers.begin());p!=peers.end();++p) { - Packet outp((*p)->address(),_r->identity.address(),Packet::VERB_FILE_INFO_REQUEST); - outp.append((unsigned char)0); - outp.append((uint16_t)_download->filename.length()); - outp.append(_download->filename.data(),_download->filename.length()); - _r->sw->send(outp,true); - } - } else { - // If that peer isn't answering, try the next queued source - _download->currentlyReceivingFrom = _download->peersThatHave.front(); - _download->peersThatHave.pop_front(); - _requestNextChunk(); - } - } else if (elapsed >= ZT_UPDATER_RETRY_TIMEOUT) { - // Re-request next chunk we don't have from current source - _requestNextChunk(); - } - } -} - -void Updater::handleChunk(const Address &from,const void *sha512,unsigned int shalen,unsigned long at,const void *chunk,unsigned long len) -{ - Mutex::Lock _l(_lock); - - if (!_download) { - TRACE("got chunk from %s while no download is in progress, ignored",from.toString().c_str()); - return; - } - - if (memcmp(_download->sha512,sha512,(shalen > 64) ? 64 : shalen)) { - TRACE("got chunk from %s for wrong download (SHA mismatch), ignored",from.toString().c_str()); - return; - } - - unsigned long whichChunk = at / ZT_UPDATER_CHUNK_SIZE; - - if ( - (at != (ZT_UPDATER_CHUNK_SIZE * whichChunk))|| - (whichChunk >= _download->haveChunks.size())|| - ((whichChunk == (_download->haveChunks.size() - 1))&&(len != _download->lastChunkSize))|| - (len != ZT_UPDATER_CHUNK_SIZE) - ) { - TRACE("got chunk from %s at invalid position or invalid size, ignored",from.toString().c_str()); - return; - } - - for(unsigned long i=0;idata[at + i] = ((const char *)chunk)[i]; - - _download->haveChunks[whichChunk] = true; - _download->lastChunkReceivedAt = Utils::now(); - - _requestNextChunk(); -} - -void Updater::handlePeerHasFile(const Address &from,const char *filename,const void *sha512,unsigned long filesize,const Address &signedBy,const void *signature,unsigned int siglen) -{ - unsigned int vMajor = 0,vMinor = 0,revision = 0; - if (!parseUpdateFilename(filename,vMajor,vMinor,revision)) { - TRACE("rejected offer of %s from %s: could not extract version information from filename",filename,from.toString().c_str()); - return; - } - - if (filesize > ZT_UPDATER_MAX_SUPPORTED_SIZE) { - TRACE("rejected offer of %s from %s: file too large (%u > %u)",filename,from.toString().c_str(),(unsigned int)filesize,(unsigned int)ZT_UPDATER_MAX_SUPPORTED_SIZE); - return; - } - - if (!compareVersions(vMajor,vMinor,revision,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION)) { - TRACE("rejected offer of %s from %s: version older than mine",filename,from.toString().c_str()); - return; - } - - Mutex::Lock _l(_lock); - - if (_download) { - if ((_download->filename == filename)&&(_download->data.length() == filesize)&&(!memcmp(sha512,_download->sha512,64))) { - // Learn another source for the current download if this is the - // same file. - LOG("learned new source for %s: %s",filename,from.toString().c_str()); - if (!_download->currentlyReceivingFrom) { - _download->currentlyReceivingFrom = from; - _requestNextChunk(); - } else _download->peersThatHave.push_back(from); - return; - } else { - // If there's a download, compare versions... only proceed if this - // file being offered is newer. - if (!compareVersions(vMajor,vMinor,revision,_download->versionMajor,_download->versionMinor,_download->revision)) { - TRACE("rejected offer of %s from %s: already downloading newer version %s",filename,from.toString().c_str(),_download->filename.c_str()); - return; - } - } - } - - // If we have no download OR if this was a different file, check its - // validity via signature and then see if it's newer. If so start a new - // download for it. - { - std::string nameAndSha(filename); - nameAndSha.append((const char *)sha512,64); - std::map< Address,Identity >::const_iterator uauth(ZT_DEFAULTS.updateAuthorities.find(signedBy)); - if (uauth == ZT_DEFAULTS.updateAuthorities.end()) { - LOG("rejected offer of %s from %s: failed authentication: unknown signer %s",filename,from.toString().c_str(),signedBy.toString().c_str()); - return; - } - if (!uauth->second.verify(nameAndSha.data(),nameAndSha.length(),signature,siglen)) { - LOG("rejected offer of %s from %s: failed authentication: signature from %s invalid",filename,from.toString().c_str(),signedBy.toString().c_str()); - return; - } - } - - // Replace existing download if any. - delete _download; - _download = (_Download *)0; - - // Create and initiate new download - _download = new _Download; - try { - LOG("beginning download of software update %s from %s (%u bytes, signed by authorized identity %s)",filename,from.toString().c_str(),(unsigned int)filesize,signedBy.toString().c_str()); - - _download->data.assign(filesize,(char)0); - _download->haveChunks.resize((filesize / ZT_UPDATER_CHUNK_SIZE) + 1,false); - _download->filename = filename; - memcpy(_download->sha512,sha512,64); - _download->currentlyReceivingFrom = from; - _download->lastChunkReceivedAt = 0; - _download->lastChunkSize = filesize % ZT_UPDATER_CHUNK_SIZE; - _download->versionMajor = vMajor; - _download->versionMinor = vMinor; - _download->revision = revision; - - _requestNextChunk(); - } catch (std::exception &exc) { - delete _download; - _download = (_Download *)0; - LOG("unable to begin download of %s from %s: %s",filename,from.toString().c_str(),exc.what()); - } catch ( ... ) { - delete _download; - _download = (_Download *)0; - LOG("unable to begin download of %s from %s: unknown exception",filename,from.toString().c_str()); - } -} - -bool Updater::findSharedUpdate(const char *filename,SharedUpdate &update) const -{ - Mutex::Lock _l(_lock); - for(std::list::const_iterator u(_sharedUpdates.begin());u!=_sharedUpdates.end();++u) { - if (u->filename == filename) { - update = *u; - return true; - } - } - return false; -} - -bool Updater::findSharedUpdate(const void *sha512,unsigned int shalen,SharedUpdate &update) const -{ - if (!shalen) - return false; - Mutex::Lock _l(_lock); - for(std::list::const_iterator u(_sharedUpdates.begin());u!=_sharedUpdates.end();++u) { - if (!memcmp(u->sha512,sha512,(shalen > 64) ? 64 : shalen)) { - update = *u; - return true; - } - } - return false; -} - -bool Updater::getSharedChunk(const void *sha512,unsigned int shalen,unsigned long at,void *chunk,unsigned long chunklen) const -{ - if (!chunklen) - return true; - if (!shalen) - return false; - Mutex::Lock _l(_lock); - for(std::list::const_iterator u(_sharedUpdates.begin());u!=_sharedUpdates.end();++u) { - if (!memcmp(u->sha512,sha512,(shalen > 64) ? 64 : shalen)) { - FILE *f = fopen(u->fullPath.c_str(),"rb"); - if (!f) - return false; - if (!fseek(f,(long)at,SEEK_SET)) { - fclose(f); - return false; - } - if (fread(chunk,chunklen,1,f) != 1) { - fclose(f); - return false; - } - fclose(f); - return true; - } - } - return false; -} - -std::string Updater::generateUpdateFilename(unsigned int vMajor,unsigned int vMinor,unsigned int revision) -{ - // Defining ZT_OFFICIAL_BUILD enables this cascade of macros, which will - // make your build auto-update itself if it's for an officially supported - // architecture. The signing identity for auto-updates is in Defaults. -#ifdef ZT_OFFICIAL_BUILD - - // Not supported... yet? Get it first cause it might identify as Linux too. -#ifdef __ANDROID__ -#define _updSupported 1 - return std::string(); -#endif - - // Linux on x86 and possibly in the future ARM -#ifdef __LINUX__ -#if defined(__i386) || defined(__i486) || defined(__i586) || defined(__i686) || defined(__amd64) || defined(__x86_64) || defined(i386) -#define _updSupported 1 - char buf[128]; - Utils::snprintf(buf,sizeof(buf),"zt1-%u_%u_%u-linux-%s-install",vMajor,vMinor,revision,(sizeof(void *) == 8) ? "x64" : "x86"); - return std::string(buf); -#endif -/* -#if defined(__arm__) || defined(__arm) || defined(__aarch64__) -#define _updSupported 1 - char buf[128]; - Utils::snprintf(buf,sizeof(buf),"zt1-%u_%u_%u-linux-%s-install",vMajor,vMinor,revision,(sizeof(void *) == 8) ? "arm64" : "arm32"); - return std::string(buf); -#endif -*/ -#endif - - // Apple stuff... only Macs so far... -#ifdef __APPLE__ -#define _updSupported 1 -#if defined(__powerpc) || defined(__powerpc__) || defined(__ppc__) || defined(__ppc64) || defined(__ppc64__) || defined(__powerpc64__) - return std::string(); -#endif -#if defined(TARGET_IPHONE_SIMULATOR) || defined(TARGET_OS_IPHONE) - return std::string(); -#endif - char buf[128]; - Utils::snprintf(buf,sizeof(buf),"zt1-%u_%u_%u-mac-x86combined-install",vMajor,vMinor,revision); - return std::string(buf); -#endif - - // ??? -#ifndef _updSupported - return std::string(); -#endif - -#else - return std::string(); -#endif // ZT_OFFICIAL_BUILD -} - -bool Updater::parseUpdateFilename(const char *filename,unsigned int &vMajor,unsigned int &vMinor,unsigned int &revision) -{ - std::vector byDash(Utils::split(filename,"-","","")); - if (byDash.size() < 2) - return false; - std::vector byUnderscore(Utils::split(byDash[1].c_str(),"_","","")); - if (byUnderscore.size() < 3) - return false; - vMajor = Utils::strToUInt(byUnderscore[0].c_str()); - vMinor = Utils::strToUInt(byUnderscore[1].c_str()); - revision = Utils::strToUInt(byUnderscore[2].c_str()); - return true; -} - -void Updater::_requestNextChunk() -{ - // assumes _lock is locked - - if (!_download) - return; - - unsigned long whichChunk = 0; - std::vector::iterator ptr(std::find(_download->haveChunks.begin(),_download->haveChunks.end(),false)); - if (ptr == _download->haveChunks.end()) { - unsigned char digest[64]; - SHA512::hash(digest,_download->data.data(),_download->data.length()); - if (memcmp(digest,_download->sha512,64)) { - LOG("retrying download of %s -- SHA-512 mismatch, file corrupt!",_download->filename.c_str()); - std::fill(_download->haveChunks.begin(),_download->haveChunks.end(),false); - whichChunk = 0; - } else { - LOG("successfully downloaded and authenticated %s, launching update...",_download->filename.c_str()); - delete _download; - _download = (_Download *)0; - return; - } - } else { - whichChunk = std::distance(_download->haveChunks.begin(),ptr); - } - - TRACE("requesting chunk %u/%u of %s from %s",(unsigned int)whichChunk,(unsigned int)_download->haveChunks.size(),_download->filename.c_str()_download->currentlyReceivingFrom.toString().c_str()); - - Packet outp(_download->currentlyReceivingFrom,_r->identity.address(),Packet::VERB_FILE_BLOCK_REQUEST); - outp.append(_download->sha512,16); - outp.append((uint32_t)(whichChunk * ZT_UPDATER_CHUNK_SIZE)); - if (whichChunk == (_download->haveChunks.size() - 1)) - outp.append((uint16_t)_download->lastChunkSize); - else outp.append((uint16_t)ZT_UPDATER_CHUNK_SIZE); - _r->sw->send(outp,true); -} - -} // namespace ZeroTier - diff --git a/node/Updater.hpp b/node/Updater.hpp deleted file mode 100644 index 241c855bf..000000000 --- a/node/Updater.hpp +++ /dev/null @@ -1,242 +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_UPDATER_HPP -#define _ZT_UPDATER_HPP - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "Constants.hpp" -#include "Packet.hpp" -#include "Mutex.hpp" -#include "Address.hpp" -#include "C25519.hpp" -#include "Array.hpp" -#include "Dictionary.hpp" - -// Chunk size-- this can be changed, picked to always fit in one packet each. -#define ZT_UPDATER_CHUNK_SIZE 1350 - -// Sanity check value for constraining max size since right now we buffer -// in RAM. -#define ZT_UPDATER_MAX_SUPPORTED_SIZE (1024 * 1024 * 16) - -// Retry timeout in ms. -#define ZT_UPDATER_RETRY_TIMEOUT 15000 - -// After this long, look for a new peer to download from -#define ZT_UPDATER_PEER_TIMEOUT 65000 - -namespace ZeroTier { - -class RuntimeEnvironment; - -/** - * Software update downloader and executer - * - * Downloads occur via the ZT1 protocol rather than out of band via http so - * that ZeroTier One can be run in secure jailed environments where it is the - * only protocol permitted over the "real" Internet. This is wanted for a - * number of potentially popular use cases, like private LANs that connect - * nodes in hostile environments or playing attack/defend on the future CTF - * network. - * - * The protocol is a simple chunk-pulling "trivial FTP" like thing that should - * be suitable for core engine software updates. Software updates themselves - * are platform-specific executables that ZeroTier One then exits and runs. - * - * Updaters are cached one-deep and can be replicated peer to peer in addition - * to coming from supernodes. This makes it just a little bit BitTorrent-like - * and helps things scale, and is also ready for further protocol - * decentralization that may occur in the future. - */ -class Updater -{ -public: - /** - * Contains information about a shared update available to other peers - */ - struct SharedUpdate - { - std::string fullPath; - std::string filename; - unsigned char sha512[64]; - C25519::Signature sig; - Address signedBy; - unsigned long size; - }; - - Updater(const RuntimeEnvironment *renv); - ~Updater(); - - /** - * Rescan home path for shareable updates - * - * This happens automatically on construction. - */ - void refreshShared(); - - /** - * Attempt to find an update if this version is newer than ours - * - * This is called whenever a peer notifies us of its version. It does nothing - * if that version is not newer, otherwise it looks around for an update. - * - * @param vMajor Major version - * @param vMinor Minor version - * @param revision Revision - */ - void getUpdateIfThisIsNewer(unsigned int vMajor,unsigned int vMinor,unsigned int revision); - - /** - * Called periodically from main loop - * - * This retries downloads if they're stalled and performs other cleanup. - */ - void retryIfNeeded(); - - /** - * Called when a chunk is received - * - * If the chunk is a final chunk and we now have an update, this may result - * in the commencement of the update process and the shutdown of ZT1. - * - * @param from Originating peer - * @param sha512 Up to 64 bytes of hash to match - * @param shalen Length of sha512[] - * @param at Position of chunk - * @param chunk Chunk data - * @param len Length of chunk - */ - void handleChunk(const Address &from,const void *sha512,unsigned int shalen,unsigned long at,const void *chunk,unsigned long len); - - /** - * Called when a reply to a search for an update is received - * - * This checks SHA-512 hash signature and version as parsed from filename - * before starting the transfer. - * - * @param from Node that sent reply saying it has the file - * @param filename Name of file (can be parsed for version info) - * @param sha512 64-byte SHA-512 hash of file's contents - * @param filesize Size of file in bytes - * @param signedBy Address of signer of filename+hash - * @param signature Signature (currently must be Ed25519) - * @param siglen Length of signature in bytes - */ - void handlePeerHasFile(const Address &from,const char *filename,const void *sha512,unsigned long filesize,const Address &signedBy,const void *signature,unsigned int siglen); - - /** - * Get data about a shared update if found - * - * @param filename File name - * @param update Empty structure to be filled with update info - * @return True if found (if false, 'update' is unmodified) - */ - bool findSharedUpdate(const char *filename,SharedUpdate &update) const; - - /** - * Get data about a shared update if found - * - * @param sha512 Up to 64 bytes of hash to match - * @param shalen Length of sha512[] - * @param update Empty structure to be filled with update info - * @return True if found (if false, 'update' is unmodified) - */ - bool findSharedUpdate(const void *sha512,unsigned int shalen,SharedUpdate &update) const; - - /** - * Get a chunk of a shared update - * - * @param sha512 Up to 64 bytes of hash to match - * @param shalen Length of sha512[] - * @param at Position in file - * @param chunk Buffer to store data - * @param chunklen Number of bytes to get - * @return True if chunk[] was successfully filled, false if not found or other error - */ - bool getSharedChunk(const void *sha512,unsigned int shalen,unsigned long at,void *chunk,unsigned long chunklen) const; - - /** - * @return Canonical update filename for this platform or empty string if unsupported - */ - static std::string generateUpdateFilename(unsigned int vMajor,unsigned int vMinor,unsigned int revision); - - /** - * Parse an updater filename and extract version info - * - * @param filename Filename to parse - * @return True if info was extracted and value-result parameters set - */ - static bool parseUpdateFilename(const char *filename,unsigned int &vMajor,unsigned int &vMinor,unsigned int &revision); - - /** - * Compare major, minor, and revision components of a version - * - * @return True if the first set is greater than the second - */ - static inline bool compareVersions(unsigned int vmaj1,unsigned int vmin1,unsigned int rev1,unsigned int vmaj2,unsigned int vmin2,unsigned int rev2) - throw() - { - return ( ((((uint64_t)(vmaj1 & 0xffff)) << 32) | (((uint64_t)(vmin1 & 0xffff)) << 16) | (((uint64_t)(rev1 & 0xffff)))) > ((((uint64_t)(vmaj2 & 0xffff)) << 32) | (((uint64_t)(vmin2 & 0xffff)) << 16) | (((uint64_t)(rev2 & 0xffff)))) ); - } - -private: - void _requestNextChunk(); - - struct _Download - { - std::string data; - std::vector haveChunks; - std::list
peersThatHave; // excluding current - std::string filename; - unsigned char sha512[64]; - Address currentlyReceivingFrom; - uint64_t lastChunkReceivedAt; - unsigned long lastChunkSize; - unsigned int versionMajor,versionMinor,revision; - }; - - const RuntimeEnvironment *_r; - _Download *_download; - std::list _sharedUpdates; // usually not more than 1 or 2 of these - Mutex _lock; -}; - -} // namespace ZeroTier - -#endif diff --git a/objects.mk b/objects.mk index f38f3e902..547033f93 100644 --- a/objects.mk +++ b/objects.mk @@ -25,5 +25,4 @@ OBJS=\ node/SysEnv.o \ node/Topology.o \ node/UdpSocket.o \ - node/Updater.o \ node/Utils.o