FileSystem.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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 (Set<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. #ifdef WIN32
  307. wchar_t exeName[MAX_PATH];
  308. exeName[0] = 0;
  309. GetModuleFileNameW(0, exeName, MAX_PATH);
  310. return GetPath(String(exeName));
  311. #endif
  312. #ifdef __APPLE__
  313. char exeName[MAX_PATH];
  314. memset(exeName, 0, MAX_PATH);
  315. unsigned size = MAX_PATH;
  316. _NSGetExecutablePath(exeName, &size);
  317. return GetPath(String(exeName));
  318. #endif
  319. #ifdef __linux__
  320. char exeName[MAX_PATH];
  321. memset(exeName, 0, MAX_PATH);
  322. pid_t pid = getpid();
  323. String link = "/proc/" + String(pid) + "/exe";
  324. readlink(link.CString(), exeName, MAX_PATH);
  325. return GetPath(String(exeName));
  326. #endif
  327. }
  328. String FileSystem::GetUserDocumentsDir()
  329. {
  330. #ifdef WIN32
  331. wchar_t pathName[MAX_PATH];
  332. pathName[0] = 0;
  333. SHGetSpecialFolderPathW(0, pathName, CSIDL_PERSONAL, 0);
  334. return AddTrailingSlash(String(pathName));
  335. #else
  336. char pathName[MAX_PATH];
  337. pathName[0] = 0;
  338. strcpy(pathName, getenv("HOME"));
  339. return AddTrailingSlash(String(pathName));
  340. #endif
  341. }
  342. void FileSystem::RegisterPath(const String& pathName)
  343. {
  344. if (pathName.Empty())
  345. return;
  346. allowedPaths_.Insert(AddTrailingSlash(pathName));
  347. }
  348. void FileSystem::ScanDirInternal(Vector<String>& result, String path, const String& startPath,
  349. const String& filter, unsigned flags, bool recursive)
  350. {
  351. path = AddTrailingSlash(path);
  352. String deltaPath;
  353. if (path.Length() > startPath.Length())
  354. deltaPath = path.Substring(startPath.Length());
  355. #ifdef WIN32
  356. String pathAndFilter = GetNativePath(path + filter);
  357. WIN32_FIND_DATAW info;
  358. HANDLE handle = FindFirstFileW(WString(pathAndFilter).CString(), &info);
  359. if (handle != INVALID_HANDLE_VALUE)
  360. {
  361. do
  362. {
  363. String fileName(info.cFileName);
  364. if (!fileName.Empty())
  365. {
  366. if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN && !(flags & SCAN_HIDDEN))
  367. continue;
  368. if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  369. {
  370. if (flags & SCAN_DIRS)
  371. result.Push(deltaPath + fileName);
  372. if (recursive && fileName != "." && fileName != "..")
  373. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  374. }
  375. else if (flags & SCAN_FILES)
  376. result.Push(deltaPath + fileName);
  377. }
  378. }
  379. while (FindNextFileW(handle, &info));
  380. FindClose(handle);
  381. }
  382. #else
  383. String filterExtension = filter.Substring(filter.Find('.'));
  384. if (filterExtension.Find('*') != String::NPOS)
  385. filterExtension.Clear();
  386. DIR *dir;
  387. struct dirent *de;
  388. struct stat st;
  389. dir = opendir(GetNativePath(path).CString());
  390. if (dir)
  391. {
  392. while (de = readdir(dir))
  393. {
  394. /// \todo Filename may be unnormalized Unicode on Mac OS X. Re-normalize as necessary
  395. String fileName(de->d_name);
  396. String pathAndName = path + fileName;
  397. if (!stat(pathAndName.CString(), &st))
  398. {
  399. if (st.st_mode & S_IFDIR)
  400. {
  401. if (flags & SCAN_DIRS)
  402. result.Push(deltaPath + fileName);
  403. if (recursive && fileName != "." && fileName != "..")
  404. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  405. }
  406. else if (flags & SCAN_FILES)
  407. {
  408. if (filterExtension.Empty() || fileName.EndsWith(filterExtension))
  409. result.Push(deltaPath + fileName);
  410. }
  411. }
  412. }
  413. closedir(dir);
  414. }
  415. #endif
  416. }
  417. void SplitPath(const String& fullPath, String& pathName, String& fileName, String& extension)
  418. {
  419. String fullPathCopy = GetInternalPath(fullPath);
  420. unsigned extPos = fullPathCopy.FindLast('.');
  421. unsigned pathPos = fullPathCopy.FindLast('/');
  422. if (extPos != String::NPOS && (pathPos == String::NPOS || extPos > pathPos))
  423. {
  424. extension = fullPathCopy.Substring(extPos).ToLower();
  425. fullPathCopy = fullPathCopy.Substring(0, extPos);
  426. }
  427. else
  428. extension.Clear();
  429. pathPos = fullPathCopy.FindLast('/');
  430. if (pathPos != String::NPOS)
  431. {
  432. fileName = fullPathCopy.Substring(pathPos + 1);
  433. pathName = fullPathCopy.Substring(0, pathPos + 1);
  434. }
  435. else
  436. {
  437. fileName = fullPathCopy;
  438. pathName.Clear();
  439. }
  440. }
  441. String GetPath(const String& fullPath)
  442. {
  443. String path, file, extension;
  444. SplitPath(fullPath, path, file, extension);
  445. return path;
  446. }
  447. String GetFileName(const String& fullPath)
  448. {
  449. String path, file, extension;
  450. SplitPath(fullPath, path, file, extension);
  451. return file;
  452. }
  453. String GetExtension(const String& fullPath)
  454. {
  455. String path, file, extension;
  456. SplitPath(fullPath, path, file, extension);
  457. return extension;
  458. }
  459. String GetFileNameAndExtension(const String& fileName)
  460. {
  461. String path, file, extension;
  462. SplitPath(fileName, path, file, extension);
  463. return file + extension;
  464. }
  465. String AddTrailingSlash(const String& pathName)
  466. {
  467. String ret = pathName;
  468. ret.Replace('\\', '/');
  469. if (!ret.Empty() && ret.Back() != '/')
  470. ret += '/';
  471. return ret;
  472. }
  473. String RemoveTrailingSlash(const String& pathName)
  474. {
  475. String ret = pathName;
  476. ret.Replace('\\', '/');
  477. if (!ret.Empty() && ret.Back() == '/')
  478. ret.Resize(ret.Length() - 1);
  479. return ret;
  480. }
  481. String GetParentPath(const String& path)
  482. {
  483. unsigned pos = RemoveTrailingSlash(path).FindLast('/');
  484. if (pos != String::NPOS)
  485. return path.Substring(0, pos + 1);
  486. else
  487. return String();
  488. }
  489. String GetInternalPath(const String& pathName)
  490. {
  491. return pathName.Replaced('\\', '/');
  492. }
  493. String GetNativePath(const String& pathName)
  494. {
  495. #ifdef WIN32
  496. return pathName.Replaced('/', '\\');
  497. #else
  498. return pathName;
  499. #endif
  500. }
  501. WString GetWideNativePath(const String& pathName)
  502. {
  503. #ifdef WIN32
  504. return WString(pathName.Replaced('/', '\\'));
  505. #else
  506. return WString(pathName);
  507. #endif
  508. }