File.cpp 10 KB

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