FileSystem.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Container/ArrayPtr.h"
  24. #include "../Core/Context.h"
  25. #include "../Core/CoreEvents.h"
  26. #include "../Core/Thread.h"
  27. #include "../Engine/EngineEvents.h"
  28. #include "../IO/File.h"
  29. #include "../IO/FileSystem.h"
  30. #include "../IO/IOEvents.h"
  31. #include "../IO/Log.h"
  32. #ifdef __ANDROID__
  33. // ATOMIC BEGIN
  34. #include <SDL/include/SDL_rwops.h>
  35. // ATOMIC END
  36. #endif
  37. #ifndef MINI_URHO
  38. // ATOMIC_BEGIN
  39. #include <SDL/include/SDL_filesystem.h>
  40. // ATOMIC END
  41. #endif
  42. #include <sys/stat.h>
  43. #include <cstdio>
  44. #ifdef _WIN32
  45. #ifndef _MSC_VER
  46. #define _WIN32_IE 0x501
  47. #endif
  48. #include <windows.h>
  49. #include <shellapi.h>
  50. #include <direct.h>
  51. #include <shlobj.h>
  52. #include <sys/types.h>
  53. #include <sys/utime.h>
  54. #else
  55. #include <dirent.h>
  56. #include <errno.h>
  57. #include <unistd.h>
  58. #include <utime.h>
  59. #include <sys/wait.h>
  60. #define MAX_PATH 256
  61. #endif
  62. #if defined(__APPLE__)
  63. #include <mach-o/dyld.h>
  64. #endif
  65. extern "C"
  66. {
  67. #ifdef __ANDROID__
  68. const char* SDL_Android_GetFilesDir();
  69. char** SDL_Android_GetFileList(const char* path, int* count);
  70. void SDL_Android_FreeFileList(char*** array, int* count);
  71. #elif IOS
  72. const char* SDL_IOS_GetResourceDir();
  73. const char* SDL_IOS_GetDocumentsDir();
  74. #endif
  75. }
  76. #include "../DebugNew.h"
  77. namespace Atomic
  78. {
  79. int DoSystemCommand(const String& commandLine, bool redirectToLog, Context* context)
  80. {
  81. #if !defined(__EMSCRIPTEN__) && !defined(MINI_URHO)
  82. if (!redirectToLog)
  83. #endif
  84. return system(commandLine.CString());
  85. #if !defined(__EMSCRIPTEN__) && !defined(MINI_URHO)
  86. // Get a platform-agnostic temporary file name for stderr redirection
  87. String stderrFilename;
  88. String adjustedCommandLine(commandLine);
  89. char* prefPath = SDL_GetPrefPath("atomic", "temp");
  90. if (prefPath)
  91. {
  92. stderrFilename = String(prefPath) + "command-stderr";
  93. adjustedCommandLine += " 2>" + stderrFilename;
  94. SDL_free(prefPath);
  95. }
  96. #ifdef _MSC_VER
  97. #define popen _popen
  98. #define pclose _pclose
  99. #endif
  100. // Use popen/pclose to capture the stdout and stderr of the command
  101. FILE* file = popen(adjustedCommandLine.CString(), "r");
  102. if (!file)
  103. return -1;
  104. // Capture the standard output stream
  105. char buffer[128];
  106. while (!feof(file))
  107. {
  108. if (fgets(buffer, sizeof(buffer), file))
  109. ATOMIC_LOGRAW(String(buffer));
  110. }
  111. int exitCode = pclose(file);
  112. // Capture the standard error stream
  113. if (!stderrFilename.Empty())
  114. {
  115. SharedPtr<File> errFile(new File(context, stderrFilename, FILE_READ));
  116. while (!errFile->IsEof())
  117. {
  118. unsigned numRead = errFile->Read(buffer, sizeof(buffer));
  119. if (numRead)
  120. Log::WriteRaw(String(buffer, numRead), true);
  121. }
  122. }
  123. return exitCode;
  124. #endif
  125. }
  126. int DoSystemRun(const String& fileName, const Vector<String>& arguments)
  127. {
  128. String fixedFileName = GetNativePath(fileName);
  129. #ifdef _WIN32
  130. // Add .exe extension if no extension defined
  131. if (GetExtension(fixedFileName).Empty())
  132. fixedFileName += ".exe";
  133. String commandLine = "\"" + fixedFileName + "\"";
  134. for (unsigned i = 0; i < arguments.Size(); ++i)
  135. commandLine += " " + arguments[i];
  136. STARTUPINFOW startupInfo;
  137. PROCESS_INFORMATION processInfo;
  138. memset(&startupInfo, 0, sizeof startupInfo);
  139. memset(&processInfo, 0, sizeof processInfo);
  140. WString commandLineW(commandLine);
  141. if (!CreateProcessW(NULL, (wchar_t*)commandLineW.CString(), 0, 0, 0, CREATE_NO_WINDOW, 0, 0, &startupInfo, &processInfo))
  142. return -1;
  143. WaitForSingleObject(processInfo.hProcess, INFINITE);
  144. DWORD exitCode;
  145. GetExitCodeProcess(processInfo.hProcess, &exitCode);
  146. CloseHandle(processInfo.hProcess);
  147. CloseHandle(processInfo.hThread);
  148. return exitCode;
  149. #else
  150. pid_t pid = fork();
  151. if (!pid)
  152. {
  153. PODVector<const char*> argPtrs;
  154. argPtrs.Push(fixedFileName.CString());
  155. for (unsigned i = 0; i < arguments.Size(); ++i)
  156. argPtrs.Push(arguments[i].CString());
  157. argPtrs.Push(0);
  158. execvp(argPtrs[0], (char**)&argPtrs[0]);
  159. return -1; // Return -1 if we could not spawn the process
  160. }
  161. else if (pid > 0)
  162. {
  163. int exitCode;
  164. wait(&exitCode);
  165. return exitCode;
  166. }
  167. else
  168. return -1;
  169. #endif
  170. }
  171. /// Base class for async execution requests.
  172. class AsyncExecRequest : public Thread
  173. {
  174. public:
  175. /// Construct.
  176. AsyncExecRequest(unsigned& requestID) :
  177. requestID_(requestID),
  178. completed_(false)
  179. {
  180. // Increment ID for next request
  181. ++requestID;
  182. if (requestID == M_MAX_UNSIGNED)
  183. requestID = 1;
  184. }
  185. /// Return request ID.
  186. unsigned GetRequestID() const { return requestID_; }
  187. /// Return exit code. Valid when IsCompleted() is true.
  188. int GetExitCode() const { return exitCode_; }
  189. /// Return completion status.
  190. bool IsCompleted() const { return completed_; }
  191. protected:
  192. /// Request ID.
  193. unsigned requestID_;
  194. /// Exit code.
  195. int exitCode_;
  196. /// Completed flag.
  197. volatile bool completed_;
  198. };
  199. /// Async system command operation.
  200. class AsyncSystemCommand : public AsyncExecRequest
  201. {
  202. public:
  203. /// Construct and run.
  204. AsyncSystemCommand(unsigned requestID, const String& commandLine) :
  205. AsyncExecRequest(requestID),
  206. commandLine_(commandLine)
  207. {
  208. Run();
  209. }
  210. /// The function to run in the thread.
  211. virtual void ThreadFunction()
  212. {
  213. exitCode_ = DoSystemCommand(commandLine_, false, 0);
  214. completed_ = true;
  215. }
  216. private:
  217. /// Command line.
  218. String commandLine_;
  219. };
  220. /// Async system run operation.
  221. class AsyncSystemRun : public AsyncExecRequest
  222. {
  223. public:
  224. /// Construct and run.
  225. AsyncSystemRun(unsigned requestID, const String& fileName, const Vector<String>& arguments) :
  226. AsyncExecRequest(requestID),
  227. fileName_(fileName),
  228. arguments_(arguments)
  229. {
  230. Run();
  231. }
  232. /// The function to run in the thread.
  233. virtual void ThreadFunction()
  234. {
  235. exitCode_ = DoSystemRun(fileName_, arguments_);
  236. completed_ = true;
  237. }
  238. private:
  239. /// File to run.
  240. String fileName_;
  241. /// Command line split in arguments.
  242. const Vector<String>& arguments_;
  243. };
  244. FileSystem::FileSystem(Context* context) :
  245. Object(context),
  246. nextAsyncExecID_(1),
  247. executeConsoleCommands_(false)
  248. {
  249. SubscribeToEvent(E_BEGINFRAME, ATOMIC_HANDLER(FileSystem, HandleBeginFrame));
  250. // Subscribe to console commands
  251. SetExecuteConsoleCommands(true);
  252. }
  253. FileSystem::~FileSystem()
  254. {
  255. // If any async exec items pending, delete them
  256. if (asyncExecQueue_.Size())
  257. {
  258. for (List<AsyncExecRequest*>::Iterator i = asyncExecQueue_.Begin(); i != asyncExecQueue_.End(); ++i)
  259. delete(*i);
  260. asyncExecQueue_.Clear();
  261. }
  262. }
  263. bool FileSystem::SetCurrentDir(const String& pathName)
  264. {
  265. if (!CheckAccess(pathName))
  266. {
  267. ATOMIC_LOGERROR("Access denied to " + pathName);
  268. return false;
  269. }
  270. #ifdef _WIN32
  271. if (SetCurrentDirectoryW(GetWideNativePath(pathName).CString()) == FALSE)
  272. {
  273. ATOMIC_LOGERROR("Failed to change directory to " + pathName);
  274. return false;
  275. }
  276. #else
  277. if (chdir(GetNativePath(pathName).CString()) != 0)
  278. {
  279. ATOMIC_LOGERROR("Failed to change directory to " + pathName);
  280. return false;
  281. }
  282. #endif
  283. return true;
  284. }
  285. bool FileSystem::CreateDir(const String& pathName)
  286. {
  287. if (!CheckAccess(pathName))
  288. {
  289. ATOMIC_LOGERROR("Access denied to " + pathName);
  290. return false;
  291. }
  292. // Create each of the parents if necessary
  293. String parentPath = GetParentPath(pathName);
  294. if (parentPath.Length() > 1 && !DirExists(parentPath))
  295. {
  296. if (!CreateDir(parentPath))
  297. return false;
  298. }
  299. #ifdef _WIN32
  300. bool success = (CreateDirectoryW(GetWideNativePath(RemoveTrailingSlash(pathName)).CString(), 0) == TRUE) ||
  301. (GetLastError() == ERROR_ALREADY_EXISTS);
  302. #else
  303. bool success = mkdir(GetNativePath(RemoveTrailingSlash(pathName)).CString(), S_IRWXU) == 0 || errno == EEXIST;
  304. #endif
  305. if (success)
  306. ATOMIC_LOGDEBUG("Created directory " + pathName);
  307. else
  308. ATOMIC_LOGERROR("Failed to create directory " + pathName);
  309. return success;
  310. }
  311. void FileSystem::SetExecuteConsoleCommands(bool enable)
  312. {
  313. if (enable == executeConsoleCommands_)
  314. return;
  315. executeConsoleCommands_ = enable;
  316. if (enable)
  317. SubscribeToEvent(E_CONSOLECOMMAND, ATOMIC_HANDLER(FileSystem, HandleConsoleCommand));
  318. else
  319. UnsubscribeFromEvent(E_CONSOLECOMMAND);
  320. }
  321. int FileSystem::SystemCommand(const String& commandLine, bool redirectStdOutToLog)
  322. {
  323. if (allowedPaths_.Empty())
  324. return DoSystemCommand(commandLine, redirectStdOutToLog, context_);
  325. else
  326. {
  327. ATOMIC_LOGERROR("Executing an external command is not allowed");
  328. return -1;
  329. }
  330. }
  331. int FileSystem::SystemRun(const String& fileName, const Vector<String>& arguments)
  332. {
  333. if (allowedPaths_.Empty())
  334. return DoSystemRun(fileName, arguments);
  335. else
  336. {
  337. ATOMIC_LOGERROR("Executing an external command is not allowed");
  338. return -1;
  339. }
  340. }
  341. unsigned FileSystem::SystemCommandAsync(const String& commandLine)
  342. {
  343. #ifdef ATOMIC_THREADING
  344. if (allowedPaths_.Empty())
  345. {
  346. unsigned requestID = nextAsyncExecID_;
  347. AsyncSystemCommand* cmd = new AsyncSystemCommand(nextAsyncExecID_, commandLine);
  348. asyncExecQueue_.Push(cmd);
  349. return requestID;
  350. }
  351. else
  352. {
  353. ATOMIC_LOGERROR("Executing an external command is not allowed");
  354. return M_MAX_UNSIGNED;
  355. }
  356. #else
  357. ATOMIC_LOGERROR("Can not execute an asynchronous command as threading is disabled");
  358. return M_MAX_UNSIGNED;
  359. #endif
  360. }
  361. unsigned FileSystem::SystemRunAsync(const String& fileName, const Vector<String>& arguments)
  362. {
  363. #ifdef ATOMIC_THREADING
  364. if (allowedPaths_.Empty())
  365. {
  366. unsigned requestID = nextAsyncExecID_;
  367. AsyncSystemRun* cmd = new AsyncSystemRun(nextAsyncExecID_, fileName, arguments);
  368. asyncExecQueue_.Push(cmd);
  369. return requestID;
  370. }
  371. else
  372. {
  373. ATOMIC_LOGERROR("Executing an external command is not allowed");
  374. return M_MAX_UNSIGNED;
  375. }
  376. #else
  377. ATOMIC_LOGERROR("Can not run asynchronously as threading is disabled");
  378. return M_MAX_UNSIGNED;
  379. #endif
  380. }
  381. bool FileSystem::SystemOpen(const String& fileName, const String& mode)
  382. {
  383. if (allowedPaths_.Empty())
  384. {
  385. // ATOMIC BEGIN
  386. // allow opening of http and file urls
  387. if (!fileName.StartsWith("http://") && !fileName.StartsWith("https://") && !fileName.StartsWith("file://"))
  388. {
  389. if (!FileExists(fileName) && !DirExists(fileName))
  390. {
  391. ATOMIC_LOGERROR("File or directory " + fileName + " not found");
  392. return false;
  393. }
  394. }
  395. // ATOMIC END
  396. #ifdef _WIN32
  397. bool success = (size_t)ShellExecuteW(0, !mode.Empty() ? WString(mode).CString() : 0,
  398. GetWideNativePath(fileName).CString(), 0, 0, SW_SHOW) > 32;
  399. #else
  400. Vector<String> arguments;
  401. arguments.Push(fileName);
  402. bool success = SystemRun(
  403. #if defined(__APPLE__)
  404. "/usr/bin/open",
  405. #else
  406. "/usr/bin/xdg-open",
  407. #endif
  408. arguments) == 0;
  409. #endif
  410. if (!success)
  411. ATOMIC_LOGERROR("Failed to open " + fileName + " externally");
  412. return success;
  413. }
  414. else
  415. {
  416. ATOMIC_LOGERROR("Opening a file externally is not allowed");
  417. return false;
  418. }
  419. }
  420. bool FileSystem::Copy(const String& srcFileName, const String& destFileName)
  421. {
  422. if (!CheckAccess(GetPath(srcFileName)))
  423. {
  424. ATOMIC_LOGERROR("Access denied to " + srcFileName);
  425. return false;
  426. }
  427. if (!CheckAccess(GetPath(destFileName)))
  428. {
  429. ATOMIC_LOGERROR("Access denied to " + destFileName);
  430. return false;
  431. }
  432. SharedPtr<File> srcFile(new File(context_, srcFileName, FILE_READ));
  433. if (!srcFile->IsOpen())
  434. return false;
  435. SharedPtr<File> destFile(new File(context_, destFileName, FILE_WRITE));
  436. if (!destFile->IsOpen())
  437. return false;
  438. unsigned fileSize = srcFile->GetSize();
  439. SharedArrayPtr<unsigned char> buffer(new unsigned char[fileSize]);
  440. unsigned bytesRead = srcFile->Read(buffer.Get(), fileSize);
  441. unsigned bytesWritten = destFile->Write(buffer.Get(), fileSize);
  442. return bytesRead == fileSize && bytesWritten == fileSize;
  443. }
  444. bool FileSystem::Rename(const String& srcFileName, const String& destFileName)
  445. {
  446. if (!CheckAccess(GetPath(srcFileName)))
  447. {
  448. ATOMIC_LOGERROR("Access denied to " + srcFileName);
  449. return false;
  450. }
  451. if (!CheckAccess(GetPath(destFileName)))
  452. {
  453. ATOMIC_LOGERROR("Access denied to " + destFileName);
  454. return false;
  455. }
  456. #ifdef _WIN32
  457. return MoveFileW(GetWideNativePath(srcFileName).CString(), GetWideNativePath(destFileName).CString()) != 0;
  458. #else
  459. return rename(GetNativePath(srcFileName).CString(), GetNativePath(destFileName).CString()) == 0;
  460. #endif
  461. }
  462. bool FileSystem::Delete(const String& fileName)
  463. {
  464. if (!CheckAccess(GetPath(fileName)))
  465. {
  466. ATOMIC_LOGERROR("Access denied to " + fileName);
  467. return false;
  468. }
  469. #ifdef _WIN32
  470. return DeleteFileW(GetWideNativePath(fileName).CString()) != 0;
  471. #else
  472. return remove(GetNativePath(fileName).CString()) == 0;
  473. #endif
  474. }
  475. String FileSystem::GetCurrentDir() const
  476. {
  477. #ifdef _WIN32
  478. wchar_t path[MAX_PATH];
  479. path[0] = 0;
  480. GetCurrentDirectoryW(MAX_PATH, path);
  481. return AddTrailingSlash(String(path));
  482. #else
  483. char path[MAX_PATH];
  484. path[0] = 0;
  485. getcwd(path, MAX_PATH);
  486. return AddTrailingSlash(String(path));
  487. #endif
  488. }
  489. bool FileSystem::CheckAccess(const String& pathName) const
  490. {
  491. String fixedPath = AddTrailingSlash(pathName);
  492. // If no allowed directories defined, succeed always
  493. if (allowedPaths_.Empty())
  494. return true;
  495. // If there is any attempt to go to a parent directory, disallow
  496. if (fixedPath.Contains(".."))
  497. return false;
  498. // Check if the path is a partial match of any of the allowed directories
  499. for (HashSet<String>::ConstIterator i = allowedPaths_.Begin(); i != allowedPaths_.End(); ++i)
  500. {
  501. if (fixedPath.Find(*i) == 0)
  502. return true;
  503. }
  504. // Not found, so disallow
  505. return false;
  506. }
  507. unsigned FileSystem::GetLastModifiedTime(const String& fileName) const
  508. {
  509. if (fileName.Empty() || !CheckAccess(fileName))
  510. return 0;
  511. #ifdef _WIN32
  512. struct _stat st;
  513. if (!_stat(fileName.CString(), &st))
  514. return (unsigned)st.st_mtime;
  515. else
  516. return 0;
  517. #else
  518. struct stat st;
  519. if (!stat(fileName.CString(), &st))
  520. return (unsigned)st.st_mtime;
  521. else
  522. return 0;
  523. #endif
  524. }
  525. bool FileSystem::FileExists(const String& fileName) const
  526. {
  527. if (!CheckAccess(GetPath(fileName)))
  528. return false;
  529. #ifdef __ANDROID__
  530. if (ATOMIC_IS_ASSET(fileName))
  531. {
  532. SDL_RWops* rwOps = SDL_RWFromFile(ATOMIC_ASSET(fileName), "rb");
  533. if (rwOps)
  534. {
  535. SDL_RWclose(rwOps);
  536. return true;
  537. }
  538. else
  539. return false;
  540. }
  541. #endif
  542. String fixedName = GetNativePath(RemoveTrailingSlash(fileName));
  543. #ifdef _WIN32
  544. DWORD attributes = GetFileAttributesW(WString(fixedName).CString());
  545. if (attributes == INVALID_FILE_ATTRIBUTES || attributes & FILE_ATTRIBUTE_DIRECTORY)
  546. return false;
  547. #else
  548. struct stat st;
  549. if (stat(fixedName.CString(), &st) || st.st_mode & S_IFDIR)
  550. return false;
  551. #endif
  552. return true;
  553. }
  554. bool FileSystem::DirExists(const String& pathName) const
  555. {
  556. if (!CheckAccess(pathName))
  557. return false;
  558. #ifndef _WIN32
  559. // Always return true for the root directory
  560. if (pathName == "/")
  561. return true;
  562. #endif
  563. String fixedName = GetNativePath(RemoveTrailingSlash(pathName));
  564. #ifdef __ANDROID__
  565. if (ATOMIC_IS_ASSET(fixedName))
  566. {
  567. // Split the pathname into two components: the longest parent directory path and the last name component
  568. String assetPath(ATOMIC_ASSET((fixedName + "/")));
  569. String parentPath;
  570. unsigned pos = assetPath.FindLast('/', assetPath.Length() - 2);
  571. if (pos != String::NPOS)
  572. {
  573. parentPath = assetPath.Substring(0, pos);
  574. assetPath = assetPath.Substring(pos + 1);
  575. }
  576. assetPath.Resize(assetPath.Length() - 1);
  577. bool exist = false;
  578. int count;
  579. char** list = SDL_Android_GetFileList(parentPath.CString(), &count);
  580. for (int i = 0; i < count; ++i)
  581. {
  582. exist = assetPath == list[i];
  583. if (exist)
  584. break;
  585. }
  586. SDL_Android_FreeFileList(&list, &count);
  587. return exist;
  588. }
  589. #endif
  590. #ifdef _WIN32
  591. DWORD attributes = GetFileAttributesW(WString(fixedName).CString());
  592. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY))
  593. return false;
  594. #else
  595. struct stat st;
  596. if (stat(fixedName.CString(), &st) || !(st.st_mode & S_IFDIR))
  597. return false;
  598. #endif
  599. return true;
  600. }
  601. void FileSystem::ScanDir(Vector<String>& result, const String& pathName, const String& filter, unsigned flags, bool recursive) const
  602. {
  603. result.Clear();
  604. if (CheckAccess(pathName))
  605. {
  606. String initialPath = AddTrailingSlash(pathName);
  607. ScanDirInternal(result, initialPath, initialPath, filter, flags, recursive);
  608. }
  609. }
  610. String FileSystem::GetProgramDir() const
  611. {
  612. #if defined(__ANDROID__)
  613. // This is an internal directory specifier pointing to the assets in the .apk
  614. // Files from this directory will be opened using special handling
  615. return APK;
  616. #elif defined(IOS)
  617. return AddTrailingSlash(SDL_IOS_GetResourceDir());
  618. #elif defined(_WIN32)
  619. wchar_t exeName[MAX_PATH];
  620. exeName[0] = 0;
  621. GetModuleFileNameW(0, exeName, MAX_PATH);
  622. return GetPath(String(exeName));
  623. #elif defined(__APPLE__)
  624. char exeName[MAX_PATH];
  625. memset(exeName, 0, MAX_PATH);
  626. unsigned size = MAX_PATH;
  627. _NSGetExecutablePath(exeName, &size);
  628. return GetPath(String(exeName));
  629. #elif defined(__linux__)
  630. char exeName[MAX_PATH];
  631. memset(exeName, 0, MAX_PATH);
  632. pid_t pid = getpid();
  633. String link = "/proc/" + String(pid) + "/exe";
  634. readlink(link.CString(), exeName, MAX_PATH);
  635. return GetPath(String(exeName));
  636. #else
  637. // ATOMIC BEGIN
  638. // Disabling this on Mac as a possible source of resource issues with app bundles
  639. // https://github.com/AtomicGameEngine/AtomicGameEngine/issues/1209
  640. #ifndef ATOMIC_PLATFORM_OSX
  641. // If the executable directory does not contain CoreData & Data directories, but the current working directory does, use the
  642. // current working directory instead
  643. /// \todo Should not rely on such fixed convention
  644. String currentDir = GetCurrentDir();
  645. if (!DirExists(programDir_ + "CoreData") && !DirExists(programDir_ + "Data") &&
  646. (DirExists(currentDir + "CoreData") || DirExists(currentDir + "Data")))
  647. programDir_ = currentDir;
  648. #endif
  649. // ATOMIC END
  650. return GetCurrentDir();
  651. #endif
  652. }
  653. String FileSystem::GetUserDocumentsDir() const
  654. {
  655. #if defined(__ANDROID__)
  656. return AddTrailingSlash(SDL_Android_GetFilesDir());
  657. #elif defined(IOS)
  658. return AddTrailingSlash(SDL_IOS_GetDocumentsDir());
  659. #elif defined(_WIN32)
  660. wchar_t pathName[MAX_PATH];
  661. pathName[0] = 0;
  662. SHGetSpecialFolderPathW(0, pathName, CSIDL_PERSONAL, 0);
  663. return AddTrailingSlash(String(pathName));
  664. #else
  665. char pathName[MAX_PATH];
  666. pathName[0] = 0;
  667. strcpy(pathName, getenv("HOME"));
  668. return AddTrailingSlash(String(pathName));
  669. #endif
  670. }
  671. String FileSystem::GetAppPreferencesDir(const String& org, const String& app) const
  672. {
  673. String dir;
  674. #ifndef MINI_URHO
  675. char* prefPath = SDL_GetPrefPath(org.CString(), app.CString());
  676. if (prefPath)
  677. {
  678. dir = GetInternalPath(String(prefPath));
  679. SDL_free(prefPath);
  680. }
  681. else
  682. #endif
  683. ATOMIC_LOGWARNING("Could not get application preferences directory");
  684. return dir;
  685. }
  686. void FileSystem::RegisterPath(const String& pathName)
  687. {
  688. if (pathName.Empty())
  689. return;
  690. allowedPaths_.Insert(AddTrailingSlash(pathName));
  691. }
  692. bool FileSystem::SetLastModifiedTime(const String& fileName, unsigned newTime)
  693. {
  694. if (fileName.Empty() || !CheckAccess(fileName))
  695. return false;
  696. #ifdef _WIN32
  697. struct _stat oldTime;
  698. struct _utimbuf newTimes;
  699. if (_stat(fileName.CString(), &oldTime) != 0)
  700. return false;
  701. newTimes.actime = oldTime.st_atime;
  702. newTimes.modtime = newTime;
  703. return _utime(fileName.CString(), &newTimes) == 0;
  704. #else
  705. struct stat oldTime;
  706. struct utimbuf newTimes;
  707. if (stat(fileName.CString(), &oldTime) != 0)
  708. return false;
  709. newTimes.actime = oldTime.st_atime;
  710. newTimes.modtime = newTime;
  711. return utime(fileName.CString(), &newTimes) == 0;
  712. #endif
  713. }
  714. void FileSystem::ScanDirInternal(Vector<String>& result, String path, const String& startPath,
  715. const String& filter, unsigned flags, bool recursive) const
  716. {
  717. path = AddTrailingSlash(path);
  718. String deltaPath;
  719. if (path.Length() > startPath.Length())
  720. deltaPath = path.Substring(startPath.Length());
  721. // ATOMIC BEGIN
  722. String filterExtension = filter.Substring(filter.FindLast('.'));
  723. // ATOMIC END
  724. if (filterExtension.Contains('*'))
  725. filterExtension.Clear();
  726. #ifdef __ANDROID__
  727. if (ATOMIC_IS_ASSET(path))
  728. {
  729. String assetPath(ATOMIC_ASSET(path));
  730. assetPath.Resize(assetPath.Length() - 1); // AssetManager.list() does not like trailing slash
  731. int count;
  732. char** list = SDL_Android_GetFileList(assetPath.CString(), &count);
  733. for (int i = 0; i < count; ++i)
  734. {
  735. String fileName(list[i]);
  736. if (!(flags & SCAN_HIDDEN) && fileName.StartsWith("."))
  737. continue;
  738. #ifdef ASSET_DIR_INDICATOR
  739. // Patch the directory name back after retrieving the directory flag
  740. bool isDirectory = fileName.EndsWith(ASSET_DIR_INDICATOR);
  741. if (isDirectory)
  742. {
  743. fileName.Resize(fileName.Length() - sizeof(ASSET_DIR_INDICATOR) / sizeof(char) + 1);
  744. if (flags & SCAN_DIRS)
  745. result.Push(deltaPath + fileName);
  746. if (recursive)
  747. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  748. }
  749. else if (flags & SCAN_FILES)
  750. #endif
  751. {
  752. if (filterExtension.Empty() || fileName.EndsWith(filterExtension))
  753. result.Push(deltaPath + fileName);
  754. }
  755. }
  756. SDL_Android_FreeFileList(&list, &count);
  757. return;
  758. }
  759. #endif
  760. #ifdef _WIN32
  761. WIN32_FIND_DATAW info;
  762. HANDLE handle = FindFirstFileW(WString(path + "*").CString(), &info);
  763. if (handle != INVALID_HANDLE_VALUE)
  764. {
  765. do
  766. {
  767. String fileName(info.cFileName);
  768. if (!fileName.Empty())
  769. {
  770. if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN && !(flags & SCAN_HIDDEN))
  771. continue;
  772. if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  773. {
  774. if (flags & SCAN_DIRS)
  775. result.Push(deltaPath + fileName);
  776. if (recursive && fileName != "." && fileName != "..")
  777. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  778. }
  779. else if (flags & SCAN_FILES)
  780. {
  781. if (filterExtension.Empty() || fileName.EndsWith(filterExtension))
  782. result.Push(deltaPath + fileName);
  783. }
  784. }
  785. }
  786. while (FindNextFileW(handle, &info));
  787. FindClose(handle);
  788. }
  789. #else
  790. DIR* dir;
  791. struct dirent* de;
  792. struct stat st;
  793. dir = opendir(GetNativePath(path).CString());
  794. if (dir)
  795. {
  796. while ((de = readdir(dir)))
  797. {
  798. /// \todo Filename may be unnormalized Unicode on Mac OS X. Re-normalize as necessary
  799. String fileName(de->d_name);
  800. bool normalEntry = fileName != "." && fileName != "..";
  801. if (normalEntry && !(flags & SCAN_HIDDEN) && fileName.StartsWith("."))
  802. continue;
  803. String pathAndName = path + fileName;
  804. if (!stat(pathAndName.CString(), &st))
  805. {
  806. if (st.st_mode & S_IFDIR)
  807. {
  808. if (flags & SCAN_DIRS)
  809. result.Push(deltaPath + fileName);
  810. if (recursive && normalEntry)
  811. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  812. }
  813. else if (flags & SCAN_FILES)
  814. {
  815. if (filterExtension.Empty() || fileName.EndsWith(filterExtension))
  816. result.Push(deltaPath + fileName);
  817. }
  818. }
  819. }
  820. closedir(dir);
  821. }
  822. #endif
  823. }
  824. void FileSystem::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  825. {
  826. /// Go through the execution queue and post + remove completed requests
  827. for (List<AsyncExecRequest*>::Iterator i = asyncExecQueue_.Begin(); i != asyncExecQueue_.End();)
  828. {
  829. AsyncExecRequest* request = *i;
  830. if (request->IsCompleted())
  831. {
  832. using namespace AsyncExecFinished;
  833. VariantMap& newEventData = GetEventDataMap();
  834. newEventData[P_REQUESTID] = request->GetRequestID();
  835. newEventData[P_EXITCODE] = request->GetExitCode();
  836. SendEvent(E_ASYNCEXECFINISHED, newEventData);
  837. delete request;
  838. i = asyncExecQueue_.Erase(i);
  839. }
  840. else
  841. ++i;
  842. }
  843. }
  844. void FileSystem::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  845. {
  846. using namespace ConsoleCommand;
  847. if (eventData[P_ID].GetString() == GetTypeName())
  848. SystemCommand(eventData[P_COMMAND].GetString(), true);
  849. }
  850. void SplitPath(const String& fullPath, String& pathName, String& fileName, String& extension, bool lowercaseExtension)
  851. {
  852. String fullPathCopy = GetInternalPath(fullPath);
  853. unsigned extPos = fullPathCopy.FindLast('.');
  854. unsigned pathPos = fullPathCopy.FindLast('/');
  855. if (extPos != String::NPOS && (pathPos == String::NPOS || extPos > pathPos))
  856. {
  857. extension = fullPathCopy.Substring(extPos);
  858. if (lowercaseExtension)
  859. extension = extension.ToLower();
  860. fullPathCopy = fullPathCopy.Substring(0, extPos);
  861. }
  862. else
  863. extension.Clear();
  864. pathPos = fullPathCopy.FindLast('/');
  865. if (pathPos != String::NPOS)
  866. {
  867. fileName = fullPathCopy.Substring(pathPos + 1);
  868. pathName = fullPathCopy.Substring(0, pathPos + 1);
  869. }
  870. else
  871. {
  872. fileName = fullPathCopy;
  873. pathName.Clear();
  874. }
  875. }
  876. String GetPath(const String& fullPath)
  877. {
  878. String path, file, extension;
  879. SplitPath(fullPath, path, file, extension);
  880. return path;
  881. }
  882. String GetFileName(const String& fullPath)
  883. {
  884. String path, file, extension;
  885. SplitPath(fullPath, path, file, extension);
  886. return file;
  887. }
  888. String GetExtension(const String& fullPath, bool lowercaseExtension)
  889. {
  890. String path, file, extension;
  891. SplitPath(fullPath, path, file, extension, lowercaseExtension);
  892. return extension;
  893. }
  894. String GetFileNameAndExtension(const String& fileName, bool lowercaseExtension)
  895. {
  896. String path, file, extension;
  897. SplitPath(fileName, path, file, extension, lowercaseExtension);
  898. return file + extension;
  899. }
  900. String ReplaceExtension(const String& fullPath, const String& newExtension)
  901. {
  902. String path, file, extension;
  903. SplitPath(fullPath, path, file, extension);
  904. return path + file + newExtension;
  905. }
  906. String AddTrailingSlash(const String& pathName)
  907. {
  908. String ret = pathName.Trimmed();
  909. ret.Replace('\\', '/');
  910. if (!ret.Empty() && ret.Back() != '/')
  911. ret += '/';
  912. return ret;
  913. }
  914. String RemoveTrailingSlash(const String& pathName)
  915. {
  916. String ret = pathName.Trimmed();
  917. ret.Replace('\\', '/');
  918. if (!ret.Empty() && ret.Back() == '/')
  919. ret.Resize(ret.Length() - 1);
  920. return ret;
  921. }
  922. String GetParentPath(const String& path)
  923. {
  924. unsigned pos = RemoveTrailingSlash(path).FindLast('/');
  925. if (pos != String::NPOS)
  926. return path.Substring(0, pos + 1);
  927. else
  928. return String();
  929. }
  930. String GetInternalPath(const String& pathName)
  931. {
  932. return pathName.Replaced('\\', '/');
  933. }
  934. String GetNativePath(const String& pathName)
  935. {
  936. #ifdef _WIN32
  937. return pathName.Replaced('/', '\\');
  938. #else
  939. return pathName;
  940. #endif
  941. }
  942. WString GetWideNativePath(const String& pathName)
  943. {
  944. #ifdef _WIN32
  945. return WString(pathName.Replaced('/', '\\'));
  946. #else
  947. return WString(pathName);
  948. #endif
  949. }
  950. bool IsAbsolutePath(const String& pathName)
  951. {
  952. if (pathName.Empty())
  953. return false;
  954. String path = GetInternalPath(pathName);
  955. if (path[0] == '/')
  956. return true;
  957. #ifdef _WIN32
  958. if (path.Length() > 1 && IsAlpha(path[0]) && path[1] == ':')
  959. return true;
  960. #endif
  961. return false;
  962. }
  963. // ATOMIC BEGIN
  964. bool FileSystem::CreateDirs(const String& root, const String& subdirectory)
  965. {
  966. String folder = AddTrailingSlash(GetInternalPath(root));
  967. String sub = GetInternalPath(subdirectory);
  968. Vector<String> subs = sub.Split('/');
  969. for (unsigned i = 0; i < subs.Size(); i++)
  970. {
  971. folder += subs[i];
  972. folder += "/";
  973. if (DirExists(folder))
  974. continue;
  975. CreateDir(folder);
  976. if (!DirExists(folder))
  977. return false;
  978. }
  979. return true;
  980. }
  981. bool FileSystem::CreateDirsRecursive(const String& directoryIn)
  982. {
  983. String directory = AddTrailingSlash(GetInternalPath(directoryIn));
  984. if (DirExists(directory))
  985. return true;
  986. if (FileExists(directory))
  987. return false;
  988. String parentPath = directory;
  989. Vector<String> paths;
  990. paths.Push(directory);
  991. while (true)
  992. {
  993. parentPath = GetParentPath(parentPath);
  994. if (!parentPath.Length())
  995. break;
  996. paths.Push(parentPath);
  997. }
  998. if (!paths.Size())
  999. return false;
  1000. for (int i = (int) (paths.Size() - 1); i >= 0; i--)
  1001. {
  1002. const String& pathName = paths[i];
  1003. if (FileExists(pathName))
  1004. return false;
  1005. if (DirExists(pathName))
  1006. continue;
  1007. if (!CreateDir(pathName))
  1008. return false;
  1009. // double check
  1010. if (!DirExists(pathName))
  1011. return false;
  1012. }
  1013. return true;
  1014. }
  1015. bool FileSystem::RemoveDir(const String& directoryIn, bool recursive)
  1016. {
  1017. String directory = AddTrailingSlash(directoryIn);
  1018. if (!DirExists(directory))
  1019. return false;
  1020. Vector<String> results;
  1021. // ensure empty if not recursive
  1022. if (!recursive)
  1023. {
  1024. ScanDir(results, directory, "*", SCAN_DIRS | SCAN_FILES | SCAN_HIDDEN, true );
  1025. while (results.Remove(".")) {}
  1026. while (results.Remove("..")) {}
  1027. if (results.Size())
  1028. return false;
  1029. #ifdef WIN32
  1030. return RemoveDirectoryW(GetWideNativePath(directory).CString()) != 0;
  1031. #endif
  1032. #ifdef __APPLE__
  1033. return remove(GetNativePath(directory).CString()) == 0;
  1034. #endif
  1035. }
  1036. // delete all files at this level
  1037. ScanDir(results, directory, "*", SCAN_FILES | SCAN_HIDDEN, false );
  1038. for (unsigned i = 0; i < results.Size(); i++)
  1039. {
  1040. if (!Delete(directory + results[i]))
  1041. return false;
  1042. }
  1043. results.Clear();
  1044. // recurse into subfolders
  1045. ScanDir(results, directory, "*", SCAN_DIRS, false );
  1046. for (unsigned i = 0; i < results.Size(); i++)
  1047. {
  1048. if (results[i] == "." || results[i] == "..")
  1049. continue;
  1050. if (!RemoveDir(directory + results[i], true))
  1051. return false;
  1052. }
  1053. return RemoveDir(directory, false);
  1054. }
  1055. bool FileSystem::CopyDir(const String& directoryIn, const String& directoryOut)
  1056. {
  1057. if (FileExists(directoryOut) || DirExists(directoryOut))
  1058. return false;
  1059. Vector<String> results;
  1060. ScanDir(results, directoryIn, "*", SCAN_FILES, true );
  1061. for (unsigned i = 0; i < results.Size(); i++)
  1062. {
  1063. String srcFile = directoryIn + "/" + results[i];
  1064. String dstFile = directoryOut + "/" + results[i];
  1065. String dstPath = GetPath(dstFile);
  1066. if (!CreateDirsRecursive(dstPath))
  1067. return false;
  1068. //LOGINFOF("SRC: %s DST: %s", srcFile.CString(), dstFile.CString());
  1069. if (!Copy(srcFile, dstFile))
  1070. return false;
  1071. }
  1072. return true;
  1073. }
  1074. bool IsAbsoluteParentPath(const String& absParentPath, const String& fullPath)
  1075. {
  1076. if (!IsAbsolutePath(absParentPath) || !IsAbsolutePath(fullPath))
  1077. return false;
  1078. String path1 = AddTrailingSlash(GetSanitizedPath(absParentPath));
  1079. String path2 = AddTrailingSlash(GetSanitizedPath(GetPath(fullPath)));
  1080. if (path2.StartsWith(path1))
  1081. return true;
  1082. return false;
  1083. }
  1084. String GetSanitizedPath(const String& path)
  1085. {
  1086. String sanitized = GetInternalPath(path);
  1087. StringVector parts = sanitized.Split('/');
  1088. bool hasTrailingSlash = path.EndsWith("/") || path.EndsWith("\\");
  1089. #ifndef ATOMIC_PLATFORM_WINDOWS
  1090. bool absolute = IsAbsolutePath(path);
  1091. sanitized = String::Joined(parts, "/");
  1092. if (absolute)
  1093. sanitized = "/" + sanitized;
  1094. #else
  1095. sanitized = String::Joined(parts, "/");
  1096. #endif
  1097. if (hasTrailingSlash)
  1098. sanitized += "/";
  1099. return sanitized;
  1100. }
  1101. bool GetRelativePath(const String& fromPath, const String& toPath, String& output)
  1102. {
  1103. output = String::EMPTY;
  1104. String from = GetSanitizedPath(fromPath);
  1105. String to = GetSanitizedPath(toPath);
  1106. StringVector fromParts = from.Split('/');
  1107. StringVector toParts = to.Split('/');
  1108. if (!fromParts.Size() || !toParts.Size())
  1109. return false;
  1110. if (fromParts == toParts)
  1111. {
  1112. return true;
  1113. }
  1114. // no common base?
  1115. if (fromParts[0] != toParts[0])
  1116. return false;
  1117. int startIdx;
  1118. for (startIdx = 0; startIdx < toParts.Size(); startIdx++)
  1119. {
  1120. if (startIdx >= fromParts.Size() || fromParts[startIdx] != toParts[startIdx])
  1121. break;
  1122. }
  1123. if (startIdx == toParts.Size())
  1124. {
  1125. if (from.EndsWith("/") && to.EndsWith("/"))
  1126. {
  1127. for (unsigned i = 0; i < fromParts.Size() - startIdx; i++)
  1128. {
  1129. output += "../";
  1130. }
  1131. return true;
  1132. }
  1133. return false;
  1134. }
  1135. for (int i = 0; i < (int)fromParts.Size() - startIdx; i++)
  1136. {
  1137. output += "../";
  1138. }
  1139. for (int i = startIdx; i < (int) toParts.Size(); i++)
  1140. {
  1141. output += toParts[i] + "/";
  1142. }
  1143. return true;
  1144. }
  1145. // ATOMIC END
  1146. }