AbstractDiskWriter.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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 <fcntl.h>
  41. #include <cerrno>
  42. #include <cstring>
  43. #include <cassert>
  44. #include "File.h"
  45. #include "util.h"
  46. #include "message.h"
  47. #include "DlAbortEx.h"
  48. #include "a2io.h"
  49. #include "fmt.h"
  50. #include "DownloadFailureException.h"
  51. #include "error_code.h"
  52. #include "LogFactory.h"
  53. namespace aria2 {
  54. AbstractDiskWriter::AbstractDiskWriter(const std::string& filename)
  55. : filename_(filename),
  56. fd_(A2_BAD_FD),
  57. #ifdef __MINGW32__
  58. mapView_(0),
  59. #else // !__MINGW32__
  60. #endif // !__MINGW32__
  61. readOnly_(false),
  62. enableMmap_(false),
  63. mapaddr_(nullptr),
  64. maplen_(0)
  65. {
  66. }
  67. AbstractDiskWriter::~AbstractDiskWriter() { closeFile(); }
  68. namespace {
  69. // Returns error code depending on the platform. For MinGW32, return
  70. // the value of GetLastError(). Otherwise, return errno.
  71. int fileError()
  72. {
  73. #ifdef __MINGW32__
  74. return GetLastError();
  75. #else // !__MINGW32__
  76. return errno;
  77. #endif // !__MINGW32__
  78. }
  79. } // namespace
  80. namespace {
  81. // Formats error message for error code errNum. For MinGW32, errNum is
  82. // assumed to be the return value of GetLastError(). Otherwise, it is
  83. // errno.
  84. std::string fileStrerror(int errNum)
  85. {
  86. #ifdef __MINGW32__
  87. auto msg = util::formatLastError(errNum);
  88. if (msg.empty()) {
  89. char buf[256];
  90. snprintf(buf, sizeof(buf), "File I/O error %x", errNum);
  91. return buf;
  92. }
  93. return msg;
  94. #else // !__MINGW32__
  95. return util::safeStrerror(errNum);
  96. #endif // !__MINGW32__
  97. }
  98. } // namespace
  99. void AbstractDiskWriter::openFile(int64_t totalLength)
  100. {
  101. try {
  102. openExistingFile(totalLength);
  103. }
  104. catch (RecoverableException& e) {
  105. if (
  106. #ifdef __MINGW32__
  107. e.getErrNum() == ERROR_FILE_NOT_FOUND ||
  108. e.getErrNum() == ERROR_PATH_NOT_FOUND
  109. #else // !__MINGW32__
  110. e.getErrNum() == ENOENT
  111. #endif // !__MINGW32__
  112. ) {
  113. initAndOpenFile(totalLength);
  114. }
  115. else {
  116. throw;
  117. }
  118. }
  119. }
  120. void AbstractDiskWriter::closeFile()
  121. {
  122. #if defined(HAVE_MMAP) || defined(__MINGW32__)
  123. if (mapaddr_) {
  124. int errNum = 0;
  125. #ifdef __MINGW32__
  126. if (!UnmapViewOfFile(mapaddr_)) {
  127. errNum = GetLastError();
  128. }
  129. CloseHandle(mapView_);
  130. mapView_ = INVALID_HANDLE_VALUE;
  131. #else // !__MINGW32__
  132. if (munmap(mapaddr_, maplen_) == -1) {
  133. errNum = errno;
  134. }
  135. #endif // !__MINGW32__
  136. if (errNum != 0) {
  137. int errNum = fileError();
  138. A2_LOG_ERROR(fmt("Unmapping file %s failed: %s", filename_.c_str(),
  139. fileStrerror(errNum).c_str()));
  140. }
  141. else {
  142. A2_LOG_INFO(fmt("Unmapping file %s succeeded", filename_.c_str()));
  143. }
  144. mapaddr_ = nullptr;
  145. maplen_ = 0;
  146. }
  147. #endif // HAVE_MMAP || defined __MINGW32__
  148. if (fd_ != A2_BAD_FD) {
  149. #ifdef __MINGW32__
  150. CloseHandle(fd_);
  151. #else // !__MINGW32__
  152. close(fd_);
  153. #endif // !__MINGW32__
  154. fd_ = A2_BAD_FD;
  155. }
  156. }
  157. namespace {
  158. #ifdef __MINGW32__
  159. HANDLE openFileWithFlags(const std::string& filename, int flags,
  160. error_code::Value errCode)
  161. {
  162. HANDLE hn;
  163. DWORD desiredAccess = 0;
  164. DWORD sharedMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
  165. DWORD creationDisp = 0;
  166. if (flags & O_RDWR) {
  167. desiredAccess = GENERIC_READ | GENERIC_WRITE;
  168. }
  169. else if (flags & O_WRONLY) {
  170. desiredAccess = GENERIC_WRITE;
  171. }
  172. else {
  173. desiredAccess = GENERIC_READ;
  174. }
  175. if (flags & O_CREAT) {
  176. if (flags & O_TRUNC) {
  177. creationDisp |= CREATE_ALWAYS;
  178. }
  179. else {
  180. creationDisp |= CREATE_NEW;
  181. }
  182. }
  183. else {
  184. creationDisp |= OPEN_EXISTING;
  185. }
  186. hn = CreateFileW(utf8ToWChar(filename).c_str(), desiredAccess, sharedMode,
  187. /* lpSecurityAttributes */ 0, creationDisp,
  188. FILE_ATTRIBUTE_NORMAL, /* hTemplateFile */ 0);
  189. if (hn == INVALID_HANDLE_VALUE) {
  190. int errNum = GetLastError();
  191. throw DL_ABORT_EX3(errNum, fmt(EX_FILE_OPEN, filename.c_str(),
  192. fileStrerror(errNum).c_str()),
  193. errCode);
  194. }
  195. return hn;
  196. }
  197. #else // !__MINGW32__
  198. int openFileWithFlags(const std::string& filename, int flags,
  199. error_code::Value errCode)
  200. {
  201. int fd;
  202. while ((fd = a2open(utf8ToWChar(filename).c_str(), flags, OPEN_MODE)) == -1 &&
  203. errno == EINTR)
  204. ;
  205. if (fd < 0) {
  206. int errNum = errno;
  207. throw DL_ABORT_EX3(errNum, fmt(EX_FILE_OPEN, filename.c_str(),
  208. util::safeStrerror(errNum).c_str()),
  209. errCode);
  210. }
  211. util::make_fd_cloexec(fd);
  212. #if defined(__APPLE__) && defined(__MACH__)
  213. // This may reduce memory consumption on Mac OS X.
  214. fcntl(fd, F_NOCACHE, 1);
  215. #endif // __APPLE__ && __MACH__
  216. return fd;
  217. }
  218. #endif // !__MINGW32__
  219. } // namespace
  220. void AbstractDiskWriter::openExistingFile(int64_t totalLength)
  221. {
  222. int flags = O_BINARY;
  223. if (readOnly_) {
  224. flags |= O_RDONLY;
  225. }
  226. else {
  227. flags |= O_RDWR;
  228. }
  229. fd_ = openFileWithFlags(filename_, flags, error_code::FILE_OPEN_ERROR);
  230. }
  231. void AbstractDiskWriter::createFile(int addFlags)
  232. {
  233. assert(!filename_.empty());
  234. util::mkdirs(File(filename_).getDirname());
  235. fd_ = openFileWithFlags(filename_,
  236. O_CREAT | O_RDWR | O_TRUNC | O_BINARY | addFlags,
  237. error_code::FILE_CREATE_ERROR);
  238. }
  239. ssize_t AbstractDiskWriter::writeDataInternal(const unsigned char* data,
  240. size_t len, int64_t offset)
  241. {
  242. if (mapaddr_) {
  243. memcpy(mapaddr_ + offset, data, len);
  244. return len;
  245. }
  246. else {
  247. ssize_t writtenLength = 0;
  248. seek(offset);
  249. while ((size_t)writtenLength < len) {
  250. #ifdef __MINGW32__
  251. DWORD nwrite;
  252. if (WriteFile(fd_, data + writtenLength, len - writtenLength, &nwrite,
  253. 0)) {
  254. writtenLength += nwrite;
  255. }
  256. else {
  257. return -1;
  258. }
  259. #else // !__MINGW32__
  260. ssize_t ret = 0;
  261. while ((ret = write(fd_, data + writtenLength, len - writtenLength)) ==
  262. -1 &&
  263. errno == EINTR)
  264. ;
  265. if (ret == -1) {
  266. return -1;
  267. }
  268. writtenLength += ret;
  269. #endif // !__MINGW32__
  270. }
  271. return writtenLength;
  272. }
  273. }
  274. ssize_t AbstractDiskWriter::readDataInternal(unsigned char* data, size_t len,
  275. int64_t offset)
  276. {
  277. if (mapaddr_) {
  278. if (offset >= maplen_) {
  279. return 0;
  280. }
  281. auto readlen = std::min(maplen_ - offset, static_cast<int64_t>(len));
  282. memcpy(data, mapaddr_ + offset, readlen);
  283. return readlen;
  284. }
  285. else {
  286. seek(offset);
  287. #ifdef __MINGW32__
  288. DWORD nread;
  289. if (ReadFile(fd_, data, len, &nread, 0)) {
  290. return nread;
  291. }
  292. else {
  293. return -1;
  294. }
  295. #else // !__MINGW32__
  296. ssize_t ret = 0;
  297. while ((ret = read(fd_, data, len)) == -1 && errno == EINTR)
  298. ;
  299. return ret;
  300. #endif // !__MINGW32__
  301. }
  302. }
  303. void AbstractDiskWriter::seek(int64_t offset)
  304. {
  305. assert(offset >= 0);
  306. #ifdef __MINGW32__
  307. LARGE_INTEGER fileLength;
  308. fileLength.QuadPart = offset;
  309. if (SetFilePointerEx(fd_, fileLength, 0, FILE_BEGIN) == 0)
  310. #else // !__MINGW32__
  311. if (a2lseek(fd_, offset, SEEK_SET) == (a2_off_t)-1)
  312. #endif // !__MINGW32__
  313. {
  314. int errNum = fileError();
  315. throw DL_ABORT_EX2(
  316. fmt(EX_FILE_SEEK, filename_.c_str(), fileStrerror(errNum).c_str()),
  317. error_code::FILE_IO_ERROR);
  318. }
  319. }
  320. void AbstractDiskWriter::ensureMmapWrite(size_t len, int64_t offset)
  321. {
  322. #if defined(HAVE_MMAP) || defined(__MINGW32__)
  323. if (enableMmap_) {
  324. if (mapaddr_) {
  325. if (static_cast<int64_t>(len + offset) > maplen_) {
  326. int errNum = 0;
  327. #ifdef __MINGW32__
  328. if (!UnmapViewOfFile(mapaddr_)) {
  329. errNum = GetLastError();
  330. }
  331. CloseHandle(mapView_);
  332. mapView_ = INVALID_HANDLE_VALUE;
  333. #else // !__MINGW32__
  334. if (munmap(mapaddr_, maplen_) == -1) {
  335. errNum = errno;
  336. }
  337. #endif // !__MINGW32__
  338. if (errNum != 0) {
  339. A2_LOG_ERROR(fmt("Unmapping file %s failed: %s", filename_.c_str(),
  340. fileStrerror(errNum).c_str()));
  341. }
  342. mapaddr_ = nullptr;
  343. maplen_ = 0;
  344. enableMmap_ = false;
  345. }
  346. }
  347. else {
  348. int64_t filesize = size();
  349. if (filesize == 0) {
  350. // mapping 0 length file is useless. Also munmap with size ==
  351. // 0 will fail with EINVAL.
  352. enableMmap_ = false;
  353. return;
  354. }
  355. if (static_cast<uint64_t>(std::numeric_limits<size_t>::max()) <
  356. static_cast<uint64_t>(filesize)) {
  357. // filesize could overflow in 32bit OS with 64bit off_t type
  358. // the filesize will be truncated if provided as a 32bit size_t
  359. enableMmap_ = false;
  360. return;
  361. }
  362. int errNum = 0;
  363. if (static_cast<int64_t>(len + offset) <= filesize) {
  364. #ifdef __MINGW32__
  365. mapView_ = CreateFileMapping(fd_, 0, PAGE_READWRITE, filesize >> 32,
  366. filesize & 0xffffffffu, 0);
  367. if (mapView_) {
  368. mapaddr_ = reinterpret_cast<unsigned char*>(
  369. MapViewOfFile(mapView_, FILE_MAP_WRITE, 0, 0, 0));
  370. if (!mapaddr_) {
  371. errNum = GetLastError();
  372. CloseHandle(mapView_);
  373. mapView_ = INVALID_HANDLE_VALUE;
  374. }
  375. }
  376. else {
  377. errNum = GetLastError();
  378. }
  379. #else // !__MINGW32__
  380. auto pa =
  381. mmap(nullptr, filesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0);
  382. if (pa == MAP_FAILED) {
  383. errNum = errno;
  384. }
  385. else {
  386. mapaddr_ = reinterpret_cast<unsigned char*>(pa);
  387. }
  388. #endif // !__MINGW32__
  389. if (mapaddr_) {
  390. A2_LOG_DEBUG(fmt("Mapping file %s succeeded, length=%" PRId64 "",
  391. filename_.c_str(), static_cast<uint64_t>(filesize)));
  392. maplen_ = filesize;
  393. }
  394. else {
  395. A2_LOG_WARN(fmt("Mapping file %s failed: %s", filename_.c_str(),
  396. fileStrerror(errNum).c_str()));
  397. enableMmap_ = false;
  398. }
  399. }
  400. }
  401. }
  402. #endif // HAVE_MMAP || __MINGW32__
  403. }
  404. void AbstractDiskWriter::writeData(const unsigned char* data, size_t len,
  405. int64_t offset)
  406. {
  407. ensureMmapWrite(len, offset);
  408. if (writeDataInternal(data, len, offset) < 0) {
  409. int errNum = fileError();
  410. if (
  411. // If the error indicates disk full situation, throw
  412. // DownloadFailureException and abort download instantly.
  413. #ifdef __MINGW32__
  414. errNum == ERROR_DISK_FULL || errNum == ERROR_HANDLE_DISK_FULL
  415. #else // !__MINGW32__
  416. errNum == ENOSPC
  417. #endif // !__MINGW32__
  418. ) {
  419. throw DOWNLOAD_FAILURE_EXCEPTION3(
  420. errNum,
  421. fmt(EX_FILE_WRITE, filename_.c_str(), fileStrerror(errNum).c_str()),
  422. error_code::NOT_ENOUGH_DISK_SPACE);
  423. }
  424. else {
  425. throw DL_ABORT_EX3(errNum, fmt(EX_FILE_WRITE, filename_.c_str(),
  426. fileStrerror(errNum).c_str()),
  427. error_code::FILE_IO_ERROR);
  428. }
  429. }
  430. }
  431. ssize_t AbstractDiskWriter::readData(unsigned char* data, size_t len,
  432. int64_t offset)
  433. {
  434. ssize_t ret;
  435. if ((ret = readDataInternal(data, len, offset)) < 0) {
  436. int errNum = fileError();
  437. throw DL_ABORT_EX3(errNum, fmt(EX_FILE_READ, filename_.c_str(),
  438. fileStrerror(errNum).c_str()),
  439. error_code::FILE_IO_ERROR);
  440. }
  441. return ret;
  442. }
  443. void AbstractDiskWriter::truncate(int64_t length)
  444. {
  445. if (fd_ == A2_BAD_FD) {
  446. throw DL_ABORT_EX("File not yet opened.");
  447. }
  448. #ifdef __MINGW32__
  449. // Since mingw32's ftruncate cannot handle over 2GB files, we use
  450. // SetEndOfFile instead.
  451. seek(length);
  452. if (SetEndOfFile(fd_) == 0)
  453. #else // !__MINGW32__
  454. if (a2ftruncate(fd_, length) == -1)
  455. #endif // !__MINGW32__
  456. {
  457. int errNum = fileError();
  458. throw DL_ABORT_EX2(
  459. fmt("File truncation failed. cause: %s", fileStrerror(errNum).c_str()),
  460. error_code::FILE_IO_ERROR);
  461. }
  462. }
  463. void AbstractDiskWriter::allocate(int64_t offset, int64_t length, bool sparse)
  464. {
  465. if (fd_ == A2_BAD_FD) {
  466. throw DL_ABORT_EX("File not yet opened.");
  467. }
  468. if (sparse) {
  469. #ifdef __MINGW32__
  470. DWORD bytesReturned;
  471. if (!DeviceIoControl(fd_, FSCTL_SET_SPARSE, 0, 0, 0, 0, &bytesReturned,
  472. 0)) {
  473. A2_LOG_WARN(fmt("Making file sparse failed or pending: %s",
  474. fileStrerror(GetLastError()).c_str()));
  475. }
  476. #endif // __MINGW32__
  477. truncate(offset + length);
  478. return;
  479. }
  480. #ifdef HAVE_SOME_FALLOCATE
  481. #ifdef __MINGW32__
  482. truncate(offset + length);
  483. if (!SetFileValidData(fd_, offset + length)) {
  484. auto errNum = fileError();
  485. A2_LOG_WARN(fmt(
  486. "File allocation (SetFileValidData) failed (cause: %s). File will be "
  487. "allocated by filling zero, which blocks whole aria2 execution. Run "
  488. "aria2 as an administrator or use a different file allocation method "
  489. "(see --file-allocation).",
  490. fileStrerror(errNum).c_str()));
  491. }
  492. #elif defined(__APPLE__) && defined(__MACH__)
  493. auto toalloc = offset + length - size();
  494. while (toalloc > 0) {
  495. fstore_t fstore = {
  496. F_ALLOCATECONTIG | F_ALLOCATEALL, F_PEOFPOSMODE, 0,
  497. // Allocate in 1GB chunks or else some OSX versions may choke.
  498. std::min(toalloc, (int64_t)1 << 30), 0};
  499. if (fcntl(fd_, F_PREALLOCATE, &fstore) == -1) {
  500. // Retry non-contig.
  501. fstore.fst_flags = F_ALLOCATEALL;
  502. if (fcntl(fd_, F_PREALLOCATE, &fstore) == -1) {
  503. int err = errno;
  504. throw DL_ABORT_EX3(
  505. err, fmt("fcntl(F_PREALLOCATE) of %" PRId64 " failed. cause: %s",
  506. fstore.fst_length, util::safeStrerror(err).c_str()),
  507. error_code::FILE_IO_ERROR);
  508. }
  509. }
  510. toalloc -= fstore.fst_bytesalloc;
  511. }
  512. // This forces the allocation on disk.
  513. ftruncate(fd_, offset + length);
  514. #elif HAVE_FALLOCATE
  515. // For linux, we use fallocate to detect file system supports
  516. // fallocate or not.
  517. int r;
  518. while ((r = fallocate(fd_, 0, offset, length)) == -1 && errno == EINTR)
  519. ;
  520. int errNum = errno;
  521. if (r == -1) {
  522. throw DL_ABORT_EX3(errNum, fmt("fallocate failed. cause: %s",
  523. util::safeStrerror(errNum).c_str()),
  524. error_code::FILE_IO_ERROR);
  525. }
  526. #elif HAVE_POSIX_FALLOCATE
  527. int r = posix_fallocate(fd_, offset, length);
  528. if (r != 0) {
  529. throw DL_ABORT_EX3(r, fmt("posix_fallocate failed. cause: %s",
  530. util::safeStrerror(r).c_str()),
  531. error_code::FILE_IO_ERROR);
  532. }
  533. #else
  534. #error "no *_fallocate function available."
  535. #endif
  536. #endif // HAVE_SOME_FALLOCATE
  537. }
  538. int64_t AbstractDiskWriter::size() { return File(filename_).size(); }
  539. void AbstractDiskWriter::enableReadOnly() { readOnly_ = true; }
  540. void AbstractDiskWriter::disableReadOnly() { readOnly_ = false; }
  541. void AbstractDiskWriter::enableMmap() { enableMmap_ = true; }
  542. void AbstractDiskWriter::dropCache(int64_t len, int64_t offset)
  543. {
  544. #ifdef HAVE_POSIX_FADVISE
  545. posix_fadvise(fd_, offset, len, POSIX_FADV_DONTNEED);
  546. #endif // HAVE_POSIX_FADVISE
  547. }
  548. } // namespace aria2