FileSystem.cpp 33 KB

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