FileSystem.cpp 36 KB

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