RequestGroup.h 13 KB

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