AbstractDiskWriter.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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(
  192. errNum,
  193. fmt(EX_FILE_OPEN, filename.c_str(), fileStrerror(errNum).c_str()),
  194. errCode);
  195. }
  196. return hn;
  197. }
  198. #else // !__MINGW32__
  199. int openFileWithFlags(const std::string& filename, int flags,
  200. error_code::Value errCode)
  201. {
  202. int fd;
  203. while ((fd = a2open(utf8ToWChar(filename).c_str(), flags, OPEN_MODE)) == -1 &&
  204. errno == EINTR)
  205. ;
  206. if (fd < 0) {
  207. int errNum = errno;
  208. throw DL_ABORT_EX3(
  209. errNum,
  210. fmt(EX_FILE_OPEN, filename.c_str(), util::safeStrerror(errNum).c_str()),
  211. errCode);
  212. }
  213. util::make_fd_cloexec(fd);
  214. # if defined(__APPLE__) && defined(__MACH__)
  215. // This may reduce memory consumption on Mac OS X.
  216. fcntl(fd, F_NOCACHE, 1);
  217. # endif // __APPLE__ && __MACH__
  218. return fd;
  219. }
  220. #endif // !__MINGW32__
  221. } // namespace
  222. void AbstractDiskWriter::openExistingFile(int64_t totalLength)
  223. {
  224. int flags = O_BINARY;
  225. if (readOnly_) {
  226. flags |= O_RDONLY;
  227. }
  228. else {
  229. flags |= O_RDWR;
  230. }
  231. fd_ = openFileWithFlags(filename_, flags, error_code::FILE_OPEN_ERROR);
  232. }
  233. void AbstractDiskWriter::createFile(int addFlags)
  234. {
  235. assert(!filename_.empty());
  236. util::mkdirs(File(filename_).getDirname());
  237. fd_ = openFileWithFlags(filename_,
  238. O_CREAT | O_RDWR | O_TRUNC | O_BINARY | addFlags,
  239. error_code::FILE_CREATE_ERROR);
  240. }
  241. ssize_t AbstractDiskWriter::writeDataInternal(const unsigned char* data,
  242. size_t len, int64_t offset)
  243. {
  244. if (mapaddr_) {
  245. memcpy(mapaddr_ + offset, data, len);
  246. return len;
  247. }
  248. else {
  249. ssize_t writtenLength = 0;
  250. seek(offset);
  251. while ((size_t)writtenLength < len) {
  252. #ifdef __MINGW32__
  253. DWORD nwrite;
  254. if (WriteFile(fd_, data + writtenLength, len - writtenLength, &nwrite,
  255. 0)) {
  256. writtenLength += nwrite;
  257. }
  258. else {
  259. return -1;
  260. }
  261. #else // !__MINGW32__
  262. ssize_t ret = 0;
  263. while ((ret = write(fd_, data + writtenLength, len - writtenLength)) ==
  264. -1 &&
  265. errno == EINTR)
  266. ;
  267. if (ret == -1) {
  268. return -1;
  269. }
  270. writtenLength += ret;
  271. #endif // !__MINGW32__
  272. }
  273. return writtenLength;
  274. }
  275. }
  276. ssize_t AbstractDiskWriter::readDataInternal(unsigned char* data, size_t len,
  277. int64_t offset)
  278. {
  279. if (mapaddr_) {
  280. if (offset >= maplen_) {
  281. return 0;
  282. }
  283. auto readlen = std::min(maplen_ - offset, static_cast<int64_t>(len));
  284. memcpy(data, mapaddr_ + offset, readlen);
  285. return readlen;
  286. }
  287. else {
  288. seek(offset);
  289. #ifdef __MINGW32__
  290. DWORD nread;
  291. if (ReadFile(fd_, data, len, &nread, 0)) {
  292. return nread;
  293. }
  294. else {
  295. return -1;
  296. }
  297. #else // !__MINGW32__
  298. ssize_t ret = 0;
  299. while ((ret = read(fd_, data, len)) == -1 && errno == EINTR)
  300. ;
  301. return ret;
  302. #endif // !__MINGW32__
  303. }
  304. }
  305. void AbstractDiskWriter::seek(int64_t offset)
  306. {
  307. assert(offset >= 0);
  308. #ifdef __MINGW32__
  309. LARGE_INTEGER fileLength;
  310. fileLength.QuadPart = offset;
  311. if (SetFilePointerEx(fd_, fileLength, 0, FILE_BEGIN) == 0)
  312. #else // !__MINGW32__
  313. if (a2lseek(fd_, offset, SEEK_SET) == (a2_off_t)-1)
  314. #endif // !__MINGW32__
  315. {
  316. int errNum = fileError();
  317. throw DL_ABORT_EX2(
  318. fmt(EX_FILE_SEEK, filename_.c_str(), fileStrerror(errNum).c_str()),
  319. error_code::FILE_IO_ERROR);
  320. }
  321. }
  322. void AbstractDiskWriter::ensureMmapWrite(size_t len, int64_t offset)
  323. {
  324. #if defined(HAVE_MMAP) || defined(__MINGW32__)
  325. if (enableMmap_) {
  326. if (mapaddr_) {
  327. if (static_cast<int64_t>(len + offset) > maplen_) {
  328. int errNum = 0;
  329. # ifdef __MINGW32__
  330. if (!UnmapViewOfFile(mapaddr_)) {
  331. errNum = GetLastError();
  332. }
  333. CloseHandle(mapView_);
  334. mapView_ = INVALID_HANDLE_VALUE;
  335. # else // !__MINGW32__
  336. if (munmap(mapaddr_, maplen_) == -1) {
  337. errNum = errno;
  338. }
  339. # endif // !__MINGW32__
  340. if (errNum != 0) {
  341. A2_LOG_ERROR(fmt("Unmapping file %s failed: %s", filename_.c_str(),
  342. fileStrerror(errNum).c_str()));
  343. }
  344. mapaddr_ = nullptr;
  345. maplen_ = 0;
  346. enableMmap_ = false;
  347. }
  348. }
  349. else {
  350. int64_t filesize = size();
  351. if (filesize == 0) {
  352. // mapping 0 length file is useless. Also munmap with size ==
  353. // 0 will fail with EINVAL.
  354. enableMmap_ = false;
  355. return;
  356. }
  357. if (static_cast<uint64_t>(std::numeric_limits<size_t>::max()) <
  358. static_cast<uint64_t>(filesize)) {
  359. // filesize could overflow in 32bit OS with 64bit off_t type
  360. // the filesize will be truncated if provided as a 32bit size_t
  361. enableMmap_ = false;
  362. return;
  363. }
  364. int errNum = 0;
  365. if (static_cast<int64_t>(len + offset) <= filesize) {
  366. # ifdef __MINGW32__
  367. mapView_ = CreateFileMapping(fd_, 0, PAGE_READWRITE, filesize >> 32,
  368. filesize & 0xffffffffu, 0);
  369. if (mapView_) {
  370. mapaddr_ = reinterpret_cast<unsigned char*>(
  371. MapViewOfFile(mapView_, FILE_MAP_WRITE, 0, 0, 0));
  372. if (!mapaddr_) {
  373. errNum = GetLastError();
  374. CloseHandle(mapView_);
  375. mapView_ = INVALID_HANDLE_VALUE;
  376. }
  377. }
  378. else {
  379. errNum = GetLastError();
  380. }
  381. # else // !__MINGW32__
  382. auto pa =
  383. mmap(nullptr, filesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0);
  384. if (pa == MAP_FAILED) {
  385. errNum = errno;
  386. }
  387. else {
  388. mapaddr_ = reinterpret_cast<unsigned char*>(pa);
  389. }
  390. # endif // !__MINGW32__
  391. if (mapaddr_) {
  392. A2_LOG_DEBUG(fmt("Mapping file %s succeeded, length=%" PRId64 "",
  393. filename_.c_str(), static_cast<uint64_t>(filesize)));
  394. maplen_ = filesize;
  395. }
  396. else {
  397. A2_LOG_WARN(fmt("Mapping file %s failed: %s", filename_.c_str(),
  398. fileStrerror(errNum).c_str()));
  399. enableMmap_ = false;
  400. }
  401. }
  402. }
  403. }
  404. #endif // HAVE_MMAP || __MINGW32__
  405. }
  406. namespace {
  407. // Returns true if |errNum| indicates that disk is full.
  408. bool isDiskFullError(int errNum)
  409. {
  410. return
  411. #ifdef __MINGW32__
  412. errNum == ERROR_DISK_FULL || errNum == ERROR_HANDLE_DISK_FULL
  413. #else // !__MINGW32__
  414. errNum == ENOSPC
  415. #endif // !__MINGW32__
  416. ;
  417. }
  418. } // namespace
  419. void AbstractDiskWriter::writeData(const unsigned char* data, size_t len,
  420. int64_t offset)
  421. {
  422. ensureMmapWrite(len, offset);
  423. if (writeDataInternal(data, len, offset) < 0) {
  424. int errNum = fileError();
  425. // If the error indicates disk full situation, throw
  426. // DownloadFailureException and abort download instantly.
  427. if (isDiskFullError(errNum)) {
  428. throw DOWNLOAD_FAILURE_EXCEPTION3(
  429. errNum,
  430. fmt(EX_FILE_WRITE, filename_.c_str(), fileStrerror(errNum).c_str()),
  431. error_code::NOT_ENOUGH_DISK_SPACE);
  432. }
  433. else {
  434. throw DL_ABORT_EX3(
  435. errNum,
  436. fmt(EX_FILE_WRITE, filename_.c_str(), fileStrerror(errNum).c_str()),
  437. error_code::FILE_IO_ERROR);
  438. }
  439. }
  440. }
  441. ssize_t AbstractDiskWriter::readData(unsigned char* data, size_t len,
  442. int64_t offset)
  443. {
  444. ssize_t ret;
  445. if ((ret = readDataInternal(data, len, offset)) < 0) {
  446. int errNum = fileError();
  447. throw DL_ABORT_EX3(
  448. errNum,
  449. fmt(EX_FILE_READ, filename_.c_str(), fileStrerror(errNum).c_str()),
  450. error_code::FILE_IO_ERROR);
  451. }
  452. return ret;
  453. }
  454. void AbstractDiskWriter::truncate(int64_t length)
  455. {
  456. if (fd_ == A2_BAD_FD) {
  457. throw DL_ABORT_EX("File not yet opened.");
  458. }
  459. #ifdef __MINGW32__
  460. // Since mingw32's ftruncate cannot handle over 2GB files, we use
  461. // SetEndOfFile instead.
  462. seek(length);
  463. if (SetEndOfFile(fd_) == 0)
  464. #else // !__MINGW32__
  465. if (a2ftruncate(fd_, length) == -1)
  466. #endif // !__MINGW32__
  467. {
  468. int errNum = fileError();
  469. throw DL_ABORT_EX2(
  470. fmt("File truncation failed. cause: %s", fileStrerror(errNum).c_str()),
  471. error_code::FILE_IO_ERROR);
  472. }
  473. }
  474. void AbstractDiskWriter::allocate(int64_t offset, int64_t length, bool sparse)
  475. {
  476. if (fd_ == A2_BAD_FD) {
  477. throw DL_ABORT_EX("File not yet opened.");
  478. }
  479. if (sparse) {
  480. #ifdef __MINGW32__
  481. DWORD bytesReturned;
  482. if (!DeviceIoControl(fd_, FSCTL_SET_SPARSE, 0, 0, 0, 0, &bytesReturned,
  483. 0)) {
  484. A2_LOG_WARN(fmt("Making file sparse failed or pending: %s",
  485. fileStrerror(GetLastError()).c_str()));
  486. }
  487. #endif // __MINGW32__
  488. truncate(offset + length);
  489. return;
  490. }
  491. #ifdef HAVE_SOME_FALLOCATE
  492. # ifdef __MINGW32__
  493. truncate(offset + length);
  494. if (!SetFileValidData(fd_, offset + length)) {
  495. auto errNum = fileError();
  496. A2_LOG_WARN(fmt(
  497. "File allocation (SetFileValidData) failed (cause: %s). File will be "
  498. "allocated by filling zero, which blocks whole aria2 execution. Run "
  499. "aria2 as an administrator or use a different file allocation method "
  500. "(see --file-allocation).",
  501. fileStrerror(errNum).c_str()));
  502. }
  503. # elif defined(__APPLE__) && defined(__MACH__)
  504. const auto toalloc = offset + length - size();
  505. fstore_t fstore = {F_ALLOCATECONTIG | F_ALLOCATEALL, F_PEOFPOSMODE, 0,
  506. toalloc, 0};
  507. if (fcntl(fd_, F_PREALLOCATE, &fstore) == -1) {
  508. // Retry non-contig.
  509. fstore.fst_flags = F_ALLOCATEALL;
  510. if (fcntl(fd_, F_PREALLOCATE, &fstore) == -1) {
  511. int err = errno;
  512. throw DL_ABORT_EX3(
  513. err,
  514. fmt("fcntl(F_PREALLOCATE) of %" PRId64 " failed. cause: %s",
  515. fstore.fst_length, util::safeStrerror(err).c_str()),
  516. error_code::FILE_IO_ERROR);
  517. }
  518. }
  519. // This forces the allocation on disk.
  520. ftruncate(fd_, offset + length);
  521. # elif HAVE_FALLOCATE
  522. // For linux, we use fallocate to detect file system supports
  523. // fallocate or not.
  524. int r;
  525. while ((r = fallocate(fd_, 0, offset, length)) == -1 && errno == EINTR)
  526. ;
  527. int errNum = errno;
  528. if (r == -1) {
  529. throw DL_ABORT_EX3(
  530. errNum,
  531. fmt("fallocate failed. cause: %s", util::safeStrerror(errNum).c_str()),
  532. isDiskFullError(errNum) ? error_code::NOT_ENOUGH_DISK_SPACE
  533. : error_code::FILE_IO_ERROR);
  534. }
  535. # elif HAVE_POSIX_FALLOCATE
  536. int r = posix_fallocate(fd_, offset, length);
  537. if (r != 0) {
  538. throw DL_ABORT_EX3(
  539. r,
  540. fmt("posix_fallocate failed. cause: %s", util::safeStrerror(r).c_str()),
  541. isDiskFullError(r) ? error_code::NOT_ENOUGH_DISK_SPACE
  542. : error_code::FILE_IO_ERROR);
  543. }
  544. # else
  545. # error "no *_fallocate function available."
  546. # endif
  547. #endif // HAVE_SOME_FALLOCATE
  548. }
  549. int64_t AbstractDiskWriter::size() { return File(filename_).size(); }
  550. void AbstractDiskWriter::enableReadOnly() { readOnly_ = true; }
  551. void AbstractDiskWriter::disableReadOnly() { readOnly_ = false; }
  552. void AbstractDiskWriter::enableMmap() { enableMmap_ = true; }
  553. void AbstractDiskWriter::dropCache(int64_t len, int64_t offset)
  554. {
  555. #ifdef HAVE_POSIX_FADVISE
  556. posix_fadvise(fd_, offset, len, POSIX_FADV_DONTNEED);
  557. #endif // HAVE_POSIX_FADVISE
  558. }
  559. void AbstractDiskWriter::flushOSBuffers()
  560. {
  561. if (fd_ == A2_BAD_FD) {
  562. return;
  563. }
  564. #ifdef __MINGW32__
  565. FlushFileBuffers(fd_);
  566. #else // !__MINGW32__
  567. fsync(fd_);
  568. #endif // __MINGW32__
  569. }
  570. } // namespace aria2