posixVolume.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  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
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell 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
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include <unistd.h>
  23. #include <stdlib.h>
  24. #include <errno.h>
  25. #include "core/crc.h"
  26. #include "core/frameAllocator.h"
  27. #include "core/util/str.h"
  28. #include "core/strings/stringFunctions.h"
  29. #include "platform/platformVolume.h"
  30. #include "platformPOSIX/posixVolume.h"
  31. #ifndef PATH_MAX
  32. #include <sys/syslimits.h>
  33. #endif
  34. #ifndef NGROUPS_UMAX
  35. #define NGROUPS_UMAX 32
  36. #endif
  37. //#define DEBUG_SPEW
  38. extern bool ResolvePathCaseInsensitive(char* pathName, S32 pathNameSize, bool requiredAbsolute);
  39. namespace Torque
  40. {
  41. namespace Posix
  42. {
  43. //-----------------------------------------------------------------------------
  44. static String buildFileName(const String& prefix,const Path& path)
  45. {
  46. // Need to join the path (minus the root) with our
  47. // internal path name.
  48. String file = prefix;
  49. file = Path::Join(file,'/',path.getPath());
  50. file = Path::Join(file,'/',path.getFileName());
  51. file = Path::Join(file,'.',path.getExtension());
  52. return file;
  53. }
  54. /*
  55. static bool isFile(const String& file)
  56. {
  57. struct stat info;
  58. if (stat(file.c_str(),&info) == 0)
  59. return S_ISREG(info.st_mode);
  60. return false;
  61. }
  62. static bool isDirectory(const String& file)
  63. {
  64. struct stat info;
  65. if (stat(file.c_str(),&info) == 0)
  66. return S_ISDIR(info.st_mode);
  67. return false;
  68. }
  69. */
  70. //-----------------------------------------------------------------------------
  71. static uid_t _Uid; // Current user id
  72. static int _GroupCount; // Number of groups in the table
  73. static gid_t _Groups[NGROUPS_UMAX+1]; // Table of all the user groups
  74. static void copyStatAttributes(const struct stat& info, FileNode::Attributes* attr)
  75. {
  76. // We need to user and group id's in order to determin file
  77. // read-only access permission. This information is only retrieved
  78. // once per execution.
  79. if (!_Uid)
  80. {
  81. _Uid = getuid();
  82. _GroupCount = getgroups(NGROUPS_UMAX,_Groups);
  83. _Groups[_GroupCount++] = getegid();
  84. }
  85. // Fill in the return struct. The read-only flag is determined
  86. // by comparing file user and group ownership.
  87. attr->flags = 0;
  88. if (S_ISDIR(info.st_mode))
  89. attr->flags |= FileNode::Directory;
  90. if (S_ISREG(info.st_mode))
  91. attr->flags |= FileNode::File;
  92. if (info.st_uid == _Uid)
  93. {
  94. if (!(info.st_mode & S_IWUSR))
  95. attr->flags |= FileNode::ReadOnly;
  96. }
  97. else
  98. {
  99. S32 i = 0;
  100. for (; i < _GroupCount; i++)
  101. {
  102. if (_Groups[i] == info.st_gid)
  103. break;
  104. }
  105. if (i != _GroupCount)
  106. {
  107. if (!(info.st_mode & S_IWGRP))
  108. attr->flags |= FileNode::ReadOnly;
  109. }
  110. else
  111. {
  112. if (!(info.st_mode & S_IWOTH))
  113. attr->flags |= FileNode::ReadOnly;
  114. }
  115. }
  116. attr->size = info.st_size;
  117. attr->mtime = UnixTimeToTime(info.st_mtime);
  118. attr->atime = UnixTimeToTime(info.st_atime);
  119. attr->ctime = UnixTimeToTime(info.st_ctime);
  120. }
  121. //-----------------------------------------------------------------------------
  122. PosixFileSystem::PosixFileSystem(String volume)
  123. {
  124. _volume = volume;
  125. }
  126. PosixFileSystem::~PosixFileSystem()
  127. {
  128. }
  129. FileNodeRef PosixFileSystem::resolve(const Path& path)
  130. {
  131. String file = buildFileName(_volume,path);
  132. struct stat info;
  133. #ifdef TORQUE_POSIX_PATH_CASE_INSENSITIVE
  134. // Resolve the case sensitive filepath
  135. String::SizeType fileLength = file.length();
  136. UTF8* caseSensitivePath = new UTF8[fileLength + 1];
  137. dMemcpy(caseSensitivePath, file.c_str(), fileLength);
  138. caseSensitivePath[fileLength] = 0x00;
  139. ResolvePathCaseInsensitive(caseSensitivePath, fileLength, false);
  140. String caseSensitiveFile(caseSensitivePath);
  141. #else
  142. String caseSensitiveFile = file;
  143. #endif
  144. FileNodeRef result = 0;
  145. if (stat(caseSensitiveFile.c_str(),&info) == 0)
  146. {
  147. // Construct the appropriate object
  148. if (S_ISREG(info.st_mode))
  149. result = new PosixFile(path,caseSensitiveFile);
  150. if (S_ISDIR(info.st_mode))
  151. result = new PosixDirectory(path,caseSensitiveFile);
  152. }
  153. #ifdef TORQUE_POSIX_PATH_CASE_INSENSITIVE
  154. delete[] caseSensitivePath;
  155. #endif
  156. return result;
  157. }
  158. FileNodeRef PosixFileSystem::create(const Path& path, FileNode::Mode mode)
  159. {
  160. // The file will be created on disk when it's opened.
  161. if (mode & FileNode::File)
  162. return new PosixFile(path,buildFileName(_volume,path));
  163. // Default permissions are read/write/search/executate by everyone,
  164. // though this will be modified by the current umask
  165. if (mode & FileNode::Directory)
  166. {
  167. String file = buildFileName(_volume,path);
  168. if (mkdir(file.c_str(),S_IRWXU | S_IRWXG | S_IRWXO) == 0)
  169. return new PosixDirectory(path,file);
  170. }
  171. return 0;
  172. }
  173. bool PosixFileSystem::remove(const Path& path)
  174. {
  175. // Should probably check for outstanding files or directory objects.
  176. String file = buildFileName(_volume,path);
  177. struct stat info;
  178. int error = stat(file.c_str(),&info);
  179. if (error < 0)
  180. return false;
  181. if (S_ISDIR(info.st_mode))
  182. return !rmdir(file);
  183. return !unlink(file);
  184. }
  185. bool PosixFileSystem::rename(const Path& from,const Path& to)
  186. {
  187. String fa = buildFileName(_volume,from);
  188. String fb = buildFileName(_volume,to);
  189. if (!::rename(fa.c_str(),fb.c_str()))
  190. return true;
  191. return false;
  192. }
  193. Path PosixFileSystem::mapTo(const Path& path)
  194. {
  195. return buildFileName(_volume,path);
  196. }
  197. Path PosixFileSystem::mapFrom(const Path& path)
  198. {
  199. const String::SizeType volumePathLen = _volume.length();
  200. String pathStr = path.getFullPath();
  201. if ( _volume.compare( pathStr, volumePathLen, String::NoCase ))
  202. return Path();
  203. return pathStr.substr( volumePathLen, pathStr.length() - volumePathLen );
  204. }
  205. //-----------------------------------------------------------------------------
  206. PosixFile::PosixFile(const Path& path,String name)
  207. {
  208. _path = path;
  209. _name = name;
  210. _status = Closed;
  211. _handle = 0;
  212. }
  213. PosixFile::~PosixFile()
  214. {
  215. if (_handle)
  216. close();
  217. }
  218. Path PosixFile::getName() const
  219. {
  220. return _path;
  221. }
  222. FileNode::NodeStatus PosixFile::getStatus() const
  223. {
  224. return _status;
  225. }
  226. bool PosixFile::getAttributes(Attributes* attr)
  227. {
  228. struct stat info;
  229. int error = _handle? fstat(fileno(_handle),&info): stat(_name.c_str(),&info);
  230. if (error < 0)
  231. {
  232. _updateStatus();
  233. return false;
  234. }
  235. copyStatAttributes(info,attr);
  236. attr->name = _path;
  237. return true;
  238. }
  239. U32 PosixFile::calculateChecksum()
  240. {
  241. if (!open( Read ))
  242. return 0;
  243. U64 fileSize = getSize();
  244. U32 bufSize = 1024 * 1024 * 4;
  245. FrameTemp< U8 > buf( bufSize );
  246. U32 crc = CRC::INITIAL_CRC_VALUE;
  247. while( fileSize > 0 )
  248. {
  249. U32 bytesRead = getMin( fileSize, bufSize );
  250. if( read( buf, bytesRead ) != bytesRead )
  251. {
  252. close();
  253. return 0;
  254. }
  255. fileSize -= bytesRead;
  256. crc = CRC::calculateCRC( buf, bytesRead, crc );
  257. }
  258. close();
  259. return crc;
  260. }
  261. bool PosixFile::open(AccessMode mode)
  262. {
  263. close();
  264. if (_name.isEmpty())
  265. {
  266. return _status;
  267. }
  268. #ifdef DEBUG_SPEW
  269. Platform::outputDebugString( "[PosixFile] opening '%s'", _name.c_str() );
  270. #endif
  271. const char* fmode = "r";
  272. switch (mode)
  273. {
  274. case Read: fmode = "r"; break;
  275. case Write: fmode = "w"; break;
  276. case ReadWrite:
  277. {
  278. fmode = "r+";
  279. // Ensure the file exists.
  280. FILE* temp = fopen( _name.c_str(), "a+" );
  281. fclose( temp );
  282. break;
  283. }
  284. case WriteAppend: fmode = "a"; break;
  285. default: break;
  286. }
  287. if (!(_handle = fopen(_name.c_str(), fmode)))
  288. {
  289. _updateStatus();
  290. return false;
  291. }
  292. _status = Open;
  293. return true;
  294. }
  295. bool PosixFile::close()
  296. {
  297. if (_handle)
  298. {
  299. #ifdef DEBUG_SPEW
  300. Platform::outputDebugString( "[PosixFile] closing '%s'", _name.c_str() );
  301. #endif
  302. fflush(_handle);
  303. fclose(_handle);
  304. _handle = 0;
  305. }
  306. _status = Closed;
  307. return true;
  308. }
  309. U32 PosixFile::getPosition()
  310. {
  311. if (_status == Open || _status == EndOfFile)
  312. return ftell(_handle);
  313. return 0;
  314. }
  315. U32 PosixFile::setPosition(U32 delta, SeekMode mode)
  316. {
  317. if (_status != Open && _status != EndOfFile)
  318. return 0;
  319. S32 fmode = 0;
  320. switch (mode)
  321. {
  322. case Begin: fmode = SEEK_SET; break;
  323. case Current: fmode = SEEK_CUR; break;
  324. case End: fmode = SEEK_END; break;
  325. default: break;
  326. }
  327. if (fseek(_handle, delta, fmode))
  328. {
  329. _status = UnknownError;
  330. return 0;
  331. }
  332. _status = Open;
  333. return ftell(_handle);
  334. }
  335. U32 PosixFile::read(void* dst, U32 size)
  336. {
  337. if (_status != Open && _status != EndOfFile)
  338. return 0;
  339. U32 bytesRead = fread(dst, 1, size, _handle);
  340. if (bytesRead != size)
  341. {
  342. if (feof(_handle))
  343. _status = EndOfFile;
  344. else
  345. _updateStatus();
  346. }
  347. return bytesRead;
  348. }
  349. U32 PosixFile::write(const void* src, U32 size)
  350. {
  351. if ((_status != Open && _status != EndOfFile) || !size)
  352. return 0;
  353. U32 bytesWritten = fwrite(src, 1, size, _handle);
  354. if (bytesWritten != size)
  355. _updateStatus();
  356. return bytesWritten;
  357. }
  358. void PosixFile::_updateStatus()
  359. {
  360. switch (errno)
  361. {
  362. case EACCES: _status = AccessDenied; break;
  363. case ENOSPC: _status = FileSystemFull; break;
  364. case ENOTDIR: _status = NoSuchFile; break;
  365. case ENOENT: _status = NoSuchFile; break;
  366. case EISDIR: _status = AccessDenied; break;
  367. case EROFS: _status = AccessDenied; break;
  368. default: _status = UnknownError; break;
  369. }
  370. }
  371. //-----------------------------------------------------------------------------
  372. PosixDirectory::PosixDirectory(const Path& path,String name)
  373. {
  374. _path = path;
  375. _name = name;
  376. _status = Closed;
  377. _handle = 0;
  378. }
  379. PosixDirectory::~PosixDirectory()
  380. {
  381. if (_handle)
  382. close();
  383. }
  384. Path PosixDirectory::getName() const
  385. {
  386. return _path;
  387. }
  388. bool PosixDirectory::open()
  389. {
  390. if ((_handle = opendir(_name)) == 0)
  391. {
  392. _updateStatus();
  393. return false;
  394. }
  395. _status = Open;
  396. return true;
  397. }
  398. bool PosixDirectory::close()
  399. {
  400. if (_handle)
  401. {
  402. closedir(_handle);
  403. _handle = NULL;
  404. return true;
  405. }
  406. return false;
  407. }
  408. bool PosixDirectory::read(Attributes* entry)
  409. {
  410. if (_status != Open)
  411. return false;
  412. struct dirent* de = readdir(_handle);
  413. if (!de)
  414. {
  415. _status = EndOfFile;
  416. return false;
  417. }
  418. // Skip "." and ".." entries
  419. if (de->d_name[0] == '.' && (de->d_name[1] == '\0' ||
  420. (de->d_name[1] == '.' && de->d_name[2] == '\0')))
  421. return read(entry);
  422. // The dirent structure doesn't actually return much beside
  423. // the name, so we must call stat for more info.
  424. struct stat info;
  425. String file = _name + "/" + de->d_name;
  426. int error = stat(file.c_str(),&info);
  427. if (error < 0)
  428. {
  429. _updateStatus();
  430. return false;
  431. }
  432. copyStatAttributes(info,entry);
  433. entry->name = de->d_name;
  434. return true;
  435. }
  436. U32 PosixDirectory::calculateChecksum()
  437. {
  438. // Return checksum of current entry
  439. return 0;
  440. }
  441. bool PosixDirectory::getAttributes(Attributes* attr)
  442. {
  443. struct stat info;
  444. if (stat(_name.c_str(),&info))
  445. {
  446. _updateStatus();
  447. return false;
  448. }
  449. copyStatAttributes(info,attr);
  450. attr->name = _path;
  451. return true;
  452. }
  453. FileNode::NodeStatus PosixDirectory::getStatus() const
  454. {
  455. return _status;
  456. }
  457. void PosixDirectory::_updateStatus()
  458. {
  459. switch (errno)
  460. {
  461. case EACCES: _status = AccessDenied; break;
  462. case ENOTDIR: _status = NoSuchFile; break;
  463. case ENOENT: _status = NoSuchFile; break;
  464. default: _status = UnknownError; break;
  465. }
  466. }
  467. } // Namespace POSIX
  468. } // Namespace Torque
  469. //-----------------------------------------------------------------------------
  470. #ifndef TORQUE_OS_MAC // Mac has its own native FS build on top of the POSIX one.
  471. Torque::FS::FileSystemRef Platform::FS::createNativeFS( const String &volume )
  472. {
  473. return new Posix::PosixFileSystem( volume );
  474. }
  475. #endif
  476. String Platform::FS::getAssetDir()
  477. {
  478. return Platform::getExecutablePath();
  479. }
  480. /// Function invoked by the kernel layer to install OS specific
  481. /// file systems.
  482. bool Platform::FS::InstallFileSystems()
  483. {
  484. #ifndef TORQUE_SECURE_VFS
  485. Platform::FS::Mount( "/", Platform::FS::createNativeFS( String() ) );
  486. // Setup the current working dir.
  487. char buffer[PATH_MAX];
  488. if (::getcwd(buffer,sizeof(buffer)))
  489. {
  490. // add trailing '/' if it isn't there
  491. if (buffer[dStrlen(buffer) - 1] != '/')
  492. dStrcat(buffer, "/", PATH_MAX);
  493. Platform::FS::SetCwd(buffer);
  494. }
  495. // Mount the home directory
  496. if (char* home = getenv("HOME"))
  497. Platform::FS::Mount( "home", Platform::FS::createNativeFS(home) );
  498. #endif
  499. return true;
  500. }