FileSystem.cpp 36 KB

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