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, unsigned flags, 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. 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. void scanDirectory(std::vector<std::string>& result, const std::string& pathName, const std::string& filter, unsigned flags, bool recursive)
  181. {
  182. result.clear();
  183. if (!checkDirectoryAccess(pathName))
  184. LOGERROR("Access denied to " + pathName);
  185. else
  186. {
  187. // Go into the directory to scan the files; this way the file names will be relative to the start path
  188. char oldDir[MAX_PATH];
  189. GetCurrentDirectory(MAX_PATH, oldDir);
  190. if (SetCurrentDirectory(getOSPath(pathName, true).c_str()) == FALSE)
  191. return;
  192. scanDirectoryInternal(result, "", filter, flags, recursive);
  193. SetCurrentDirectory(oldDir);
  194. }
  195. }
  196. void registerDirectory(const std::string& pathName)
  197. {
  198. if (pathName.empty())
  199. return;
  200. allowedDirectories.insert(fixPath(pathName));
  201. }
  202. bool checkDirectoryAccess(const std::string& pathName)
  203. {
  204. std::string fixedPath = fixPath(pathName);
  205. // If no allowed directories defined, succeed always
  206. if (allowedDirectories.empty())
  207. return true;
  208. // Access to the working directory is always allowed
  209. if ((fixedPath.empty()) || (fixedPath == "./"))
  210. return true;
  211. // If there is any attempt to go to a parent directory, disallow
  212. if (fixedPath.find("..") != std::string::npos)
  213. return false;
  214. // Check if the path is a partial match of any of the allowed directories
  215. for (std::set<std::string>::const_iterator i = allowedDirectories.begin(); i != allowedDirectories.end(); ++i)
  216. {
  217. if (fixedPath.find(*i) == 0)
  218. return true;
  219. }
  220. // Not found, so disallow
  221. return false;
  222. }
  223. void splitPath(const std::string& fullPath, std::string& pathName, std::string& fileName, std::string& extension, bool lowerCaseExtension)
  224. {
  225. std::string fullPathCopy = replace(fullPath, '\\', '/');
  226. size_t extPos = fullPathCopy.rfind('.');
  227. if (extPos != std::string::npos)
  228. {
  229. extension = fullPathCopy.substr(extPos);
  230. fullPathCopy = fullPathCopy.substr(0, extPos);
  231. }
  232. else
  233. extension = "";
  234. size_t pathPos = fullPathCopy.rfind('/');
  235. if (pathPos != std::string::npos)
  236. {
  237. fileName = fullPathCopy.substr(pathPos + 1);
  238. pathName = fullPathCopy.substr(0, pathPos + 1);
  239. }
  240. else
  241. {
  242. fileName = fullPathCopy;
  243. pathName = "";
  244. }
  245. if (lowerCaseExtension)
  246. extension = toLower(extension);
  247. }
  248. std::string getPath(const std::string& fullPath)
  249. {
  250. std::string path, file, extension;
  251. splitPath(fullPath, path, file, extension);
  252. return path;
  253. }
  254. std::string getFileName(const std::string& fullPath)
  255. {
  256. std::string path, file, extension;
  257. splitPath(fullPath, path, file, extension);
  258. return file;
  259. }
  260. std::string getExtension(const std::string& fullPath, bool lowerCaseExtension)
  261. {
  262. std::string path, file, extension;
  263. splitPath(fullPath, path, file, extension, lowerCaseExtension);
  264. return extension;
  265. }
  266. std::string getFileNameAndExtension(const std::string& fileName, bool lowerCaseExtension)
  267. {
  268. std::string path, file, extension;
  269. splitPath(fileName, path, file, extension, lowerCaseExtension);
  270. return file + extension;
  271. }
  272. std::string fixPath(const std::string& path)
  273. {
  274. std::string ret;
  275. if (!path.empty())
  276. {
  277. ret = path;
  278. char last = path[path.length() - 1];
  279. if ((last != '/') && (last != '\\'))
  280. ret += '/';
  281. }
  282. return replace(ret, '\\', '/');
  283. }
  284. std::string unfixPath(const std::string& path)
  285. {
  286. if (!path.empty())
  287. {
  288. char last = path[path.length() - 1];
  289. if ((last == '/') || (last == '\\'))
  290. return path.substr(0, path.length() - 1);
  291. }
  292. return path;
  293. }
  294. std::string getOSPath(const std::string& pathName, bool forNativeApi)
  295. {
  296. // On MSVC, replace slash always with backslash. On MinGW only if going to do Win32 native calls
  297. #ifdef _MSC_VER
  298. forNativeApi = true;
  299. #endif
  300. if (forNativeApi)
  301. return replace(pathName, '/', '\\');
  302. else
  303. return pathName;
  304. }
  305. void scanDirectoryInternal(std::vector<std::string>& result, std::string path, const std::string& filter, unsigned flags, bool recursive)
  306. {
  307. path = fixPath(path);
  308. std::string pathAndFilter = getOSPath(path + filter, true);
  309. WIN32_FIND_DATA info;
  310. HANDLE handle = FindFirstFile(pathAndFilter.c_str(), &info);
  311. if (handle != INVALID_HANDLE_VALUE)
  312. {
  313. do
  314. {
  315. std::string fileName((const char*)&info.cFileName[0]);
  316. if (!fileName.empty())
  317. {
  318. if ((info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) && (!(flags & SCAN_HIDDEN)))
  319. continue;
  320. if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  321. {
  322. if (flags & SCAN_DIRECTORIES)
  323. result.push_back(path + fileName);
  324. if ((recursive) && (fileName != ".") && (fileName != ".."))
  325. scanDirectoryInternal(result, path + fileName, filter, flags, recursive);
  326. }
  327. else if (flags & SCAN_FILES)
  328. result.push_back(path + fileName);
  329. }
  330. }
  331. while (FindNextFile(handle, &info));
  332. FindClose(handle);
  333. }
  334. }