FileSystem.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "ArrayPtr.h"
  24. #include "Context.h"
  25. #include "File.h"
  26. #include "FileSystem.h"
  27. #include "Log.h"
  28. #include <cstdio>
  29. #include <cstring>
  30. #ifdef WIN32
  31. #ifndef _MSC_VER
  32. #define _WIN32_IE 0x400
  33. #endif
  34. #include <windows.h>
  35. #include <shellapi.h>
  36. #include <direct.h>
  37. #include <shlobj.h>
  38. #else
  39. #include <dirent.h>
  40. #include <errno.h>
  41. #include <unistd.h>
  42. #include <sys/stat.h>
  43. #include <sys/wait.h>
  44. #define MAX_PATH 256
  45. #endif
  46. #if defined(__APPLE__)
  47. #include <mach-o/dyld.h>
  48. #endif
  49. #ifdef ANDROID
  50. extern "C" const char* SDL_Android_GetFilesDir();
  51. #endif
  52. #ifdef IOS
  53. extern "C" const char* SDL_IOS_GetResourceDir();
  54. #endif
  55. #include "DebugNew.h"
  56. namespace Urho3D
  57. {
  58. FileSystem::FileSystem(Context* context) :
  59. Object(context)
  60. {
  61. }
  62. FileSystem::~FileSystem()
  63. {
  64. }
  65. bool FileSystem::SetCurrentDir(const String& pathName)
  66. {
  67. if (!CheckAccess(pathName))
  68. {
  69. LOGERROR("Access denied to " + pathName);
  70. return false;
  71. }
  72. #ifdef WIN32
  73. if (SetCurrentDirectoryW(GetWideNativePath(pathName).CString()) == FALSE)
  74. {
  75. LOGERROR("Failed to change directory to " + pathName);
  76. return false;
  77. }
  78. #else
  79. if (chdir(GetNativePath(pathName).CString()) != 0)
  80. {
  81. LOGERROR("Failed to change directory to " + pathName);
  82. return false;
  83. }
  84. #endif
  85. return true;
  86. }
  87. bool FileSystem::CreateDir(const String& pathName)
  88. {
  89. if (!CheckAccess(pathName))
  90. {
  91. LOGERROR("Access denied to " + pathName);
  92. return false;
  93. }
  94. #ifdef WIN32
  95. bool success = (CreateDirectoryW(GetWideNativePath(RemoveTrailingSlash(pathName)).CString(), 0) == TRUE) ||
  96. (GetLastError() == ERROR_ALREADY_EXISTS);
  97. #else
  98. bool success = mkdir(GetNativePath(RemoveTrailingSlash(pathName)).CString(), S_IRWXU) == 0 || errno == EEXIST;
  99. #endif
  100. if (success)
  101. LOGDEBUG("Created directory " + pathName);
  102. else
  103. LOGERROR("Failed to create directory " + pathName);
  104. return success;
  105. }
  106. int FileSystem::SystemCommand(const String& commandLine)
  107. {
  108. if (allowedPaths_.Empty())
  109. return system(commandLine.CString());
  110. else
  111. {
  112. LOGERROR("Executing an external command is not allowed");
  113. return -1;
  114. }
  115. }
  116. int FileSystem::SystemRun(const String& fileName, const Vector<String>& arguments)
  117. {
  118. if (allowedPaths_.Empty())
  119. {
  120. String fixedFileName = GetNativePath(fileName);
  121. #ifdef WIN32
  122. // Add .exe extension if no extension defined
  123. if (GetExtension(fixedFileName).Empty())
  124. fixedFileName += ".exe";
  125. String commandLine = "\"" + fixedFileName + "\"";
  126. for (unsigned i = 0; i < arguments.Size(); ++i)
  127. commandLine += " " + arguments[i];
  128. STARTUPINFOW startupInfo;
  129. PROCESS_INFORMATION processInfo;
  130. memset(&startupInfo, 0, sizeof startupInfo);
  131. memset(&processInfo, 0, sizeof processInfo);
  132. WString commandLineW(commandLine);
  133. if (!CreateProcessW(NULL, (wchar_t*)commandLineW.CString(), 0, 0, 0, CREATE_NO_WINDOW, 0, 0, &startupInfo, &processInfo))
  134. {
  135. LOGERROR("Failed to execute command " + commandLine);
  136. return -1;
  137. }
  138. WaitForSingleObject(processInfo.hProcess, INFINITE);
  139. DWORD exitCode;
  140. GetExitCodeProcess(processInfo.hProcess, &exitCode);
  141. CloseHandle(processInfo.hProcess);
  142. CloseHandle(processInfo.hThread);
  143. return exitCode;
  144. #else
  145. pid_t pid = fork();
  146. if (!pid)
  147. {
  148. PODVector<const char*> argPtrs;
  149. argPtrs.Push(fixedFileName.CString());
  150. for (unsigned i = 0; i < arguments.Size(); ++i)
  151. argPtrs.Push(arguments[i].CString());
  152. argPtrs.Push(0);
  153. execvp(argPtrs[0], (char**)&argPtrs[0]);
  154. return -1; // Return -1 if we could not spawn the process
  155. }
  156. else if (pid > 0)
  157. {
  158. int exitCode;
  159. wait(&exitCode);
  160. return exitCode;
  161. }
  162. else
  163. {
  164. LOGERROR("Failed to fork");
  165. return -1;
  166. }
  167. #endif
  168. }
  169. else
  170. {
  171. LOGERROR("Executing an external command is not allowed");
  172. return -1;
  173. }
  174. }
  175. bool FileSystem::SystemOpen(const String& fileName, const String& mode)
  176. {
  177. if (allowedPaths_.Empty())
  178. {
  179. if (!FileExists(fileName) && !DirExists(fileName))
  180. {
  181. LOGERROR("File or directory " + fileName + " not found");
  182. return false;
  183. }
  184. #ifdef WIN32
  185. bool success = (int)ShellExecuteW(0, !mode.Empty() ? WString(mode).CString() : 0,
  186. GetWideNativePath(fileName).CString(), 0, 0, SW_SHOW) > 32;
  187. #else
  188. Vector<String> arguments;
  189. arguments.Push(fileName);
  190. bool success = SystemRun(
  191. #if defined(__APPLE__)
  192. "open",
  193. #else
  194. "xdg-open",
  195. #endif
  196. arguments) == 0;
  197. #endif
  198. if (!success)
  199. LOGERROR("Failed to open " + fileName + " externally");
  200. return success;
  201. }
  202. else
  203. {
  204. LOGERROR("Opening a file externally is not allowed");
  205. return false;
  206. }
  207. }
  208. bool FileSystem::Copy(const String& srcFileName, const String& destFileName)
  209. {
  210. if (!CheckAccess(GetPath(srcFileName)))
  211. {
  212. LOGERROR("Access denied to " + srcFileName);
  213. return false;
  214. }
  215. if (!CheckAccess(GetPath(destFileName)))
  216. {
  217. LOGERROR("Access denied to " + destFileName);
  218. return false;
  219. }
  220. SharedPtr<File> srcFile(new File(context_, srcFileName, FILE_READ));
  221. SharedPtr<File> destFile(new File(context_, destFileName, FILE_WRITE));
  222. if (!srcFile->IsOpen() || !destFile->IsOpen())
  223. return false;
  224. unsigned fileSize = srcFile->GetSize();
  225. SharedArrayPtr<unsigned char> buffer(new unsigned char[fileSize]);
  226. unsigned bytesRead = srcFile->Read(buffer.Get(), fileSize);
  227. unsigned bytesWritten = destFile->Write(buffer.Get(), fileSize);
  228. return bytesRead == fileSize && bytesWritten == fileSize;
  229. }
  230. bool FileSystem::Rename(const String& srcFileName, const String& destFileName)
  231. {
  232. if (!CheckAccess(GetPath(srcFileName)))
  233. {
  234. LOGERROR("Access denied to " + srcFileName);
  235. return false;
  236. }
  237. if (!CheckAccess(GetPath(destFileName)))
  238. {
  239. LOGERROR("Access denied to " + destFileName);
  240. return false;
  241. }
  242. #ifdef WIN32
  243. return MoveFileW(GetWideNativePath(srcFileName).CString(), GetWideNativePath(destFileName).CString()) != 0;
  244. #else
  245. return rename(GetNativePath(srcFileName).CString(), GetNativePath(destFileName).CString()) == 0;
  246. #endif
  247. }
  248. bool FileSystem::Delete(const String& fileName)
  249. {
  250. if (!CheckAccess(GetPath(fileName)))
  251. {
  252. LOGERROR("Access denied to " + fileName);
  253. return false;
  254. }
  255. #ifdef WIN32
  256. return DeleteFileW(GetWideNativePath(fileName).CString()) != 0;
  257. #else
  258. return remove(GetNativePath(fileName).CString()) == 0;
  259. #endif
  260. }
  261. String FileSystem::GetCurrentDir() const
  262. {
  263. #ifdef WIN32
  264. wchar_t path[MAX_PATH];
  265. path[0] = 0;
  266. GetCurrentDirectoryW(MAX_PATH, path);
  267. return AddTrailingSlash(String(path));
  268. #else
  269. char path[MAX_PATH];
  270. path[0] = 0;
  271. getcwd(path, MAX_PATH);
  272. return AddTrailingSlash(String(path));
  273. #endif
  274. }
  275. bool FileSystem::CheckAccess(const String& pathName) const
  276. {
  277. String fixedPath = AddTrailingSlash(pathName);
  278. // If no allowed directories defined, succeed always
  279. if (allowedPaths_.Empty())
  280. return true;
  281. // If there is any attempt to go to a parent directory, disallow
  282. if (fixedPath.Contains(".."))
  283. return false;
  284. // Check if the path is a partial match of any of the allowed directories
  285. for (HashSet<String>::ConstIterator i = allowedPaths_.Begin(); i != allowedPaths_.End(); ++i)
  286. {
  287. if (fixedPath.Find(*i) == 0)
  288. return true;
  289. }
  290. // Not found, so disallow
  291. return false;
  292. }
  293. unsigned FileSystem::GetLastModifiedTime(const String& fileName) const
  294. {
  295. if (fileName.Empty() || !CheckAccess(fileName))
  296. return 0;
  297. #ifdef WIN32
  298. WIN32_FILE_ATTRIBUTE_DATA fileAttrData;
  299. memset(&fileAttrData, 0, sizeof fileAttrData);
  300. if (GetFileAttributesExW(WString(fileName).CString(), GetFileExInfoStandard, &fileAttrData))
  301. {
  302. ULARGE_INTEGER ull;
  303. ull.LowPart = fileAttrData.ftLastWriteTime.dwLowDateTime;
  304. ull.HighPart = fileAttrData.ftLastWriteTime.dwHighDateTime;
  305. return (unsigned)(ull.QuadPart / 10000000ULL - 11644473600ULL);
  306. }
  307. else
  308. return 0;
  309. #else
  310. struct stat st;
  311. if (!stat(fileName.CString(), &st))
  312. return (unsigned)st.st_mtime;
  313. else
  314. return 0;
  315. #endif
  316. }
  317. bool FileSystem::FileExists(const String& fileName) const
  318. {
  319. if (!CheckAccess(GetPath(fileName)))
  320. return false;
  321. String fixedName = GetNativePath(RemoveTrailingSlash(fileName));
  322. #ifdef ANDROID
  323. if (fixedName.StartsWith("/apk/"))
  324. {
  325. SDL_RWops* rwOps = SDL_RWFromFile(fileName.Substring(5).CString(), "rb");
  326. if (rwOps)
  327. {
  328. SDL_RWclose(rwOps);
  329. return true;
  330. }
  331. else
  332. return false;
  333. }
  334. #endif
  335. #ifdef WIN32
  336. DWORD attributes = GetFileAttributesW(WString(fixedName).CString());
  337. if (attributes == INVALID_FILE_ATTRIBUTES || attributes & FILE_ATTRIBUTE_DIRECTORY)
  338. return false;
  339. #else
  340. struct stat st;
  341. if (stat(fixedName.CString(), &st) || st.st_mode & S_IFDIR)
  342. return false;
  343. #endif
  344. return true;
  345. }
  346. bool FileSystem::DirExists(const String& pathName) const
  347. {
  348. if (!CheckAccess(pathName))
  349. return false;
  350. #ifndef WIN32
  351. // Always return true for the root directory
  352. if (pathName == "/")
  353. return true;
  354. #endif
  355. String fixedName = GetNativePath(RemoveTrailingSlash(pathName));
  356. #ifdef ANDROID
  357. /// \todo Actually check for existence, now true is always returned for directories within the APK
  358. if (fixedName.StartsWith("/apk/"))
  359. return true;
  360. #endif
  361. #ifdef WIN32
  362. DWORD attributes = GetFileAttributesW(WString(fixedName).CString());
  363. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY))
  364. return false;
  365. #else
  366. struct stat st;
  367. if (stat(fixedName.CString(), &st) || !(st.st_mode & S_IFDIR))
  368. return false;
  369. #endif
  370. return true;
  371. }
  372. void FileSystem::ScanDir(Vector<String>& result, const String& pathName, const String& filter, unsigned flags, bool recursive) const
  373. {
  374. result.Clear();
  375. if (CheckAccess(pathName))
  376. {
  377. String initialPath = AddTrailingSlash(pathName);
  378. ScanDirInternal(result, initialPath, initialPath, filter, flags, recursive);
  379. }
  380. }
  381. String FileSystem::GetProgramDir() const
  382. {
  383. #if defined(ANDROID)
  384. // This is an internal directory specifier pointing to the assets in the .apk
  385. // Files from this directory will be opened using special handling
  386. return "/apk/";
  387. #elif defined(IOS)
  388. return AddTrailingSlash(SDL_IOS_GetResourceDir());
  389. #elif defined(WIN32)
  390. wchar_t exeName[MAX_PATH];
  391. exeName[0] = 0;
  392. GetModuleFileNameW(0, exeName, MAX_PATH);
  393. return GetPath(String(exeName));
  394. #elif defined(__APPLE__)
  395. char exeName[MAX_PATH];
  396. memset(exeName, 0, MAX_PATH);
  397. unsigned size = MAX_PATH;
  398. _NSGetExecutablePath(exeName, &size);
  399. return GetPath(String(exeName));
  400. #elif defined(__linux__)
  401. char exeName[MAX_PATH];
  402. memset(exeName, 0, MAX_PATH);
  403. pid_t pid = getpid();
  404. String link = "/proc/" + String(pid) + "/exe";
  405. readlink(link.CString(), exeName, MAX_PATH);
  406. return GetPath(String(exeName));
  407. #else
  408. return String();
  409. #endif
  410. }
  411. String FileSystem::GetUserDocumentsDir() const
  412. {
  413. #if defined(ANDROID)
  414. return AddTrailingSlash(SDL_Android_GetFilesDir());
  415. #elif defined(IOS)
  416. return AddTrailingSlash(SDL_IOS_GetResourceDir());
  417. #elif defined(WIN32)
  418. wchar_t pathName[MAX_PATH];
  419. pathName[0] = 0;
  420. SHGetSpecialFolderPathW(0, pathName, CSIDL_PERSONAL, 0);
  421. return AddTrailingSlash(String(pathName));
  422. #else
  423. char pathName[MAX_PATH];
  424. pathName[0] = 0;
  425. strcpy(pathName, getenv("HOME"));
  426. return AddTrailingSlash(String(pathName));
  427. #endif
  428. }
  429. void FileSystem::RegisterPath(const String& pathName)
  430. {
  431. if (pathName.Empty())
  432. return;
  433. allowedPaths_.Insert(AddTrailingSlash(pathName));
  434. }
  435. void FileSystem::ScanDirInternal(Vector<String>& result, String path, const String& startPath,
  436. const String& filter, unsigned flags, bool recursive) const
  437. {
  438. path = AddTrailingSlash(path);
  439. String deltaPath;
  440. if (path.Length() > startPath.Length())
  441. deltaPath = path.Substring(startPath.Length());
  442. String filterExtension = filter.Substring(filter.Find('.'));
  443. if (filterExtension.Contains('*'))
  444. filterExtension.Clear();
  445. #ifdef WIN32
  446. WIN32_FIND_DATAW info;
  447. HANDLE handle = FindFirstFileW(WString(path + "*").CString(), &info);
  448. if (handle != INVALID_HANDLE_VALUE)
  449. {
  450. do
  451. {
  452. String fileName(info.cFileName);
  453. if (!fileName.Empty())
  454. {
  455. if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN && !(flags & SCAN_HIDDEN))
  456. continue;
  457. if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  458. {
  459. if (flags & SCAN_DIRS)
  460. result.Push(deltaPath + fileName);
  461. if (recursive && fileName != "." && fileName != "..")
  462. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  463. }
  464. else if (flags & SCAN_FILES)
  465. {
  466. if (filterExtension.Empty() || fileName.EndsWith(filterExtension))
  467. result.Push(deltaPath + fileName);
  468. }
  469. }
  470. }
  471. while (FindNextFileW(handle, &info));
  472. FindClose(handle);
  473. }
  474. #else
  475. DIR *dir;
  476. struct dirent *de;
  477. struct stat st;
  478. dir = opendir(GetNativePath(path).CString());
  479. if (dir)
  480. {
  481. while ((de = readdir(dir)))
  482. {
  483. /// \todo Filename may be unnormalized Unicode on Mac OS X. Re-normalize as necessary
  484. String fileName(de->d_name);
  485. bool normalEntry = fileName != "." && fileName != "..";
  486. if (normalEntry && !(flags & SCAN_HIDDEN) && fileName.StartsWith("."))
  487. continue;
  488. String pathAndName = path + fileName;
  489. if (!stat(pathAndName.CString(), &st))
  490. {
  491. if (st.st_mode & S_IFDIR)
  492. {
  493. if (flags & SCAN_DIRS)
  494. result.Push(deltaPath + fileName);
  495. if (recursive && normalEntry)
  496. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  497. }
  498. else if (flags & SCAN_FILES)
  499. {
  500. if (filterExtension.Empty() || fileName.EndsWith(filterExtension))
  501. result.Push(deltaPath + fileName);
  502. }
  503. }
  504. }
  505. closedir(dir);
  506. }
  507. #endif
  508. }
  509. void SplitPath(const String& fullPath, String& pathName, String& fileName, String& extension)
  510. {
  511. String fullPathCopy = GetInternalPath(fullPath);
  512. unsigned extPos = fullPathCopy.FindLast('.');
  513. unsigned pathPos = fullPathCopy.FindLast('/');
  514. if (extPos != String::NPOS && (pathPos == String::NPOS || extPos > pathPos))
  515. {
  516. extension = fullPathCopy.Substring(extPos).ToLower();
  517. fullPathCopy = fullPathCopy.Substring(0, extPos);
  518. }
  519. else
  520. extension.Clear();
  521. pathPos = fullPathCopy.FindLast('/');
  522. if (pathPos != String::NPOS)
  523. {
  524. fileName = fullPathCopy.Substring(pathPos + 1);
  525. pathName = fullPathCopy.Substring(0, pathPos + 1);
  526. }
  527. else
  528. {
  529. fileName = fullPathCopy;
  530. pathName.Clear();
  531. }
  532. }
  533. String GetPath(const String& fullPath)
  534. {
  535. String path, file, extension;
  536. SplitPath(fullPath, path, file, extension);
  537. return path;
  538. }
  539. String GetFileName(const String& fullPath)
  540. {
  541. String path, file, extension;
  542. SplitPath(fullPath, path, file, extension);
  543. return file;
  544. }
  545. String GetExtension(const String& fullPath)
  546. {
  547. String path, file, extension;
  548. SplitPath(fullPath, path, file, extension);
  549. return extension;
  550. }
  551. String GetFileNameAndExtension(const String& fileName)
  552. {
  553. String path, file, extension;
  554. SplitPath(fileName, path, file, extension);
  555. return file + extension;
  556. }
  557. String ReplaceExtension(const String& fullPath, const String& newExtension)
  558. {
  559. String path, file, extension;
  560. SplitPath(fullPath, path, file, extension);
  561. return path + file + newExtension;
  562. }
  563. String AddTrailingSlash(const String& pathName)
  564. {
  565. String ret = pathName;
  566. ret.Replace('\\', '/');
  567. if (!ret.Empty() && ret.Back() != '/')
  568. ret += '/';
  569. return ret;
  570. }
  571. String RemoveTrailingSlash(const String& pathName)
  572. {
  573. String ret = pathName;
  574. ret.Replace('\\', '/');
  575. if (!ret.Empty() && ret.Back() == '/')
  576. ret.Resize(ret.Length() - 1);
  577. return ret;
  578. }
  579. String GetParentPath(const String& path)
  580. {
  581. unsigned pos = RemoveTrailingSlash(path).FindLast('/');
  582. if (pos != String::NPOS)
  583. return path.Substring(0, pos + 1);
  584. else
  585. return String();
  586. }
  587. String GetInternalPath(const String& pathName)
  588. {
  589. return pathName.Replaced('\\', '/');
  590. }
  591. String GetNativePath(const String& pathName)
  592. {
  593. #ifdef WIN32
  594. return pathName.Replaced('/', '\\');
  595. #else
  596. return pathName;
  597. #endif
  598. }
  599. WString GetWideNativePath(const String& pathName)
  600. {
  601. #ifdef WIN32
  602. return WString(pathName.Replaced('/', '\\'));
  603. #else
  604. return WString(pathName);
  605. #endif
  606. }
  607. }