FileSystem.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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 <direct.h>
  31. #include <process.h>
  32. #include <Windows.h>
  33. #include <shellapi.h>
  34. // Enable SHGetSpecialFolderPath on MinGW
  35. #ifndef _MSC_VER
  36. #define _WIN32_IE 0x0400
  37. #endif
  38. #include <shlobj.h>
  39. #include "DebugNew.h"
  40. OBJECTTYPESTATIC(FileSystem);
  41. FileSystem::FileSystem(Context* context) :
  42. Object(context)
  43. {
  44. }
  45. FileSystem::~FileSystem()
  46. {
  47. }
  48. bool FileSystem::SetCurrentDir(const String& pathName)
  49. {
  50. if (!CheckAccess(pathName))
  51. {
  52. LOGERROR("Access denied to " + pathName);
  53. return false;
  54. }
  55. if (SetCurrentDirectory(GetNativePath(pathName, true).CString()) == FALSE)
  56. {
  57. LOGERROR("Failed to change directory to " + pathName);
  58. return false;
  59. }
  60. return true;
  61. }
  62. bool FileSystem::CreateDir(const String& pathName)
  63. {
  64. if (!CheckAccess(pathName))
  65. {
  66. LOGERROR("Access denied to " + pathName);
  67. return false;
  68. }
  69. bool success = (CreateDirectory(GetNativePath(RemoveTrailingSlash(pathName), true).CString(), 0) == TRUE) || (GetLastError() == ERROR_ALREADY_EXISTS);
  70. if (success)
  71. LOGDEBUG("Created directory " + pathName);
  72. else
  73. LOGERROR("Failed to create directory " + pathName);
  74. return success;
  75. }
  76. int FileSystem::SystemCommand(const String& commandLine)
  77. {
  78. if (allowedPaths_.Empty())
  79. return system(commandLine.CString());
  80. else
  81. {
  82. LOGERROR("Executing an external command is not allowed");
  83. return -1;
  84. }
  85. }
  86. int FileSystem::SystemRun(const String& fileName, const Vector<String>& arguments)
  87. {
  88. if (allowedPaths_.Empty())
  89. {
  90. String fixedFileName = GetNativePath(fileName, true);
  91. PODVector<const char*> argPtrs;
  92. argPtrs.Push(fixedFileName.CString());
  93. for (unsigned i = 0; i < arguments.Size(); ++i)
  94. argPtrs.Push(arguments[i].CString());
  95. argPtrs.Push(0);
  96. return _spawnv(_P_WAIT, fixedFileName.CString(), &argPtrs[0]);
  97. }
  98. else
  99. {
  100. LOGERROR("Executing an external command is not allowed");
  101. return -1;
  102. }
  103. }
  104. bool FileSystem::SystemOpen(const String& fileName, const String& mode)
  105. {
  106. if (allowedPaths_.Empty())
  107. {
  108. if ((!FileExists(fileName)) && (!DirExists(fileName)))
  109. {
  110. LOGERROR("File or directory " + fileName + " not found");
  111. return false;
  112. }
  113. bool success = (int)ShellExecute(0, !mode.Empty() ? (char*)mode.CString() : 0,
  114. (char*)GetNativePath(fileName, true).CString(), 0, 0, SW_SHOW) > 32;
  115. if (!success)
  116. LOGERROR("Failed to open " + fileName + " externally");
  117. return success;
  118. }
  119. else
  120. {
  121. LOGERROR("Opening a file externally is not allowed");
  122. return false;
  123. }
  124. }
  125. bool FileSystem::Copy(const String& srcFileName, const String& destFileName)
  126. {
  127. if (!CheckAccess(GetPath(srcFileName)))
  128. {
  129. LOGERROR("Access denied to " + srcFileName);
  130. return false;
  131. }
  132. if (!CheckAccess(GetPath(destFileName)))
  133. {
  134. LOGERROR("Access denied to " + destFileName);
  135. return false;
  136. }
  137. SharedPtr<File> srcFile(new File(context_, srcFileName, FILE_READ));
  138. SharedPtr<File> destFile(new File(context_, destFileName, FILE_WRITE));
  139. if ((!srcFile->IsOpen()) || (!destFile->IsOpen()))
  140. return false;
  141. unsigned fileSize = srcFile->GetSize();
  142. SharedArrayPtr<unsigned char> buffer(new unsigned char[fileSize]);
  143. unsigned bytesRead = srcFile->Read(buffer.GetPtr(), fileSize);
  144. unsigned bytesWritten = destFile->Write(buffer.GetPtr(), fileSize);
  145. return (bytesRead == fileSize) && (bytesWritten == fileSize);
  146. }
  147. bool FileSystem::Rename(const String& srcFileName, const String& destFileName)
  148. {
  149. if (!CheckAccess(GetPath(srcFileName)))
  150. {
  151. LOGERROR("Access denied to " + srcFileName);
  152. return false;
  153. }
  154. if (!CheckAccess(GetPath(destFileName)))
  155. {
  156. LOGERROR("Access denied to " + destFileName);
  157. return false;
  158. }
  159. return rename(GetNativePath(srcFileName).CString(), GetNativePath(destFileName).CString()) == 0;
  160. }
  161. bool FileSystem::Delete(const String& fileName)
  162. {
  163. if (!CheckAccess(GetPath(fileName)))
  164. {
  165. LOGERROR("Access denied to " + fileName);
  166. return false;
  167. }
  168. return remove(GetNativePath(fileName).CString()) == 0;
  169. }
  170. String FileSystem::GetCurrentDir()
  171. {
  172. char path[MAX_PATH];
  173. GetCurrentDirectory(MAX_PATH, path);
  174. return AddTrailingSlash(String(path));
  175. }
  176. bool FileSystem::CheckAccess(const String& pathName)
  177. {
  178. String fixedPath = AddTrailingSlash(pathName);
  179. // If no allowed directories defined, succeed always
  180. if (allowedPaths_.Empty())
  181. return true;
  182. // If there is any attempt to go to a parent directory, disallow
  183. if (fixedPath.Find("..") != String::NPOS)
  184. return false;
  185. // Check if the path is a partial match of any of the allowed directories
  186. for (Set<String>::ConstIterator i = allowedPaths_.Begin(); i != allowedPaths_.End(); ++i)
  187. {
  188. if (fixedPath.Find(*i) == 0)
  189. return true;
  190. }
  191. // Not found, so disallow
  192. return false;
  193. }
  194. bool FileSystem::FileExists(const String& fileName)
  195. {
  196. if (!CheckAccess(GetPath(fileName)))
  197. return false;
  198. String fixedName = GetNativePath(RemoveTrailingSlash(fileName), true);
  199. DWORD attributes = GetFileAttributes(fixedName.CString());
  200. if ((attributes == INVALID_FILE_ATTRIBUTES) || (attributes & FILE_ATTRIBUTE_DIRECTORY))
  201. return false;
  202. return true;
  203. }
  204. bool FileSystem::DirExists(const String& pathName)
  205. {
  206. if (!CheckAccess(pathName))
  207. return false;
  208. String fixedName = GetNativePath(RemoveTrailingSlash(pathName), true);
  209. DWORD attributes = GetFileAttributes(fixedName.CString());
  210. if ((attributes == INVALID_FILE_ATTRIBUTES) || (!(attributes & FILE_ATTRIBUTE_DIRECTORY)))
  211. return false;
  212. return true;
  213. }
  214. void FileSystem::ScanDir(Vector<String>& result, const String& pathName, const String& filter, unsigned flags, bool recursive)
  215. {
  216. result.Clear();
  217. if (CheckAccess(pathName))
  218. {
  219. String initialPath = AddTrailingSlash(pathName);
  220. ScanDirInternal(result, initialPath, initialPath, filter, flags, recursive);
  221. }
  222. }
  223. String FileSystem::GetProgramDir()
  224. {
  225. char exeName[MAX_PATH];
  226. exeName[0] = 0;
  227. GetModuleFileName(0, exeName, MAX_PATH);
  228. return GetPath(String(exeName));
  229. }
  230. String FileSystem::GetUserDocumentsDir()
  231. {
  232. char pathName[MAX_PATH];
  233. pathName[0] = 0;
  234. SHGetSpecialFolderPath(0, pathName, CSIDL_PERSONAL, 0);
  235. return AddTrailingSlash(String(pathName));
  236. }
  237. String FileSystem::GetSystemFontDir()
  238. {
  239. char pathName[MAX_PATH];
  240. if (!ExpandEnvironmentStrings("%WinDir%", pathName, MAX_PATH))
  241. return String();
  242. return AddTrailingSlash(String(pathName)) + "Fonts";
  243. }
  244. void FileSystem::RegisterPath(const String& pathName)
  245. {
  246. if (pathName.Empty())
  247. return;
  248. allowedPaths_.Insert(AddTrailingSlash(pathName));
  249. }
  250. void FileSystem::ScanDirInternal(Vector<String>& result, String path, const String& startPath,
  251. const String& filter, unsigned flags, bool recursive)
  252. {
  253. path = AddTrailingSlash(path);
  254. String pathAndFilter = GetNativePath(path + filter, true);
  255. String deltaPath;
  256. if (path.Length() > startPath.Length())
  257. deltaPath = path.Substring(startPath.Length());
  258. WIN32_FIND_DATA info;
  259. HANDLE handle = FindFirstFile(pathAndFilter.CString(), &info);
  260. if (handle != INVALID_HANDLE_VALUE)
  261. {
  262. do
  263. {
  264. String fileName((const char*)&info.cFileName[0]);
  265. if (!fileName.Empty())
  266. {
  267. if ((info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) && (!(flags & SCAN_HIDDEN)))
  268. continue;
  269. if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  270. {
  271. if (flags & SCAN_DIRS)
  272. result.Push(deltaPath + fileName);
  273. if ((recursive) && (fileName != ".") && (fileName != ".."))
  274. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  275. }
  276. else if (flags & SCAN_FILES)
  277. result.Push(deltaPath + fileName);
  278. }
  279. }
  280. while (FindNextFile(handle, &info));
  281. FindClose(handle);
  282. }
  283. }
  284. void SplitPath(const String& fullPath, String& pathName, String& fileName, String& extension)
  285. {
  286. String fullPathCopy = fullPath.Replace('\\', '/');
  287. unsigned extPos = fullPathCopy.FindLast('.');
  288. if (extPos != String::NPOS)
  289. {
  290. extension = fullPathCopy.Substring(extPos).ToLower();
  291. fullPathCopy = fullPathCopy.Substring(0, extPos);
  292. }
  293. else
  294. extension.Clear();
  295. unsigned pathPos = fullPathCopy.FindLast('/');
  296. if (pathPos != String::NPOS)
  297. {
  298. fileName = fullPathCopy.Substring(pathPos + 1);
  299. pathName = fullPathCopy.Substring(0, pathPos + 1);
  300. }
  301. else
  302. {
  303. fileName = fullPathCopy;
  304. pathName.Clear();
  305. }
  306. }
  307. String GetPath(const String& fullPath)
  308. {
  309. String path, file, extension;
  310. SplitPath(fullPath, path, file, extension);
  311. return path;
  312. }
  313. String GetFileName(const String& fullPath)
  314. {
  315. String path, file, extension;
  316. SplitPath(fullPath, path, file, extension);
  317. return file;
  318. }
  319. String GetExtension(const String& fullPath)
  320. {
  321. String path, file, extension;
  322. SplitPath(fullPath, path, file, extension);
  323. return extension;
  324. }
  325. String GetFileNameAndExtension(const String& fileName)
  326. {
  327. String path, file, extension;
  328. SplitPath(fileName, path, file, extension);
  329. return file + extension;
  330. }
  331. String AddTrailingSlash(const String& path)
  332. {
  333. String ret;
  334. if (!path.Empty())
  335. {
  336. ret = path;
  337. char last = path[path.Length() - 1];
  338. if ((last != '/') && (last != '\\'))
  339. ret += '/';
  340. }
  341. ret.ReplaceInPlace('\\', '/');
  342. return ret;
  343. }
  344. String RemoveTrailingSlash(const String& path)
  345. {
  346. if (!path.Empty())
  347. {
  348. char last = path[path.Length() - 1];
  349. if ((last == '/') || (last == '\\'))
  350. return path.Substring(0, path.Length() - 1);
  351. }
  352. return path;
  353. }
  354. String GetParentPath(const String& path)
  355. {
  356. unsigned pos = RemoveTrailingSlash(path).FindLast('/');
  357. if (pos != String::NPOS)
  358. return path.Substring(0, pos + 1);
  359. else
  360. return path;
  361. }
  362. String GetNativePath(const String& pathName, bool forNativeApi)
  363. {
  364. // On MSVC, replace slash always with backslash. On MinGW only if going to do Win32 native calls
  365. #ifdef _MSC_VER
  366. forNativeApi = true;
  367. #endif
  368. if (forNativeApi)
  369. return pathName.Replace('/', '\\');
  370. else
  371. return pathName;
  372. }