FileSystem.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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(WString(GetNativePath(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(WString(GetNativePath(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. WString(GetNativePath(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. return rename(GetNativePath(srcFileName).CString(), GetNativePath(destFileName).CString()) == 0;
  213. }
  214. bool FileSystem::Delete(const String& fileName)
  215. {
  216. if (!CheckAccess(GetPath(fileName)))
  217. {
  218. LOGERROR("Access denied to " + fileName);
  219. return false;
  220. }
  221. return remove(GetNativePath(fileName).CString()) == 0;
  222. }
  223. String FileSystem::GetCurrentDir()
  224. {
  225. #ifdef WIN32
  226. wchar_t path[MAX_PATH];
  227. path[0] = 0;
  228. GetCurrentDirectoryW(MAX_PATH, path);
  229. return AddTrailingSlash(String(path));
  230. #else
  231. char path[MAX_PATH];
  232. path[0] = 0;
  233. getcwd(path, MAX_PATH);
  234. return AddTrailingSlash(String(path));
  235. #endif
  236. }
  237. bool FileSystem::CheckAccess(const String& pathName)
  238. {
  239. String fixedPath = AddTrailingSlash(pathName);
  240. // If no allowed directories defined, succeed always
  241. if (allowedPaths_.Empty())
  242. return true;
  243. // If there is any attempt to go to a parent directory, disallow
  244. if (fixedPath.Find("..") != String::NPOS)
  245. return false;
  246. // Check if the path is a partial match of any of the allowed directories
  247. for (Set<String>::ConstIterator i = allowedPaths_.Begin(); i != allowedPaths_.End(); ++i)
  248. {
  249. if (fixedPath.Find(*i) == 0)
  250. return true;
  251. }
  252. // Not found, so disallow
  253. return false;
  254. }
  255. bool FileSystem::FileExists(const String& fileName)
  256. {
  257. if (!CheckAccess(GetPath(fileName)))
  258. return false;
  259. String fixedName = GetNativePath(RemoveTrailingSlash(fileName));
  260. #ifdef WIN32
  261. DWORD attributes = GetFileAttributesW(WString(fixedName).CString());
  262. if (attributes == INVALID_FILE_ATTRIBUTES || attributes & FILE_ATTRIBUTE_DIRECTORY)
  263. return false;
  264. #else
  265. struct stat st;
  266. if (stat(fixedName.CString(), &st) || st.st_mode & S_IFDIR)
  267. return false;
  268. #endif
  269. return true;
  270. }
  271. bool FileSystem::DirExists(const String& pathName)
  272. {
  273. if (!CheckAccess(pathName))
  274. return false;
  275. String fixedName = GetNativePath(RemoveTrailingSlash(pathName));
  276. #ifdef WIN32
  277. DWORD attributes = GetFileAttributes(WString(fixedName).CString());
  278. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY))
  279. return false;
  280. #else
  281. struct stat st;
  282. if (stat(fixedName.CString(), &st) || !(st.st_mode & S_IFDIR))
  283. return false;
  284. #endif
  285. return true;
  286. }
  287. void FileSystem::ScanDir(Vector<String>& result, const String& pathName, const String& filter, unsigned flags, bool recursive)
  288. {
  289. result.Clear();
  290. if (CheckAccess(pathName))
  291. {
  292. String initialPath = AddTrailingSlash(pathName);
  293. ScanDirInternal(result, initialPath, initialPath, filter, flags, recursive);
  294. }
  295. }
  296. String FileSystem::GetProgramDir()
  297. {
  298. #ifdef WIN32
  299. wchar_t exeName[MAX_PATH];
  300. exeName[0] = 0;
  301. GetModuleFileNameW(0, exeName, MAX_PATH);
  302. return GetPath(String(exeName));
  303. #endif
  304. #ifdef __APPLE__
  305. char exeName[MAX_PATH];
  306. memset(exeName, 0, MAX_PATH);
  307. unsigned size = MAX_PATH;
  308. _NSGetExecutablePath(exeName, &size);
  309. return GetPath(String(exeName));
  310. #endif
  311. #ifdef __linux__
  312. char exeName[MAX_PATH];
  313. memset(exeName, 0, MAX_PATH);
  314. pid_t pid = getpid();
  315. String link = "/proc/" + String(pid) + "/exe";
  316. readlink(link.CString(), exeName, MAX_PATH);
  317. return GetPath(String(exeName));
  318. #endif
  319. }
  320. String FileSystem::GetUserDocumentsDir()
  321. {
  322. #ifdef WIN32
  323. wchar_t pathName[MAX_PATH];
  324. pathName[0] = 0;
  325. SHGetSpecialFolderPathW(0, pathName, CSIDL_PERSONAL, 0);
  326. return AddTrailingSlash(String(pathName));
  327. #else
  328. char pathName[MAX_PATH];
  329. pathName[0] = 0;
  330. strcpy(pathName, getenv("HOME"));
  331. return AddTrailingSlash(String(pathName));
  332. #endif
  333. }
  334. void FileSystem::RegisterPath(const String& pathName)
  335. {
  336. if (pathName.Empty())
  337. return;
  338. allowedPaths_.Insert(AddTrailingSlash(pathName));
  339. }
  340. void FileSystem::ScanDirInternal(Vector<String>& result, String path, const String& startPath,
  341. const String& filter, unsigned flags, bool recursive)
  342. {
  343. path = AddTrailingSlash(path);
  344. String deltaPath;
  345. if (path.Length() > startPath.Length())
  346. deltaPath = path.Substring(startPath.Length());
  347. #ifdef WIN32
  348. String pathAndFilter = GetNativePath(path + filter);
  349. WIN32_FIND_DATA info;
  350. HANDLE handle = FindFirstFileW(WString(pathAndFilter).CString(), &info);
  351. if (handle != INVALID_HANDLE_VALUE)
  352. {
  353. do
  354. {
  355. String fileName((const char*)&info.cFileName[0]);
  356. if (!fileName.Empty())
  357. {
  358. if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN && !(flags & SCAN_HIDDEN))
  359. continue;
  360. if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  361. {
  362. if (flags & SCAN_DIRS)
  363. result.Push(deltaPath + fileName);
  364. if (recursive && fileName != "." && fileName != "..")
  365. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  366. }
  367. else if (flags & SCAN_FILES)
  368. result.Push(deltaPath + fileName);
  369. }
  370. }
  371. while (FindNextFile(handle, &info));
  372. FindClose(handle);
  373. }
  374. #else
  375. String filterExtension = filter.Substring(filter.Find('.'));
  376. if (filterExtension.Find('*') != String::NPOS)
  377. filterExtension.Clear();
  378. DIR *dir;
  379. struct dirent *de;
  380. struct stat st;
  381. dir = opendir(GetNativePath(path).CString());
  382. if (dir)
  383. {
  384. while (de = readdir(dir))
  385. {
  386. String fileName(de->d_name);
  387. String pathAndName = path + fileName;
  388. if (!stat(pathAndName.CString(), &st))
  389. {
  390. if (st.st_mode & S_IFDIR)
  391. {
  392. if (flags & SCAN_DIRS)
  393. result.Push(deltaPath + fileName);
  394. if (recursive && fileName != "." && fileName != "..")
  395. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  396. }
  397. else if (flags & SCAN_FILES)
  398. {
  399. if (filterExtension.Empty() || fileName.EndsWith(filterExtension))
  400. result.Push(deltaPath + fileName);
  401. }
  402. }
  403. }
  404. closedir(dir);
  405. }
  406. #endif
  407. }
  408. void SplitPath(const String& fullPath, String& pathName, String& fileName, String& extension)
  409. {
  410. String fullPathCopy = GetInternalPath(fullPath);
  411. unsigned extPos = fullPathCopy.FindLast('.');
  412. unsigned pathPos = fullPathCopy.FindLast('/');
  413. if (extPos != String::NPOS && (pathPos == String::NPOS || extPos > pathPos))
  414. {
  415. extension = fullPathCopy.Substring(extPos).ToLower();
  416. fullPathCopy = fullPathCopy.Substring(0, extPos);
  417. }
  418. else
  419. extension.Clear();
  420. pathPos = fullPathCopy.FindLast('/');
  421. if (pathPos != String::NPOS)
  422. {
  423. fileName = fullPathCopy.Substring(pathPos + 1);
  424. pathName = fullPathCopy.Substring(0, pathPos + 1);
  425. }
  426. else
  427. {
  428. fileName = fullPathCopy;
  429. pathName.Clear();
  430. }
  431. }
  432. String GetPath(const String& fullPath)
  433. {
  434. String path, file, extension;
  435. SplitPath(fullPath, path, file, extension);
  436. return path;
  437. }
  438. String GetFileName(const String& fullPath)
  439. {
  440. String path, file, extension;
  441. SplitPath(fullPath, path, file, extension);
  442. return file;
  443. }
  444. String GetExtension(const String& fullPath)
  445. {
  446. String path, file, extension;
  447. SplitPath(fullPath, path, file, extension);
  448. return extension;
  449. }
  450. String GetFileNameAndExtension(const String& fileName)
  451. {
  452. String path, file, extension;
  453. SplitPath(fileName, path, file, extension);
  454. return file + extension;
  455. }
  456. String AddTrailingSlash(const String& pathName)
  457. {
  458. String ret = pathName;
  459. ret.Replace('\\', '/');
  460. if (!ret.Empty() && ret.Back() != '/')
  461. ret += '/';
  462. return ret;
  463. }
  464. String RemoveTrailingSlash(const String& pathName)
  465. {
  466. String ret = pathName;
  467. ret.Replace('\\', '/');
  468. if (!ret.Empty() && ret.Back() == '/')
  469. ret.Resize(ret.Length() - 1);
  470. return ret;
  471. }
  472. String GetParentPath(const String& path)
  473. {
  474. unsigned pos = RemoveTrailingSlash(path).FindLast('/');
  475. if (pos != String::NPOS)
  476. return path.Substring(0, pos + 1);
  477. else
  478. return String();
  479. }
  480. String GetInternalPath(const String& pathName)
  481. {
  482. return pathName.Replaced('\\', '/');
  483. }
  484. String GetNativePath(const String& pathName)
  485. {
  486. #ifdef WIN32
  487. return pathName.Replaced('/', '\\');
  488. #else
  489. return pathName;
  490. #endif
  491. }