File.cc 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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) : name_(c.name_) {}
  54. File::~File() {}
  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::isFile()
  72. {
  73. a2_struct_stat fstat;
  74. if (fillStat(fstat) < 0) {
  75. return false;
  76. }
  77. return S_ISREG(fstat.st_mode) == 1;
  78. }
  79. bool File::isDir()
  80. {
  81. a2_struct_stat fstat;
  82. if (fillStat(fstat) < 0) {
  83. return false;
  84. }
  85. return S_ISDIR(fstat.st_mode) == 1;
  86. }
  87. bool File::remove()
  88. {
  89. if (isFile()) {
  90. return a2unlink(utf8ToWChar(name_).c_str()) == 0;
  91. }
  92. else if (isDir()) {
  93. return a2rmdir(utf8ToWChar(name_).c_str()) == 0;
  94. }
  95. else {
  96. return false;
  97. }
  98. }
  99. #ifdef __MINGW32__
  100. namespace {
  101. HANDLE openFile(const std::string& filename)
  102. {
  103. DWORD desiredAccess = GENERIC_READ;
  104. DWORD sharedMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
  105. DWORD creationDisp = OPEN_EXISTING;
  106. return CreateFileW(utf8ToWChar(filename).c_str(), desiredAccess, sharedMode,
  107. /* lpSecurityAttributes */ nullptr, creationDisp,
  108. FILE_ATTRIBUTE_NORMAL, /* hTemplateFile */ nullptr);
  109. }
  110. } // namespace
  111. #endif // __MINGW32__
  112. int64_t File::size()
  113. {
  114. #ifdef __MINGW32__
  115. // _wstat cannot be used for symlink. It always returns 0. Quoted
  116. // from https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx:
  117. //
  118. // _wstat does not work with Windows Vista symbolic links. In
  119. // these cases, _wstat will always report a file size of 0. _stat
  120. // does work correctly with symbolic links.
  121. auto hn = openFile(name_);
  122. if (hn == INVALID_HANDLE_VALUE) {
  123. return 0;
  124. }
  125. LARGE_INTEGER fileSize;
  126. const auto rv = GetFileSizeEx(hn, &fileSize);
  127. CloseHandle(hn);
  128. return rv ? fileSize.QuadPart : 0;
  129. #else // !__MINGW32__
  130. a2_struct_stat fstat;
  131. if (fillStat(fstat) < 0) {
  132. return 0;
  133. }
  134. return fstat.st_size;
  135. #endif // !__MINGW32__
  136. }
  137. bool File::mkdirs()
  138. {
  139. if (isDir()) {
  140. return false;
  141. }
  142. #ifdef __MINGW32__
  143. std::string path = name_;
  144. for (std::string::iterator i = path.begin(), eoi = path.end(); i != eoi;
  145. ++i) {
  146. if (*i == '\\') {
  147. *i = '/';
  148. }
  149. }
  150. std::string::iterator dbegin;
  151. if (util::startsWith(path, "//")) {
  152. // UNC path
  153. std::string::size_type hostEnd = path.find('/', 2);
  154. if (hostEnd == std::string::npos) {
  155. // UNC path with only hostname considered as an error.
  156. return false;
  157. }
  158. else if (hostEnd == 2) {
  159. // If path starts with "///", it is not considered as UNC.
  160. dbegin = path.begin();
  161. }
  162. else {
  163. std::string::iterator i = path.begin() + hostEnd;
  164. std::string::iterator eoi = path.end();
  165. // //host/mount/dir/...
  166. // | |
  167. // i (at this point)
  168. // |
  169. // dbegin (will be)
  170. // Skip to after first directory part. This is because
  171. // //host/dir appears to be non-directory and mkdir it fails.
  172. for (; i != eoi && *i == '/'; ++i)
  173. ;
  174. for (; i != eoi && *i != '/'; ++i)
  175. ;
  176. dbegin = i;
  177. A2_LOG_DEBUG(
  178. fmt("UNC Prefix %s", std::string(path.begin(), dbegin).c_str()));
  179. }
  180. }
  181. else {
  182. dbegin = path.begin();
  183. }
  184. std::string::iterator begin = path.begin();
  185. std::string::iterator end = path.end();
  186. for (std::string::iterator i = dbegin; i != end;) {
  187. #else // !__MINGW32__
  188. std::string::iterator begin = name_.begin();
  189. std::string::iterator end = name_.end();
  190. for (std::string::iterator i = begin; i != end;) {
  191. #endif // !__MINGW32__
  192. std::string::iterator j = std::find(i, end, '/');
  193. if (std::distance(i, j) == 0) {
  194. ++i;
  195. continue;
  196. }
  197. i = j;
  198. if (i != end) {
  199. ++i;
  200. }
  201. #ifdef __MINGW32__
  202. if (*(j - 1) == ':') {
  203. // This is a drive letter, e.g. C:, so skip it.
  204. continue;
  205. }
  206. #endif // __MINGW32__
  207. std::string dir(begin, j);
  208. A2_LOG_DEBUG(fmt("Making directory %s", dir.c_str()));
  209. if (File(dir).isDir()) {
  210. A2_LOG_DEBUG(fmt("%s exists and is a directory.", dir.c_str()));
  211. continue;
  212. }
  213. if (a2mkdir(utf8ToWChar(dir).c_str(), DIR_OPEN_MODE) == -1) {
  214. A2_LOG_DEBUG(fmt("Failed to create %s", dir.c_str()));
  215. return false;
  216. }
  217. }
  218. return true;
  219. }
  220. mode_t File::mode()
  221. {
  222. a2_struct_stat fstat;
  223. if (fillStat(fstat) < 0) {
  224. return 0;
  225. }
  226. return fstat.st_mode;
  227. }
  228. std::string File::getBasename() const
  229. {
  230. std::string::size_type lastSlashIndex =
  231. name_.find_last_of(getPathSeparators());
  232. if (lastSlashIndex == std::string::npos) {
  233. return name_;
  234. }
  235. else {
  236. return name_.substr(lastSlashIndex + 1);
  237. }
  238. }
  239. std::string File::getDirname() const
  240. {
  241. std::string::size_type lastSlashIndex =
  242. name_.find_last_of(getPathSeparators());
  243. if (lastSlashIndex == std::string::npos) {
  244. if (name_.empty()) {
  245. return A2STR::NIL;
  246. }
  247. else {
  248. return ".";
  249. }
  250. }
  251. else if (lastSlashIndex == 0) {
  252. return "/";
  253. }
  254. else {
  255. return name_.substr(0, lastSlashIndex);
  256. }
  257. }
  258. bool File::isDir(const std::string& filename) { return File(filename).isDir(); }
  259. bool File::renameTo(const std::string& dest)
  260. {
  261. #ifdef __MINGW32__
  262. // MinGW's rename() doesn't delete an existing destination. Better
  263. // to use MoveFileEx, which usually provides atomic move in aria2
  264. // usecase.
  265. if (MoveFileExW(utf8ToWChar(name_).c_str(), utf8ToWChar(dest).c_str(),
  266. MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING)) {
  267. name_ = dest;
  268. return true;
  269. }
  270. return false;
  271. #else // !__MINGW32__
  272. if (rename(name_.c_str(), dest.c_str()) == 0) {
  273. name_ = dest;
  274. return true;
  275. }
  276. else {
  277. return false;
  278. }
  279. #endif // !__MINGW32__
  280. }
  281. bool File::utime(const Time& actime, const Time& modtime) const
  282. {
  283. #if defined(HAVE_UTIMES) && !defined(__MINGW32__)
  284. struct timeval times[2] = {{actime.getTimeFromEpoch(), 0},
  285. {modtime.getTimeFromEpoch(), 0}};
  286. return utimes(name_.c_str(), times) == 0;
  287. #else // !HAVE_UTIMES
  288. a2utimbuf ub;
  289. ub.actime = actime.getTimeFromEpoch();
  290. ub.modtime = modtime.getTimeFromEpoch();
  291. return a2utime(utf8ToWChar(name_).c_str(), &ub) == 0;
  292. #endif // !HAVE_UTIMES
  293. }
  294. Time File::getModifiedTime()
  295. {
  296. a2_struct_stat fstat;
  297. if (fillStat(fstat) < 0) {
  298. return 0;
  299. }
  300. return Time(fstat.st_mtime);
  301. }
  302. std::string File::getCurrentDir()
  303. {
  304. #ifdef __MINGW32__
  305. const size_t buflen = 2048;
  306. wchar_t buf[buflen];
  307. if (_wgetcwd(buf, buflen)) {
  308. return wCharToUtf8(buf);
  309. }
  310. else {
  311. return ".";
  312. }
  313. #else // !__MINGW32__
  314. const size_t buflen = 2048;
  315. char buf[buflen];
  316. if (getcwd(buf, buflen)) {
  317. return std::string(buf);
  318. }
  319. else {
  320. return ".";
  321. }
  322. #endif // !__MINGW32__
  323. }
  324. const char* File::getPathSeparators()
  325. {
  326. #ifdef __MINGW32__
  327. return "/\\";
  328. #else // !__MINGW32__
  329. return "/";
  330. #endif // !__MINGW32__
  331. }
  332. } // namespace aria2