File.cpp 12 KB

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