Updater.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include "Updater.hpp"
  28. #include "RuntimeEnvironment.hpp"
  29. #include "Logger.hpp"
  30. #include "Defaults.hpp"
  31. #include "Utils.hpp"
  32. #include "Topology.hpp"
  33. #include "Switch.hpp"
  34. #include "SHA512.hpp"
  35. #include "../version.h"
  36. namespace ZeroTier {
  37. Updater::Updater(const RuntimeEnvironment *renv) :
  38. _r(renv),
  39. _download((_Download *)0)
  40. {
  41. refreshShared();
  42. }
  43. Updater::~Updater()
  44. {
  45. Mutex::Lock _l(_lock);
  46. delete _download;
  47. }
  48. void Updater::refreshShared()
  49. {
  50. std::string updatesPath(_r->homePath + ZT_PATH_SEPARATOR_S + "updates.d");
  51. std::map<std::string,bool> ud(Utils::listDirectory(updatesPath.c_str()));
  52. Mutex::Lock _l(_lock);
  53. _sharedUpdates.clear();
  54. for(std::map<std::string,bool>::iterator u(ud.begin());u!=ud.end();++u) {
  55. if (u->second)
  56. continue; // skip directories
  57. if ((u->first.length() >= 4)&&(!strcasecmp(u->first.substr(u->first.length() - 4).c_str(),".nfo")))
  58. continue; // skip .nfo companion files
  59. std::string fullPath(updatesPath + ZT_PATH_SEPARATOR_S + u->first);
  60. std::string nfoPath(fullPath + ".nfo");
  61. std::string buf;
  62. if (Utils::readFile(nfoPath.c_str(),buf)) {
  63. Dictionary nfo(buf);
  64. SharedUpdate shared;
  65. shared.fullPath = fullPath;
  66. shared.filename = u->first;
  67. std::string sha512(Utils::unhex(nfo.get("sha512",std::string())));
  68. if (sha512.length() < sizeof(shared.sha512)) {
  69. TRACE("skipped shareable update due to missing fields in companion .nfo: %s",fullPath.c_str());
  70. continue;
  71. }
  72. memcpy(shared.sha512,sha512.data(),sizeof(shared.sha512));
  73. std::string sig(Utils::unhex(nfo.get("sha512sig_ed25519",std::string())));
  74. if (sig.length() < shared.sig.size()) {
  75. TRACE("skipped shareable update due to missing fields in companion .nfo: %s",fullPath.c_str());
  76. continue;
  77. }
  78. memcpy(shared.sig.data,sig.data(),shared.sig.size());
  79. // Check signature to guard against updates.d being used as a data
  80. // exfiltration mechanism. We will only share properly signed updates,
  81. // nothing else.
  82. Address signedBy(nfo.get("signedBy",std::string()));
  83. std::map< Address,Identity >::const_iterator authority(ZT_DEFAULTS.updateAuthorities.find(signedBy));
  84. if ((authority == ZT_DEFAULTS.updateAuthorities.end())||(!authority->second.verify(shared.sha512,64,shared.sig))) {
  85. TRACE("skipped shareable update: not signed by valid authority or signature invalid: %s",fullPath.c_str());
  86. continue;
  87. }
  88. shared.signedBy = signedBy;
  89. int64_t fs = Utils::getFileSize(fullPath.c_str());
  90. if (fs <= 0) {
  91. TRACE("skipped shareable update due to unreadable, invalid, or 0-byte file: %s",fullPath.c_str());
  92. continue;
  93. }
  94. shared.size = (unsigned long)fs;
  95. LOG("sharing software update %s to other peers",shared.filename.c_str());
  96. _sharedUpdates.push_back(shared);
  97. } else {
  98. TRACE("skipped shareable update due to missing companion .nfo: %s",fullPath.c_str());
  99. continue;
  100. }
  101. }
  102. }
  103. void Updater::getUpdateIfThisIsNewer(unsigned int vMajor,unsigned int vMinor,unsigned int revision)
  104. {
  105. if (!compareVersions(vMajor,vMinor,revision,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION))
  106. return;
  107. std::string updateFilename(generateUpdateFilename(vMajor,vMinor,revision));
  108. if (!updateFilename.length()) {
  109. TRACE("an update to %u.%u.%u is available, but this platform or build doesn't support auto-update",vMajor,vMinor,revision);
  110. return;
  111. }
  112. std::vector< SharedPtr<Peer> > peers;
  113. _r->topology->eachPeer(Topology::CollectPeersWithActiveDirectPath(peers,Utils::now()));
  114. TRACE("new update available to %u.%u.%u, looking for %s from %u peers",vMajor,vMinor,revision,updateFilename.c_str(),(unsigned int)peers.size());
  115. for(std::vector< SharedPtr<Peer> >::iterator p(peers.begin());p!=peers.end();++p) {
  116. Packet outp((*p)->address(),_r->identity.address(),Packet::VERB_FILE_INFO_REQUEST);
  117. outp.append((unsigned char)0);
  118. outp.append((uint16_t)updateFilename.length());
  119. outp.append(updateFilename.data(),updateFilename.length());
  120. _r->sw->send(outp,true);
  121. }
  122. }
  123. void Updater::retryIfNeeded()
  124. {
  125. Mutex::Lock _l(_lock);
  126. if (_download) {
  127. uint64_t elapsed = Utils::now() - _download->lastChunkReceivedAt;
  128. if ((elapsed >= ZT_UPDATER_PEER_TIMEOUT)||(!_download->currentlyReceivingFrom)) {
  129. if (_download->peersThatHave.empty()) {
  130. // Search for more sources if we have no more possibilities queued
  131. TRACE("all sources for %s timed out, searching for more...",_download->filename.c_str());
  132. _download->currentlyReceivingFrom.zero();
  133. std::vector< SharedPtr<Peer> > peers;
  134. _r->topology->eachPeer(Topology::CollectPeersWithActiveDirectPath(peers,Utils::now()));
  135. for(std::vector< SharedPtr<Peer> >::iterator p(peers.begin());p!=peers.end();++p) {
  136. Packet outp((*p)->address(),_r->identity.address(),Packet::VERB_FILE_INFO_REQUEST);
  137. outp.append((unsigned char)0);
  138. outp.append((uint16_t)_download->filename.length());
  139. outp.append(_download->filename.data(),_download->filename.length());
  140. _r->sw->send(outp,true);
  141. }
  142. } else {
  143. // If that peer isn't answering, try the next queued source
  144. _download->currentlyReceivingFrom = _download->peersThatHave.front();
  145. _download->peersThatHave.pop_front();
  146. _requestNextChunk();
  147. }
  148. } else if (elapsed >= ZT_UPDATER_RETRY_TIMEOUT) {
  149. // Re-request next chunk we don't have from current source
  150. _requestNextChunk();
  151. }
  152. }
  153. }
  154. void Updater::handleChunk(const Address &from,const void *sha512,unsigned int shalen,unsigned long at,const void *chunk,unsigned long len)
  155. {
  156. Mutex::Lock _l(_lock);
  157. if (!_download) {
  158. TRACE("got chunk from %s while no download is in progress, ignored",from.toString().c_str());
  159. return;
  160. }
  161. if (memcmp(_download->sha512,sha512,(shalen > 64) ? 64 : shalen)) {
  162. TRACE("got chunk from %s for wrong download (SHA mismatch), ignored",from.toString().c_str());
  163. return;
  164. }
  165. unsigned long whichChunk = at / ZT_UPDATER_CHUNK_SIZE;
  166. if (
  167. (at != (ZT_UPDATER_CHUNK_SIZE * whichChunk))||
  168. (whichChunk >= _download->haveChunks.size())||
  169. ((whichChunk == (_download->haveChunks.size() - 1))&&(len != _download->lastChunkSize))||
  170. (len != ZT_UPDATER_CHUNK_SIZE)
  171. ) {
  172. TRACE("got chunk from %s at invalid position or invalid size, ignored",from.toString().c_str());
  173. return;
  174. }
  175. for(unsigned long i=0;i<len;++i)
  176. _download->data[at + i] = ((const char *)chunk)[i];
  177. _download->haveChunks[whichChunk] = true;
  178. _download->lastChunkReceivedAt = Utils::now();
  179. _requestNextChunk();
  180. }
  181. void Updater::handlePeerHasFile(const Address &from,const char *filename,const void *sha512,unsigned long filesize,const Address &signedBy,const void *signature,unsigned int siglen)
  182. {
  183. unsigned int vMajor = 0,vMinor = 0,revision = 0;
  184. if (!parseUpdateFilename(filename,vMajor,vMinor,revision)) {
  185. TRACE("rejected offer of %s from %s: could not extract version information from filename",filename,from.toString().c_str());
  186. return;
  187. }
  188. if (filesize > ZT_UPDATER_MAX_SUPPORTED_SIZE) {
  189. 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);
  190. return;
  191. }
  192. if (!compareVersions(vMajor,vMinor,revision,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION)) {
  193. TRACE("rejected offer of %s from %s: version older than mine",filename,from.toString().c_str());
  194. return;
  195. }
  196. Mutex::Lock _l(_lock);
  197. if (_download) {
  198. if ((_download->filename == filename)&&(_download->data.length() == filesize)&&(!memcmp(sha512,_download->sha512,64))) {
  199. // Learn another source for the current download if this is the
  200. // same file.
  201. LOG("learned new source for %s: %s",filename,from.toString().c_str());
  202. if (!_download->currentlyReceivingFrom) {
  203. _download->currentlyReceivingFrom = from;
  204. _requestNextChunk();
  205. } else _download->peersThatHave.push_back(from);
  206. return;
  207. } else {
  208. // If there's a download, compare versions... only proceed if this
  209. // file being offered is newer.
  210. if (!compareVersions(vMajor,vMinor,revision,_download->versionMajor,_download->versionMinor,_download->revision)) {
  211. TRACE("rejected offer of %s from %s: already downloading newer version %s",filename,from.toString().c_str(),_download->filename.c_str());
  212. return;
  213. }
  214. }
  215. }
  216. // If we have no download OR if this was a different file, check its
  217. // validity via signature and then see if it's newer. If so start a new
  218. // download for it.
  219. {
  220. std::string nameAndSha(filename);
  221. nameAndSha.append((const char *)sha512,64);
  222. std::map< Address,Identity >::const_iterator uauth(ZT_DEFAULTS.updateAuthorities.find(signedBy));
  223. if (uauth == ZT_DEFAULTS.updateAuthorities.end()) {
  224. LOG("rejected offer of %s from %s: failed authentication: unknown signer %s",filename,from.toString().c_str(),signedBy.toString().c_str());
  225. return;
  226. }
  227. if (!uauth->second.verify(nameAndSha.data(),nameAndSha.length(),signature,siglen)) {
  228. LOG("rejected offer of %s from %s: failed authentication: signature from %s invalid",filename,from.toString().c_str(),signedBy.toString().c_str());
  229. return;
  230. }
  231. }
  232. // Replace existing download if any.
  233. delete _download;
  234. _download = (_Download *)0;
  235. // Create and initiate new download
  236. _download = new _Download;
  237. try {
  238. 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());
  239. _download->data.assign(filesize,(char)0);
  240. _download->haveChunks.resize((filesize / ZT_UPDATER_CHUNK_SIZE) + 1,false);
  241. _download->filename = filename;
  242. memcpy(_download->sha512,sha512,64);
  243. _download->currentlyReceivingFrom = from;
  244. _download->lastChunkReceivedAt = 0;
  245. _download->lastChunkSize = filesize % ZT_UPDATER_CHUNK_SIZE;
  246. _download->versionMajor = vMajor;
  247. _download->versionMinor = vMinor;
  248. _download->revision = revision;
  249. _requestNextChunk();
  250. } catch (std::exception &exc) {
  251. delete _download;
  252. _download = (_Download *)0;
  253. LOG("unable to begin download of %s from %s: %s",filename,from.toString().c_str(),exc.what());
  254. } catch ( ... ) {
  255. delete _download;
  256. _download = (_Download *)0;
  257. LOG("unable to begin download of %s from %s: unknown exception",filename,from.toString().c_str());
  258. }
  259. }
  260. bool Updater::findSharedUpdate(const char *filename,SharedUpdate &update) const
  261. {
  262. Mutex::Lock _l(_lock);
  263. for(std::list<SharedUpdate>::const_iterator u(_sharedUpdates.begin());u!=_sharedUpdates.end();++u) {
  264. if (u->filename == filename) {
  265. update = *u;
  266. return true;
  267. }
  268. }
  269. return false;
  270. }
  271. bool Updater::findSharedUpdate(const void *sha512,unsigned int shalen,SharedUpdate &update) const
  272. {
  273. if (!shalen)
  274. return false;
  275. Mutex::Lock _l(_lock);
  276. for(std::list<SharedUpdate>::const_iterator u(_sharedUpdates.begin());u!=_sharedUpdates.end();++u) {
  277. if (!memcmp(u->sha512,sha512,(shalen > 64) ? 64 : shalen)) {
  278. update = *u;
  279. return true;
  280. }
  281. }
  282. return false;
  283. }
  284. bool Updater::getSharedChunk(const void *sha512,unsigned int shalen,unsigned long at,void *chunk,unsigned long chunklen) const
  285. {
  286. if (!chunklen)
  287. return true;
  288. if (!shalen)
  289. return false;
  290. Mutex::Lock _l(_lock);
  291. for(std::list<SharedUpdate>::const_iterator u(_sharedUpdates.begin());u!=_sharedUpdates.end();++u) {
  292. if (!memcmp(u->sha512,sha512,(shalen > 64) ? 64 : shalen)) {
  293. FILE *f = fopen(u->fullPath.c_str(),"rb");
  294. if (!f)
  295. return false;
  296. if (!fseek(f,(long)at,SEEK_SET)) {
  297. fclose(f);
  298. return false;
  299. }
  300. if (fread(chunk,chunklen,1,f) != 1) {
  301. fclose(f);
  302. return false;
  303. }
  304. fclose(f);
  305. return true;
  306. }
  307. }
  308. return false;
  309. }
  310. std::string Updater::generateUpdateFilename(unsigned int vMajor,unsigned int vMinor,unsigned int revision)
  311. {
  312. // Defining ZT_OFFICIAL_BUILD enables this cascade of macros, which will
  313. // make your build auto-update itself if it's for an officially supported
  314. // architecture. The signing identity for auto-updates is in Defaults.
  315. #ifdef ZT_OFFICIAL_BUILD
  316. // Not supported... yet? Get it first cause it might identify as Linux too.
  317. #ifdef __ANDROID__
  318. #define _updSupported 1
  319. return std::string();
  320. #endif
  321. // Linux on x86 and possibly in the future ARM
  322. #ifdef __LINUX__
  323. #if defined(__i386) || defined(__i486) || defined(__i586) || defined(__i686) || defined(__amd64) || defined(__x86_64) || defined(i386)
  324. #define _updSupported 1
  325. char buf[128];
  326. Utils::snprintf(buf,sizeof(buf),"zt1-%u_%u_%u-linux-%s-update",vMajor,vMinor,revision,(sizeof(void *) == 8) ? "x64" : "x86");
  327. return std::string(buf);
  328. #endif
  329. /*
  330. #if defined(__arm__) || defined(__arm) || defined(__aarch64__)
  331. #define _updSupported 1
  332. char buf[128];
  333. Utils::snprintf(buf,sizeof(buf),"zt1-%u_%u_%u-linux-%s-update",vMajor,vMinor,revision,(sizeof(void *) == 8) ? "arm64" : "arm32");
  334. return std::string(buf);
  335. #endif
  336. */
  337. #endif
  338. // Apple stuff... only Macs so far...
  339. #ifdef __APPLE__
  340. #define _updSupported 1
  341. #if defined(__powerpc) || defined(__powerpc__) || defined(__ppc__) || defined(__ppc64) || defined(__ppc64__) || defined(__powerpc64__)
  342. return std::string();
  343. #endif
  344. #if defined(TARGET_IPHONE_SIMULATOR) || defined(TARGET_OS_IPHONE)
  345. return std::string();
  346. #endif
  347. char buf[128];
  348. Utils::snprintf(buf,sizeof(buf),"zt1-%u_%u_%u-mac-x86combined-update",vMajor,vMinor,revision);
  349. return std::string(buf);
  350. #endif
  351. // ???
  352. #ifndef _updSupported
  353. return std::string();
  354. #endif
  355. #else
  356. return std::string();
  357. #endif // ZT_OFFICIAL_BUILD
  358. }
  359. bool Updater::parseUpdateFilename(const char *filename,unsigned int &vMajor,unsigned int &vMinor,unsigned int &revision)
  360. {
  361. std::vector<std::string> byDash(Utils::split(filename,"-","",""));
  362. if (byDash.size() < 2)
  363. return false;
  364. std::vector<std::string> byUnderscore(Utils::split(byDash[1].c_str(),"_","",""));
  365. if (byUnderscore.size() < 3)
  366. return false;
  367. vMajor = Utils::strToUInt(byUnderscore[0].c_str());
  368. vMinor = Utils::strToUInt(byUnderscore[1].c_str());
  369. revision = Utils::strToUInt(byUnderscore[2].c_str());
  370. return true;
  371. }
  372. void Updater::_requestNextChunk()
  373. {
  374. // assumes _lock is locked
  375. if (!_download)
  376. return;
  377. unsigned long whichChunk = 0;
  378. std::vector<bool>::iterator ptr(std::find(_download->haveChunks.begin(),_download->haveChunks.end(),false));
  379. if (ptr == _download->haveChunks.end()) {
  380. unsigned char digest[64];
  381. SHA512::hash(digest,_download->data.data(),_download->data.length());
  382. if (memcmp(digest,_download->sha512,64)) {
  383. LOG("retrying download of %s -- SHA-512 mismatch, file corrupt!",_download->filename.c_str());
  384. std::fill(_download->haveChunks.begin(),_download->haveChunks.end(),false);
  385. whichChunk = 0;
  386. } else {
  387. LOG("successfully downloaded and authenticated %s, launching update...",_download->filename.c_str());
  388. delete _download;
  389. _download = (_Download *)0;
  390. return;
  391. }
  392. } else {
  393. whichChunk = std::distance(_download->haveChunks.begin(),ptr);
  394. }
  395. 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());
  396. Packet outp(_download->currentlyReceivingFrom,_r->identity.address(),Packet::VERB_FILE_BLOCK_REQUEST);
  397. outp.append(_download->sha512,16);
  398. outp.append((uint32_t)(whichChunk * ZT_UPDATER_CHUNK_SIZE));
  399. if (whichChunk == (_download->haveChunks.size() - 1))
  400. outp.append((uint16_t)_download->lastChunkSize);
  401. else outp.append((uint16_t)ZT_UPDATER_CHUNK_SIZE);
  402. _r->sw->send(outp,true);
  403. }
  404. } // namespace ZeroTier