Metalink2RequestGroup.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 "TrueRequestGroupCriteria.h"
  49. #include "MetalinkEntry.h"
  50. #include "MetalinkResource.h"
  51. #include "MetalinkMetaurl.h"
  52. #include "FileEntry.h"
  53. #include "A2STR.h"
  54. #include "a2functional.h"
  55. #include "download_helper.h"
  56. #include "fmt.h"
  57. #ifdef ENABLE_BITTORRENT
  58. # include "BtDependency.h"
  59. # include "download_helper.h"
  60. #endif // ENABLE_BITTORRENT
  61. #ifdef ENABLE_MESSAGE_DIGEST
  62. # include "Checksum.h"
  63. # include "ChunkChecksum.h"
  64. #endif // ENABLE_MESSAGE_DIGEST
  65. namespace aria2 {
  66. Metalink2RequestGroup::Metalink2RequestGroup() {}
  67. namespace {
  68. class AccumulateNonP2PUri {
  69. private:
  70. std::vector<std::string>& urisPtr;
  71. public:
  72. AccumulateNonP2PUri(std::vector<std::string>& urisPtr)
  73. :urisPtr(urisPtr) {}
  74. void operator()(const SharedHandle<MetalinkResource>& resource) {
  75. switch(resource->type) {
  76. case MetalinkResource::TYPE_HTTP:
  77. case MetalinkResource::TYPE_HTTPS:
  78. case MetalinkResource::TYPE_FTP:
  79. urisPtr.push_back(resource->url);
  80. break;
  81. default:
  82. break;
  83. }
  84. }
  85. };
  86. } // namespace
  87. namespace {
  88. class FindBitTorrentUri {
  89. public:
  90. FindBitTorrentUri() {}
  91. bool operator()(const SharedHandle<MetalinkResource>& resource) {
  92. if(resource->type == MetalinkResource::TYPE_BITTORRENT) {
  93. return true;
  94. } else {
  95. return false;
  96. }
  97. }
  98. };
  99. } // namespace
  100. void
  101. Metalink2RequestGroup::generate
  102. (std::vector<SharedHandle<RequestGroup> >& groups,
  103. const std::string& metalinkFile,
  104. const SharedHandle<Option>& option,
  105. const std::string& baseUri)
  106. {
  107. std::vector<SharedHandle<MetalinkEntry> > entries;
  108. metalink::parseAndQuery(entries, metalinkFile, option.get(), baseUri);
  109. std::vector<SharedHandle<RequestGroup> > tempgroups;
  110. createRequestGroup(tempgroups, entries, option);
  111. SharedHandle<MetadataInfo> mi;
  112. if(metalinkFile == DEV_STDIN) {
  113. mi.reset(new MetadataInfo());
  114. } else {
  115. mi.reset(new MetadataInfo(metalinkFile));
  116. }
  117. setMetadataInfo(tempgroups.begin(), tempgroups.end(), mi);
  118. groups.insert(groups.end(), tempgroups.begin(), tempgroups.end());
  119. }
  120. void
  121. Metalink2RequestGroup::generate
  122. (std::vector<SharedHandle<RequestGroup> >& groups,
  123. const SharedHandle<BinaryStream>& binaryStream,
  124. const SharedHandle<Option>& option,
  125. const std::string& baseUri)
  126. {
  127. std::vector<SharedHandle<MetalinkEntry> > entries;
  128. metalink::parseAndQuery(entries, binaryStream, option.get(), baseUri);
  129. std::vector<SharedHandle<RequestGroup> > tempgroups;
  130. createRequestGroup(tempgroups, entries, option);
  131. SharedHandle<MetadataInfo> mi(new MetadataInfo());
  132. setMetadataInfo(tempgroups.begin(), tempgroups.end(), mi);
  133. groups.insert(groups.end(), tempgroups.begin(), tempgroups.end());
  134. }
  135. void
  136. Metalink2RequestGroup::createRequestGroup
  137. (std::vector<SharedHandle<RequestGroup> >& groups,
  138. const std::vector<SharedHandle<MetalinkEntry> >& entries,
  139. const SharedHandle<Option>& option)
  140. {
  141. if(entries.empty()) {
  142. A2_LOG_NOTICE(EX_NO_RESULT_WITH_YOUR_PREFS);
  143. return;
  144. }
  145. std::vector<int32_t> selectIndexes =
  146. util::parseIntRange(option->get(PREF_SELECT_FILE)).flush();
  147. std::sort(selectIndexes.begin(), selectIndexes.end());
  148. std::vector<std::string> locations;
  149. if(option->defined(PREF_METALINK_LOCATION)) {
  150. util::split(util::toLower(option->get(PREF_METALINK_LOCATION)),
  151. std::back_inserter(locations), ",", true);
  152. }
  153. std::string preferredProtocol;
  154. if(option->get(PREF_METALINK_PREFERRED_PROTOCOL) != V_NONE) {
  155. preferredProtocol = option->get(PREF_METALINK_PREFERRED_PROTOCOL);
  156. }
  157. std::vector<SharedHandle<MetalinkEntry> > selectedEntries;
  158. selectedEntries.reserve(entries.size());
  159. {
  160. int32_t count = 1;
  161. for(std::vector<SharedHandle<MetalinkEntry> >::const_iterator i =
  162. entries.begin(), eoi = entries.end(); i != eoi; ++i, ++count) {
  163. (*i)->dropUnsupportedResource();
  164. if((*i)->resources.empty() && (*i)->metaurls.empty()) {
  165. continue;
  166. }
  167. (*i)->setLocationPriority
  168. (locations, -MetalinkResource::getLowestPriority());
  169. if(!preferredProtocol.empty()) {
  170. (*i)->setProtocolPriority
  171. (preferredProtocol, -MetalinkResource::getLowestPriority());
  172. }
  173. if(selectIndexes.empty() ||
  174. std::binary_search(selectIndexes.begin(), selectIndexes.end(), count)){
  175. selectedEntries.push_back(*i);
  176. }
  177. }
  178. }
  179. std::for_each(selectedEntries.begin(), selectedEntries.end(),
  180. mem_fun_sh(&MetalinkEntry::reorderMetaurlsByPriority));
  181. std::vector<std::pair<std::string,
  182. std::vector<SharedHandle<MetalinkEntry> > > > entryGroups;
  183. metalink::groupEntryByMetaurlName(entryGroups, selectedEntries);
  184. for(std::vector<std::pair<std::string,
  185. std::vector<SharedHandle<MetalinkEntry> > > >::const_iterator itr =
  186. entryGroups.begin(), eoi = entryGroups.end(); itr != eoi; ++itr) {
  187. const std::string& metaurl = (*itr).first;
  188. const std::vector<SharedHandle<MetalinkEntry> >& mes = (*itr).second;
  189. A2_LOG_INFO(fmt("Processing metaurl group metaurl=%s", metaurl.c_str()));
  190. #ifdef ENABLE_BITTORRENT
  191. SharedHandle<RequestGroup> torrentRg;
  192. if(!metaurl.empty()) {
  193. std::vector<std::string> uris;
  194. uris.push_back(metaurl);
  195. {
  196. std::vector<SharedHandle<RequestGroup> > result;
  197. createRequestGroupForUri(result, option, uris,
  198. /* ignoreForceSequential = */true,
  199. /* ignoreLocalPath = */true);
  200. if(!uris.empty()) {
  201. torrentRg = result[0];
  202. }
  203. }
  204. if(torrentRg) {
  205. torrentRg->setNumConcurrentCommand(1);
  206. torrentRg->clearPreDownloadHandler();
  207. torrentRg->clearPostDownloadHandler();
  208. // remove "metalink" from Accept Type list to avoid loop in
  209. // tranparent metalink
  210. util::removeMetalinkContentTypes(torrentRg);
  211. // make it in-memory download
  212. SharedHandle<PreDownloadHandler> preh
  213. (new MemoryBufferPreDownloadHandler());
  214. SharedHandle<RequestGroupCriteria> cri(new TrueRequestGroupCriteria());
  215. preh->setCriteria(cri);
  216. torrentRg->addPreDownloadHandler(preh);
  217. groups.push_back(torrentRg);
  218. }
  219. }
  220. #endif // ENABLE_BITTORRENT
  221. SharedHandle<RequestGroup> rg(new RequestGroup(option));
  222. SharedHandle<DownloadContext> dctx;
  223. if(mes.size() == 1) {
  224. SharedHandle<MetalinkEntry> entry = mes[0];
  225. A2_LOG_INFO(fmt(MSG_METALINK_QUEUEING, entry->getPath().c_str()));
  226. entry->reorderResourcesByPriority();
  227. std::vector<std::string> uris;
  228. std::for_each(entry->resources.begin(), entry->resources.end(),
  229. AccumulateNonP2PUri(uris));
  230. // If piece hash is specified in the metalink,
  231. // make segment size equal to piece hash size.
  232. size_t pieceLength;
  233. #ifdef ENABLE_MESSAGE_DIGEST
  234. if(!entry->chunkChecksum) {
  235. pieceLength = option->getAsInt(PREF_SEGMENT_SIZE);
  236. } else {
  237. pieceLength = entry->chunkChecksum->getChecksumLength();
  238. }
  239. #else
  240. pieceLength = option->getAsInt(PREF_SEGMENT_SIZE);
  241. #endif // ENABLE_MESSAGE_DIGEST
  242. dctx.reset(new DownloadContext
  243. (pieceLength,
  244. entry->getLength(),
  245. util::applyDir(option->get(PREF_DIR),
  246. entry->file->getPath())));
  247. dctx->getFirstFileEntry()->setUris(uris);
  248. dctx->getFirstFileEntry()->setMaxConnectionPerServer
  249. (option->getAsInt(PREF_MAX_CONNECTION_PER_SERVER));
  250. if(option->getAsBool(PREF_METALINK_ENABLE_UNIQUE_PROTOCOL)) {
  251. dctx->getFirstFileEntry()->setUniqueProtocol(true);
  252. }
  253. #ifdef ENABLE_MESSAGE_DIGEST
  254. if(entry->checksum) {
  255. dctx->setChecksum(entry->checksum->getMessageDigest());
  256. dctx->setChecksumHashAlgo(entry->checksum->getAlgo());
  257. }
  258. if(entry->chunkChecksum) {
  259. dctx->setPieceHashes(entry->chunkChecksum->getChecksums().begin(),
  260. entry->chunkChecksum->getChecksums().end());
  261. dctx->setPieceHashAlgo(entry->chunkChecksum->getAlgo());
  262. }
  263. #endif // ENABLE_MESSAGE_DIGEST
  264. dctx->setSignature(entry->getSignature());
  265. rg->setNumConcurrentCommand
  266. (entry->maxConnections < 0 ?
  267. option->getAsInt(PREF_METALINK_SERVERS) :
  268. std::min(option->getAsInt(PREF_METALINK_SERVERS),
  269. static_cast<int32_t>(entry->maxConnections)));
  270. } else {
  271. dctx.reset(new DownloadContext());
  272. // piece length is overridden by the one in torrent file.
  273. dctx->setPieceLength(option->getAsInt(PREF_SEGMENT_SIZE));
  274. std::vector<SharedHandle<FileEntry> > fileEntries;
  275. off_t offset = 0;
  276. for(std::vector<SharedHandle<MetalinkEntry> >::const_iterator i =
  277. mes.begin(), eoi = mes.end(); i != eoi; ++i) {
  278. A2_LOG_INFO(fmt("Metalink: Queueing %s for download as a member.",
  279. (*i)->getPath().c_str()));
  280. A2_LOG_DEBUG(fmt("originalName = %s", (*i)->metaurls[0]->name.c_str()));
  281. (*i)->reorderResourcesByPriority();
  282. std::vector<std::string> uris;
  283. std::for_each((*i)->resources.begin(), (*i)->resources.end(),
  284. AccumulateNonP2PUri(uris));
  285. SharedHandle<FileEntry> fe
  286. (new FileEntry
  287. (util::applyDir(option->get(PREF_DIR), (*i)->file->getPath()),
  288. (*i)->file->getLength(), offset, uris));
  289. fe->setMaxConnectionPerServer
  290. (option->getAsInt(PREF_MAX_CONNECTION_PER_SERVER));
  291. if(option->getAsBool(PREF_METALINK_ENABLE_UNIQUE_PROTOCOL)) {
  292. fe->setUniqueProtocol(true);
  293. }
  294. fe->setOriginalName((*i)->metaurls[0]->name);
  295. fileEntries.push_back(fe);
  296. offset += (*i)->file->getLength();
  297. }
  298. dctx->setFileEntries(fileEntries.begin(), fileEntries.end());
  299. rg->setNumConcurrentCommand(option->getAsInt(PREF_METALINK_SERVERS));
  300. }
  301. rg->setDownloadContext(dctx);
  302. rg->setPauseRequested(option->getAsBool(PREF_PAUSE));
  303. removeOneshotOption(rg->getOption());
  304. // remove "metalink" from Accept Type list to avoid loop in
  305. // tranparent metalink
  306. util::removeMetalinkContentTypes(rg);
  307. #ifdef ENABLE_BITTORRENT
  308. // Inject depenency between rg and torrentRg here if
  309. // torrentRg is true
  310. if(torrentRg) {
  311. SharedHandle<Dependency> dep(new BtDependency(rg.get(), torrentRg));
  312. rg->dependsOn(dep);
  313. torrentRg->belongsTo(rg->getGID());
  314. // metadata download may take very long time. If URIs are
  315. // available, give up metadata download in at most 30 seconds.
  316. const time_t btStopTimeout = 30;
  317. time_t currentBtStopTimeout =
  318. torrentRg->getOption()->getAsInt(PREF_BT_STOP_TIMEOUT);
  319. if(currentBtStopTimeout == 0 || currentBtStopTimeout > btStopTimeout) {
  320. std::vector<SharedHandle<FileEntry> >::const_iterator i;
  321. std::vector<SharedHandle<FileEntry> >::const_iterator eoi
  322. = dctx->getFileEntries().end();
  323. for(i = dctx->getFileEntries().begin(); i != eoi; ++i) {
  324. if((*i)->getRemainingUris().empty()) {
  325. break;
  326. }
  327. }
  328. if(i == dctx->getFileEntries().end()) {
  329. torrentRg->getOption()->put
  330. (PREF_BT_STOP_TIMEOUT, util::itos(btStopTimeout));
  331. }
  332. }
  333. }
  334. #endif // ENABLE_BITTORRENT
  335. groups.push_back(rg);
  336. }
  337. }
  338. } // namespace aria2