FileSystem.cpp 37 KB

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