FileSystem.cpp 19 KB

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