File.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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 "SharedArrayPtr.h"
  28. #include "StringUtils.h"
  29. #include <cstdlib>
  30. #include <direct.h>
  31. #include <process.h>
  32. #include <windows.h>
  33. #include <shellapi.h>
  34. #include "DebugNew.h"
  35. static std::set<std::string> allowedDirectories;
  36. void scanDirectoryInternal(std::vector<std::string>& result, std::string path, const std::string& startPath, const std::string& filter, unsigned flags, bool recursive);
  37. File::File(const std::string& fileName, FileMode mode) :
  38. mHandle(0),
  39. mFileName(fileName),
  40. mMode(mode),
  41. mOffset(0),
  42. mChecksum(0)
  43. {
  44. static const char* openMode[] =
  45. {
  46. "rb",
  47. "wb",
  48. "w+b"
  49. };
  50. if (!checkDirectoryAccess(getPath(mFileName)))
  51. EXCEPTION("Access denied to " + fileName);
  52. mHandle = fopen(getOSPath(mFileName).c_str(), openMode[mMode]);
  53. if (!mHandle)
  54. EXCEPTION("Could not open file " + fileName);
  55. fseek(mHandle, 0, SEEK_END);
  56. mSize = ftell(mHandle);
  57. fseek(mHandle, 0, SEEK_SET);
  58. }
  59. File::File(const PackageFile& package, const std::string& fileName) :
  60. mHandle(0),
  61. mFileName(fileName),
  62. mMode(FILE_READ)
  63. {
  64. const PackageEntry& entry = package.getEntry(fileName);
  65. mOffset = entry.mOffset;
  66. mSize = entry.mSize;
  67. mChecksum = entry.mChecksum;
  68. mHandle = fopen(getOSPath(package.getName()).c_str(), "rb");
  69. if (!mHandle)
  70. EXCEPTION("Could not open package file " + fileName);
  71. fseek(mHandle, mOffset, SEEK_SET);
  72. }
  73. File::~File()
  74. {
  75. close();
  76. }
  77. void File::read(void* dest, unsigned size)
  78. {
  79. if (!size)
  80. return;
  81. if (mMode == FILE_WRITE)
  82. SAFE_EXCEPTION("File not opened for reading");
  83. if (size + mPosition > mSize)
  84. SAFE_EXCEPTION("Attempted to read past file end");
  85. if (!mHandle)
  86. SAFE_EXCEPTION("File not open");
  87. size_t ret = fread(dest, size, 1, mHandle);
  88. if (ret != 1)
  89. {
  90. // Return to the position where the read began
  91. fseek(mHandle, mPosition + mOffset, SEEK_SET);
  92. SAFE_EXCEPTION("Error while reading from file");
  93. }
  94. mPosition += size;
  95. }
  96. unsigned File::seek(unsigned position)
  97. {
  98. if (position > mSize)
  99. position = mSize;
  100. if (!mHandle)
  101. SAFE_EXCEPTION_RET("File not open", 0);
  102. fseek(mHandle, position + mOffset, SEEK_SET);
  103. mPosition = position;
  104. return mPosition;
  105. }
  106. void File::write(const void* data, unsigned size)
  107. {
  108. if (!size)
  109. return;
  110. if (mMode == FILE_READ)
  111. SAFE_EXCEPTION("File not opened for writing");
  112. if (!mHandle)
  113. SAFE_EXCEPTION("File not open");
  114. if (fwrite(data, size, 1, mHandle) != 1)
  115. {
  116. // Return to the position where the write began
  117. fseek(mHandle, mPosition + mOffset, SEEK_SET);
  118. SAFE_EXCEPTION("Error while writing to file");
  119. }
  120. mPosition += size;
  121. if (mPosition > mSize)
  122. mSize = mPosition;
  123. }
  124. void File::close()
  125. {
  126. if (mHandle)
  127. {
  128. fclose(mHandle);
  129. mHandle = 0;
  130. }
  131. }
  132. void File::setName(const std::string& name)
  133. {
  134. mFileName = name;
  135. }
  136. unsigned File::getChecksum()
  137. {
  138. if ((mOffset) || (mChecksum))
  139. return mChecksum;
  140. unsigned oldPos = mPosition;
  141. mChecksum = 0;
  142. seek(0);
  143. while (!isEof())
  144. updateHash(mChecksum, readUByte());
  145. seek(oldPos);
  146. return mChecksum;
  147. }
  148. bool fileExists(const std::string& fileName)
  149. {
  150. if (!checkDirectoryAccess(getPath(fileName)))
  151. return false;
  152. std::string fixedName = getOSPath(unfixPath(fileName), true);
  153. DWORD attributes = GetFileAttributes(fixedName.c_str());
  154. if ((attributes == INVALID_FILE_ATTRIBUTES) || (attributes & FILE_ATTRIBUTE_DIRECTORY))
  155. return false;
  156. return true;
  157. }
  158. bool directoryExists(const std::string& pathName)
  159. {
  160. if (!checkDirectoryAccess(pathName))
  161. return false;
  162. std::string fixedName = getOSPath(unfixPath(pathName), true);
  163. DWORD attributes = GetFileAttributes(fixedName.c_str());
  164. if ((attributes == INVALID_FILE_ATTRIBUTES) || (!(attributes & FILE_ATTRIBUTE_DIRECTORY)))
  165. return false;
  166. return true;
  167. }
  168. void scanDirectory(std::vector<std::string>& result, const std::string& pathName, const std::string& filter, unsigned flags, bool recursive)
  169. {
  170. result.clear();
  171. if (!checkDirectoryAccess(pathName))
  172. LOGERROR("Access denied to " + pathName);
  173. else
  174. {
  175. std::string initialPath = fixPath(pathName);
  176. scanDirectoryInternal(result, initialPath, initialPath, filter, flags, recursive);
  177. }
  178. }
  179. std::string getCurrentDirectory()
  180. {
  181. char path[MAX_PATH];
  182. GetCurrentDirectory(MAX_PATH, path);
  183. return fixPath(std::string(path));
  184. }
  185. bool setCurrentDirectory(const std::string& pathName)
  186. {
  187. if (!checkDirectoryAccess(pathName))
  188. {
  189. LOGERROR("Access denied to " + pathName);
  190. return false;
  191. }
  192. if (SetCurrentDirectory(getOSPath(pathName, true).c_str()) == FALSE)
  193. {
  194. LOGERROR("Failed to change directory to " + pathName);
  195. return false;
  196. }
  197. return true;
  198. }
  199. bool createDirectory(const std::string& pathName)
  200. {
  201. if (!checkDirectoryAccess(pathName))
  202. {
  203. LOGERROR("Access denied to " + pathName);
  204. return false;
  205. }
  206. bool success = (CreateDirectory(getOSPath(unfixPath(pathName), true).c_str(), 0) == TRUE) || (GetLastError() == ERROR_ALREADY_EXISTS);
  207. if (success)
  208. LOGDEBUG("Created directory " + pathName);
  209. else
  210. LOGERROR("Failed to create directory " + pathName);
  211. return success;
  212. }
  213. int systemCommand(const std::string& commandLine)
  214. {
  215. if (allowedDirectories.empty())
  216. return system(commandLine.c_str());
  217. else
  218. {
  219. LOGERROR("Executing an external command is not allowed");
  220. return -1;
  221. }
  222. }
  223. int systemRun(const std::string& fileName, const std::vector<std::string>& arguments)
  224. {
  225. if (allowedDirectories.empty())
  226. {
  227. std::string fixedFileName = getOSPath(fileName, true);
  228. std::vector<const char*> argPtrs;
  229. argPtrs.push_back(fixedFileName.c_str());
  230. for (unsigned i = 0; i < arguments.size(); ++i)
  231. argPtrs.push_back(arguments[i].c_str());
  232. argPtrs.push_back(0);
  233. return _spawnv(_P_WAIT, fixedFileName.c_str(), &argPtrs[0]);
  234. }
  235. else
  236. {
  237. LOGERROR("Executing an external command is not allowed");
  238. return -1;
  239. }
  240. }
  241. bool systemOpenFile(const std::string& fileName, const std::string& mode)
  242. {
  243. if (allowedDirectories.empty())
  244. {
  245. if ((!fileExists(fileName)) && (!directoryExists(fileName)))
  246. {
  247. LOGERROR("File or directory " + fileName + " not found");
  248. return false;
  249. }
  250. bool success = (int)ShellExecute(0, !mode.empty() ? (char*)mode.c_str() : 0, (char*)getOSPath(fileName, true).c_str(), 0, 0, SW_SHOW) > 32;
  251. if (!success)
  252. LOGERROR("Failed to open " + fileName + " externally");
  253. return success;
  254. }
  255. else
  256. {
  257. LOGERROR("Opening a file externally is not allowed");
  258. return false;
  259. }
  260. }
  261. bool copyFile(const std::string& srcFileName, const std::string& destFileName)
  262. {
  263. if (!checkDirectoryAccess(getPath(srcFileName)))
  264. {
  265. LOGERROR("Access denied to " + srcFileName);
  266. return false;
  267. }
  268. if (!checkDirectoryAccess(getPath(destFileName)))
  269. {
  270. LOGERROR("Access denied to " + destFileName);
  271. return false;
  272. }
  273. try
  274. {
  275. File srcFile(srcFileName, FILE_READ);
  276. File destFile(destFileName, FILE_WRITE);
  277. SharedArrayPtr<unsigned char> buffer(new unsigned char[srcFile.getSize()]);
  278. srcFile.read(buffer.getPtr(), srcFile.getSize());
  279. srcFile.close();
  280. destFile.write(buffer.getPtr(), srcFile.getSize());
  281. destFile.close();
  282. }
  283. catch (...)
  284. {
  285. return false;
  286. }
  287. return true;
  288. }
  289. bool renameFile(const std::string& srcFileName, const std::string& destFileName)
  290. {
  291. if (!checkDirectoryAccess(getPath(srcFileName)))
  292. {
  293. LOGERROR("Access denied to " + srcFileName);
  294. return false;
  295. }
  296. if (!checkDirectoryAccess(getPath(destFileName)))
  297. {
  298. LOGERROR("Access denied to " + destFileName);
  299. return false;
  300. }
  301. return rename(getOSPath(srcFileName).c_str(), getOSPath(destFileName).c_str()) == 0;
  302. }
  303. bool deleteFile(const std::string& fileName)
  304. {
  305. if (!checkDirectoryAccess(getPath(fileName)))
  306. {
  307. LOGERROR("Access denied to " + fileName);
  308. return false;
  309. }
  310. return remove(getOSPath(fileName).c_str()) == 0;
  311. }
  312. void registerDirectory(const std::string& pathName)
  313. {
  314. if (pathName.empty())
  315. return;
  316. allowedDirectories.insert(fixPath(pathName));
  317. }
  318. bool checkDirectoryAccess(const std::string& pathName)
  319. {
  320. std::string fixedPath = fixPath(pathName);
  321. // If no allowed directories defined, succeed always
  322. if (allowedDirectories.empty())
  323. return true;
  324. // If there is any attempt to go to a parent directory, disallow
  325. if (fixedPath.find("..") != std::string::npos)
  326. return false;
  327. // Check if the path is a partial match of any of the allowed directories
  328. for (std::set<std::string>::const_iterator i = allowedDirectories.begin(); i != allowedDirectories.end(); ++i)
  329. {
  330. if (fixedPath.find(*i) == 0)
  331. return true;
  332. }
  333. // Not found, so disallow
  334. return false;
  335. }
  336. void splitPath(const std::string& fullPath, std::string& pathName, std::string& fileName, std::string& extension)
  337. {
  338. std::string fullPathCopy = replace(fullPath, '\\', '/');
  339. size_t extPos = fullPathCopy.rfind('.');
  340. if (extPos != std::string::npos)
  341. {
  342. extension = toLower(fullPathCopy.substr(extPos));
  343. fullPathCopy = fullPathCopy.substr(0, extPos);
  344. }
  345. else
  346. extension.clear();
  347. size_t pathPos = fullPathCopy.rfind('/');
  348. if (pathPos != std::string::npos)
  349. {
  350. fileName = fullPathCopy.substr(pathPos + 1);
  351. pathName = fullPathCopy.substr(0, pathPos + 1);
  352. }
  353. else
  354. {
  355. fileName = fullPathCopy;
  356. pathName.clear();
  357. }
  358. }
  359. std::string getPath(const std::string& fullPath)
  360. {
  361. std::string path, file, extension;
  362. splitPath(fullPath, path, file, extension);
  363. return path;
  364. }
  365. std::string getFileName(const std::string& fullPath)
  366. {
  367. std::string path, file, extension;
  368. splitPath(fullPath, path, file, extension);
  369. return file;
  370. }
  371. std::string getExtension(const std::string& fullPath)
  372. {
  373. std::string path, file, extension;
  374. splitPath(fullPath, path, file, extension);
  375. return extension;
  376. }
  377. std::string getFileNameAndExtension(const std::string& fileName)
  378. {
  379. std::string path, file, extension;
  380. splitPath(fileName, path, file, extension);
  381. return file + extension;
  382. }
  383. std::string fixPath(const std::string& path)
  384. {
  385. std::string ret;
  386. if (!path.empty())
  387. {
  388. ret = path;
  389. char last = path[path.length() - 1];
  390. if ((last != '/') && (last != '\\'))
  391. ret += '/';
  392. }
  393. return replace(ret, '\\', '/');
  394. }
  395. std::string unfixPath(const std::string& path)
  396. {
  397. if (!path.empty())
  398. {
  399. char last = path[path.length() - 1];
  400. if ((last == '/') || (last == '\\'))
  401. return path.substr(0, path.length() - 1);
  402. }
  403. return path;
  404. }
  405. std::string getParentPath(const std::string& path)
  406. {
  407. unsigned pos = unfixPath(path).rfind('/');
  408. if (pos != std::string::npos)
  409. return path.substr(0, pos + 1);
  410. else
  411. return path;
  412. }
  413. std::string getAbsoluteFileName(const std::string& fileName)
  414. {
  415. //! \todo Though this routine does not use Win32 API calls, it assumes Win32 filename structure
  416. if (fileName.empty())
  417. return fileName;
  418. std::string fixedPath = replace(fileName, '\\', '/');
  419. // Check for a network path or a drive letter, in this case we do not have to do anything
  420. if (fixedPath.length() >= 2)
  421. {
  422. if ((fixedPath[1] == ':') || (fixedPath.substr(0, 2) == "//"))
  423. return fixedPath;
  424. // Remove redundant ./ if exists
  425. if (fixedPath.substr(0, 2) == "./")
  426. fixedPath = fixedPath.substr(2);
  427. }
  428. std::string workingDir = getCurrentDirectory();
  429. // If path is absolute in relation to current drive letter, just add it
  430. if (fixedPath[0] == '/')
  431. return workingDir.substr(0, 2) + fixedPath;
  432. // Navigate any ../ in the filename
  433. //! \todo Only supported in the beginning
  434. while ((fixedPath.length() >= 3) && (fixedPath.substr(0,3) == "../"))
  435. {
  436. fixedPath = fixedPath.substr(3);
  437. workingDir = getParentPath(workingDir);
  438. }
  439. return workingDir + fixedPath;
  440. }
  441. std::string getOSPath(const std::string& pathName, bool forNativeApi)
  442. {
  443. // On MSVC, replace slash always with backslash. On MinGW only if going to do Win32 native calls
  444. #ifdef _MSC_VER
  445. forNativeApi = true;
  446. #endif
  447. if (forNativeApi)
  448. return replace(pathName, '/', '\\');
  449. else
  450. return pathName;
  451. }
  452. void scanDirectoryInternal(std::vector<std::string>& result, std::string path, const std::string& startPath, const std::string& filter, unsigned flags, bool recursive)
  453. {
  454. path = fixPath(path);
  455. std::string pathAndFilter = getOSPath(path + filter, true);
  456. std::string deltaPath;
  457. if (path.length() > startPath.length())
  458. deltaPath = path.substr(startPath.length());
  459. WIN32_FIND_DATA info;
  460. HANDLE handle = FindFirstFile(pathAndFilter.c_str(), &info);
  461. if (handle != INVALID_HANDLE_VALUE)
  462. {
  463. do
  464. {
  465. std::string fileName((const char*)&info.cFileName[0]);
  466. if (!fileName.empty())
  467. {
  468. if ((info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) && (!(flags & SCAN_HIDDEN)))
  469. continue;
  470. if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  471. {
  472. if (flags & SCAN_DIRECTORIES)
  473. result.push_back(deltaPath + fileName);
  474. if ((recursive) && (fileName != ".") && (fileName != ".."))
  475. scanDirectoryInternal(result, path + fileName, startPath, filter, flags, recursive);
  476. }
  477. else if (flags & SCAN_FILES)
  478. result.push_back(deltaPath + fileName);
  479. }
  480. }
  481. while (FindNextFile(handle, &info));
  482. FindClose(handle);
  483. }
  484. }