FileSystem.cpp 15 KB

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