FileSystem.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. //
  2. // Copyright (c) 2008-2016 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(NO_POPEN) && !defined(MINI_URHO)
  82. if (!redirectToLog)
  83. #endif
  84. return system(commandLine.CString());
  85. #if !defined(NO_POPEN) && !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("urho3d", "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. if (!FileExists(fileName) && !DirExists(fileName))
  389. {
  390. ATOMIC_LOGERROR("File or directory " + fileName + " not found");
  391. return false;
  392. }
  393. // ATOMIC END
  394. #ifdef _WIN32
  395. bool success = (size_t)ShellExecuteW(0, !mode.Empty() ? WString(mode).CString() : 0,
  396. GetWideNativePath(fileName).CString(), 0, 0, SW_SHOW) > 32;
  397. #else
  398. Vector<String> arguments;
  399. arguments.Push(fileName);
  400. bool success = SystemRun(
  401. #if defined(__APPLE__)
  402. "/usr/bin/open",
  403. #else
  404. "/usr/bin/xdg-open",
  405. #endif
  406. arguments) == 0;
  407. #endif
  408. if (!success)
  409. ATOMIC_LOGERROR("Failed to open " + fileName + " externally");
  410. return success;
  411. }
  412. else
  413. {
  414. ATOMIC_LOGERROR("Opening a file externally is not allowed");
  415. return false;
  416. }
  417. }
  418. bool FileSystem::Copy(const String& srcFileName, const String& destFileName)
  419. {
  420. if (!CheckAccess(GetPath(srcFileName)))
  421. {
  422. ATOMIC_LOGERROR("Access denied to " + srcFileName);
  423. return false;
  424. }
  425. if (!CheckAccess(GetPath(destFileName)))
  426. {
  427. ATOMIC_LOGERROR("Access denied to " + destFileName);
  428. return false;
  429. }
  430. SharedPtr<File> srcFile(new File(context_, srcFileName, FILE_READ));
  431. if (!srcFile->IsOpen())
  432. return false;
  433. SharedPtr<File> destFile(new File(context_, destFileName, FILE_WRITE));
  434. if (!destFile->IsOpen())
  435. return false;
  436. unsigned fileSize = srcFile->GetSize();
  437. SharedArrayPtr<unsigned char> buffer(new unsigned char[fileSize]);
  438. unsigned bytesRead = srcFile->Read(buffer.Get(), fileSize);
  439. unsigned bytesWritten = destFile->Write(buffer.Get(), fileSize);
  440. return bytesRead == fileSize && bytesWritten == fileSize;
  441. }
  442. bool FileSystem::Rename(const String& srcFileName, const String& destFileName)
  443. {
  444. if (!CheckAccess(GetPath(srcFileName)))
  445. {
  446. ATOMIC_LOGERROR("Access denied to " + srcFileName);
  447. return false;
  448. }
  449. if (!CheckAccess(GetPath(destFileName)))
  450. {
  451. ATOMIC_LOGERROR("Access denied to " + destFileName);
  452. return false;
  453. }
  454. #ifdef _WIN32
  455. return MoveFileW(GetWideNativePath(srcFileName).CString(), GetWideNativePath(destFileName).CString()) != 0;
  456. #else
  457. return rename(GetNativePath(srcFileName).CString(), GetNativePath(destFileName).CString()) == 0;
  458. #endif
  459. }
  460. bool FileSystem::Delete(const String& fileName)
  461. {
  462. if (!CheckAccess(GetPath(fileName)))
  463. {
  464. ATOMIC_LOGERROR("Access denied to " + fileName);
  465. return false;
  466. }
  467. #ifdef _WIN32
  468. return DeleteFileW(GetWideNativePath(fileName).CString()) != 0;
  469. #else
  470. return remove(GetNativePath(fileName).CString()) == 0;
  471. #endif
  472. }
  473. String FileSystem::GetCurrentDir() const
  474. {
  475. #ifdef _WIN32
  476. wchar_t path[MAX_PATH];
  477. path[0] = 0;
  478. GetCurrentDirectoryW(MAX_PATH, path);
  479. return AddTrailingSlash(String(path));
  480. #else
  481. char path[MAX_PATH];
  482. path[0] = 0;
  483. getcwd(path, MAX_PATH);
  484. return AddTrailingSlash(String(path));
  485. #endif
  486. }
  487. bool FileSystem::CheckAccess(const String& pathName) const
  488. {
  489. String fixedPath = AddTrailingSlash(pathName);
  490. // If no allowed directories defined, succeed always
  491. if (allowedPaths_.Empty())
  492. return true;
  493. // If there is any attempt to go to a parent directory, disallow
  494. if (fixedPath.Contains(".."))
  495. return false;
  496. // Check if the path is a partial match of any of the allowed directories
  497. for (HashSet<String>::ConstIterator i = allowedPaths_.Begin(); i != allowedPaths_.End(); ++i)
  498. {
  499. if (fixedPath.Find(*i) == 0)
  500. return true;
  501. }
  502. // Not found, so disallow
  503. return false;
  504. }
  505. unsigned FileSystem::GetLastModifiedTime(const String& fileName) const
  506. {
  507. if (fileName.Empty() || !CheckAccess(fileName))
  508. return 0;
  509. #ifdef _WIN32
  510. struct _stat st;
  511. if (!_stat(fileName.CString(), &st))
  512. return (unsigned)st.st_mtime;
  513. else
  514. return 0;
  515. #else
  516. struct stat st;
  517. if (!stat(fileName.CString(), &st))
  518. return (unsigned)st.st_mtime;
  519. else
  520. return 0;
  521. #endif
  522. }
  523. bool FileSystem::FileExists(const String& fileName) const
  524. {
  525. if (!CheckAccess(GetPath(fileName)))
  526. return false;
  527. #ifdef __ANDROID__
  528. if (ATOMIC_IS_ASSET(fileName))
  529. {
  530. SDL_RWops* rwOps = SDL_RWFromFile(ATOMIC_ASSET(fileName), "rb");
  531. if (rwOps)
  532. {
  533. SDL_RWclose(rwOps);
  534. return true;
  535. }
  536. else
  537. return false;
  538. }
  539. #endif
  540. String fixedName = GetNativePath(RemoveTrailingSlash(fileName));
  541. #ifdef _WIN32
  542. DWORD attributes = GetFileAttributesW(WString(fixedName).CString());
  543. if (attributes == INVALID_FILE_ATTRIBUTES || attributes & FILE_ATTRIBUTE_DIRECTORY)
  544. return false;
  545. #else
  546. struct stat st;
  547. if (stat(fixedName.CString(), &st) || st.st_mode & S_IFDIR)
  548. return false;
  549. #endif
  550. return true;
  551. }
  552. bool FileSystem::DirExists(const String& pathName) const
  553. {
  554. if (!CheckAccess(pathName))
  555. return false;
  556. #ifndef _WIN32
  557. // Always return true for the root directory
  558. if (pathName == "/")
  559. return true;
  560. #endif
  561. String fixedName = GetNativePath(RemoveTrailingSlash(pathName));
  562. #ifdef __ANDROID__
  563. if (ATOMIC_IS_ASSET(fixedName))
  564. {
  565. // Split the pathname into two components: the longest parent directory path and the last name component
  566. String assetPath(ATOMIC_ASSET((fixedName + "/")));
  567. String parentPath;
  568. unsigned pos = assetPath.FindLast('/', assetPath.Length() - 2);
  569. if (pos != String::NPOS)
  570. {
  571. parentPath = assetPath.Substring(0, pos);
  572. assetPath = assetPath.Substring(pos + 1);
  573. }
  574. assetPath.Resize(assetPath.Length() - 1);
  575. bool exist = false;
  576. int count;
  577. char** list = SDL_Android_GetFileList(parentPath.CString(), &count);
  578. for (int i = 0; i < count; ++i)
  579. {
  580. exist = assetPath == list[i];
  581. if (exist)
  582. break;
  583. }
  584. SDL_Android_FreeFileList(&list, &count);
  585. return exist;
  586. }
  587. #endif
  588. #ifdef _WIN32
  589. DWORD attributes = GetFileAttributesW(WString(fixedName).CString());
  590. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY))
  591. return false;
  592. #else
  593. struct stat st;
  594. if (stat(fixedName.CString(), &st) || !(st.st_mode & S_IFDIR))
  595. return false;
  596. #endif
  597. return true;
  598. }
  599. void FileSystem::ScanDir(Vector<String>& result, const String& pathName, const String& filter, unsigned flags, bool recursive) const
  600. {
  601. result.Clear();
  602. if (CheckAccess(pathName))
  603. {
  604. String initialPath = AddTrailingSlash(pathName);
  605. ScanDirInternal(result, initialPath, initialPath, filter, flags, recursive);
  606. }
  607. }
  608. String FileSystem::GetProgramDir() const
  609. {
  610. // Return cached value if possible
  611. if (!programDir_.Empty())
  612. return programDir_;
  613. #if defined(__ANDROID__)
  614. // This is an internal directory specifier pointing to the assets in the .apk
  615. // Files from this directory will be opened using special handling
  616. programDir_ = APK;
  617. return programDir_;
  618. #elif defined(IOS)
  619. programDir_ = AddTrailingSlash(SDL_IOS_GetResourceDir());
  620. return programDir_;
  621. #elif defined(_WIN32)
  622. wchar_t exeName[MAX_PATH];
  623. exeName[0] = 0;
  624. GetModuleFileNameW(0, exeName, MAX_PATH);
  625. programDir_ = GetPath(String(exeName));
  626. #elif defined(__APPLE__)
  627. char exeName[MAX_PATH];
  628. memset(exeName, 0, MAX_PATH);
  629. unsigned size = MAX_PATH;
  630. _NSGetExecutablePath(exeName, &size);
  631. programDir_ = GetPath(String(exeName));
  632. #elif defined(__linux__)
  633. char exeName[MAX_PATH];
  634. memset(exeName, 0, MAX_PATH);
  635. pid_t pid = getpid();
  636. String link = "/proc/" + String(pid) + "/exe";
  637. readlink(link.CString(), exeName, MAX_PATH);
  638. programDir_ = GetPath(String(exeName));
  639. #endif
  640. // ATOMIC BEGIN
  641. // Disabling this on Mac as a possible source of resource issues with app bundles
  642. // https://github.com/AtomicGameEngine/AtomicGameEngine/issues/1209
  643. #ifndef ATOMIC_PLATFORM_OSX
  644. // If the executable directory does not contain CoreData & Data directories, but the current working directory does, use the
  645. // current working directory instead
  646. /// \todo Should not rely on such fixed convention
  647. String currentDir = GetCurrentDir();
  648. if (!DirExists(programDir_ + "CoreData") && !DirExists(programDir_ + "Data") &&
  649. (DirExists(currentDir + "CoreData") || DirExists(currentDir + "Data")))
  650. programDir_ = currentDir;
  651. #endif
  652. // ATOMIC END
  653. // Sanitate /./ construct away
  654. programDir_.Replace("/./", "/");
  655. return programDir_;
  656. }
  657. String FileSystem::GetUserDocumentsDir() const
  658. {
  659. #if defined(__ANDROID__)
  660. return AddTrailingSlash(SDL_Android_GetFilesDir());
  661. #elif defined(IOS)
  662. return AddTrailingSlash(SDL_IOS_GetDocumentsDir());
  663. #elif defined(_WIN32)
  664. wchar_t pathName[MAX_PATH];
  665. pathName[0] = 0;
  666. SHGetSpecialFolderPathW(0, pathName, CSIDL_PERSONAL, 0);
  667. return AddTrailingSlash(String(pathName));
  668. #else
  669. char pathName[MAX_PATH];
  670. pathName[0] = 0;
  671. strcpy(pathName, getenv("HOME"));
  672. return AddTrailingSlash(String(pathName));
  673. #endif
  674. }
  675. String FileSystem::GetAppPreferencesDir(const String& org, const String& app) const
  676. {
  677. String dir;
  678. #ifndef MINI_URHO
  679. char* prefPath = SDL_GetPrefPath(org.CString(), app.CString());
  680. if (prefPath)
  681. {
  682. dir = GetInternalPath(String(prefPath));
  683. SDL_free(prefPath);
  684. }
  685. else
  686. #endif
  687. ATOMIC_LOGWARNING("Could not get application preferences directory");
  688. return dir;
  689. }
  690. void FileSystem::RegisterPath(const String& pathName)
  691. {
  692. if (pathName.Empty())
  693. return;
  694. allowedPaths_.Insert(AddTrailingSlash(pathName));
  695. }
  696. bool FileSystem::SetLastModifiedTime(const String& fileName, unsigned newTime)
  697. {
  698. if (fileName.Empty() || !CheckAccess(fileName))
  699. return false;
  700. #ifdef _WIN32
  701. struct _stat oldTime;
  702. struct _utimbuf newTimes;
  703. if (_stat(fileName.CString(), &oldTime) != 0)
  704. return false;
  705. newTimes.actime = oldTime.st_atime;
  706. newTimes.modtime = newTime;
  707. return _utime(fileName.CString(), &newTimes) == 0;
  708. #else
  709. struct stat oldTime;
  710. struct utimbuf newTimes;
  711. if (stat(fileName.CString(), &oldTime) != 0)
  712. return false;
  713. newTimes.actime = oldTime.st_atime;
  714. newTimes.modtime = newTime;
  715. return utime(fileName.CString(), &newTimes) == 0;
  716. #endif
  717. }
  718. void FileSystem::ScanDirInternal(Vector<String>& result, String path, const String& startPath,
  719. const String& filter, unsigned flags, bool recursive) const
  720. {
  721. path = AddTrailingSlash(path);
  722. String deltaPath;
  723. if (path.Length() > startPath.Length())
  724. deltaPath = path.Substring(startPath.Length());
  725. // ATOMIC BEGIN
  726. String filterExtension = filter.Substring(filter.FindLast('.'));
  727. // ATOMIC END
  728. if (filterExtension.Contains('*'))
  729. filterExtension.Clear();
  730. #ifdef __ANDROID__
  731. if (ATOMIC_IS_ASSET(path))
  732. {
  733. String assetPath(ATOMIC_ASSET(path));
  734. assetPath.Resize(assetPath.Length() - 1); // AssetManager.list() does not like trailing slash
  735. int count;
  736. char** list = SDL_Android_GetFileList(assetPath.CString(), &count);
  737. for (int i = 0; i < count; ++i)
  738. {
  739. String fileName(list[i]);
  740. if (!(flags & SCAN_HIDDEN) && fileName.StartsWith("."))
  741. continue;
  742. #ifdef ASSET_DIR_INDICATOR
  743. // Patch the directory name back after retrieving the directory flag
  744. bool isDirectory = fileName.EndsWith(ASSET_DIR_INDICATOR);
  745. if (isDirectory)
  746. {
  747. fileName.Resize(fileName.Length() - sizeof(ASSET_DIR_INDICATOR) / sizeof(char) + 1);
  748. if (flags & SCAN_DIRS)
  749. result.Push(deltaPath + fileName);
  750. if (recursive)
  751. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  752. }
  753. else if (flags & SCAN_FILES)
  754. #endif
  755. {
  756. if (filterExtension.Empty() || fileName.EndsWith(filterExtension))
  757. result.Push(deltaPath + fileName);
  758. }
  759. }
  760. SDL_Android_FreeFileList(&list, &count);
  761. return;
  762. }
  763. #endif
  764. #ifdef _WIN32
  765. WIN32_FIND_DATAW info;
  766. HANDLE handle = FindFirstFileW(WString(path + "*").CString(), &info);
  767. if (handle != INVALID_HANDLE_VALUE)
  768. {
  769. do
  770. {
  771. String fileName(info.cFileName);
  772. if (!fileName.Empty())
  773. {
  774. if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN && !(flags & SCAN_HIDDEN))
  775. continue;
  776. if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  777. {
  778. if (flags & SCAN_DIRS)
  779. result.Push(deltaPath + fileName);
  780. if (recursive && fileName != "." && fileName != "..")
  781. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  782. }
  783. else if (flags & SCAN_FILES)
  784. {
  785. if (filterExtension.Empty() || fileName.EndsWith(filterExtension))
  786. result.Push(deltaPath + fileName);
  787. }
  788. }
  789. }
  790. while (FindNextFileW(handle, &info));
  791. FindClose(handle);
  792. }
  793. #else
  794. DIR* dir;
  795. struct dirent* de;
  796. struct stat st;
  797. dir = opendir(GetNativePath(path).CString());
  798. if (dir)
  799. {
  800. while ((de = readdir(dir)))
  801. {
  802. /// \todo Filename may be unnormalized Unicode on Mac OS X. Re-normalize as necessary
  803. String fileName(de->d_name);
  804. bool normalEntry = fileName != "." && fileName != "..";
  805. if (normalEntry && !(flags & SCAN_HIDDEN) && fileName.StartsWith("."))
  806. continue;
  807. String pathAndName = path + fileName;
  808. if (!stat(pathAndName.CString(), &st))
  809. {
  810. if (st.st_mode & S_IFDIR)
  811. {
  812. if (flags & SCAN_DIRS)
  813. result.Push(deltaPath + fileName);
  814. if (recursive && normalEntry)
  815. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  816. }
  817. else if (flags & SCAN_FILES)
  818. {
  819. if (filterExtension.Empty() || fileName.EndsWith(filterExtension))
  820. result.Push(deltaPath + fileName);
  821. }
  822. }
  823. }
  824. closedir(dir);
  825. }
  826. #endif
  827. }
  828. void FileSystem::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  829. {
  830. /// Go through the execution queue and post + remove completed requests
  831. for (List<AsyncExecRequest*>::Iterator i = asyncExecQueue_.Begin(); i != asyncExecQueue_.End();)
  832. {
  833. AsyncExecRequest* request = *i;
  834. if (request->IsCompleted())
  835. {
  836. using namespace AsyncExecFinished;
  837. VariantMap& newEventData = GetEventDataMap();
  838. newEventData[P_REQUESTID] = request->GetRequestID();
  839. newEventData[P_EXITCODE] = request->GetExitCode();
  840. SendEvent(E_ASYNCEXECFINISHED, newEventData);
  841. delete request;
  842. i = asyncExecQueue_.Erase(i);
  843. }
  844. else
  845. ++i;
  846. }
  847. }
  848. void FileSystem::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  849. {
  850. using namespace ConsoleCommand;
  851. if (eventData[P_ID].GetString() == GetTypeName())
  852. SystemCommand(eventData[P_COMMAND].GetString(), true);
  853. }
  854. void SplitPath(const String& fullPath, String& pathName, String& fileName, String& extension, bool lowercaseExtension)
  855. {
  856. String fullPathCopy = GetInternalPath(fullPath);
  857. unsigned extPos = fullPathCopy.FindLast('.');
  858. unsigned pathPos = fullPathCopy.FindLast('/');
  859. if (extPos != String::NPOS && (pathPos == String::NPOS || extPos > pathPos))
  860. {
  861. extension = fullPathCopy.Substring(extPos);
  862. if (lowercaseExtension)
  863. extension = extension.ToLower();
  864. fullPathCopy = fullPathCopy.Substring(0, extPos);
  865. }
  866. else
  867. extension.Clear();
  868. pathPos = fullPathCopy.FindLast('/');
  869. if (pathPos != String::NPOS)
  870. {
  871. fileName = fullPathCopy.Substring(pathPos + 1);
  872. pathName = fullPathCopy.Substring(0, pathPos + 1);
  873. }
  874. else
  875. {
  876. fileName = fullPathCopy;
  877. pathName.Clear();
  878. }
  879. }
  880. String GetPath(const String& fullPath)
  881. {
  882. String path, file, extension;
  883. SplitPath(fullPath, path, file, extension);
  884. return path;
  885. }
  886. String GetFileName(const String& fullPath)
  887. {
  888. String path, file, extension;
  889. SplitPath(fullPath, path, file, extension);
  890. return file;
  891. }
  892. String GetExtension(const String& fullPath, bool lowercaseExtension)
  893. {
  894. String path, file, extension;
  895. SplitPath(fullPath, path, file, extension, lowercaseExtension);
  896. return extension;
  897. }
  898. String GetFileNameAndExtension(const String& fileName, bool lowercaseExtension)
  899. {
  900. String path, file, extension;
  901. SplitPath(fileName, path, file, extension, lowercaseExtension);
  902. return file + extension;
  903. }
  904. String ReplaceExtension(const String& fullPath, const String& newExtension)
  905. {
  906. String path, file, extension;
  907. SplitPath(fullPath, path, file, extension);
  908. return path + file + newExtension;
  909. }
  910. String AddTrailingSlash(const String& pathName)
  911. {
  912. String ret = pathName.Trimmed();
  913. ret.Replace('\\', '/');
  914. if (!ret.Empty() && ret.Back() != '/')
  915. ret += '/';
  916. return ret;
  917. }
  918. String RemoveTrailingSlash(const String& pathName)
  919. {
  920. String ret = pathName.Trimmed();
  921. ret.Replace('\\', '/');
  922. if (!ret.Empty() && ret.Back() == '/')
  923. ret.Resize(ret.Length() - 1);
  924. return ret;
  925. }
  926. String GetParentPath(const String& path)
  927. {
  928. unsigned pos = RemoveTrailingSlash(path).FindLast('/');
  929. if (pos != String::NPOS)
  930. return path.Substring(0, pos + 1);
  931. else
  932. return String();
  933. }
  934. String GetInternalPath(const String& pathName)
  935. {
  936. return pathName.Replaced('\\', '/');
  937. }
  938. String GetNativePath(const String& pathName)
  939. {
  940. #ifdef _WIN32
  941. return pathName.Replaced('/', '\\');
  942. #else
  943. return pathName;
  944. #endif
  945. }
  946. WString GetWideNativePath(const String& pathName)
  947. {
  948. #ifdef _WIN32
  949. return WString(pathName.Replaced('/', '\\'));
  950. #else
  951. return WString(pathName);
  952. #endif
  953. }
  954. bool IsAbsolutePath(const String& pathName)
  955. {
  956. if (pathName.Empty())
  957. return false;
  958. String path = GetInternalPath(pathName);
  959. if (path[0] == '/')
  960. return true;
  961. #ifdef _WIN32
  962. if (path.Length() > 1 && IsAlpha(path[0]) && path[1] == ':')
  963. return true;
  964. #endif
  965. return false;
  966. }
  967. // ATOMIC BEGIN
  968. bool FileSystem::CreateDirs(const String& root, const String& subdirectory)
  969. {
  970. String folder = AddTrailingSlash(GetInternalPath(root));
  971. String sub = GetInternalPath(subdirectory);
  972. Vector<String> subs = sub.Split('/');
  973. for (unsigned i = 0; i < subs.Size(); i++)
  974. {
  975. folder += subs[i];
  976. folder += "/";
  977. if (DirExists(folder))
  978. continue;
  979. CreateDir(folder);
  980. if (!DirExists(folder))
  981. return false;
  982. }
  983. return true;
  984. }
  985. bool FileSystem::CreateDirsRecursive(const String& directoryIn)
  986. {
  987. String directory = AddTrailingSlash(GetInternalPath(directoryIn));
  988. if (DirExists(directory))
  989. return true;
  990. if (FileExists(directory))
  991. return false;
  992. String parentPath = directory;
  993. Vector<String> paths;
  994. paths.Push(directory);
  995. while (true)
  996. {
  997. parentPath = GetParentPath(parentPath);
  998. if (!parentPath.Length())
  999. break;
  1000. paths.Push(parentPath);
  1001. }
  1002. if (!paths.Size())
  1003. return false;
  1004. for (int i = (int) (paths.Size() - 1); i >= 0; i--)
  1005. {
  1006. const String& pathName = paths[i];
  1007. if (FileExists(pathName))
  1008. return false;
  1009. if (DirExists(pathName))
  1010. continue;
  1011. if (!CreateDir(pathName))
  1012. return false;
  1013. // double check
  1014. if (!DirExists(pathName))
  1015. return false;
  1016. }
  1017. return true;
  1018. }
  1019. bool FileSystem::RemoveDir(const String& directoryIn, bool recursive)
  1020. {
  1021. String directory = AddTrailingSlash(directoryIn);
  1022. if (!DirExists(directory))
  1023. return false;
  1024. Vector<String> results;
  1025. // ensure empty if not recursive
  1026. if (!recursive)
  1027. {
  1028. ScanDir(results, directory, "*", SCAN_DIRS | SCAN_FILES | SCAN_HIDDEN, true );
  1029. while (results.Remove(".")) {}
  1030. while (results.Remove("..")) {}
  1031. if (results.Size())
  1032. return false;
  1033. #ifdef WIN32
  1034. return RemoveDirectoryW(GetWideNativePath(directory).CString()) != 0;
  1035. #endif
  1036. #ifdef __APPLE__
  1037. return remove(GetNativePath(directory).CString()) == 0;
  1038. #endif
  1039. }
  1040. // delete all files at this level
  1041. ScanDir(results, directory, "*", SCAN_FILES | SCAN_HIDDEN, false );
  1042. for (unsigned i = 0; i < results.Size(); i++)
  1043. {
  1044. if (!Delete(directory + results[i]))
  1045. return false;
  1046. }
  1047. results.Clear();
  1048. // recurse into subfolders
  1049. ScanDir(results, directory, "*", SCAN_DIRS, false );
  1050. for (unsigned i = 0; i < results.Size(); i++)
  1051. {
  1052. if (results[i] == "." || results[i] == "..")
  1053. continue;
  1054. if (!RemoveDir(directory + results[i], true))
  1055. return false;
  1056. }
  1057. return RemoveDir(directory, false);
  1058. }
  1059. bool FileSystem::CopyDir(const String& directoryIn, const String& directoryOut)
  1060. {
  1061. if (FileExists(directoryOut) || DirExists(directoryOut))
  1062. return false;
  1063. Vector<String> results;
  1064. ScanDir(results, directoryIn, "*", SCAN_FILES, true );
  1065. for (unsigned i = 0; i < results.Size(); i++)
  1066. {
  1067. String srcFile = directoryIn + "/" + results[i];
  1068. String dstFile = directoryOut + "/" + results[i];
  1069. String dstPath = GetPath(dstFile);
  1070. if (!CreateDirsRecursive(dstPath))
  1071. return false;
  1072. //LOGINFOF("SRC: %s DST: %s", srcFile.CString(), dstFile.CString());
  1073. if (!Copy(srcFile, dstFile))
  1074. return false;
  1075. }
  1076. return true;
  1077. }
  1078. bool IsAbsoluteParentPath(const String& absParentPath, const String& fullPath)
  1079. {
  1080. if (!IsAbsolutePath(absParentPath) || !IsAbsolutePath(fullPath))
  1081. return false;
  1082. String path1 = AddTrailingSlash(GetSanitizedPath(absParentPath));
  1083. String path2 = AddTrailingSlash(GetSanitizedPath(GetPath(fullPath)));
  1084. if (path2.StartsWith(path1))
  1085. return true;
  1086. return false;
  1087. }
  1088. String GetSanitizedPath(const String& path)
  1089. {
  1090. String sanitized = GetInternalPath(path);
  1091. StringVector parts = sanitized.Split('/');
  1092. bool hasTrailingSlash = path.EndsWith("/") || path.EndsWith("\\");
  1093. #ifndef ATOMIC_PLATFORM_WINDOWS
  1094. bool absolute = IsAbsolutePath(path);
  1095. sanitized = String::Joined(parts, "/");
  1096. if (absolute)
  1097. sanitized = "/" + sanitized;
  1098. #else
  1099. sanitized = String::Joined(parts, "/");
  1100. #endif
  1101. if (hasTrailingSlash)
  1102. sanitized += "/";
  1103. return sanitized;
  1104. }
  1105. bool GetRelativePath(const String& fromPath, const String& toPath, String& output)
  1106. {
  1107. output = String::EMPTY;
  1108. String from = GetSanitizedPath(fromPath);
  1109. String to = GetSanitizedPath(toPath);
  1110. StringVector fromParts = from.Split('/');
  1111. StringVector toParts = to.Split('/');
  1112. if (!fromParts.Size() || !toParts.Size())
  1113. return false;
  1114. if (fromParts == toParts)
  1115. {
  1116. return true;
  1117. }
  1118. // no common base?
  1119. if (fromParts[0] != toParts[0])
  1120. return false;
  1121. int startIdx;
  1122. for (startIdx = 0; startIdx < toParts.Size(); startIdx++)
  1123. {
  1124. if (startIdx >= fromParts.Size() || fromParts[startIdx] != toParts[startIdx])
  1125. break;
  1126. }
  1127. if (startIdx == toParts.Size())
  1128. {
  1129. if (from.EndsWith("/") && to.EndsWith("/"))
  1130. {
  1131. for (unsigned i = 0; i < fromParts.Size() - startIdx; i++)
  1132. {
  1133. output += "../";
  1134. }
  1135. return true;
  1136. }
  1137. return false;
  1138. }
  1139. for (int i = 0; i < (int)fromParts.Size() - startIdx; i++)
  1140. {
  1141. output += "../";
  1142. }
  1143. for (int i = startIdx; i < (int) toParts.Size(); i++)
  1144. {
  1145. output += toParts[i] + "/";
  1146. }
  1147. return true;
  1148. }
  1149. // ATOMIC END
  1150. }