File.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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 "Hash.h"
  25. #include "Log.h"
  26. #include "PackageFile.h"
  27. #include "StringUtils.h"
  28. #include <direct.h>
  29. #include <windows.h>
  30. #include "DebugNew.h"
  31. static std::set<std::string> allowedDirectories;
  32. void scanDirectoryInternal(std::vector<std::string>& result, std::string path, const std::string& filter, bool recursive, bool directories, bool hidden);
  33. File::File(const std::string& fileName, FileMode mode) :
  34. mHandle(0),
  35. mFileName(fileName),
  36. mMode(mode),
  37. mOffset(0),
  38. mChecksum(0)
  39. {
  40. static const char* openMode[] =
  41. {
  42. "rb",
  43. "wb",
  44. "w+b"
  45. };
  46. if (!checkDirectoryAccess(getPath(mFileName)))
  47. EXCEPTION("Access denied to " + fileName);
  48. mHandle = fopen(getOSPath(mFileName).c_str(), openMode[mMode]);
  49. if (!mHandle)
  50. EXCEPTION("Could not open file " + fileName);
  51. fseek(mHandle, 0, SEEK_END);
  52. mSize = ftell(mHandle);
  53. fseek(mHandle, 0, SEEK_SET);
  54. }
  55. File::File(const PackageFile& package, const std::string& fileName) :
  56. mHandle(0),
  57. mFileName(fileName),
  58. mMode(FILE_READ)
  59. {
  60. const PackageEntry& entry = package.getEntry(fileName);
  61. mOffset = entry.mOffset;
  62. mSize = entry.mSize;
  63. mChecksum = entry.mChecksum;
  64. mHandle = fopen(getOSPath(package.getName()).c_str(), "rb");
  65. if (!mHandle)
  66. EXCEPTION("Could not open package file " + fileName);
  67. fseek(mHandle, mOffset, SEEK_SET);
  68. }
  69. File::~File()
  70. {
  71. close();
  72. }
  73. void File::read(void* dest, unsigned size)
  74. {
  75. if (!size)
  76. return;
  77. if (mMode == FILE_WRITE)
  78. SAFE_EXCEPTION("File not opened for reading");
  79. if (size + mPosition > mSize)
  80. SAFE_EXCEPTION("Attempted to read past file end");
  81. if (!mHandle)
  82. SAFE_EXCEPTION("File not open");
  83. size_t ret = fread(dest, size, 1, mHandle);
  84. if (ret != 1)
  85. {
  86. // Return to the position where the read began
  87. fseek(mHandle, mPosition + mOffset, SEEK_SET);
  88. SAFE_EXCEPTION("Error while reading from file");
  89. }
  90. mPosition += size;
  91. }
  92. unsigned File::seek(unsigned position)
  93. {
  94. if (position > mSize)
  95. position = mSize;
  96. if (!mHandle)
  97. SAFE_EXCEPTION_RET("File not open", 0);
  98. fseek(mHandle, position + mOffset, SEEK_SET);
  99. mPosition = position;
  100. return mPosition;
  101. }
  102. void File::write(const void* data, unsigned size)
  103. {
  104. if (!size)
  105. return;
  106. if (mMode == FILE_READ)
  107. SAFE_EXCEPTION("File not opened for writing");
  108. if (!mHandle)
  109. SAFE_EXCEPTION("File not open");
  110. if (fwrite(data, size, 1, mHandle) != 1)
  111. {
  112. // Return to the position where the write began
  113. fseek(mHandle, mPosition + mOffset, SEEK_SET);
  114. SAFE_EXCEPTION("Error while writing to file");
  115. }
  116. mPosition += size;
  117. if (mPosition > mSize)
  118. mSize = mPosition;
  119. }
  120. void File::close()
  121. {
  122. if (mHandle)
  123. {
  124. fclose(mHandle);
  125. mHandle = 0;
  126. }
  127. }
  128. void File::setName(const std::string& name)
  129. {
  130. mFileName = name;
  131. }
  132. unsigned File::getChecksum()
  133. {
  134. if ((mOffset) || (mChecksum))
  135. return mChecksum;
  136. unsigned oldPos = mPosition;
  137. mChecksum = 0;
  138. seek(0);
  139. while (!isEof())
  140. updateHash(mChecksum, readUByte());
  141. seek(oldPos);
  142. return mChecksum;
  143. }
  144. bool fileExists(const std::string& fileName)
  145. {
  146. if (!checkDirectoryAccess(getPath(fileName)))
  147. return false;
  148. std::string fixedName = getOSPath(unfixPath(fileName), true);
  149. DWORD attributes = GetFileAttributes(fixedName.c_str());
  150. if ((attributes == INVALID_FILE_ATTRIBUTES) || (attributes & FILE_ATTRIBUTE_DIRECTORY))
  151. return false;
  152. return true;
  153. }
  154. bool directoryExists(const std::string& pathName)
  155. {
  156. if (!checkDirectoryAccess(pathName))
  157. return false;
  158. std::string fixedName = getOSPath(unfixPath(pathName), true);
  159. DWORD attributes = GetFileAttributes(fixedName.c_str());
  160. if ((attributes == INVALID_FILE_ATTRIBUTES) || (!(attributes & FILE_ATTRIBUTE_DIRECTORY)))
  161. return false;
  162. return true;
  163. }
  164. void createDirectory(const std::string& pathName)
  165. {
  166. if (!checkDirectoryAccess(pathName))
  167. SAFE_EXCEPTION("Access denied to " + pathName);
  168. if (CreateDirectory(getOSPath(pathName, true).c_str(), 0))
  169. return;
  170. if (GetLastError() == ERROR_ALREADY_EXISTS)
  171. return;
  172. SAFE_EXCEPTION("Failed to create directory " + pathName);
  173. }
  174. std::string getWorkingDirectory()
  175. {
  176. char currentDir[MAX_PATH];
  177. GetCurrentDirectory(MAX_PATH, currentDir);
  178. return fixPath(std::string(currentDir));
  179. }
  180. std::vector<std::string> scanDirectory(const std::string& pathName, const std::string& filter, bool recursive, bool directories, bool hidden)
  181. {
  182. std::vector<std::string> ret;
  183. if (!checkDirectoryAccess(pathName))
  184. SAFE_EXCEPTION_RET("Access denied to " + pathName, ret);
  185. // Go into the directory to scan the files; this way the file names will be relative to the start path
  186. char oldDir[MAX_PATH];
  187. GetCurrentDirectory(MAX_PATH, oldDir);
  188. if (SetCurrentDirectory(getOSPath(pathName, true).c_str()) == FALSE)
  189. return ret;
  190. scanDirectoryInternal(ret, "", filter, recursive, directories, hidden);
  191. SetCurrentDirectory(oldDir);
  192. return ret;
  193. }
  194. void registerDirectory(const std::string& pathName)
  195. {
  196. if (pathName.empty())
  197. return;
  198. allowedDirectories.insert(fixPath(pathName));
  199. }
  200. bool checkDirectoryAccess(const std::string& pathName)
  201. {
  202. std::string fixedPath = fixPath(pathName);
  203. // If no allowed directories defined, succeed always
  204. if (allowedDirectories.empty())
  205. return true;
  206. // Access to the working directory is always allowed
  207. if ((fixedPath.empty()) || (fixedPath == "./"))
  208. return true;
  209. // If there is any attempt to go to a parent directory, disallow
  210. if (fixedPath.find("..") != std::string::npos)
  211. return false;
  212. // Check if the path is a partial match of any of the allowed directories
  213. for (std::set<std::string>::const_iterator i = allowedDirectories.begin(); i != allowedDirectories.end(); ++i)
  214. {
  215. if (fixedPath.find(*i) == 0)
  216. return true;
  217. }
  218. // Not found, so disallow
  219. return false;
  220. }
  221. void splitPath(const std::string& fullPath, std::string& pathName, std::string& fileName, std::string& extension, bool lowerCaseExtension)
  222. {
  223. std::string fullPathCopy = replace(fullPath, '\\', '/');
  224. size_t extPos = fullPathCopy.rfind('.');
  225. if (extPos != std::string::npos)
  226. {
  227. extension = fullPathCopy.substr(extPos);
  228. fullPathCopy = fullPathCopy.substr(0, extPos);
  229. }
  230. else
  231. extension = "";
  232. size_t pathPos = fullPathCopy.rfind('/');
  233. if (pathPos != std::string::npos)
  234. {
  235. fileName = fullPathCopy.substr(pathPos + 1);
  236. pathName = fullPathCopy.substr(0, pathPos + 1);
  237. }
  238. else
  239. {
  240. fileName = fullPathCopy;
  241. pathName = "";
  242. }
  243. if (lowerCaseExtension)
  244. extension = toLower(extension);
  245. }
  246. std::string getPath(const std::string& fullPath)
  247. {
  248. std::string path, file, extension;
  249. splitPath(fullPath, path, file, extension);
  250. return path;
  251. }
  252. std::string getFileName(const std::string& fullPath)
  253. {
  254. std::string path, file, extension;
  255. splitPath(fullPath, path, file, extension);
  256. return file;
  257. }
  258. std::string getExtension(const std::string& fullPath, bool lowerCaseExtension)
  259. {
  260. std::string path, file, extension;
  261. splitPath(fullPath, path, file, extension, lowerCaseExtension);
  262. return extension;
  263. }
  264. std::string getFileNameAndExtension(const std::string& fileName, bool lowerCaseExtension)
  265. {
  266. std::string path, file, extension;
  267. splitPath(fileName, path, file, extension, lowerCaseExtension);
  268. return file + extension;
  269. }
  270. std::string fixPath(const std::string& path)
  271. {
  272. std::string ret;
  273. if (!path.empty())
  274. {
  275. ret = path;
  276. char last = path[path.length() - 1];
  277. if ((last != '/') && (last != '\\'))
  278. ret += '/';
  279. }
  280. return replace(ret, '\\', '/');
  281. }
  282. std::string unfixPath(const std::string& path)
  283. {
  284. if (!path.empty())
  285. {
  286. char last = path[path.length() - 1];
  287. if ((last == '/') || (last == '\\'))
  288. return path.substr(0, path.length() - 1);
  289. }
  290. return path;
  291. }
  292. std::string getOSPath(const std::string& pathName, bool forNativeApi)
  293. {
  294. // On MSVC, replace slash always with backslash. On MinGW only if going to do Win32 native calls
  295. #ifdef _MSC_VER
  296. forNativeApi = true;
  297. #endif
  298. if (forNativeApi)
  299. return replace(pathName, '/', '\\');
  300. else
  301. return pathName;
  302. }
  303. void scanDirectoryInternal(std::vector<std::string>& result, std::string path, const std::string& filter, bool recursive, bool directories, bool hidden)
  304. {
  305. path = fixPath(path);
  306. std::string pathAndFilter = getOSPath(path + filter, true);
  307. WIN32_FIND_DATA info;
  308. HANDLE handle = FindFirstFile(pathAndFilter.c_str(), &info);
  309. if (handle != INVALID_HANDLE_VALUE)
  310. {
  311. do
  312. {
  313. std::string fileName((const char*)&info.cFileName[0]);
  314. if (!fileName.empty())
  315. {
  316. if ((info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) && (!hidden))
  317. continue;
  318. if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  319. {
  320. if (directories)
  321. result.push_back(path + fileName);
  322. if ((recursive) && (fileName != ".") && (fileName != ".."))
  323. scanDirectoryInternal(result, path + fileName, filter, recursive, directories, hidden);
  324. }
  325. else if (!directories)
  326. result.push_back(path + fileName);
  327. }
  328. }
  329. while (FindNextFile(handle, &info));
  330. FindClose(handle);
  331. }
  332. }