FileSystem.cpp 17 KB

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