File.cpp 12 KB

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