file_access_windows.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /**************************************************************************/
  2. /* file_access_windows.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #ifdef WINDOWS_ENABLED
  31. #include "file_access_windows.h"
  32. #include "core/config/project_settings.h"
  33. #include "core/os/os.h"
  34. #include "core/string/print_string.h"
  35. #include <share.h> // _SH_DENYNO
  36. #include <shlwapi.h>
  37. #define WIN32_LEAN_AND_MEAN
  38. #include <windows.h>
  39. #include <errno.h>
  40. #include <io.h>
  41. #include <sys/stat.h>
  42. #include <sys/types.h>
  43. #include <tchar.h>
  44. #include <wchar.h>
  45. #ifdef _MSC_VER
  46. #define S_ISREG(m) ((m) & _S_IFREG)
  47. #endif
  48. void FileAccessWindows::check_errors() const {
  49. ERR_FAIL_NULL(f);
  50. if (feof(f)) {
  51. last_error = ERR_FILE_EOF;
  52. }
  53. }
  54. bool FileAccessWindows::is_path_invalid(const String &p_path) {
  55. // Check for invalid operating system file.
  56. String fname = p_path.get_file().to_lower();
  57. int dot = fname.find_char('.');
  58. if (dot != -1) {
  59. fname = fname.substr(0, dot);
  60. }
  61. return invalid_files.has(fname);
  62. }
  63. String FileAccessWindows::fix_path(const String &p_path) const {
  64. String r_path = FileAccess::fix_path(p_path);
  65. if (r_path.is_relative_path()) {
  66. Char16String current_dir_name;
  67. size_t str_len = GetCurrentDirectoryW(0, nullptr);
  68. current_dir_name.resize(str_len + 1);
  69. GetCurrentDirectoryW(current_dir_name.size(), (LPWSTR)current_dir_name.ptrw());
  70. r_path = String::utf16((const char16_t *)current_dir_name.get_data()).trim_prefix(R"(\\?\)").replace("\\", "/").path_join(r_path);
  71. }
  72. r_path = r_path.simplify_path();
  73. r_path = r_path.replace("/", "\\");
  74. if (!r_path.is_network_share_path() && !r_path.begins_with(R"(\\?\)")) {
  75. r_path = R"(\\?\)" + r_path;
  76. }
  77. return r_path;
  78. }
  79. Error FileAccessWindows::open_internal(const String &p_path, int p_mode_flags) {
  80. if (is_path_invalid(p_path)) {
  81. #ifdef DEBUG_ENABLED
  82. if (p_mode_flags != READ) {
  83. WARN_PRINT("The path :" + p_path + " is a reserved Windows system pipe, so it can't be used for creating files.");
  84. }
  85. #endif
  86. return ERR_INVALID_PARAMETER;
  87. }
  88. _close();
  89. path_src = p_path;
  90. path = fix_path(p_path);
  91. const WCHAR *mode_string;
  92. if (p_mode_flags == READ) {
  93. mode_string = L"rb";
  94. } else if (p_mode_flags == WRITE) {
  95. mode_string = L"wb";
  96. } else if (p_mode_flags == READ_WRITE) {
  97. mode_string = L"rb+";
  98. } else if (p_mode_flags == WRITE_READ) {
  99. mode_string = L"wb+";
  100. } else {
  101. return ERR_INVALID_PARAMETER;
  102. }
  103. if (path.ends_with(":\\") || path.ends_with(":")) {
  104. return ERR_FILE_CANT_OPEN;
  105. }
  106. DWORD file_attr = GetFileAttributesW((LPCWSTR)(path.utf16().get_data()));
  107. if (file_attr != INVALID_FILE_ATTRIBUTES && (file_attr & FILE_ATTRIBUTE_DIRECTORY)) {
  108. return ERR_FILE_CANT_OPEN;
  109. }
  110. #ifdef TOOLS_ENABLED
  111. // Windows is case insensitive in the default configuration, but other platforms can be sensitive to it
  112. // To ease cross-platform development, we issue a warning if users try to access
  113. // a file using the wrong case (which *works* on Windows, but won't on other
  114. // platforms), we only check for relative paths, or paths in res:// or user://,
  115. // other paths aren't likely to be portable anyway.
  116. if (p_mode_flags == READ && (p_path.is_relative_path() || get_access_type() != ACCESS_FILESYSTEM)) {
  117. String base_path = p_path;
  118. String working_path;
  119. String proper_path;
  120. if (get_access_type() == ACCESS_RESOURCES) {
  121. if (ProjectSettings::get_singleton()) {
  122. working_path = ProjectSettings::get_singleton()->get_resource_path();
  123. if (!working_path.is_empty()) {
  124. base_path = working_path.path_to_file(base_path);
  125. }
  126. }
  127. proper_path = "res://";
  128. } else if (get_access_type() == ACCESS_USERDATA) {
  129. working_path = OS::get_singleton()->get_user_data_dir();
  130. if (!working_path.is_empty()) {
  131. base_path = working_path.path_to_file(base_path);
  132. }
  133. proper_path = "user://";
  134. }
  135. working_path = fix_path(working_path);
  136. WIN32_FIND_DATAW d;
  137. Vector<String> parts = base_path.simplify_path().split("/");
  138. bool mismatch = false;
  139. for (const String &part : parts) {
  140. working_path = working_path + "\\" + part;
  141. HANDLE fnd = FindFirstFileW((LPCWSTR)(working_path.utf16().get_data()), &d);
  142. if (fnd == INVALID_HANDLE_VALUE) {
  143. mismatch = false;
  144. break;
  145. }
  146. const String fname = String::utf16((const char16_t *)(d.cFileName));
  147. FindClose(fnd);
  148. if (!mismatch) {
  149. mismatch = (part != fname && part.findn(fname) == 0);
  150. }
  151. proper_path = proper_path.path_join(fname);
  152. }
  153. if (mismatch) {
  154. WARN_PRINT("Case mismatch opening requested file '" + p_path + "', stored as '" + proper_path + "' in the filesystem. This file will not open when exported to other case-sensitive platforms.");
  155. }
  156. }
  157. #endif
  158. if (is_backup_save_enabled() && p_mode_flags == WRITE) {
  159. save_path = path;
  160. // Create a temporary file in the same directory as the target file.
  161. // Note: do not use GetTempFileNameW, it's not long path aware!
  162. String tmpfile;
  163. uint64_t id = OS::get_singleton()->get_ticks_usec();
  164. while (true) {
  165. tmpfile = path + itos(id++) + ".tmp";
  166. HANDLE handle = CreateFileW((LPCWSTR)tmpfile.utf16().get_data(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);
  167. if (handle != INVALID_HANDLE_VALUE) {
  168. CloseHandle(handle);
  169. break;
  170. }
  171. if (GetLastError() != ERROR_FILE_EXISTS && GetLastError() != ERROR_SHARING_VIOLATION) {
  172. last_error = ERR_FILE_CANT_WRITE;
  173. return FAILED;
  174. }
  175. }
  176. path = tmpfile;
  177. }
  178. f = _wfsopen((LPCWSTR)(path.utf16().get_data()), mode_string, is_backup_save_enabled() ? _SH_SECURE : _SH_DENYNO);
  179. if (f == nullptr) {
  180. switch (errno) {
  181. case ENOENT: {
  182. last_error = ERR_FILE_NOT_FOUND;
  183. } break;
  184. default: {
  185. last_error = ERR_FILE_CANT_OPEN;
  186. } break;
  187. }
  188. return last_error;
  189. } else {
  190. last_error = OK;
  191. flags = p_mode_flags;
  192. return OK;
  193. }
  194. }
  195. void FileAccessWindows::_close() {
  196. if (!f) {
  197. return;
  198. }
  199. fclose(f);
  200. f = nullptr;
  201. if (!save_path.is_empty()) {
  202. // This workaround of trying multiple times is added to deal with paranoid Windows
  203. // antiviruses that love reading just written files even if they are not executable, thus
  204. // locking the file and preventing renaming from happening.
  205. bool rename_error = true;
  206. const Char16String &path_utf16 = path.utf16();
  207. const Char16String &save_path_utf16 = save_path.utf16();
  208. for (int i = 0; i < 1000; i++) {
  209. if (ReplaceFileW((LPCWSTR)(save_path_utf16.get_data()), (LPCWSTR)(path_utf16.get_data()), nullptr, REPLACEFILE_IGNORE_MERGE_ERRORS | REPLACEFILE_IGNORE_ACL_ERRORS, nullptr, nullptr)) {
  210. rename_error = false;
  211. } else {
  212. // Either the target exists and is locked (temporarily, hopefully)
  213. // or it doesn't exist; let's assume the latter before re-trying.
  214. rename_error = MoveFileW((LPCWSTR)(path_utf16.get_data()), (LPCWSTR)(save_path_utf16.get_data())) == 0;
  215. }
  216. if (!rename_error) {
  217. break;
  218. }
  219. OS::get_singleton()->delay_usec(1000);
  220. }
  221. if (rename_error) {
  222. if (close_fail_notify) {
  223. close_fail_notify(save_path);
  224. }
  225. }
  226. save_path = "";
  227. ERR_FAIL_COND_MSG(rename_error, "Safe save failed. This may be a permissions problem, but also may happen because you are running a paranoid antivirus. If this is the case, please switch to Windows Defender or disable the 'safe save' option in editor settings. This makes it work, but increases the risk of file corruption in a crash.");
  228. }
  229. }
  230. String FileAccessWindows::get_path() const {
  231. return path_src;
  232. }
  233. String FileAccessWindows::get_path_absolute() const {
  234. return path.trim_prefix(R"(\\?\)").replace("\\", "/");
  235. }
  236. bool FileAccessWindows::is_open() const {
  237. return (f != nullptr);
  238. }
  239. void FileAccessWindows::seek(uint64_t p_position) {
  240. ERR_FAIL_NULL(f);
  241. last_error = OK;
  242. if (_fseeki64(f, p_position, SEEK_SET)) {
  243. check_errors();
  244. }
  245. prev_op = 0;
  246. }
  247. void FileAccessWindows::seek_end(int64_t p_position) {
  248. ERR_FAIL_NULL(f);
  249. if (_fseeki64(f, p_position, SEEK_END)) {
  250. check_errors();
  251. }
  252. prev_op = 0;
  253. }
  254. uint64_t FileAccessWindows::get_position() const {
  255. int64_t aux_position = _ftelli64(f);
  256. if (aux_position < 0) {
  257. check_errors();
  258. }
  259. return aux_position;
  260. }
  261. uint64_t FileAccessWindows::get_length() const {
  262. ERR_FAIL_NULL_V(f, 0);
  263. uint64_t pos = get_position();
  264. _fseeki64(f, 0, SEEK_END);
  265. uint64_t size = get_position();
  266. _fseeki64(f, pos, SEEK_SET);
  267. return size;
  268. }
  269. bool FileAccessWindows::eof_reached() const {
  270. check_errors();
  271. return last_error == ERR_FILE_EOF;
  272. }
  273. uint64_t FileAccessWindows::get_buffer(uint8_t *p_dst, uint64_t p_length) const {
  274. ERR_FAIL_NULL_V(f, -1);
  275. ERR_FAIL_COND_V(!p_dst && p_length > 0, -1);
  276. if (flags == READ_WRITE || flags == WRITE_READ) {
  277. if (prev_op == WRITE) {
  278. fflush(f);
  279. }
  280. prev_op = READ;
  281. }
  282. uint64_t read = fread(p_dst, 1, p_length, f);
  283. check_errors();
  284. return read;
  285. }
  286. Error FileAccessWindows::get_error() const {
  287. return last_error;
  288. }
  289. Error FileAccessWindows::resize(int64_t p_length) {
  290. ERR_FAIL_NULL_V_MSG(f, FAILED, "File must be opened before use.");
  291. errno_t res = _chsize_s(_fileno(f), p_length);
  292. switch (res) {
  293. case 0:
  294. return OK;
  295. case EACCES:
  296. case EBADF:
  297. return ERR_FILE_CANT_OPEN;
  298. case ENOSPC:
  299. return ERR_OUT_OF_MEMORY;
  300. case EINVAL:
  301. return ERR_INVALID_PARAMETER;
  302. default:
  303. return FAILED;
  304. }
  305. }
  306. void FileAccessWindows::flush() {
  307. ERR_FAIL_NULL(f);
  308. fflush(f);
  309. if (prev_op == WRITE) {
  310. prev_op = 0;
  311. }
  312. }
  313. void FileAccessWindows::store_buffer(const uint8_t *p_src, uint64_t p_length) {
  314. ERR_FAIL_NULL(f);
  315. ERR_FAIL_COND(!p_src && p_length > 0);
  316. if (flags == READ_WRITE || flags == WRITE_READ) {
  317. if (prev_op == READ) {
  318. if (last_error != ERR_FILE_EOF) {
  319. fseek(f, 0, SEEK_CUR);
  320. }
  321. }
  322. prev_op = WRITE;
  323. }
  324. ERR_FAIL_COND(fwrite(p_src, 1, p_length, f) != (size_t)p_length);
  325. }
  326. bool FileAccessWindows::file_exists(const String &p_name) {
  327. if (is_path_invalid(p_name)) {
  328. return false;
  329. }
  330. String filename = fix_path(p_name);
  331. FILE *g = _wfsopen((LPCWSTR)(filename.utf16().get_data()), L"rb", _SH_DENYNO);
  332. if (g == nullptr) {
  333. return false;
  334. } else {
  335. fclose(g);
  336. return true;
  337. }
  338. }
  339. uint64_t FileAccessWindows::_get_modified_time(const String &p_file) {
  340. if (is_path_invalid(p_file)) {
  341. return 0;
  342. }
  343. String file = fix_path(p_file);
  344. if (file.ends_with("\\") && file != "\\") {
  345. file = file.substr(0, file.length() - 1);
  346. }
  347. HANDLE handle = CreateFileW((LPCWSTR)(file.utf16().get_data()), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr);
  348. if (handle != INVALID_HANDLE_VALUE) {
  349. FILETIME ft_create, ft_write;
  350. bool status = GetFileTime(handle, &ft_create, nullptr, &ft_write);
  351. CloseHandle(handle);
  352. if (status) {
  353. uint64_t ret = 0;
  354. // If write time is invalid, fallback to creation time.
  355. if (ft_write.dwHighDateTime == 0 && ft_write.dwLowDateTime == 0) {
  356. ret = ft_create.dwHighDateTime;
  357. ret <<= 32;
  358. ret |= ft_create.dwLowDateTime;
  359. } else {
  360. ret = ft_write.dwHighDateTime;
  361. ret <<= 32;
  362. ret |= ft_write.dwLowDateTime;
  363. }
  364. const uint64_t WINDOWS_TICKS_PER_SECOND = 10000000;
  365. const uint64_t TICKS_TO_UNIX_EPOCH = 116444736000000000LL;
  366. if (ret >= TICKS_TO_UNIX_EPOCH) {
  367. return (ret - TICKS_TO_UNIX_EPOCH) / WINDOWS_TICKS_PER_SECOND;
  368. }
  369. }
  370. }
  371. return 0;
  372. }
  373. BitField<FileAccess::UnixPermissionFlags> FileAccessWindows::_get_unix_permissions(const String &p_file) {
  374. return 0;
  375. }
  376. Error FileAccessWindows::_set_unix_permissions(const String &p_file, BitField<FileAccess::UnixPermissionFlags> p_permissions) {
  377. return ERR_UNAVAILABLE;
  378. }
  379. bool FileAccessWindows::_get_hidden_attribute(const String &p_file) {
  380. String file = fix_path(p_file);
  381. DWORD attrib = GetFileAttributesW((LPCWSTR)file.utf16().get_data());
  382. ERR_FAIL_COND_V_MSG(attrib == INVALID_FILE_ATTRIBUTES, false, "Failed to get attributes for: " + p_file);
  383. return (attrib & FILE_ATTRIBUTE_HIDDEN);
  384. }
  385. Error FileAccessWindows::_set_hidden_attribute(const String &p_file, bool p_hidden) {
  386. String file = fix_path(p_file);
  387. const Char16String &file_utf16 = file.utf16();
  388. DWORD attrib = GetFileAttributesW((LPCWSTR)file_utf16.get_data());
  389. ERR_FAIL_COND_V_MSG(attrib == INVALID_FILE_ATTRIBUTES, FAILED, "Failed to get attributes for: " + p_file);
  390. BOOL ok;
  391. if (p_hidden) {
  392. ok = SetFileAttributesW((LPCWSTR)file_utf16.get_data(), attrib | FILE_ATTRIBUTE_HIDDEN);
  393. } else {
  394. ok = SetFileAttributesW((LPCWSTR)file_utf16.get_data(), attrib & ~FILE_ATTRIBUTE_HIDDEN);
  395. }
  396. ERR_FAIL_COND_V_MSG(!ok, FAILED, "Failed to set attributes for: " + p_file);
  397. return OK;
  398. }
  399. bool FileAccessWindows::_get_read_only_attribute(const String &p_file) {
  400. String file = fix_path(p_file);
  401. DWORD attrib = GetFileAttributesW((LPCWSTR)file.utf16().get_data());
  402. ERR_FAIL_COND_V_MSG(attrib == INVALID_FILE_ATTRIBUTES, false, "Failed to get attributes for: " + p_file);
  403. return (attrib & FILE_ATTRIBUTE_READONLY);
  404. }
  405. Error FileAccessWindows::_set_read_only_attribute(const String &p_file, bool p_ro) {
  406. String file = fix_path(p_file);
  407. const Char16String &file_utf16 = file.utf16();
  408. DWORD attrib = GetFileAttributesW((LPCWSTR)file_utf16.get_data());
  409. ERR_FAIL_COND_V_MSG(attrib == INVALID_FILE_ATTRIBUTES, FAILED, "Failed to get attributes for: " + p_file);
  410. BOOL ok;
  411. if (p_ro) {
  412. ok = SetFileAttributesW((LPCWSTR)file_utf16.get_data(), attrib | FILE_ATTRIBUTE_READONLY);
  413. } else {
  414. ok = SetFileAttributesW((LPCWSTR)file_utf16.get_data(), attrib & ~FILE_ATTRIBUTE_READONLY);
  415. }
  416. ERR_FAIL_COND_V_MSG(!ok, FAILED, "Failed to set attributes for: " + p_file);
  417. return OK;
  418. }
  419. void FileAccessWindows::close() {
  420. _close();
  421. }
  422. FileAccessWindows::~FileAccessWindows() {
  423. _close();
  424. }
  425. HashSet<String> FileAccessWindows::invalid_files;
  426. void FileAccessWindows::initialize() {
  427. static const char *reserved_files[]{
  428. "con", "prn", "aux", "nul", "com0", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9", "lpt0", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", nullptr
  429. };
  430. int reserved_file_index = 0;
  431. while (reserved_files[reserved_file_index] != nullptr) {
  432. invalid_files.insert(reserved_files[reserved_file_index]);
  433. reserved_file_index++;
  434. }
  435. }
  436. void FileAccessWindows::finalize() {
  437. invalid_files.clear();
  438. }
  439. #endif // WINDOWS_ENABLED