File.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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 "File.h"
  36. #include <stdlib.h>
  37. #include <sys/types.h>
  38. #ifdef HAVE_UTIME_H
  39. #include <utime.h>
  40. #endif // HAVE_UTIME_H
  41. #include <unistd.h>
  42. #include <vector>
  43. #include <cstring>
  44. #include <cstdio>
  45. #include "util.h"
  46. #include "A2STR.h"
  47. #include "array_fun.h"
  48. #include "Logger.h"
  49. #include "LogFactory.h"
  50. #include "fmt.h"
  51. namespace aria2 {
  52. File::File(const std::string& name) : name_(name) {}
  53. File::File(const File& c) = default;
  54. File::~File() = default;
  55. File& File::operator=(const File& c)
  56. {
  57. if (this != &c) {
  58. name_ = c.name_;
  59. }
  60. return *this;
  61. }
  62. int File::fillStat(a2_struct_stat& fstat)
  63. {
  64. return a2stat(utf8ToWChar(name_).c_str(), &fstat);
  65. }
  66. bool File::exists()
  67. {
  68. a2_struct_stat fstat;
  69. return fillStat(fstat) == 0;
  70. }
  71. bool File::exists(std::string& err)
  72. {
  73. a2_struct_stat fstat;
  74. if (fillStat(fstat) != 0) {
  75. err = fmt("Could not get file status: %s", strerror(errno));
  76. return false;
  77. }
  78. return true;
  79. }
  80. bool File::isFile()
  81. {
  82. a2_struct_stat fstat;
  83. if (fillStat(fstat) < 0) {
  84. return false;
  85. }
  86. return S_ISREG(fstat.st_mode) == 1;
  87. }
  88. bool File::isDir()
  89. {
  90. a2_struct_stat fstat;
  91. if (fillStat(fstat) < 0) {
  92. return false;
  93. }
  94. return S_ISDIR(fstat.st_mode) == 1;
  95. }
  96. bool File::remove()
  97. {
  98. if (isFile()) {
  99. return a2unlink(utf8ToWChar(name_).c_str()) == 0;
  100. }
  101. else if (isDir()) {
  102. return a2rmdir(utf8ToWChar(name_).c_str()) == 0;
  103. }
  104. else {
  105. return false;
  106. }
  107. }
  108. #ifdef __MINGW32__
  109. namespace {
  110. HANDLE openFile(const std::string& filename, bool readOnly = true)
  111. {
  112. DWORD desiredAccess = GENERIC_READ | (readOnly ? 0 : GENERIC_WRITE);
  113. DWORD sharedMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
  114. DWORD creationDisp = OPEN_EXISTING;
  115. return CreateFileW(utf8ToWChar(filename).c_str(), desiredAccess, sharedMode,
  116. /* lpSecurityAttributes */ nullptr, creationDisp,
  117. FILE_ATTRIBUTE_NORMAL, /* hTemplateFile */ nullptr);
  118. }
  119. } // namespace
  120. #endif // __MINGW32__
  121. int64_t File::size()
  122. {
  123. #ifdef __MINGW32__
  124. // _wstat cannot be used for symlink. It always returns 0. Quoted
  125. // from https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx:
  126. //
  127. // _wstat does not work with Windows Vista symbolic links. In
  128. // these cases, _wstat will always report a file size of 0. _stat
  129. // does work correctly with symbolic links.
  130. auto hn = openFile(name_);
  131. if (hn == INVALID_HANDLE_VALUE) {
  132. return 0;
  133. }
  134. LARGE_INTEGER fileSize;
  135. const auto rv = GetFileSizeEx(hn, &fileSize);
  136. CloseHandle(hn);
  137. return rv ? fileSize.QuadPart : 0;
  138. #else // !__MINGW32__
  139. a2_struct_stat fstat;
  140. if (fillStat(fstat) < 0) {
  141. return 0;
  142. }
  143. return fstat.st_size;
  144. #endif // !__MINGW32__
  145. }
  146. bool File::mkdirs()
  147. {
  148. if (isDir()) {
  149. return false;
  150. }
  151. #ifdef __MINGW32__
  152. std::string path = name_;
  153. for (std::string::iterator i = path.begin(), eoi = path.end(); i != eoi;
  154. ++i) {
  155. if (*i == '\\') {
  156. *i = '/';
  157. }
  158. }
  159. std::string::iterator dbegin;
  160. if (util::startsWith(path, "//")) {
  161. // UNC path
  162. std::string::size_type hostEnd = path.find('/', 2);
  163. if (hostEnd == std::string::npos) {
  164. // UNC path with only hostname considered as an error.
  165. return false;
  166. }
  167. else if (hostEnd == 2) {
  168. // If path starts with "///", it is not considered as UNC.
  169. dbegin = path.begin();
  170. }
  171. else {
  172. std::string::iterator i = path.begin() + hostEnd;
  173. std::string::iterator eoi = path.end();
  174. // //host/mount/dir/...
  175. // | |
  176. // i (at this point)
  177. // |
  178. // dbegin (will be)
  179. // Skip to after first directory part. This is because
  180. // //host/dir appears to be non-directory and mkdir it fails.
  181. for (; i != eoi && *i == '/'; ++i)
  182. ;
  183. for (; i != eoi && *i != '/'; ++i)
  184. ;
  185. dbegin = i;
  186. A2_LOG_DEBUG(
  187. fmt("UNC Prefix %s", std::string(path.begin(), dbegin).c_str()));
  188. }
  189. }
  190. else {
  191. dbegin = path.begin();
  192. }
  193. std::string::iterator begin = path.begin();
  194. std::string::iterator end = path.end();
  195. for (std::string::iterator i = dbegin; i != end;) {
  196. #else // !__MINGW32__
  197. std::string::iterator begin = name_.begin();
  198. std::string::iterator end = name_.end();
  199. for (std::string::iterator i = begin; i != end;) {
  200. #endif // !__MINGW32__
  201. std::string::iterator j = std::find(i, end, '/');
  202. if (std::distance(i, j) == 0) {
  203. ++i;
  204. continue;
  205. }
  206. i = j;
  207. if (i != end) {
  208. ++i;
  209. }
  210. #ifdef __MINGW32__
  211. if (*(j - 1) == ':') {
  212. // This is a drive letter, e.g. C:, so skip it.
  213. continue;
  214. }
  215. #endif // __MINGW32__
  216. std::string dir(begin, j);
  217. A2_LOG_DEBUG(fmt("Making directory %s", dir.c_str()));
  218. if (File(dir).isDir()) {
  219. A2_LOG_DEBUG(fmt("%s exists and is a directory.", dir.c_str()));
  220. continue;
  221. }
  222. if (a2mkdir(utf8ToWChar(dir).c_str(), DIR_OPEN_MODE) == -1) {
  223. A2_LOG_DEBUG(fmt("Failed to create %s", dir.c_str()));
  224. return false;
  225. }
  226. }
  227. return true;
  228. }
  229. mode_t File::mode()
  230. {
  231. a2_struct_stat fstat;
  232. if (fillStat(fstat) < 0) {
  233. return 0;
  234. }
  235. return fstat.st_mode;
  236. }
  237. std::string File::getBasename() const
  238. {
  239. std::string::size_type lastSlashIndex =
  240. name_.find_last_of(getPathSeparators());
  241. if (lastSlashIndex == std::string::npos) {
  242. return name_;
  243. }
  244. else {
  245. return name_.substr(lastSlashIndex + 1);
  246. }
  247. }
  248. std::string File::getDirname() const
  249. {
  250. std::string::size_type lastSlashIndex =
  251. name_.find_last_of(getPathSeparators());
  252. if (lastSlashIndex == std::string::npos) {
  253. if (name_.empty()) {
  254. return A2STR::NIL;
  255. }
  256. else {
  257. return ".";
  258. }
  259. }
  260. else if (lastSlashIndex == 0) {
  261. return "/";
  262. }
  263. else {
  264. return name_.substr(0, lastSlashIndex);
  265. }
  266. }
  267. bool File::isDir(const std::string& filename) { return File(filename).isDir(); }
  268. bool File::renameTo(const std::string& dest)
  269. {
  270. #ifdef __MINGW32__
  271. // MinGW's rename() doesn't delete an existing destination. Better
  272. // to use MoveFileEx, which usually provides atomic move in aria2
  273. // usecase.
  274. if (MoveFileExW(utf8ToWChar(name_).c_str(), utf8ToWChar(dest).c_str(),
  275. MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING)) {
  276. name_ = dest;
  277. return true;
  278. }
  279. return false;
  280. #else // !__MINGW32__
  281. if (rename(name_.c_str(), dest.c_str()) == 0) {
  282. name_ = dest;
  283. return true;
  284. }
  285. else {
  286. return false;
  287. }
  288. #endif // !__MINGW32__
  289. }
  290. bool File::utime(const Time& actime, const Time& modtime) const
  291. {
  292. #if defined(HAVE_UTIMES) && !defined(__MINGW32__)
  293. struct timeval times[2] = {{actime.getTimeFromEpoch(), 0},
  294. {modtime.getTimeFromEpoch(), 0}};
  295. return utimes(name_.c_str(), times) == 0;
  296. #elif defined(__MINGW32__)
  297. auto hn = openFile(name_, false);
  298. if (hn == INVALID_HANDLE_VALUE) {
  299. auto errNum = GetLastError();
  300. A2_LOG_ERROR(fmt(EX_FILE_OPEN, name_.c_str(),
  301. util::formatLastError(errNum).c_str()));
  302. return false;
  303. }
  304. // Use SetFileTime because Windows _wutime takes DST into
  305. // consideration.
  306. //
  307. // std::chrono::time_point::time_since_epoch returns the amount of
  308. // time between it and epoch Jan 1, 1970. OTOH, FILETIME structure
  309. // expects the epoch as Jan 1, 1601. The resolution is 100
  310. // nanoseconds.
  311. constexpr auto offset = 116444736000000000LL;
  312. uint64_t at = std::chrono::duration_cast<std::chrono::nanoseconds>(
  313. actime.getTime().time_since_epoch())
  314. .count() /
  315. 100 +
  316. offset;
  317. uint64_t mt = std::chrono::duration_cast<std::chrono::nanoseconds>(
  318. modtime.getTime().time_since_epoch())
  319. .count() /
  320. 100 +
  321. offset;
  322. FILETIME att{static_cast<DWORD>(at & 0xffffffff),
  323. static_cast<DWORD>(at >> 32)};
  324. FILETIME mtt{static_cast<DWORD>(mt & 0xffffffff),
  325. static_cast<DWORD>(mt >> 32)};
  326. auto rv = SetFileTime(hn, nullptr, &att, &mtt);
  327. if (!rv) {
  328. auto errNum = GetLastError();
  329. A2_LOG_ERROR(fmt("SetFileTime failed, cause: %s",
  330. util::formatLastError(errNum).c_str()));
  331. }
  332. CloseHandle(hn);
  333. return rv;
  334. #else // !defined(HAVE_UTIMES) && !defined(__MINGW32__)
  335. a2utimbuf ub;
  336. ub.actime = actime.getTimeFromEpoch();
  337. ub.modtime = modtime.getTimeFromEpoch();
  338. return a2utime(utf8ToWChar(name_).c_str(), &ub) == 0;
  339. #endif // !defined(HAVE_UTIMES) && !defined(__MINGW32__)
  340. }
  341. Time File::getModifiedTime()
  342. {
  343. a2_struct_stat fstat;
  344. if (fillStat(fstat) < 0) {
  345. return 0;
  346. }
  347. return Time(fstat.st_mtime);
  348. }
  349. std::string File::getCurrentDir()
  350. {
  351. #ifdef __MINGW32__
  352. const size_t buflen = 2048;
  353. wchar_t buf[buflen];
  354. if (_wgetcwd(buf, buflen)) {
  355. return wCharToUtf8(buf);
  356. }
  357. else {
  358. return ".";
  359. }
  360. #else // !__MINGW32__
  361. const size_t buflen = 2048;
  362. char buf[buflen];
  363. if (getcwd(buf, buflen)) {
  364. return std::string(buf);
  365. }
  366. else {
  367. return ".";
  368. }
  369. #endif // !__MINGW32__
  370. }
  371. const char* File::getPathSeparators()
  372. {
  373. #ifdef __MINGW32__
  374. return "/\\";
  375. #else // !__MINGW32__
  376. return "/";
  377. #endif // !__MINGW32__
  378. }
  379. } // namespace aria2