FileSystem.cpp 15 KB

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