FileSystem.cpp 34 KB

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