FileSystem.cpp 16 KB

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