Metalink2RequestGroup.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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(option->get(PREF_METALINK_LOCATION),
  151. std::back_inserter(locations), ",", true);
  152. std::transform
  153. (locations.begin(), locations.end(), locations.begin(), util::toLower);
  154. }
  155. std::string preferredProtocol;
  156. if(option->get(PREF_METALINK_PREFERRED_PROTOCOL) != V_NONE) {
  157. preferredProtocol = option->get(PREF_METALINK_PREFERRED_PROTOCOL);
  158. }
  159. std::vector<SharedHandle<MetalinkEntry> > selectedEntries;
  160. selectedEntries.reserve(entries.size());
  161. {
  162. int32_t count = 1;
  163. for(std::vector<SharedHandle<MetalinkEntry> >::const_iterator i =
  164. entries.begin(), eoi = entries.end(); i != eoi; ++i, ++count) {
  165. (*i)->dropUnsupportedResource();
  166. if((*i)->resources.empty() && (*i)->metaurls.empty()) {
  167. continue;
  168. }
  169. (*i)->setLocationPriority
  170. (locations, -MetalinkResource::getLowestPriority());
  171. if(!preferredProtocol.empty()) {
  172. (*i)->setProtocolPriority
  173. (preferredProtocol, -MetalinkResource::getLowestPriority());
  174. }
  175. if(selectIndexes.empty() ||
  176. std::binary_search(selectIndexes.begin(), selectIndexes.end(), count)){
  177. selectedEntries.push_back(*i);
  178. }
  179. }
  180. }
  181. std::for_each(selectedEntries.begin(), selectedEntries.end(),
  182. mem_fun_sh(&MetalinkEntry::reorderMetaurlsByPriority));
  183. std::vector<std::pair<std::string,
  184. std::vector<SharedHandle<MetalinkEntry> > > > entryGroups;
  185. metalink::groupEntryByMetaurlName(entryGroups, selectedEntries);
  186. for(std::vector<std::pair<std::string,
  187. std::vector<SharedHandle<MetalinkEntry> > > >::const_iterator itr =
  188. entryGroups.begin(), eoi = entryGroups.end(); itr != eoi; ++itr) {
  189. const std::string& metaurl = (*itr).first;
  190. const std::vector<SharedHandle<MetalinkEntry> >& mes = (*itr).second;
  191. A2_LOG_INFO(fmt("Processing metaurl group metaurl=%s", metaurl.c_str()));
  192. #ifdef ENABLE_BITTORRENT
  193. SharedHandle<RequestGroup> torrentRg;
  194. if(!metaurl.empty()) {
  195. std::vector<std::string> uris;
  196. uris.push_back(metaurl);
  197. {
  198. std::vector<SharedHandle<RequestGroup> > result;
  199. createRequestGroupForUri(result, option, uris,
  200. /* ignoreForceSequential = */true,
  201. /* ignoreLocalPath = */true);
  202. if(!uris.empty()) {
  203. torrentRg = result[0];
  204. }
  205. }
  206. if(torrentRg) {
  207. torrentRg->setNumConcurrentCommand(1);
  208. torrentRg->clearPreDownloadHandler();
  209. torrentRg->clearPostDownloadHandler();
  210. // remove "metalink" from Accept Type list to avoid loop in
  211. // tranparent metalink
  212. util::removeMetalinkContentTypes(torrentRg);
  213. // make it in-memory download
  214. SharedHandle<PreDownloadHandler> preh
  215. (new MemoryBufferPreDownloadHandler());
  216. SharedHandle<RequestGroupCriteria> cri(new TrueRequestGroupCriteria());
  217. preh->setCriteria(cri);
  218. torrentRg->addPreDownloadHandler(preh);
  219. groups.push_back(torrentRg);
  220. }
  221. }
  222. #endif // ENABLE_BITTORRENT
  223. SharedHandle<RequestGroup> rg(new RequestGroup(option));
  224. SharedHandle<DownloadContext> dctx;
  225. if(mes.size() == 1) {
  226. SharedHandle<MetalinkEntry> entry = mes[0];
  227. A2_LOG_INFO(fmt(MSG_METALINK_QUEUEING, entry->getPath().c_str()));
  228. entry->reorderResourcesByPriority();
  229. std::vector<std::string> uris;
  230. std::for_each(entry->resources.begin(), entry->resources.end(),
  231. AccumulateNonP2PUri(uris));
  232. // If piece hash is specified in the metalink,
  233. // make segment size equal to piece hash size.
  234. size_t pieceLength;
  235. #ifdef ENABLE_MESSAGE_DIGEST
  236. if(!entry->chunkChecksum) {
  237. pieceLength = option->getAsInt(PREF_SEGMENT_SIZE);
  238. } else {
  239. pieceLength = entry->chunkChecksum->getChecksumLength();
  240. }
  241. #else
  242. pieceLength = option->getAsInt(PREF_SEGMENT_SIZE);
  243. #endif // ENABLE_MESSAGE_DIGEST
  244. dctx.reset(new DownloadContext
  245. (pieceLength,
  246. entry->getLength(),
  247. util::applyDir(option->get(PREF_DIR),
  248. entry->file->getPath())));
  249. dctx->getFirstFileEntry()->setUris(uris);
  250. dctx->getFirstFileEntry()->setMaxConnectionPerServer
  251. (option->getAsInt(PREF_MAX_CONNECTION_PER_SERVER));
  252. if(option->getAsBool(PREF_METALINK_ENABLE_UNIQUE_PROTOCOL)) {
  253. dctx->getFirstFileEntry()->setUniqueProtocol(true);
  254. }
  255. #ifdef ENABLE_MESSAGE_DIGEST
  256. if(entry->checksum) {
  257. dctx->setChecksum(entry->checksum->getMessageDigest());
  258. dctx->setChecksumHashAlgo(entry->checksum->getAlgo());
  259. }
  260. if(entry->chunkChecksum) {
  261. dctx->setPieceHashes(entry->chunkChecksum->getChecksums().begin(),
  262. entry->chunkChecksum->getChecksums().end());
  263. dctx->setPieceHashAlgo(entry->chunkChecksum->getAlgo());
  264. }
  265. #endif // ENABLE_MESSAGE_DIGEST
  266. dctx->setSignature(entry->getSignature());
  267. rg->setNumConcurrentCommand
  268. (entry->maxConnections < 0 ?
  269. option->getAsInt(PREF_METALINK_SERVERS) :
  270. std::min(option->getAsInt(PREF_METALINK_SERVERS),
  271. static_cast<int32_t>(entry->maxConnections)));
  272. } else {
  273. dctx.reset(new DownloadContext());
  274. // piece length is overridden by the one in torrent file.
  275. dctx->setPieceLength(option->getAsInt(PREF_SEGMENT_SIZE));
  276. std::vector<SharedHandle<FileEntry> > fileEntries;
  277. off_t offset = 0;
  278. for(std::vector<SharedHandle<MetalinkEntry> >::const_iterator i =
  279. mes.begin(), eoi = mes.end(); i != eoi; ++i) {
  280. A2_LOG_INFO(fmt("Metalink: Queueing %s for download as a member.",
  281. (*i)->getPath().c_str()));
  282. A2_LOG_DEBUG(fmt("originalName = %s", (*i)->metaurls[0]->name.c_str()));
  283. (*i)->reorderResourcesByPriority();
  284. std::vector<std::string> uris;
  285. std::for_each((*i)->resources.begin(), (*i)->resources.end(),
  286. AccumulateNonP2PUri(uris));
  287. SharedHandle<FileEntry> fe
  288. (new FileEntry
  289. (util::applyDir(option->get(PREF_DIR), (*i)->file->getPath()),
  290. (*i)->file->getLength(), offset, uris));
  291. fe->setMaxConnectionPerServer
  292. (option->getAsInt(PREF_MAX_CONNECTION_PER_SERVER));
  293. if(option->getAsBool(PREF_METALINK_ENABLE_UNIQUE_PROTOCOL)) {
  294. fe->setUniqueProtocol(true);
  295. }
  296. fe->setOriginalName((*i)->metaurls[0]->name);
  297. fileEntries.push_back(fe);
  298. offset += (*i)->file->getLength();
  299. }
  300. dctx->setFileEntries(fileEntries.begin(), fileEntries.end());
  301. rg->setNumConcurrentCommand(option->getAsInt(PREF_METALINK_SERVERS));
  302. }
  303. rg->setDownloadContext(dctx);
  304. rg->setPauseRequested(option->getAsBool(PREF_PAUSE));
  305. removeOneshotOption(rg->getOption());
  306. // remove "metalink" from Accept Type list to avoid loop in
  307. // tranparent metalink
  308. util::removeMetalinkContentTypes(rg);
  309. #ifdef ENABLE_BITTORRENT
  310. // Inject depenency between rg and torrentRg here if
  311. // torrentRg is true
  312. if(torrentRg) {
  313. SharedHandle<Dependency> dep(new BtDependency(rg.get(), torrentRg));
  314. rg->dependsOn(dep);
  315. torrentRg->belongsTo(rg->getGID());
  316. // metadata download may take very long time. If URIs are
  317. // available, give up metadata download in at most 30 seconds.
  318. const time_t btStopTimeout = 30;
  319. time_t currentBtStopTimeout =
  320. torrentRg->getOption()->getAsInt(PREF_BT_STOP_TIMEOUT);
  321. if(currentBtStopTimeout == 0 || currentBtStopTimeout > btStopTimeout) {
  322. std::vector<SharedHandle<FileEntry> >::const_iterator i;
  323. std::vector<SharedHandle<FileEntry> >::const_iterator eoi
  324. = dctx->getFileEntries().end();
  325. for(i = dctx->getFileEntries().begin(); i != eoi; ++i) {
  326. if((*i)->getRemainingUris().empty()) {
  327. break;
  328. }
  329. }
  330. if(i == dctx->getFileEntries().end()) {
  331. torrentRg->getOption()->put
  332. (PREF_BT_STOP_TIMEOUT, util::itos(btStopTimeout));
  333. }
  334. }
  335. }
  336. #endif // ENABLE_BITTORRENT
  337. groups.push_back(rg);
  338. }
  339. }
  340. } // namespace aria2