FileSystem.cpp 36 KB

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