SessionSerializer.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2010 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "SessionSerializer.h"
  36. #include <cstdio>
  37. #include <cassert>
  38. #include <iterator>
  39. #include <set>
  40. #include "RequestGroupMan.h"
  41. #include "a2functional.h"
  42. #include "File.h"
  43. #include "A2STR.h"
  44. #include "download_helper.h"
  45. #include "Option.h"
  46. #include "DownloadResult.h"
  47. #include "FileEntry.h"
  48. #include "prefs.h"
  49. #include "util.h"
  50. #include "array_fun.h"
  51. #include "BufferedFile.h"
  52. #include "OptionParser.h"
  53. #include "OptionHandler.h"
  54. #include "SHA1IOFile.h"
  55. #if HAVE_ZLIB
  56. #include "GZipFile.h"
  57. #endif
  58. namespace aria2 {
  59. SessionSerializer::SessionSerializer(RequestGroupMan* requestGroupMan)
  60. : rgman_{requestGroupMan},
  61. saveError_{true},
  62. saveInProgress_{true},
  63. saveWaiting_{true}
  64. {
  65. }
  66. bool SessionSerializer::save(const std::string& filename) const
  67. {
  68. std::string tempFilename = filename;
  69. tempFilename += "__temp";
  70. {
  71. std::unique_ptr<IOFile> fp;
  72. #if HAVE_ZLIB
  73. if (util::endsWith(filename, ".gz")) {
  74. fp = make_unique<GZipFile>(tempFilename.c_str(), IOFile::WRITE);
  75. }
  76. else
  77. #endif
  78. {
  79. fp = make_unique<BufferedFile>(tempFilename.c_str(), IOFile::WRITE);
  80. }
  81. if (!*fp) {
  82. return false;
  83. }
  84. if (!save(*fp) || fp->close() == EOF) {
  85. return false;
  86. }
  87. }
  88. return File(tempFilename).renameTo(filename);
  89. }
  90. namespace {
  91. // Write 1 line of option name/value pair. This function returns true
  92. // if it succeeds, or false.
  93. bool writeOptionLine(IOFile& fp, PrefPtr pref, const std::string& val)
  94. {
  95. size_t prefLen = strlen(pref->k);
  96. return fp.write(" ", 1) == 1 && fp.write(pref->k, prefLen) == prefLen &&
  97. fp.write("=", 1) == 1 &&
  98. fp.write(val.c_str(), val.size()) == val.size() &&
  99. fp.write("\n", 1) == 1;
  100. }
  101. } // namespace
  102. namespace {
  103. bool writeOption(IOFile& fp, const std::shared_ptr<Option>& op)
  104. {
  105. const std::shared_ptr<OptionParser>& oparser = OptionParser::getInstance();
  106. for (size_t i = 1, len = option::countOption(); i < len; ++i) {
  107. PrefPtr pref = option::i2p(i);
  108. const OptionHandler* h = oparser->find(pref);
  109. if (h && h->getInitialOption() && op->definedLocal(pref)) {
  110. if (h->getCumulative()) {
  111. const std::string& val = op->get(pref);
  112. std::vector<std::string> v;
  113. util::split(val.begin(), val.end(), std::back_inserter(v), '\n', false,
  114. false);
  115. for (std::vector<std::string>::const_iterator j = v.begin(),
  116. eoj = v.end();
  117. j != eoj; ++j) {
  118. if (!writeOptionLine(fp, pref, *j)) {
  119. return false;
  120. }
  121. }
  122. }
  123. else {
  124. if (!writeOptionLine(fp, pref, op->get(pref))) {
  125. return false;
  126. }
  127. }
  128. }
  129. }
  130. return true;
  131. }
  132. } // namespace
  133. namespace {
  134. template <typename T> class Unique {
  135. typedef T type;
  136. struct PointerCmp {
  137. inline bool operator()(const type* x, const type* y) { return *x < *y; }
  138. };
  139. std::set<const type*, PointerCmp> known;
  140. public:
  141. inline bool operator()(const type& v) { return known.insert(&v).second; }
  142. };
  143. bool writeUri(IOFile& fp, const std::string& uri)
  144. {
  145. return fp.write(uri.c_str(), uri.size()) == uri.size() &&
  146. fp.write("\t", 1) == 1;
  147. }
  148. template <typename InputIterator, class UnaryPredicate>
  149. bool writeUri(IOFile& fp, InputIterator first, InputIterator last,
  150. UnaryPredicate& filter)
  151. {
  152. for (; first != last; ++first) {
  153. if (!filter(*first)) {
  154. continue;
  155. }
  156. if (!writeUri(fp, *first)) {
  157. return false;
  158. }
  159. }
  160. return true;
  161. }
  162. } // namespace
  163. // The downloads whose followedBy() is empty is persisted with its
  164. // GID without no problem. For other cases, there are several patterns.
  165. //
  166. // 1. magnet URI
  167. // GID of metadata download is persisted.
  168. // 2. URI to torrent file
  169. // GID of torrent file download is persisted.
  170. // 3. URI to metalink file
  171. // GID of metalink file download is persisted.
  172. // 4. local torrent file
  173. // GID of torrent download itself is persisted.
  174. // 5. local metalink file
  175. // No GID is persisted. GID is saved but it is just a random GID.
  176. namespace {
  177. bool writeDownloadResult(IOFile& fp, std::set<a2_gid_t>& metainfoCache,
  178. const std::shared_ptr<DownloadResult>& dr,
  179. bool pauseRequested)
  180. {
  181. const std::shared_ptr<MetadataInfo>& mi = dr->metadataInfo;
  182. if (dr->belongsTo != 0 || (mi && mi->dataOnly()) || !dr->followedBy.empty()) {
  183. return true;
  184. }
  185. if (!mi) {
  186. // With --force-save option, same gid may be saved twice. (e.g.,
  187. // Downloading .meta4 followed by its content download. First
  188. // .meta4 download is saved and second content download is also
  189. // saved with the same gid.)
  190. if (metainfoCache.count(dr->gid->getNumericId()) != 0) {
  191. return true;
  192. }
  193. else {
  194. metainfoCache.insert(dr->gid->getNumericId());
  195. }
  196. // only save first file entry
  197. if (dr->fileEntries.empty()) {
  198. return true;
  199. }
  200. const std::shared_ptr<FileEntry>& file = dr->fileEntries[0];
  201. // Don't save download if there are no URIs.
  202. const bool hasRemaining = !file->getRemainingUris().empty();
  203. const bool hasSpent = !file->getSpentUris().empty();
  204. if (!hasRemaining && !hasSpent) {
  205. return true;
  206. }
  207. // Save spent URIs + remaining URIs. Remove URI in spent URI which
  208. // also exists in remaining URIs.
  209. {
  210. Unique<std::string> unique;
  211. if (hasRemaining &&
  212. !writeUri(fp, file->getRemainingUris().begin(),
  213. file->getRemainingUris().end(), unique)) {
  214. return false;
  215. }
  216. if (hasSpent &&
  217. !writeUri(fp, file->getSpentUris().begin(),
  218. file->getSpentUris().end(), unique)) {
  219. return false;
  220. }
  221. }
  222. if (fp.write("\n", 1) != 1) {
  223. return false;
  224. }
  225. if (!writeOptionLine(fp, PREF_GID, dr->gid->toHex())) {
  226. return false;
  227. }
  228. }
  229. else {
  230. if (metainfoCache.count(mi->getGID()) != 0) {
  231. return true;
  232. }
  233. else {
  234. metainfoCache.insert(mi->getGID());
  235. if (fp.write(mi->getUri().c_str(), mi->getUri().size()) !=
  236. mi->getUri().size() ||
  237. fp.write("\n", 1) != 1) {
  238. return false;
  239. }
  240. // For downloads generated by metadata (e.g., BitTorrent,
  241. // Metalink), save gid of Metadata download.
  242. if (!writeOptionLine(fp, PREF_GID, GroupId::toHex(mi->getGID()))) {
  243. return false;
  244. }
  245. }
  246. }
  247. // PREF_PAUSE was removed from option, so save it here looking
  248. // property separately.
  249. if (pauseRequested) {
  250. if (!writeOptionLine(fp, PREF_PAUSE, A2_V_TRUE)) {
  251. return false;
  252. }
  253. }
  254. return writeOption(fp, dr->option);
  255. }
  256. } // namespace
  257. namespace {
  258. template <typename InputIt>
  259. bool saveDownloadResult(IOFile& fp, std::set<a2_gid_t>& metainfoCache,
  260. InputIt first, InputIt last, bool saveInProgress,
  261. bool saveError)
  262. {
  263. for (; first != last; ++first) {
  264. const auto& dr = *first;
  265. auto save = false;
  266. switch (dr->result) {
  267. case error_code::FINISHED:
  268. case error_code::REMOVED:
  269. save = dr->option->getAsBool(PREF_FORCE_SAVE);
  270. break;
  271. case error_code::IN_PROGRESS:
  272. save = saveInProgress;
  273. break;
  274. case error_code::RESOURCE_NOT_FOUND:
  275. case error_code::MAX_FILE_NOT_FOUND:
  276. save = saveError && dr->option->getAsBool(PREF_SAVE_NOT_FOUND);
  277. break;
  278. default:
  279. save = saveError;
  280. break;
  281. }
  282. if (save && !writeDownloadResult(fp, metainfoCache, dr, false)) {
  283. return false;
  284. }
  285. }
  286. return true;
  287. }
  288. } // namespace
  289. bool SessionSerializer::save(IOFile& fp) const
  290. {
  291. std::set<a2_gid_t> metainfoCache;
  292. const auto& unfinishedResults = rgman_->getUnfinishedDownloadResult();
  293. if (!saveDownloadResult(fp, metainfoCache, std::begin(unfinishedResults),
  294. std::end(unfinishedResults), saveInProgress_,
  295. saveError_)) {
  296. return false;
  297. }
  298. const auto& results = rgman_->getDownloadResults();
  299. if (!saveDownloadResult(fp, metainfoCache, std::begin(results),
  300. std::end(results), saveInProgress_, saveError_)) {
  301. return false;
  302. }
  303. {
  304. // Save active downloads.
  305. const RequestGroupList& groups = rgman_->getRequestGroups();
  306. for (const auto& rg : groups) {
  307. auto dr = rg->createDownloadResult();
  308. bool stopped = dr->result == error_code::FINISHED ||
  309. dr->result == error_code::REMOVED;
  310. if ((!stopped && saveInProgress_) ||
  311. (stopped && dr->option->getAsBool(PREF_FORCE_SAVE))) {
  312. if (!writeDownloadResult(fp, metainfoCache, dr,
  313. rg->isPauseRequested())) {
  314. return false;
  315. }
  316. }
  317. }
  318. }
  319. if (saveWaiting_) {
  320. const auto& groups = rgman_->getReservedGroups();
  321. for (const auto& rg : groups) {
  322. auto result = rg->createDownloadResult();
  323. if (!writeDownloadResult(fp, metainfoCache, result,
  324. rg->isPauseRequested())) {
  325. return false;
  326. }
  327. }
  328. }
  329. return true;
  330. }
  331. std::string SessionSerializer::calculateHash() const
  332. {
  333. SHA1IOFile sha1io;
  334. auto rv = save(sha1io);
  335. if (!rv) {
  336. return "";
  337. }
  338. return sha1io.digest();
  339. }
  340. } // namespace aria2