FileSystem.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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. #include <windows.h>
  33. #include <shellapi.h>
  34. #include <direct.h>
  35. #include <process.h>
  36. #include <shlobj.h>
  37. #else
  38. #include <dirent.h>
  39. #include <errno.h>
  40. #include <unistd.h>
  41. #include <sys/stat.h>
  42. #include <sys/wait.h>
  43. #define MAX_PATH 256
  44. #endif
  45. #if defined(__APPLE__)
  46. #include <mach-o/dyld.h>
  47. #endif
  48. #ifdef ANDROID
  49. extern "C" const char* SDL_Android_GetFilesDir();
  50. #endif
  51. #ifdef IOS
  52. extern "C" const char* SDL_IOS_GetResourceDir();
  53. #endif
  54. #include "DebugNew.h"
  55. OBJECTTYPESTATIC(FileSystem);
  56. FileSystem::FileSystem(Context* context) :
  57. Object(context)
  58. {
  59. }
  60. FileSystem::~FileSystem()
  61. {
  62. }
  63. bool FileSystem::SetCurrentDir(const String& pathName)
  64. {
  65. if (!CheckAccess(pathName))
  66. {
  67. LOGERROR("Access denied to " + pathName);
  68. return false;
  69. }
  70. #ifdef WIN32
  71. if (SetCurrentDirectoryW(GetWideNativePath(pathName).CString()) == FALSE)
  72. {
  73. LOGERROR("Failed to change directory to " + pathName);
  74. return false;
  75. }
  76. #else
  77. if (chdir(GetNativePath(pathName).CString()) != 0)
  78. {
  79. LOGERROR("Failed to change directory to " + pathName);
  80. return false;
  81. }
  82. #endif
  83. return true;
  84. }
  85. bool FileSystem::CreateDir(const String& pathName)
  86. {
  87. if (!CheckAccess(pathName))
  88. {
  89. LOGERROR("Access denied to " + pathName);
  90. return false;
  91. }
  92. #ifdef WIN32
  93. bool success = (CreateDirectoryW(GetWideNativePath(RemoveTrailingSlash(pathName)).CString(), 0) == TRUE) ||
  94. (GetLastError() == ERROR_ALREADY_EXISTS);
  95. #else
  96. bool success = mkdir(GetNativePath(RemoveTrailingSlash(pathName)).CString(), S_IRWXU) == 0 || errno == EEXIST;
  97. #endif
  98. if (success)
  99. LOGDEBUG("Created directory " + pathName);
  100. else
  101. LOGERROR("Failed to create directory " + pathName);
  102. return success;
  103. }
  104. int FileSystem::SystemCommand(const String& commandLine)
  105. {
  106. if (allowedPaths_.Empty())
  107. return system(commandLine.CString());
  108. else
  109. {
  110. LOGERROR("Executing an external command is not allowed");
  111. return -1;
  112. }
  113. }
  114. int FileSystem::SystemRun(const String& fileName, const Vector<String>& arguments)
  115. {
  116. if (allowedPaths_.Empty())
  117. {
  118. String fixedFileName = GetNativePath(fileName);
  119. #ifdef WIN32
  120. PODVector<const char*> argPtrs;
  121. argPtrs.Push(fixedFileName.CString());
  122. for (unsigned i = 0; i < arguments.Size(); ++i)
  123. argPtrs.Push(arguments[i].CString());
  124. argPtrs.Push(0);
  125. return _spawnv(_P_WAIT, fixedFileName.CString(), &argPtrs[0]);
  126. #else
  127. pid_t pid = fork();
  128. if (!pid)
  129. {
  130. PODVector<const char*> argPtrs;
  131. argPtrs.Push(fixedFileName.CString());
  132. for (unsigned i = 0; i < arguments.Size(); ++i)
  133. argPtrs.Push(arguments[i].CString());
  134. argPtrs.Push(0);
  135. execvp(argPtrs[0], (char**)&argPtrs[0]);
  136. return -1; // Return -1 if we could not spawn the process
  137. }
  138. else if (pid > 0)
  139. {
  140. int exitCode;
  141. wait(&exitCode);
  142. return exitCode ? 1 : 0;
  143. }
  144. else
  145. {
  146. LOGERROR("Failed to fork");
  147. return -1;
  148. }
  149. #endif
  150. }
  151. else
  152. {
  153. LOGERROR("Executing an external command is not allowed");
  154. return -1;
  155. }
  156. }
  157. bool FileSystem::SystemOpen(const String& fileName, const String& mode)
  158. {
  159. #ifdef WIN32
  160. if (allowedPaths_.Empty())
  161. {
  162. if (!FileExists(fileName) && !DirExists(fileName))
  163. {
  164. LOGERROR("File or directory " + fileName + " not found");
  165. return false;
  166. }
  167. bool success = (int)ShellExecuteW(0, !mode.Empty() ? WString(mode).CString() : 0,
  168. GetWideNativePath(fileName).CString(), 0, 0, SW_SHOW) > 32;
  169. if (!success)
  170. LOGERROR("Failed to open " + fileName + " externally");
  171. return success;
  172. }
  173. else
  174. {
  175. LOGERROR("Opening a file externally is not allowed");
  176. return false;
  177. }
  178. #else
  179. /// \todo Implement on Unix-like systems
  180. LOGERROR("SystemOpen not implemented");
  181. return false;
  182. #endif
  183. }
  184. bool FileSystem::Copy(const String& srcFileName, const String& destFileName)
  185. {
  186. if (!CheckAccess(GetPath(srcFileName)))
  187. {
  188. LOGERROR("Access denied to " + srcFileName);
  189. return false;
  190. }
  191. if (!CheckAccess(GetPath(destFileName)))
  192. {
  193. LOGERROR("Access denied to " + destFileName);
  194. return false;
  195. }
  196. SharedPtr<File> srcFile(new File(context_, srcFileName, FILE_READ));
  197. SharedPtr<File> destFile(new File(context_, destFileName, FILE_WRITE));
  198. if (!srcFile->IsOpen() || !destFile->IsOpen())
  199. return false;
  200. unsigned fileSize = srcFile->GetSize();
  201. SharedArrayPtr<unsigned char> buffer(new unsigned char[fileSize]);
  202. unsigned bytesRead = srcFile->Read(buffer.Get(), fileSize);
  203. unsigned bytesWritten = destFile->Write(buffer.Get(), fileSize);
  204. return bytesRead == fileSize && bytesWritten == fileSize;
  205. }
  206. bool FileSystem::Rename(const String& srcFileName, const String& destFileName)
  207. {
  208. if (!CheckAccess(GetPath(srcFileName)))
  209. {
  210. LOGERROR("Access denied to " + srcFileName);
  211. return false;
  212. }
  213. if (!CheckAccess(GetPath(destFileName)))
  214. {
  215. LOGERROR("Access denied to " + destFileName);
  216. return false;
  217. }
  218. #ifdef WIN32
  219. return MoveFileW(GetWideNativePath(srcFileName).CString(), GetWideNativePath(destFileName).CString()) != 0;
  220. #else
  221. return rename(GetNativePath(srcFileName).CString(), GetNativePath(destFileName).CString()) == 0;
  222. #endif
  223. }
  224. bool FileSystem::Delete(const String& fileName)
  225. {
  226. if (!CheckAccess(GetPath(fileName)))
  227. {
  228. LOGERROR("Access denied to " + fileName);
  229. return false;
  230. }
  231. #ifdef WIN32
  232. return DeleteFileW(GetWideNativePath(fileName).CString()) != 0;
  233. #else
  234. return remove(GetNativePath(fileName).CString()) == 0;
  235. #endif
  236. }
  237. String FileSystem::GetCurrentDir()
  238. {
  239. #ifdef WIN32
  240. wchar_t path[MAX_PATH];
  241. path[0] = 0;
  242. GetCurrentDirectoryW(MAX_PATH, path);
  243. return AddTrailingSlash(String(path));
  244. #else
  245. char path[MAX_PATH];
  246. path[0] = 0;
  247. getcwd(path, MAX_PATH);
  248. return AddTrailingSlash(String(path));
  249. #endif
  250. }
  251. bool FileSystem::CheckAccess(const String& pathName)
  252. {
  253. String fixedPath = AddTrailingSlash(pathName);
  254. // If no allowed directories defined, succeed always
  255. if (allowedPaths_.Empty())
  256. return true;
  257. // If there is any attempt to go to a parent directory, disallow
  258. if (fixedPath.Find("..") != String::NPOS)
  259. return false;
  260. // Check if the path is a partial match of any of the allowed directories
  261. for (HashSet<String>::ConstIterator i = allowedPaths_.Begin(); i != allowedPaths_.End(); ++i)
  262. {
  263. if (fixedPath.Find(*i) == 0)
  264. return true;
  265. }
  266. // Not found, so disallow
  267. return false;
  268. }
  269. bool FileSystem::FileExists(const String& fileName)
  270. {
  271. if (!CheckAccess(GetPath(fileName)))
  272. return false;
  273. String fixedName = GetNativePath(RemoveTrailingSlash(fileName));
  274. #ifdef ANDROID
  275. if (fixedName.StartsWith("/apk/"))
  276. {
  277. SDL_RWops* rwOps = SDL_RWFromFile(fileName.Substring(5).CString(), "rb");
  278. if (rwOps)
  279. {
  280. SDL_RWclose(rwOps);
  281. return true;
  282. }
  283. else
  284. return false;
  285. }
  286. #endif
  287. #ifdef WIN32
  288. DWORD attributes = GetFileAttributesW(WString(fixedName).CString());
  289. if (attributes == INVALID_FILE_ATTRIBUTES || attributes & FILE_ATTRIBUTE_DIRECTORY)
  290. return false;
  291. #else
  292. struct stat st;
  293. if (stat(fixedName.CString(), &st) || st.st_mode & S_IFDIR)
  294. return false;
  295. #endif
  296. return true;
  297. }
  298. bool FileSystem::DirExists(const String& pathName)
  299. {
  300. if (!CheckAccess(pathName))
  301. return false;
  302. String fixedName = GetNativePath(RemoveTrailingSlash(pathName));
  303. #ifdef ANDROID
  304. /// \todo Actually check for existence, now true is always returned for directories within the APK
  305. if (fixedName.StartsWith("/apk/"))
  306. return true;
  307. #endif
  308. #ifdef WIN32
  309. DWORD attributes = GetFileAttributesW(WString(fixedName).CString());
  310. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY))
  311. return false;
  312. #else
  313. struct stat st;
  314. if (stat(fixedName.CString(), &st) || !(st.st_mode & S_IFDIR))
  315. return false;
  316. #endif
  317. return true;
  318. }
  319. void FileSystem::ScanDir(Vector<String>& result, const String& pathName, const String& filter, unsigned flags, bool recursive)
  320. {
  321. result.Clear();
  322. if (CheckAccess(pathName))
  323. {
  324. String initialPath = AddTrailingSlash(pathName);
  325. ScanDirInternal(result, initialPath, initialPath, filter, flags, recursive);
  326. }
  327. }
  328. String FileSystem::GetProgramDir()
  329. {
  330. #if defined(ANDROID)
  331. // This is an internal directory specifier pointing to the assets in the .apk
  332. // Files from this directory will be opened using special handling
  333. return "/apk/";
  334. #elif defined(IOS)
  335. return AddTrailingSlash(SDL_IOS_GetResourceDir());
  336. #elif defined(WIN32)
  337. wchar_t exeName[MAX_PATH];
  338. exeName[0] = 0;
  339. GetModuleFileNameW(0, exeName, MAX_PATH);
  340. return GetPath(String(exeName));
  341. #elif defined(__APPLE__)
  342. char exeName[MAX_PATH];
  343. memset(exeName, 0, MAX_PATH);
  344. unsigned size = MAX_PATH;
  345. _NSGetExecutablePath(exeName, &size);
  346. return GetPath(String(exeName));
  347. #elif defined(__linux__)
  348. char exeName[MAX_PATH];
  349. memset(exeName, 0, MAX_PATH);
  350. pid_t pid = getpid();
  351. String link = "/proc/" + String(pid) + "/exe";
  352. readlink(link.CString(), exeName, MAX_PATH);
  353. return GetPath(String(exeName));
  354. #else
  355. return String();
  356. #endif
  357. }
  358. String FileSystem::GetUserDocumentsDir()
  359. {
  360. #if defined(ANDROID)
  361. return AddTrailingSlash(SDL_Android_GetFilesDir());
  362. #elif defined(IOS)
  363. return AddTrailingSlash(SDL_IOS_GetResourceDir());
  364. #elif defined(WIN32)
  365. wchar_t pathName[MAX_PATH];
  366. pathName[0] = 0;
  367. SHGetSpecialFolderPathW(0, pathName, CSIDL_PERSONAL, 0);
  368. return AddTrailingSlash(String(pathName));
  369. #else
  370. char pathName[MAX_PATH];
  371. pathName[0] = 0;
  372. strcpy(pathName, getenv("HOME"));
  373. return AddTrailingSlash(String(pathName));
  374. #endif
  375. }
  376. void FileSystem::RegisterPath(const String& pathName)
  377. {
  378. if (pathName.Empty())
  379. return;
  380. allowedPaths_.Insert(AddTrailingSlash(pathName));
  381. }
  382. void FileSystem::ScanDirInternal(Vector<String>& result, String path, const String& startPath,
  383. const String& filter, unsigned flags, bool recursive)
  384. {
  385. path = AddTrailingSlash(path);
  386. String deltaPath;
  387. if (path.Length() > startPath.Length())
  388. deltaPath = path.Substring(startPath.Length());
  389. #ifdef WIN32
  390. String pathAndFilter = GetNativePath(path + filter);
  391. WIN32_FIND_DATAW info;
  392. HANDLE handle = FindFirstFileW(WString(pathAndFilter).CString(), &info);
  393. if (handle != INVALID_HANDLE_VALUE)
  394. {
  395. do
  396. {
  397. String fileName(info.cFileName);
  398. if (!fileName.Empty())
  399. {
  400. if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN && !(flags & SCAN_HIDDEN))
  401. continue;
  402. if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  403. {
  404. if (flags & SCAN_DIRS)
  405. result.Push(deltaPath + fileName);
  406. if (recursive && fileName != "." && fileName != "..")
  407. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  408. }
  409. else if (flags & SCAN_FILES)
  410. result.Push(deltaPath + fileName);
  411. }
  412. }
  413. while (FindNextFileW(handle, &info));
  414. FindClose(handle);
  415. }
  416. #else
  417. String filterExtension = filter.Substring(filter.Find('.'));
  418. if (filterExtension.Find('*') != String::NPOS)
  419. filterExtension.Clear();
  420. DIR *dir;
  421. struct dirent *de;
  422. struct stat st;
  423. dir = opendir(GetNativePath(path).CString());
  424. if (dir)
  425. {
  426. while (de = readdir(dir))
  427. {
  428. /// \todo Filename may be unnormalized Unicode on Mac OS X. Re-normalize as necessary
  429. String fileName(de->d_name);
  430. String pathAndName = path + fileName;
  431. if (!stat(pathAndName.CString(), &st))
  432. {
  433. if (st.st_mode & S_IFDIR)
  434. {
  435. if (flags & SCAN_DIRS)
  436. result.Push(deltaPath + fileName);
  437. if (recursive && fileName != "." && fileName != "..")
  438. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  439. }
  440. else if (flags & SCAN_FILES)
  441. {
  442. if (filterExtension.Empty() || fileName.EndsWith(filterExtension))
  443. result.Push(deltaPath + fileName);
  444. }
  445. }
  446. }
  447. closedir(dir);
  448. }
  449. #endif
  450. }
  451. void SplitPath(const String& fullPath, String& pathName, String& fileName, String& extension)
  452. {
  453. String fullPathCopy = GetInternalPath(fullPath);
  454. unsigned extPos = fullPathCopy.FindLast('.');
  455. unsigned pathPos = fullPathCopy.FindLast('/');
  456. if (extPos != String::NPOS && (pathPos == String::NPOS || extPos > pathPos))
  457. {
  458. extension = fullPathCopy.Substring(extPos).ToLower();
  459. fullPathCopy = fullPathCopy.Substring(0, extPos);
  460. }
  461. else
  462. extension.Clear();
  463. pathPos = fullPathCopy.FindLast('/');
  464. if (pathPos != String::NPOS)
  465. {
  466. fileName = fullPathCopy.Substring(pathPos + 1);
  467. pathName = fullPathCopy.Substring(0, pathPos + 1);
  468. }
  469. else
  470. {
  471. fileName = fullPathCopy;
  472. pathName.Clear();
  473. }
  474. }
  475. String GetPath(const String& fullPath)
  476. {
  477. String path, file, extension;
  478. SplitPath(fullPath, path, file, extension);
  479. return path;
  480. }
  481. String GetFileName(const String& fullPath)
  482. {
  483. String path, file, extension;
  484. SplitPath(fullPath, path, file, extension);
  485. return file;
  486. }
  487. String GetExtension(const String& fullPath)
  488. {
  489. String path, file, extension;
  490. SplitPath(fullPath, path, file, extension);
  491. return extension;
  492. }
  493. String GetFileNameAndExtension(const String& fileName)
  494. {
  495. String path, file, extension;
  496. SplitPath(fileName, path, file, extension);
  497. return file + extension;
  498. }
  499. String AddTrailingSlash(const String& pathName)
  500. {
  501. String ret = pathName;
  502. ret.Replace('\\', '/');
  503. if (!ret.Empty() && ret.Back() != '/')
  504. ret += '/';
  505. return ret;
  506. }
  507. String RemoveTrailingSlash(const String& pathName)
  508. {
  509. String ret = pathName;
  510. ret.Replace('\\', '/');
  511. if (!ret.Empty() && ret.Back() == '/')
  512. ret.Resize(ret.Length() - 1);
  513. return ret;
  514. }
  515. String GetParentPath(const String& path)
  516. {
  517. unsigned pos = RemoveTrailingSlash(path).FindLast('/');
  518. if (pos != String::NPOS)
  519. return path.Substring(0, pos + 1);
  520. else
  521. return String();
  522. }
  523. String GetInternalPath(const String& pathName)
  524. {
  525. return pathName.Replaced('\\', '/');
  526. }
  527. String GetNativePath(const String& pathName)
  528. {
  529. #ifdef WIN32
  530. return pathName.Replaced('/', '\\');
  531. #else
  532. return pathName;
  533. #endif
  534. }
  535. WString GetWideNativePath(const String& pathName)
  536. {
  537. #ifdef WIN32
  538. return WString(pathName.Replaced('/', '\\'));
  539. #else
  540. return WString(pathName);
  541. #endif
  542. }