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