FileSystem.cpp 36 KB

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