AbstractDiskWriter.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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 "AbstractDiskWriter.h"
  36. #include <unistd.h>
  37. #ifdef HAVE_MMAP
  38. # include <sys/mman.h>
  39. #endif // HAVE_MMAP
  40. #include <cerrno>
  41. #include <cstring>
  42. #include <cassert>
  43. #include "File.h"
  44. #include "util.h"
  45. #include "message.h"
  46. #include "DlAbortEx.h"
  47. #include "a2io.h"
  48. #include "fmt.h"
  49. #include "DownloadFailureException.h"
  50. #include "error_code.h"
  51. #include "LogFactory.h"
  52. namespace aria2 {
  53. AbstractDiskWriter::AbstractDiskWriter(const std::string& filename)
  54. : filename_(filename),
  55. fd_(-1),
  56. readOnly_(false),
  57. enableMmap_(false),
  58. mapaddr_(0),
  59. maplen_(0)
  60. {}
  61. AbstractDiskWriter::~AbstractDiskWriter()
  62. {
  63. closeFile();
  64. }
  65. void AbstractDiskWriter::openFile(int64_t totalLength)
  66. {
  67. try {
  68. openExistingFile(totalLength);
  69. } catch(RecoverableException& e) {
  70. if(e.getErrNum() == ENOENT) {
  71. initAndOpenFile(totalLength);
  72. } else {
  73. throw;
  74. }
  75. }
  76. }
  77. void AbstractDiskWriter::closeFile()
  78. {
  79. #ifdef HAVE_MMAP
  80. if(mapaddr_) {
  81. int rv = munmap(mapaddr_, maplen_);
  82. if(rv == -1) {
  83. int errNum = errno;
  84. A2_LOG_ERROR(fmt("munmap for file %s failed: %s",
  85. filename_.c_str(), strerror(errNum)));
  86. } else {
  87. A2_LOG_INFO(fmt("munmap for file %s succeeded", filename_.c_str()));
  88. }
  89. mapaddr_ = 0;
  90. maplen_ = 0;
  91. }
  92. #endif // HAVE_MMAP
  93. if(fd_ != -1) {
  94. close(fd_);
  95. fd_ = -1;
  96. }
  97. }
  98. namespace {
  99. int openFileWithFlags(const std::string& filename, int flags,
  100. error_code::Value errCode)
  101. {
  102. int fd;
  103. while((fd = a2open(utf8ToWChar(filename).c_str(), flags, OPEN_MODE)) == -1
  104. && errno == EINTR);
  105. if(fd < 0) {
  106. int errNum = errno;
  107. throw DL_ABORT_EX3(errNum, fmt(EX_FILE_OPEN,
  108. filename.c_str(),
  109. util::safeStrerror(errNum).c_str()),
  110. errCode);
  111. }
  112. #if defined(__APPLE__) && defined(__MACH__)
  113. fcntl(fd, F_GLOBAL_NOCACHE, 1);
  114. #endif // __APPLE__ && __MACH__
  115. return fd;
  116. }
  117. } // namespace
  118. void AbstractDiskWriter::openExistingFile(int64_t totalLength)
  119. {
  120. int flags = O_BINARY;
  121. if(readOnly_) {
  122. flags |= O_RDONLY;
  123. } else {
  124. flags |= O_RDWR;
  125. }
  126. fd_ = openFileWithFlags(filename_, flags, error_code::FILE_OPEN_ERROR);
  127. }
  128. void AbstractDiskWriter::createFile(int addFlags)
  129. {
  130. assert(!filename_.empty());
  131. util::mkdirs(File(filename_).getDirname());
  132. fd_ = openFileWithFlags(filename_, O_CREAT|O_RDWR|O_TRUNC|O_BINARY|addFlags,
  133. error_code::FILE_CREATE_ERROR);
  134. }
  135. ssize_t AbstractDiskWriter::writeDataInternal(const unsigned char* data,
  136. size_t len, int64_t offset)
  137. {
  138. if(mapaddr_) {
  139. memcpy(mapaddr_ + offset, data, len);
  140. return len;
  141. } else {
  142. ssize_t writtenLength = 0;
  143. seek(offset);
  144. while((size_t)writtenLength < len) {
  145. ssize_t ret = 0;
  146. while((ret = write(fd_, data+writtenLength, len-writtenLength)) == -1 &&
  147. errno == EINTR);
  148. if(ret == -1) {
  149. return -1;
  150. }
  151. writtenLength += ret;
  152. }
  153. return writtenLength;
  154. }
  155. }
  156. ssize_t AbstractDiskWriter::readDataInternal(unsigned char* data, size_t len,
  157. int64_t offset)
  158. {
  159. if(mapaddr_) {
  160. ssize_t readlen;
  161. if(offset > maplen_) {
  162. readlen = 0;
  163. } else {
  164. readlen = std::min(static_cast<size_t>(maplen_ - offset), len);
  165. }
  166. memcpy(data, mapaddr_ + offset, readlen);
  167. return readlen;
  168. } else {
  169. ssize_t ret = 0;
  170. seek(offset);
  171. while((ret = read(fd_, data, len)) == -1 && errno == EINTR);
  172. return ret;
  173. }
  174. }
  175. void AbstractDiskWriter::seek(int64_t offset)
  176. {
  177. if(a2lseek(fd_, offset, SEEK_SET) == (off_t)-1) {
  178. int errNum = errno;
  179. throw DL_ABORT_EX2(fmt(EX_FILE_SEEK,
  180. filename_.c_str(),
  181. util::safeStrerror(errNum).c_str()),
  182. error_code::FILE_IO_ERROR);
  183. }
  184. }
  185. void AbstractDiskWriter::ensureMmapWrite(size_t len, int64_t offset)
  186. {
  187. #ifdef HAVE_MMAP
  188. if(enableMmap_) {
  189. if(mapaddr_) {
  190. if(static_cast<int64_t>(len + offset) > maplen_) {
  191. munmap(mapaddr_, maplen_);
  192. mapaddr_ = 0;
  193. maplen_ = 0;
  194. enableMmap_ = false;
  195. }
  196. } else {
  197. int64_t filesize = size();
  198. if(static_cast<int64_t>(len + offset) <= filesize) {
  199. mapaddr_ = reinterpret_cast<unsigned char*>
  200. (mmap(0, size(), PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0));
  201. if(mapaddr_) {
  202. A2_LOG_DEBUG(fmt("mmap for file %s succeeded, length=%" PRId64 "",
  203. filename_.c_str(),
  204. static_cast<uint64_t>(filesize)));
  205. maplen_ = filesize;
  206. } else {
  207. int errNum = errno;
  208. A2_LOG_INFO(fmt("mmap for file %s failed: %s",
  209. filename_.c_str(), strerror(errNum)));
  210. enableMmap_ = false;
  211. }
  212. }
  213. }
  214. }
  215. #endif // HAVE_MMAP
  216. }
  217. void AbstractDiskWriter::writeData(const unsigned char* data, size_t len, int64_t offset)
  218. {
  219. ensureMmapWrite(len, offset);
  220. if(writeDataInternal(data, len, offset) < 0) {
  221. int errNum = errno;
  222. // If errno is ENOSPC(not enough space in device), throw
  223. // DownloadFailureException and abort download instantly.
  224. if(errNum == ENOSPC) {
  225. throw DOWNLOAD_FAILURE_EXCEPTION3
  226. (errNum,
  227. fmt(EX_FILE_WRITE,
  228. filename_.c_str(),
  229. util::safeStrerror(errNum).c_str()),
  230. error_code::NOT_ENOUGH_DISK_SPACE);
  231. } else {
  232. throw DL_ABORT_EX3
  233. (errNum,
  234. fmt(EX_FILE_WRITE,
  235. filename_.c_str(),
  236. util::safeStrerror(errNum).c_str()),
  237. error_code::FILE_IO_ERROR);
  238. }
  239. }
  240. }
  241. ssize_t AbstractDiskWriter::readData(unsigned char* data, size_t len, int64_t offset)
  242. {
  243. ssize_t ret;
  244. if((ret = readDataInternal(data, len, offset)) < 0) {
  245. int errNum = errno;
  246. throw DL_ABORT_EX3
  247. (errNum,
  248. fmt(EX_FILE_READ,
  249. filename_.c_str(),
  250. util::safeStrerror(errNum).c_str()),
  251. error_code::FILE_IO_ERROR);
  252. }
  253. return ret;
  254. }
  255. void AbstractDiskWriter::truncate(int64_t length)
  256. {
  257. if(fd_ == -1) {
  258. throw DL_ABORT_EX("File not opened.");
  259. }
  260. #ifdef __MINGW32__
  261. // Since mingw32's ftruncate cannot handle over 2GB files, we use SetEndOfFile
  262. // instead.
  263. HANDLE handle = LongToHandle(_get_osfhandle(fd_));
  264. seek(length);
  265. if(SetEndOfFile(handle) == 0) {
  266. throw DL_ABORT_EX2(fmt("SetEndOfFile failed. cause: %lx",
  267. GetLastError()),
  268. error_code::FILE_IO_ERROR);
  269. }
  270. #else
  271. if(ftruncate(fd_, length) == -1) {
  272. int errNum = errno;
  273. throw DL_ABORT_EX3(errNum,
  274. fmt("ftruncate failed. cause: %s",
  275. util::safeStrerror(errNum).c_str()),
  276. error_code::FILE_IO_ERROR);
  277. }
  278. #endif
  279. }
  280. void AbstractDiskWriter::allocate(int64_t offset, int64_t length)
  281. {
  282. #ifdef HAVE_SOME_FALLOCATE
  283. if(fd_ == -1) {
  284. throw DL_ABORT_EX("File not yet opened.");
  285. }
  286. # ifdef __MINGW32__
  287. LARGE_INTEGER fileLength;
  288. fileLength.QuadPart = offset+length;
  289. HANDLE handle = LongToHandle(_get_osfhandle(fd_));
  290. int r;
  291. r = SetFilePointerEx(handle, fileLength, 0, FILE_BEGIN);
  292. if(r == 0) {
  293. throw DL_ABORT_EX2(fmt("SetFilePointerEx failed. cause: %lx",
  294. GetLastError()),
  295. error_code::FILE_IO_ERROR);
  296. }
  297. r = SetEndOfFile(handle);
  298. if(r == 0) {
  299. throw DL_ABORT_EX2(fmt("SetEndOfFile failed. cause: %lx",
  300. GetLastError()),
  301. error_code::FILE_IO_ERROR);
  302. }
  303. # elif HAVE_FALLOCATE
  304. // For linux, we use fallocate to detect file system supports
  305. // fallocate or not.
  306. int r;
  307. while((r = fallocate(fd_, 0, offset, length)) == -1 && errno == EINTR);
  308. int errNum = errno;
  309. if(r == -1) {
  310. throw DL_ABORT_EX3(errNum,
  311. fmt("fallocate failed. cause: %s",
  312. util::safeStrerror(errNum).c_str()),
  313. error_code::FILE_IO_ERROR);
  314. }
  315. # elif HAVE_POSIX_FALLOCATE
  316. int r = posix_fallocate(fd_, offset, length);
  317. if(r != 0) {
  318. throw DL_ABORT_EX3(r,
  319. fmt("posix_fallocate failed. cause: %s",
  320. util::safeStrerror(r).c_str()),
  321. error_code::FILE_IO_ERROR);
  322. }
  323. # else
  324. # error "no *_fallocate function available."
  325. # endif
  326. #endif // HAVE_SOME_FALLOCATE
  327. }
  328. int64_t AbstractDiskWriter::size()
  329. {
  330. return File(filename_).size();
  331. }
  332. void AbstractDiskWriter::enableReadOnly()
  333. {
  334. readOnly_ = true;
  335. }
  336. void AbstractDiskWriter::disableReadOnly()
  337. {
  338. readOnly_ = false;
  339. }
  340. void AbstractDiskWriter::enableMmap()
  341. {
  342. enableMmap_ = true;
  343. }
  344. } // namespace aria2