RequestGroup.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. #ifndef _D_REQUEST_GROUP_H_
  36. #define _D_REQUEST_GROUP_H_
  37. #include "common.h"
  38. #include <string>
  39. #include <algorithm>
  40. #include <vector>
  41. #include "SharedHandle.h"
  42. #include "TransferStat.h"
  43. #include "TimeA2.h"
  44. #include "Request.h"
  45. #include "DownloadResultCode.h"
  46. #include "MetadataInfo.h"
  47. namespace aria2 {
  48. class DownloadEngine;
  49. class SegmentMan;
  50. class Command;
  51. class DownloadCommand;
  52. class DownloadContext;
  53. class PieceStorage;
  54. class BtProgressInfoFile;
  55. class Dependency;
  56. class PreDownloadHandler;
  57. class PostDownloadHandler;
  58. class DiskWriterFactory;
  59. class Option;
  60. class Logger;
  61. class RequestGroup;
  62. class CheckIntegrityEntry;
  63. struct DownloadResult;
  64. class URISelector;
  65. class URIResult;
  66. class RequestGroupMan;
  67. #ifdef ENABLE_BITTORRENT
  68. class BtRuntime;
  69. class PeerStorage;
  70. #endif // ENABLE_BITTORRENT
  71. typedef int64_t gid_t;
  72. class RequestGroup {
  73. public:
  74. enum HaltReason {
  75. NONE,
  76. SHUTDOWN_SIGNAL,
  77. USER_REQUEST
  78. };
  79. private:
  80. static gid_t gidCounter_;
  81. gid_t gid_;
  82. SharedHandle<Option> option_;
  83. size_t numConcurrentCommand_;
  84. /**
  85. * This is the number of connections used in streaming protocol(http/ftp)
  86. */
  87. unsigned int numStreamConnection_;
  88. unsigned int numStreamCommand_;
  89. unsigned int numCommand_;
  90. SharedHandle<SegmentMan> segmentMan_;
  91. SharedHandle<DownloadContext> downloadContext_;
  92. SharedHandle<PieceStorage> pieceStorage_;
  93. bool saveControlFile_;
  94. SharedHandle<BtProgressInfoFile> progressInfoFile_;
  95. SharedHandle<DiskWriterFactory> diskWriterFactory_;
  96. SharedHandle<Dependency> dependency_;
  97. bool fileAllocationEnabled_;
  98. bool preLocalFileCheckEnabled_;
  99. bool haltRequested_;
  100. bool forceHaltRequested_;
  101. HaltReason haltReason_;
  102. bool pauseRequested_;
  103. std::vector<SharedHandle<PreDownloadHandler> > preDownloadHandlers_;
  104. std::vector<SharedHandle<PostDownloadHandler> > postDownloadHandlers_;
  105. std::vector<std::string> acceptTypes_;
  106. SharedHandle<URISelector> uriSelector_;
  107. Time lastModifiedTime_;
  108. unsigned int fileNotFoundCount_;
  109. // Timeout used for HTTP/FTP downloads.
  110. time_t timeout_;
  111. #ifdef ENABLE_BITTORRENT
  112. WeakHandle<BtRuntime> btRuntime_;
  113. WeakHandle<PeerStorage> peerStorage_;
  114. #endif // ENABLE_BITTORRENT
  115. // This flag just indicates that the downloaded file is not saved disk but
  116. // just sits in memory.
  117. bool inMemoryDownload_;
  118. unsigned int maxDownloadSpeedLimit_;
  119. unsigned int maxUploadSpeedLimit_;
  120. SharedHandle<URIResult> lastUriResult_;
  121. // If this download generates another downloads when completed(for
  122. // example, downloads generated by PostDownloadHandler), this field
  123. // has the GID of generated RequestGroups. empty list means there is
  124. // no such RequestGroup.
  125. std::vector<gid_t> followedByGIDs_;
  126. // If this download is a part of another download(for example,
  127. // downloading torrent file described in Metalink file), this field
  128. // has the GID of parent RequestGroup. 0 means this is a parent
  129. // RequestGroup.
  130. gid_t belongsToGID_;
  131. SharedHandle<MetadataInfo> metadataInfo_;
  132. RequestGroupMan* requestGroupMan_;
  133. int resumeFailureCount_;
  134. Logger* logger_;
  135. void validateFilename(const std::string& expectedFilename,
  136. const std::string& actualFilename) const;
  137. void initializePreDownloadHandler();
  138. void initializePostDownloadHandler();
  139. bool tryAutoFileRenaming();
  140. // Returns the result code of this RequestGroup. If the download
  141. // finished, then returns downloadresultcode::FINISHED. If the
  142. // download didn't finish and error result is available in
  143. // _uriResults, then last result code is returned. Otherwise
  144. // returns downloadresultcode::UNKNOWN_ERROR.
  145. downloadresultcode::RESULT downloadResult() const;
  146. void removeDefunctControlFile
  147. (const SharedHandle<BtProgressInfoFile>& progressInfoFile);
  148. bool isCheckIntegrityReady() const;
  149. public:
  150. // The copy of option is stored in RequestGroup object.
  151. RequestGroup(const SharedHandle<Option>& option);
  152. ~RequestGroup();
  153. const SharedHandle<SegmentMan>& getSegmentMan() const
  154. {
  155. return segmentMan_;
  156. }
  157. SharedHandle<CheckIntegrityEntry> createCheckIntegrityEntry();
  158. // Returns first bootstrap commands to initiate a download.
  159. // If this is HTTP/FTP download and file size is unknown, only 1 command
  160. // (usually, HttpInitiateConnection or FtpInitiateConnection) will be created.
  161. void createInitialCommand(std::vector<Command*>& commands,
  162. DownloadEngine* e);
  163. void createNextCommandWithAdj(std::vector<Command*>& commands,
  164. DownloadEngine* e, int numAdj);
  165. void createNextCommand(std::vector<Command*>& commands,
  166. DownloadEngine* e, unsigned int numCommand);
  167. void createNextCommand(std::vector<Command*>& commands, DownloadEngine* e);
  168. bool downloadFinished() const;
  169. bool allDownloadFinished() const;
  170. void closeFile();
  171. std::string getFirstFilePath() const;
  172. uint64_t getTotalLength() const;
  173. uint64_t getCompletedLength() const;
  174. /**
  175. * Compares expected filename with specified actualFilename.
  176. * The expected filename refers to FileEntry::getBasename() of the first
  177. * element of DownloadContext::getFileEntries()
  178. */
  179. void validateFilename(const std::string& actualFilename) const;
  180. void validateTotalLength(uint64_t expectedTotalLength,
  181. uint64_t actualTotalLength) const;
  182. void validateTotalLength(uint64_t actualTotalLength) const;
  183. void setNumConcurrentCommand(unsigned int num)
  184. {
  185. numConcurrentCommand_ = num;
  186. }
  187. unsigned int getNumConcurrentCommand() const
  188. {
  189. return numConcurrentCommand_;
  190. }
  191. gid_t getGID() const
  192. {
  193. return gid_;
  194. }
  195. TransferStat calculateStat() const;
  196. const SharedHandle<DownloadContext>& getDownloadContext() const
  197. {
  198. return downloadContext_;
  199. }
  200. // This function also calls
  201. // downloadContext->setOwnerRequestGroup(this).
  202. void setDownloadContext(const SharedHandle<DownloadContext>& downloadContext);
  203. const SharedHandle<PieceStorage>& getPieceStorage() const
  204. {
  205. return pieceStorage_;
  206. }
  207. void setPieceStorage(const SharedHandle<PieceStorage>& pieceStorage);
  208. void setProgressInfoFile(const SharedHandle<BtProgressInfoFile>& progressInfoFile);
  209. void increaseStreamCommand();
  210. void decreaseStreamCommand();
  211. void increaseStreamConnection();
  212. void decreaseStreamConnection();
  213. unsigned int getNumConnection() const;
  214. void increaseNumCommand();
  215. void decreaseNumCommand();
  216. unsigned int getNumCommand() const
  217. {
  218. return numCommand_;
  219. }
  220. // TODO is it better to move the following 2 methods to SingleFileDownloadContext?
  221. void setDiskWriterFactory(const SharedHandle<DiskWriterFactory>& diskWriterFactory);
  222. const SharedHandle<DiskWriterFactory>& getDiskWriterFactory() const
  223. {
  224. return diskWriterFactory_;
  225. }
  226. void setFileAllocationEnabled(bool f)
  227. {
  228. fileAllocationEnabled_ = f;
  229. }
  230. bool isFileAllocationEnabled() const
  231. {
  232. return fileAllocationEnabled_;
  233. }
  234. bool needsFileAllocation() const;
  235. /**
  236. * Setting preLocalFileCheckEnabled_ to false, then skip the check to see
  237. * if a file is already exists and control file exists etc.
  238. * Always open file with DiskAdaptor::initAndOpenFile()
  239. */
  240. void setPreLocalFileCheckEnabled(bool f)
  241. {
  242. preLocalFileCheckEnabled_ = f;
  243. }
  244. bool isPreLocalFileCheckEnabled() const
  245. {
  246. return preLocalFileCheckEnabled_;
  247. }
  248. void setHaltRequested(bool f, HaltReason = SHUTDOWN_SIGNAL);
  249. void setForceHaltRequested(bool f, HaltReason = SHUTDOWN_SIGNAL);
  250. bool isHaltRequested() const
  251. {
  252. return haltRequested_;
  253. }
  254. bool isForceHaltRequested() const
  255. {
  256. return forceHaltRequested_;
  257. }
  258. void setPauseRequested(bool f);
  259. bool isPauseRequested() const
  260. {
  261. return pauseRequested_;
  262. }
  263. void dependsOn(const SharedHandle<Dependency>& dep);
  264. bool isDependencyResolved();
  265. void releaseRuntimeResource(DownloadEngine* e);
  266. void postDownloadProcessing(std::vector<SharedHandle<RequestGroup> >& groups);
  267. void addPostDownloadHandler(const SharedHandle<PostDownloadHandler>& handler);
  268. void clearPostDownloadHandler();
  269. void preDownloadProcessing();
  270. void addPreDownloadHandler(const SharedHandle<PreDownloadHandler>& handler);
  271. void clearPreDownloadHandler();
  272. void processCheckIntegrityEntry(std::vector<Command*>& commands,
  273. const SharedHandle<CheckIntegrityEntry>& entry,
  274. DownloadEngine* e);
  275. // Initializes pieceStorage_ and segmentMan_. We guarantee that
  276. // either both of pieceStorage_ and segmentMan_ are initialized or
  277. // they are not.
  278. void initPieceStorage();
  279. void dropPieceStorage();
  280. bool downloadFinishedByFileLength();
  281. void loadAndOpenFile(const SharedHandle<BtProgressInfoFile>& progressInfoFile);
  282. void shouldCancelDownloadForSafety();
  283. void adjustFilename(const SharedHandle<BtProgressInfoFile>& infoFile);
  284. SharedHandle<DownloadResult> createDownloadResult() const;
  285. const SharedHandle<Option>& getOption() const
  286. {
  287. return option_;
  288. }
  289. void reportDownloadFinished();
  290. const std::vector<std::string>& getAcceptTypes() const
  291. {
  292. return acceptTypes_;
  293. }
  294. void addAcceptType(const std::string& type);
  295. template<typename InputIterator>
  296. void addAcceptType(InputIterator first, InputIterator last)
  297. {
  298. for(; first != last; ++first) {
  299. if(std::find(acceptTypes_.begin(), acceptTypes_.end(), *first) ==
  300. acceptTypes_.end()) {
  301. acceptTypes_.push_back(*first);
  302. }
  303. }
  304. }
  305. void removeAcceptType(const std::string& type);
  306. void setURISelector(const SharedHandle<URISelector>& uriSelector);
  307. const SharedHandle<URISelector>& getURISelector() const
  308. {
  309. return uriSelector_;
  310. }
  311. void applyLastModifiedTimeToLocalFiles();
  312. void updateLastModifiedTime(const Time& time);
  313. void increaseAndValidateFileNotFoundCount();
  314. // Just set inMemoryDownload flag true.
  315. void markInMemoryDownload();
  316. // Returns inMemoryDownload flag.
  317. bool inMemoryDownload() const
  318. {
  319. return inMemoryDownload_;
  320. }
  321. void setTimeout(time_t timeout);
  322. time_t getTimeout() const
  323. {
  324. return timeout_;
  325. }
  326. // Returns true if current download speed exceeds
  327. // maxDownloadSpeedLimit_. Always returns false if
  328. // maxDownloadSpeedLimit_ == 0. Otherwise returns false.
  329. bool doesDownloadSpeedExceed();
  330. // Returns true if current upload speed exceeds
  331. // maxUploadSpeedLimit_. Always returns false if
  332. // maxUploadSpeedLimit_ == 0. Otherwise returns false.
  333. bool doesUploadSpeedExceed();
  334. unsigned int getMaxDownloadSpeedLimit() const
  335. {
  336. return maxDownloadSpeedLimit_;
  337. }
  338. void setMaxDownloadSpeedLimit(unsigned int speed)
  339. {
  340. maxDownloadSpeedLimit_ = speed;
  341. }
  342. unsigned int getMaxUploadSpeedLimit() const
  343. {
  344. return maxUploadSpeedLimit_;
  345. }
  346. void setMaxUploadSpeedLimit(unsigned int speed)
  347. {
  348. maxUploadSpeedLimit_ = speed;
  349. }
  350. void setLastUriResult(std::string uri, downloadresultcode::RESULT result);
  351. void saveControlFile() const;
  352. void removeControlFile() const;
  353. void enableSaveControlFile() { saveControlFile_ = true; }
  354. void disableSaveControlFile() { saveControlFile_ = false; }
  355. template<typename InputIterator>
  356. void followedBy(InputIterator groupFirst, InputIterator groupLast)
  357. {
  358. followedByGIDs_.clear();
  359. for(; groupFirst != groupLast; ++groupFirst) {
  360. followedByGIDs_.push_back((*groupFirst)->getGID());
  361. }
  362. }
  363. const std::vector<gid_t>& followedBy() const
  364. {
  365. return followedByGIDs_;
  366. }
  367. void belongsTo(gid_t gid)
  368. {
  369. belongsToGID_ = gid;
  370. }
  371. gid_t belongsTo() const
  372. {
  373. return belongsToGID_;
  374. }
  375. void setRequestGroupMan(RequestGroupMan* requestGroupMan)
  376. {
  377. requestGroupMan_ = requestGroupMan;
  378. }
  379. int getResumeFailureCount() const
  380. {
  381. return resumeFailureCount_;
  382. }
  383. void increaseResumeFailureCount()
  384. {
  385. ++resumeFailureCount_;
  386. }
  387. bool p2pInvolved() const;
  388. void setMetadataInfo(const SharedHandle<MetadataInfo>& info)
  389. {
  390. metadataInfo_ = info;
  391. }
  392. const SharedHandle<MetadataInfo>& getMetadataInfo() const
  393. {
  394. return metadataInfo_;
  395. }
  396. static void resetGIDCounter() { gidCounter_ = 0; }
  397. static gid_t newGID();
  398. };
  399. } // namespace aria2
  400. #endif // _D_REQUEST_GROUP_H_