Metalink2RequestGroup.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 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 "Metalink2RequestGroup.h"
  36. #include <algorithm>
  37. #include "RequestGroup.h"
  38. #include "Option.h"
  39. #include "LogFactory.h"
  40. #include "Logger.h"
  41. #include "prefs.h"
  42. #include "util.h"
  43. #include "message.h"
  44. #include "DownloadContext.h"
  45. #include "metalink_helper.h"
  46. #include "BinaryStream.h"
  47. #include "MemoryBufferPreDownloadHandler.h"
  48. #include "MetalinkEntry.h"
  49. #include "MetalinkResource.h"
  50. #include "MetalinkMetaurl.h"
  51. #include "FileEntry.h"
  52. #include "A2STR.h"
  53. #include "a2functional.h"
  54. #include "download_helper.h"
  55. #include "fmt.h"
  56. #include "SegList.h"
  57. #include "DownloadFailureException.h"
  58. #include "Signature.h"
  59. #include "download_handlers.h"
  60. #include "RequestGroupCriteria.h"
  61. #ifdef ENABLE_BITTORRENT
  62. #include "BtDependency.h"
  63. #include "download_helper.h"
  64. #endif // ENABLE_BITTORRENT
  65. #include "Checksum.h"
  66. #include "ChunkChecksum.h"
  67. namespace aria2 {
  68. Metalink2RequestGroup::Metalink2RequestGroup() {}
  69. namespace {
  70. class AccumulateNonP2PUri {
  71. private:
  72. std::vector<std::string>& urisPtr;
  73. public:
  74. AccumulateNonP2PUri(std::vector<std::string>& urisPtr) : urisPtr(urisPtr) {}
  75. void operator()(const std::unique_ptr<MetalinkResource>& resource)
  76. {
  77. switch (resource->type) {
  78. case MetalinkResource::TYPE_HTTP:
  79. case MetalinkResource::TYPE_HTTPS:
  80. case MetalinkResource::TYPE_FTP:
  81. urisPtr.push_back(resource->url);
  82. break;
  83. default:
  84. break;
  85. }
  86. }
  87. };
  88. } // namespace
  89. namespace {
  90. class FindBitTorrentUri {
  91. public:
  92. FindBitTorrentUri() {}
  93. bool operator()(const std::shared_ptr<MetalinkResource>& resource)
  94. {
  95. if (resource->type == MetalinkResource::TYPE_BITTORRENT) {
  96. return true;
  97. }
  98. else {
  99. return false;
  100. }
  101. }
  102. };
  103. } // namespace
  104. void Metalink2RequestGroup::generate(
  105. std::vector<std::shared_ptr<RequestGroup>>& groups,
  106. const std::string& metalinkFile, const std::shared_ptr<Option>& option,
  107. const std::string& baseUri)
  108. {
  109. std::vector<std::shared_ptr<RequestGroup>> tempgroups;
  110. createRequestGroup(
  111. tempgroups, metalink::parseAndQuery(metalinkFile, option.get(), baseUri),
  112. option);
  113. std::shared_ptr<MetadataInfo> mi;
  114. if (metalinkFile == DEV_STDIN) {
  115. mi = std::make_shared<MetadataInfo>();
  116. }
  117. else {
  118. // TODO Downloads from local metalink file does not save neither
  119. // its gid nor MetadataInfo's gid.
  120. mi = std::make_shared<MetadataInfo>(GroupId::create(), metalinkFile);
  121. }
  122. setMetadataInfo(std::begin(tempgroups), std::end(tempgroups), mi);
  123. groups.insert(std::end(groups), std::begin(tempgroups), std::end(tempgroups));
  124. }
  125. void Metalink2RequestGroup::generate(
  126. std::vector<std::shared_ptr<RequestGroup>>& groups,
  127. const std::shared_ptr<BinaryStream>& binaryStream,
  128. const std::shared_ptr<Option>& option, const std::string& baseUri)
  129. {
  130. std::vector<std::shared_ptr<RequestGroup>> tempgroups;
  131. createRequestGroup(tempgroups, metalink::parseAndQuery(binaryStream.get(),
  132. option.get(), baseUri),
  133. option);
  134. auto mi = std::make_shared<MetadataInfo>();
  135. setMetadataInfo(std::begin(tempgroups), std::end(tempgroups), mi);
  136. groups.insert(std::end(groups), std::begin(tempgroups), std::end(tempgroups));
  137. }
  138. void Metalink2RequestGroup::createRequestGroup(
  139. std::vector<std::shared_ptr<RequestGroup>>& groups,
  140. std::vector<std::unique_ptr<MetalinkEntry>> entries,
  141. const std::shared_ptr<Option>& optionTemplate)
  142. {
  143. if (entries.empty()) {
  144. A2_LOG_NOTICE(EX_NO_RESULT_WITH_YOUR_PREFS);
  145. return;
  146. }
  147. std::vector<std::string> locations;
  148. if (optionTemplate->defined(PREF_METALINK_LOCATION)) {
  149. auto& loc = optionTemplate->get(PREF_METALINK_LOCATION);
  150. util::split(std::begin(loc), std::end(loc), std::back_inserter(locations),
  151. ',', true);
  152. for (auto& s : locations) {
  153. util::lowercase(s);
  154. }
  155. }
  156. std::string preferredProtocol;
  157. if (optionTemplate->get(PREF_METALINK_PREFERRED_PROTOCOL) != V_NONE) {
  158. preferredProtocol = optionTemplate->get(PREF_METALINK_PREFERRED_PROTOCOL);
  159. }
  160. for (auto& entry : entries) {
  161. entry->dropUnsupportedResource();
  162. if (entry->resources.empty() && entry->metaurls.empty()) {
  163. continue;
  164. }
  165. entry->setLocationPriority(locations,
  166. -MetalinkResource::getLowestPriority());
  167. if (!preferredProtocol.empty()) {
  168. entry->setProtocolPriority(preferredProtocol,
  169. -MetalinkResource::getLowestPriority());
  170. }
  171. }
  172. auto sgl = util::parseIntSegments(optionTemplate->get(PREF_SELECT_FILE));
  173. sgl.normalize();
  174. if (sgl.hasNext()) {
  175. size_t inspoint = 0;
  176. for (size_t i = 0, len = entries.size(); i < len && sgl.hasNext(); ++i) {
  177. size_t j = sgl.peek() - 1;
  178. if (i == j) {
  179. if (inspoint != i) {
  180. entries[inspoint] = std::move(entries[i]);
  181. }
  182. ++inspoint;
  183. sgl.next();
  184. }
  185. }
  186. entries.resize(inspoint);
  187. }
  188. std::for_each(std::begin(entries), std::end(entries),
  189. std::mem_fn(&MetalinkEntry::reorderMetaurlsByPriority));
  190. auto entryGroups = metalink::groupEntryByMetaurlName(entries);
  191. for (auto& entryGroup : entryGroups) {
  192. auto& metaurl = entryGroup.first;
  193. auto& mes = entryGroup.second;
  194. A2_LOG_INFO(fmt("Processing metaurl group metaurl=%s", metaurl.c_str()));
  195. #ifdef ENABLE_BITTORRENT
  196. std::shared_ptr<RequestGroup> torrentRg;
  197. if (!metaurl.empty()) {
  198. std::vector<std::string> uris;
  199. uris.push_back(metaurl);
  200. {
  201. std::vector<std::shared_ptr<RequestGroup>> result;
  202. createRequestGroupForUri(result, optionTemplate, uris,
  203. /* ignoreForceSequential = */ true,
  204. /* ignoreLocalPath = */ true);
  205. if (!result.empty()) {
  206. torrentRg = result[0];
  207. }
  208. }
  209. if (torrentRg) {
  210. torrentRg->setNumConcurrentCommand(1);
  211. torrentRg->clearPreDownloadHandler();
  212. torrentRg->clearPostDownloadHandler();
  213. // remove "metalink" from Accept Type list to avoid loop in
  214. // transparent metalink
  215. torrentRg->getDownloadContext()->setAcceptMetalink(false);
  216. // make it in-memory download
  217. torrentRg->addPreDownloadHandler(
  218. download_handlers::getMemoryPreDownloadHandler());
  219. groups.push_back(torrentRg);
  220. }
  221. }
  222. #endif // ENABLE_BITTORRENT
  223. auto option = util::copy(optionTemplate);
  224. auto rg = std::make_shared<RequestGroup>(GroupId::create(), option);
  225. std::shared_ptr<DownloadContext> dctx;
  226. int numSplit = option->getAsInt(PREF_SPLIT);
  227. int maxConn = option->getAsInt(PREF_MAX_CONNECTION_PER_SERVER);
  228. if (mes.size() == 1) {
  229. auto entry = mes[0];
  230. A2_LOG_INFO(fmt(MSG_METALINK_QUEUEING, entry->getPath().c_str()));
  231. entry->reorderResourcesByPriority();
  232. for (auto& mr : entry->resources) {
  233. A2_LOG_DEBUG(fmt("priority=%d url=%s", mr->priority, mr->url.c_str()));
  234. }
  235. std::vector<std::string> uris;
  236. std::for_each(std::begin(entry->resources), std::end(entry->resources),
  237. AccumulateNonP2PUri(uris));
  238. // If piece hash is specified in the metalink,
  239. // make segment size equal to piece hash size.
  240. int32_t pieceLength;
  241. if (!entry->chunkChecksum) {
  242. pieceLength = option->getAsInt(PREF_PIECE_LENGTH);
  243. }
  244. else {
  245. pieceLength = entry->chunkChecksum->getPieceLength();
  246. }
  247. dctx = std::make_shared<DownloadContext>(
  248. pieceLength, entry->getLength(),
  249. util::applyDir(option->get(PREF_DIR), entry->file->getPath()));
  250. dctx->getFirstFileEntry()->setUris(uris);
  251. dctx->getFirstFileEntry()->setMaxConnectionPerServer(maxConn);
  252. dctx->getFirstFileEntry()->setSuffixPath(entry->file->getPath());
  253. if (option->getAsBool(PREF_METALINK_ENABLE_UNIQUE_PROTOCOL)) {
  254. dctx->getFirstFileEntry()->setUniqueProtocol(true);
  255. }
  256. if (entry->checksum) {
  257. dctx->setDigest(entry->checksum->getHashType(),
  258. entry->checksum->getDigest());
  259. }
  260. if (entry->chunkChecksum) {
  261. dctx->setPieceHashes(entry->chunkChecksum->getHashType(),
  262. std::begin(entry->chunkChecksum->getPieceHashes()),
  263. std::end(entry->chunkChecksum->getPieceHashes()));
  264. }
  265. dctx->setSignature(entry->popSignature());
  266. rg->setNumConcurrentCommand(
  267. entry->maxConnections < 0
  268. ? numSplit
  269. : std::min(numSplit, entry->maxConnections));
  270. }
  271. else {
  272. dctx = std::make_shared<DownloadContext>();
  273. // piece length is overridden by the one in torrent file.
  274. dctx->setPieceLength(option->getAsInt(PREF_PIECE_LENGTH));
  275. std::vector<std::shared_ptr<FileEntry>> fileEntries;
  276. int64_t offset = 0;
  277. for (auto entry : mes) {
  278. A2_LOG_INFO(fmt("Metalink: Queueing %s for download as a member.",
  279. entry->getPath().c_str()));
  280. A2_LOG_DEBUG(
  281. fmt("originalName = %s", entry->metaurls[0]->name.c_str()));
  282. entry->reorderResourcesByPriority();
  283. std::vector<std::string> uris;
  284. std::for_each(std::begin(entry->resources), std::end(entry->resources),
  285. AccumulateNonP2PUri(uris));
  286. auto fe = std::make_shared<FileEntry>(
  287. util::applyDir(option->get(PREF_DIR), entry->file->getPath()),
  288. entry->file->getLength(), offset, uris);
  289. fe->setMaxConnectionPerServer(maxConn);
  290. if (option->getAsBool(PREF_METALINK_ENABLE_UNIQUE_PROTOCOL)) {
  291. fe->setUniqueProtocol(true);
  292. }
  293. fe->setOriginalName(entry->metaurls[0]->name);
  294. fe->setSuffixPath(entry->file->getPath());
  295. fileEntries.push_back(fe);
  296. if (offset >
  297. std::numeric_limits<int64_t>::max() - entry->file->getLength()) {
  298. throw DOWNLOAD_FAILURE_EXCEPTION(fmt(EX_TOO_LARGE_FILE, offset));
  299. }
  300. offset += entry->file->getLength();
  301. }
  302. dctx->setFileEntries(std::begin(fileEntries), std::end(fileEntries));
  303. rg->setNumConcurrentCommand(numSplit);
  304. }
  305. rg->setDownloadContext(dctx);
  306. if (option->getAsBool(PREF_ENABLE_RPC)) {
  307. rg->setPauseRequested(option->getAsBool(PREF_PAUSE));
  308. }
  309. removeOneshotOption(option);
  310. // remove "metalink" from Accept Type list to avoid loop in
  311. // transparent metalink
  312. dctx->setAcceptMetalink(false);
  313. #ifdef ENABLE_BITTORRENT
  314. // Inject dependency between rg and torrentRg here if
  315. // torrentRg is true
  316. if (torrentRg) {
  317. auto dep = std::make_shared<BtDependency>(rg.get(), torrentRg);
  318. rg->dependsOn(dep);
  319. torrentRg->belongsTo(rg->getGID());
  320. // metadata download may take very long time. If URIs are
  321. // available, give up metadata download in at most 30 seconds.
  322. const time_t btStopTimeout = 30;
  323. time_t currentBtStopTimeout =
  324. torrentRg->getOption()->getAsInt(PREF_BT_STOP_TIMEOUT);
  325. if (currentBtStopTimeout == 0 || currentBtStopTimeout > btStopTimeout) {
  326. bool allHaveUri = true;
  327. for (auto& fe : dctx->getFileEntries()) {
  328. if (fe->getRemainingUris().empty()) {
  329. allHaveUri = false;
  330. break;
  331. }
  332. }
  333. if (allHaveUri) {
  334. torrentRg->getOption()->put(PREF_BT_STOP_TIMEOUT,
  335. util::itos(btStopTimeout));
  336. }
  337. }
  338. }
  339. #endif // ENABLE_BITTORRENT
  340. groups.push_back(rg);
  341. }
  342. }
  343. } // namespace aria2