AbstractDiskWriter.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. int errNum = 0;
  356. if (static_cast<int64_t>(len + offset) <= filesize) {
  357. #ifdef __MINGW32__
  358. mapView_ = CreateFileMapping(fd_, 0, PAGE_READWRITE, filesize >> 32,
  359. filesize & 0xffffffffu, 0);
  360. if (mapView_) {
  361. mapaddr_ = reinterpret_cast<unsigned char*>(
  362. MapViewOfFile(mapView_, FILE_MAP_WRITE, 0, 0, 0));
  363. if (!mapaddr_) {
  364. errNum = GetLastError();
  365. CloseHandle(mapView_);
  366. mapView_ = INVALID_HANDLE_VALUE;
  367. }
  368. }
  369. else {
  370. errNum = GetLastError();
  371. }
  372. #else // !__MINGW32__
  373. mapaddr_ = reinterpret_cast<unsigned char*>(mmap(
  374. nullptr, filesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0));
  375. if (!mapaddr_) {
  376. errNum = errno;
  377. }
  378. #endif // !__MINGW32__
  379. if (mapaddr_) {
  380. A2_LOG_DEBUG(fmt("Mapping file %s succeeded, length=%" PRId64 "",
  381. filename_.c_str(), static_cast<uint64_t>(filesize)));
  382. maplen_ = filesize;
  383. }
  384. else {
  385. A2_LOG_WARN(fmt("Mapping file %s failed: %s", filename_.c_str(),
  386. fileStrerror(errNum).c_str()));
  387. enableMmap_ = false;
  388. }
  389. }
  390. }
  391. }
  392. #endif // HAVE_MMAP || __MINGW32__
  393. }
  394. void AbstractDiskWriter::writeData(const unsigned char* data, size_t len,
  395. int64_t offset)
  396. {
  397. ensureMmapWrite(len, offset);
  398. if (writeDataInternal(data, len, offset) < 0) {
  399. int errNum = fileError();
  400. if (
  401. // If the error indicates disk full situation, throw
  402. // DownloadFailureException and abort download instantly.
  403. #ifdef __MINGW32__
  404. errNum == ERROR_DISK_FULL || errNum == ERROR_HANDLE_DISK_FULL
  405. #else // !__MINGW32__
  406. errNum == ENOSPC
  407. #endif // !__MINGW32__
  408. ) {
  409. throw DOWNLOAD_FAILURE_EXCEPTION3(
  410. errNum,
  411. fmt(EX_FILE_WRITE, filename_.c_str(), fileStrerror(errNum).c_str()),
  412. error_code::NOT_ENOUGH_DISK_SPACE);
  413. }
  414. else {
  415. throw DL_ABORT_EX3(errNum, fmt(EX_FILE_WRITE, filename_.c_str(),
  416. fileStrerror(errNum).c_str()),
  417. error_code::FILE_IO_ERROR);
  418. }
  419. }
  420. }
  421. ssize_t AbstractDiskWriter::readData(unsigned char* data, size_t len,
  422. int64_t offset)
  423. {
  424. ssize_t ret;
  425. if ((ret = readDataInternal(data, len, offset)) < 0) {
  426. int errNum = fileError();
  427. throw DL_ABORT_EX3(errNum, fmt(EX_FILE_READ, filename_.c_str(),
  428. fileStrerror(errNum).c_str()),
  429. error_code::FILE_IO_ERROR);
  430. }
  431. return ret;
  432. }
  433. void AbstractDiskWriter::truncate(int64_t length)
  434. {
  435. if (fd_ == A2_BAD_FD) {
  436. throw DL_ABORT_EX("File not yet opened.");
  437. }
  438. #ifdef __MINGW32__
  439. // Since mingw32's ftruncate cannot handle over 2GB files, we use
  440. // SetEndOfFile instead.
  441. seek(length);
  442. if (SetEndOfFile(fd_) == 0)
  443. #else // !__MINGW32__
  444. if (a2ftruncate(fd_, length) == -1)
  445. #endif // !__MINGW32__
  446. {
  447. int errNum = fileError();
  448. throw DL_ABORT_EX2(
  449. fmt("File truncation failed. cause: %s", fileStrerror(errNum).c_str()),
  450. error_code::FILE_IO_ERROR);
  451. }
  452. }
  453. void AbstractDiskWriter::allocate(int64_t offset, int64_t length, bool sparse)
  454. {
  455. if (fd_ == A2_BAD_FD) {
  456. throw DL_ABORT_EX("File not yet opened.");
  457. }
  458. if (sparse) {
  459. #ifdef __MINGW32__
  460. DWORD bytesReturned;
  461. if (!DeviceIoControl(fd_, FSCTL_SET_SPARSE, 0, 0, 0, 0, &bytesReturned,
  462. 0)) {
  463. A2_LOG_WARN(fmt("Making file sparse failed or pending: %s",
  464. fileStrerror(GetLastError()).c_str()));
  465. }
  466. #endif // __MINGW32__
  467. truncate(offset + length);
  468. return;
  469. }
  470. #ifdef HAVE_SOME_FALLOCATE
  471. #ifdef __MINGW32__
  472. truncate(offset + length);
  473. if (!SetFileValidData(fd_, offset + length)) {
  474. auto errNum = fileError();
  475. A2_LOG_WARN(fmt(
  476. "File allocation (SetFileValidData) failed (cause: %s). File will be "
  477. "allocated by filling zero, which blocks whole aria2 execution. Run "
  478. "aria2 as an administrator or use a different file allocation method "
  479. "(see --file-allocation).",
  480. fileStrerror(errNum).c_str()));
  481. }
  482. #elif defined(__APPLE__) && defined(__MACH__)
  483. auto toalloc = offset + length - size();
  484. while (toalloc > 0) {
  485. fstore_t fstore = {
  486. F_ALLOCATECONTIG | F_ALLOCATEALL, F_PEOFPOSMODE, 0,
  487. // Allocate in 1GB chunks or else some OSX versions may choke.
  488. std::min(toalloc, (int64_t)1 << 30), 0};
  489. if (fcntl(fd_, F_PREALLOCATE, &fstore) == -1) {
  490. // Retry non-contig.
  491. fstore.fst_flags = F_ALLOCATEALL;
  492. if (fcntl(fd_, F_PREALLOCATE, &fstore) == -1) {
  493. int err = errno;
  494. throw DL_ABORT_EX3(
  495. err, fmt("fcntl(F_PREALLOCATE) of %" PRId64 " failed. cause: %s",
  496. fstore.fst_length, util::safeStrerror(err).c_str()),
  497. error_code::FILE_IO_ERROR);
  498. }
  499. }
  500. toalloc -= fstore.fst_bytesalloc;
  501. }
  502. // This forces the allocation on disk.
  503. ftruncate(fd_, offset + length);
  504. #elif HAVE_FALLOCATE
  505. // For linux, we use fallocate to detect file system supports
  506. // fallocate or not.
  507. int r;
  508. while ((r = fallocate(fd_, 0, offset, length)) == -1 && errno == EINTR)
  509. ;
  510. int errNum = errno;
  511. if (r == -1) {
  512. throw DL_ABORT_EX3(errNum, fmt("fallocate failed. cause: %s",
  513. util::safeStrerror(errNum).c_str()),
  514. error_code::FILE_IO_ERROR);
  515. }
  516. #elif HAVE_POSIX_FALLOCATE
  517. int r = posix_fallocate(fd_, offset, length);
  518. if (r != 0) {
  519. throw DL_ABORT_EX3(r, fmt("posix_fallocate failed. cause: %s",
  520. util::safeStrerror(r).c_str()),
  521. error_code::FILE_IO_ERROR);
  522. }
  523. #else
  524. #error "no *_fallocate function available."
  525. #endif
  526. #endif // HAVE_SOME_FALLOCATE
  527. }
  528. int64_t AbstractDiskWriter::size() { return File(filename_).size(); }
  529. void AbstractDiskWriter::enableReadOnly() { readOnly_ = true; }
  530. void AbstractDiskWriter::disableReadOnly() { readOnly_ = false; }
  531. void AbstractDiskWriter::enableMmap() { enableMmap_ = true; }
  532. void AbstractDiskWriter::dropCache(int64_t len, int64_t offset)
  533. {
  534. #ifdef HAVE_POSIX_FADVISE
  535. posix_fadvise(fd_, offset, len, POSIX_FADV_DONTNEED);
  536. #endif // HAVE_POSIX_FADVISE
  537. }
  538. } // namespace aria2