File.cpp 12 KB

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