File.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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);
  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. FILE* file = fopen(getOSPath(fileName).c_str(), "rb");
  149. if (file)
  150. {
  151. fclose(file);
  152. return true;
  153. }
  154. else
  155. return false;
  156. }
  157. void createDirectory(const std::string& pathName)
  158. {
  159. if (!checkDirectoryAccess(pathName))
  160. SAFE_EXCEPTION("Access denied to " + pathName);
  161. if (CreateDirectory(getOSPath(pathName, true).c_str(), 0))
  162. return;
  163. if (GetLastError() == ERROR_ALREADY_EXISTS)
  164. return;
  165. SAFE_EXCEPTION("Failed to create directory " + pathName);
  166. }
  167. std::vector<std::string> scanDirectory(const std::string& pathName, const std::string& filter, bool recursive)
  168. {
  169. std::vector<std::string> ret;
  170. if (!checkDirectoryAccess(pathName))
  171. SAFE_EXCEPTION_RET("Access denied to " + pathName, ret);
  172. // Go into the directory to scan the files; this way the file names will be relative to the start path
  173. char oldDir[MAX_PATH];
  174. GetCurrentDirectory(MAX_PATH, oldDir);
  175. if (SetCurrentDirectory(getOSPath(pathName, true).c_str()) == FALSE)
  176. return ret;
  177. scanDirectoryInternal(ret, "", filter, recursive);
  178. SetCurrentDirectory(oldDir);
  179. return ret;
  180. }
  181. void registerDirectory(const std::string& pathName)
  182. {
  183. if (pathName.empty())
  184. return;
  185. allowedDirectories.insert(fixPath(pathName));
  186. }
  187. bool checkDirectoryAccess(const std::string& pathName)
  188. {
  189. std::string fixedPath = fixPath(pathName);
  190. // If no allowed directories defined, succeed always
  191. if (allowedDirectories.empty())
  192. return true;
  193. // Access to the working directory is always allowed
  194. if ((fixedPath.empty()) || (fixedPath == "./"))
  195. return true;
  196. // If there is any attempt to go to a parent directory, disallow
  197. if (fixedPath.find("..") != std::string::npos)
  198. return false;
  199. // Check if the path is a partial match of any of the allowed directories
  200. for (std::set<std::string>::const_iterator i = allowedDirectories.begin(); i != allowedDirectories.end(); ++i)
  201. {
  202. if (fixedPath.find(*i) == 0)
  203. return true;
  204. }
  205. // Not found, so disallow
  206. return false;
  207. }
  208. void splitPath(const std::string& fullPath, std::string& pathName, std::string& fileName, std::string& extension, bool lowerCaseExtension)
  209. {
  210. std::string fullPathCopy = replace(fullPath, '\\', '/');
  211. size_t extPos = fullPathCopy.rfind('.');
  212. if (extPos != std::string::npos)
  213. {
  214. extension = fullPathCopy.substr(extPos);
  215. fullPathCopy = fullPathCopy.substr(0, extPos);
  216. }
  217. else
  218. extension = "";
  219. size_t pathPos = fullPathCopy.rfind('/');
  220. if (pathPos != std::string::npos)
  221. {
  222. fileName = fullPathCopy.substr(pathPos + 1);
  223. pathName = fullPathCopy.substr(0, pathPos + 1);
  224. }
  225. else
  226. {
  227. fileName = fullPathCopy;
  228. pathName = "";
  229. }
  230. if (lowerCaseExtension)
  231. extension = toLower(extension);
  232. }
  233. std::string getPath(const std::string& fullPath)
  234. {
  235. std::string path, file, extension;
  236. splitPath(fullPath, path, file, extension);
  237. return path;
  238. }
  239. std::string getFileName(const std::string& fullPath)
  240. {
  241. std::string path, file, extension;
  242. splitPath(fullPath, path, file, extension);
  243. return file;
  244. }
  245. std::string getExtension(const std::string& fullPath, bool lowerCaseExtension)
  246. {
  247. std::string path, file, extension;
  248. splitPath(fullPath, path, file, extension, lowerCaseExtension);
  249. return extension;
  250. }
  251. std::string getFileNameAndExtension(const std::string& fileName, bool lowerCaseExtension)
  252. {
  253. std::string path, file, extension;
  254. splitPath(fileName, path, file, extension, lowerCaseExtension);
  255. return file + extension;
  256. }
  257. std::string fixPath(const std::string& path)
  258. {
  259. std::string ret;
  260. if (!path.empty())
  261. {
  262. ret = path;
  263. char last = path[path.length() - 1];
  264. if ((last != '/') && (last != '\\'))
  265. ret += '/';
  266. }
  267. return replace(ret, '\\', '/');
  268. }
  269. std::string getOSPath(const std::string& pathName, bool forNativeApi)
  270. {
  271. // On MSVC, replace slash always with backslash. On MinGW only if going to do Win32 native calls
  272. #ifdef _MSC_VER
  273. forNativeApi = true;
  274. #endif
  275. if (forNativeApi)
  276. return replace(pathName, '/', '\\');
  277. else
  278. return pathName;
  279. }
  280. void scanDirectoryInternal(std::vector<std::string>& result, std::string path, const std::string& filter, bool recursive)
  281. {
  282. path = fixPath(path);
  283. std::string pathAndFilter = getOSPath(path + filter, true);
  284. WIN32_FIND_DATA info;
  285. HANDLE handle = FindFirstFile(pathAndFilter.c_str(), &info);
  286. if (handle != INVALID_HANDLE_VALUE)
  287. {
  288. do
  289. {
  290. std::string fileName((const char*)&info.cFileName[0]);
  291. // Avoid files like . .. and .svn
  292. if ((!fileName.empty()) && (fileName[0] != '.'))
  293. {
  294. if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  295. {
  296. if (recursive)
  297. scanDirectoryInternal(result, path + fileName, filter, true);
  298. }
  299. else
  300. result.push_back(path + fileName);
  301. }
  302. }
  303. while (FindNextFile(handle, &info));
  304. FindClose(handle);
  305. }
  306. }