posixVolume.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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. }
  120. //-----------------------------------------------------------------------------
  121. PosixFileSystem::PosixFileSystem(String volume)
  122. {
  123. _volume = volume;
  124. }
  125. PosixFileSystem::~PosixFileSystem()
  126. {
  127. }
  128. FileNodeRef PosixFileSystem::resolve(const Path& path)
  129. {
  130. String file = buildFileName(_volume,path);
  131. struct stat info;
  132. #ifdef TORQUE_POSIX_PATH_CASE_INSENSITIVE
  133. // Resolve the case sensitive filepath
  134. String::SizeType fileLength = file.length();
  135. UTF8* caseSensitivePath = new UTF8[fileLength + 1];
  136. dMemcpy(caseSensitivePath, file.c_str(), fileLength);
  137. caseSensitivePath[fileLength] = 0x00;
  138. ResolvePathCaseInsensitive(caseSensitivePath, fileLength, false);
  139. String caseSensitiveFile(caseSensitivePath);
  140. #else
  141. String caseSensitiveFile = file;
  142. #endif
  143. FileNodeRef result = 0;
  144. if (stat(caseSensitiveFile.c_str(),&info) == 0)
  145. {
  146. // Construct the appropriate object
  147. if (S_ISREG(info.st_mode))
  148. result = new PosixFile(path,caseSensitiveFile);
  149. if (S_ISDIR(info.st_mode))
  150. result = new PosixDirectory(path,caseSensitiveFile);
  151. }
  152. #ifdef TORQUE_POSIX_PATH_CASE_INSENSITIVE
  153. delete[] caseSensitivePath;
  154. #endif
  155. return result;
  156. }
  157. FileNodeRef PosixFileSystem::create(const Path& path, FileNode::Mode mode)
  158. {
  159. // The file will be created on disk when it's opened.
  160. if (mode & FileNode::File)
  161. return new PosixFile(path,buildFileName(_volume,path));
  162. // Default permissions are read/write/search/executate by everyone,
  163. // though this will be modified by the current umask
  164. if (mode & FileNode::Directory)
  165. {
  166. String file = buildFileName(_volume,path);
  167. if (mkdir(file.c_str(),S_IRWXU | S_IRWXG | S_IRWXO) == 0)
  168. return new PosixDirectory(path,file);
  169. }
  170. return 0;
  171. }
  172. bool PosixFileSystem::remove(const Path& path)
  173. {
  174. // Should probably check for outstanding files or directory objects.
  175. String file = buildFileName(_volume,path);
  176. struct stat info;
  177. int error = stat(file.c_str(),&info);
  178. if (error < 0)
  179. return false;
  180. if (S_ISDIR(info.st_mode))
  181. return !rmdir(file);
  182. return !unlink(file);
  183. }
  184. bool PosixFileSystem::rename(const Path& from,const Path& to)
  185. {
  186. String fa = buildFileName(_volume,from);
  187. String fb = buildFileName(_volume,to);
  188. if (!::rename(fa.c_str(),fb.c_str()))
  189. return true;
  190. return false;
  191. }
  192. Path PosixFileSystem::mapTo(const Path& path)
  193. {
  194. return buildFileName(_volume,path);
  195. }
  196. Path PosixFileSystem::mapFrom(const Path& path)
  197. {
  198. const String::SizeType volumePathLen = _volume.length();
  199. String pathStr = path.getFullPath();
  200. if ( _volume.compare( pathStr, volumePathLen, String::NoCase ))
  201. return Path();
  202. return pathStr.substr( volumePathLen, pathStr.length() - volumePathLen );
  203. }
  204. //-----------------------------------------------------------------------------
  205. PosixFile::PosixFile(const Path& path,String name)
  206. {
  207. _path = path;
  208. _name = name;
  209. _status = Closed;
  210. _handle = 0;
  211. }
  212. PosixFile::~PosixFile()
  213. {
  214. if (_handle)
  215. close();
  216. }
  217. Path PosixFile::getName() const
  218. {
  219. return _path;
  220. }
  221. FileNode::NodeStatus PosixFile::getStatus() const
  222. {
  223. return _status;
  224. }
  225. bool PosixFile::getAttributes(Attributes* attr)
  226. {
  227. struct stat info;
  228. int error = _handle? fstat(fileno(_handle),&info): stat(_name.c_str(),&info);
  229. if (error < 0)
  230. {
  231. _updateStatus();
  232. return false;
  233. }
  234. copyStatAttributes(info,attr);
  235. attr->name = _path;
  236. return true;
  237. }
  238. U32 PosixFile::calculateChecksum()
  239. {
  240. if (!open( Read ))
  241. return 0;
  242. U64 fileSize = getSize();
  243. U32 bufSize = 1024 * 1024 * 4;
  244. FrameTemp< U8 > buf( bufSize );
  245. U32 crc = CRC::INITIAL_CRC_VALUE;
  246. while( fileSize > 0 )
  247. {
  248. U32 bytesRead = getMin( fileSize, bufSize );
  249. if( read( buf, bytesRead ) != bytesRead )
  250. {
  251. close();
  252. return 0;
  253. }
  254. fileSize -= bytesRead;
  255. crc = CRC::calculateCRC( buf, bytesRead, crc );
  256. }
  257. close();
  258. return crc;
  259. }
  260. bool PosixFile::open(AccessMode mode)
  261. {
  262. close();
  263. if (_name.isEmpty())
  264. {
  265. return _status;
  266. }
  267. #ifdef DEBUG_SPEW
  268. Platform::outputDebugString( "[PosixFile] opening '%s'", _name.c_str() );
  269. #endif
  270. const char* fmode = "r";
  271. switch (mode)
  272. {
  273. case Read: fmode = "r"; break;
  274. case Write: fmode = "w"; break;
  275. case ReadWrite:
  276. {
  277. fmode = "r+";
  278. // Ensure the file exists.
  279. FILE* temp = fopen( _name.c_str(), "a+" );
  280. fclose( temp );
  281. break;
  282. }
  283. case WriteAppend: fmode = "a"; break;
  284. default: break;
  285. }
  286. if (!(_handle = fopen(_name.c_str(), fmode)))
  287. {
  288. _updateStatus();
  289. return false;
  290. }
  291. _status = Open;
  292. return true;
  293. }
  294. bool PosixFile::close()
  295. {
  296. if (_handle)
  297. {
  298. #ifdef DEBUG_SPEW
  299. Platform::outputDebugString( "[PosixFile] closing '%s'", _name.c_str() );
  300. #endif
  301. fflush(_handle);
  302. fclose(_handle);
  303. _handle = 0;
  304. }
  305. _status = Closed;
  306. return true;
  307. }
  308. U32 PosixFile::getPosition()
  309. {
  310. if (_status == Open || _status == EndOfFile)
  311. return ftell(_handle);
  312. return 0;
  313. }
  314. U32 PosixFile::setPosition(U32 delta, SeekMode mode)
  315. {
  316. if (_status != Open && _status != EndOfFile)
  317. return 0;
  318. S32 fmode = 0;
  319. switch (mode)
  320. {
  321. case Begin: fmode = SEEK_SET; break;
  322. case Current: fmode = SEEK_CUR; break;
  323. case End: fmode = SEEK_END; break;
  324. default: break;
  325. }
  326. if (fseek(_handle, delta, fmode))
  327. {
  328. _status = UnknownError;
  329. return 0;
  330. }
  331. _status = Open;
  332. return ftell(_handle);
  333. }
  334. U32 PosixFile::read(void* dst, U32 size)
  335. {
  336. if (_status != Open && _status != EndOfFile)
  337. return 0;
  338. U32 bytesRead = fread(dst, 1, size, _handle);
  339. if (bytesRead != size)
  340. {
  341. if (feof(_handle))
  342. _status = EndOfFile;
  343. else
  344. _updateStatus();
  345. }
  346. return bytesRead;
  347. }
  348. U32 PosixFile::write(const void* src, U32 size)
  349. {
  350. if ((_status != Open && _status != EndOfFile) || !size)
  351. return 0;
  352. U32 bytesWritten = fwrite(src, 1, size, _handle);
  353. if (bytesWritten != size)
  354. _updateStatus();
  355. return bytesWritten;
  356. }
  357. void PosixFile::_updateStatus()
  358. {
  359. switch (errno)
  360. {
  361. case EACCES: _status = AccessDenied; break;
  362. case ENOSPC: _status = FileSystemFull; break;
  363. case ENOTDIR: _status = NoSuchFile; break;
  364. case ENOENT: _status = NoSuchFile; break;
  365. case EISDIR: _status = AccessDenied; break;
  366. case EROFS: _status = AccessDenied; break;
  367. default: _status = UnknownError; break;
  368. }
  369. }
  370. //-----------------------------------------------------------------------------
  371. PosixDirectory::PosixDirectory(const Path& path,String name)
  372. {
  373. _path = path;
  374. _name = name;
  375. _status = Closed;
  376. _handle = 0;
  377. }
  378. PosixDirectory::~PosixDirectory()
  379. {
  380. if (_handle)
  381. close();
  382. }
  383. Path PosixDirectory::getName() const
  384. {
  385. return _path;
  386. }
  387. bool PosixDirectory::open()
  388. {
  389. if ((_handle = opendir(_name)) == 0)
  390. {
  391. _updateStatus();
  392. return false;
  393. }
  394. _status = Open;
  395. return true;
  396. }
  397. bool PosixDirectory::close()
  398. {
  399. if (_handle)
  400. {
  401. closedir(_handle);
  402. _handle = NULL;
  403. return true;
  404. }
  405. return false;
  406. }
  407. bool PosixDirectory::read(Attributes* entry)
  408. {
  409. if (_status != Open)
  410. return false;
  411. struct dirent* de = readdir(_handle);
  412. if (!de)
  413. {
  414. _status = EndOfFile;
  415. return false;
  416. }
  417. // Skip "." and ".." entries
  418. if (de->d_name[0] == '.' && (de->d_name[1] == '\0' ||
  419. (de->d_name[1] == '.' && de->d_name[2] == '\0')))
  420. return read(entry);
  421. // The dirent structure doesn't actually return much beside
  422. // the name, so we must call stat for more info.
  423. struct stat info;
  424. String file = _name + "/" + de->d_name;
  425. int error = stat(file.c_str(),&info);
  426. if (error < 0)
  427. {
  428. _updateStatus();
  429. return false;
  430. }
  431. copyStatAttributes(info,entry);
  432. entry->name = de->d_name;
  433. return true;
  434. }
  435. U32 PosixDirectory::calculateChecksum()
  436. {
  437. // Return checksum of current entry
  438. return 0;
  439. }
  440. bool PosixDirectory::getAttributes(Attributes* attr)
  441. {
  442. struct stat info;
  443. if (stat(_name.c_str(),&info))
  444. {
  445. _updateStatus();
  446. return false;
  447. }
  448. copyStatAttributes(info,attr);
  449. attr->name = _path;
  450. return true;
  451. }
  452. FileNode::NodeStatus PosixDirectory::getStatus() const
  453. {
  454. return _status;
  455. }
  456. void PosixDirectory::_updateStatus()
  457. {
  458. switch (errno)
  459. {
  460. case EACCES: _status = AccessDenied; break;
  461. case ENOTDIR: _status = NoSuchFile; break;
  462. case ENOENT: _status = NoSuchFile; break;
  463. default: _status = UnknownError; break;
  464. }
  465. }
  466. } // Namespace POSIX
  467. } // Namespace Torque
  468. //-----------------------------------------------------------------------------
  469. #ifndef TORQUE_OS_MAC // Mac has its own native FS build on top of the POSIX one.
  470. Torque::FS::FileSystemRef Platform::FS::createNativeFS( const String &volume )
  471. {
  472. return new Posix::PosixFileSystem( volume );
  473. }
  474. #endif
  475. String Platform::FS::getAssetDir()
  476. {
  477. return Platform::getExecutablePath();
  478. }
  479. /// Function invoked by the kernel layer to install OS specific
  480. /// file systems.
  481. bool Platform::FS::InstallFileSystems()
  482. {
  483. Platform::FS::Mount( "/", Platform::FS::createNativeFS( String() ) );
  484. // Setup the current working dir.
  485. char buffer[PATH_MAX];
  486. if (::getcwd(buffer,sizeof(buffer)))
  487. {
  488. // add trailing '/' if it isn't there
  489. if (buffer[dStrlen(buffer) - 1] != '/')
  490. dStrcat(buffer, "/", PATH_MAX);
  491. Platform::FS::SetCwd(buffer);
  492. }
  493. // Mount the home directory
  494. if (char* home = getenv("HOME"))
  495. Platform::FS::Mount( "home", Platform::FS::createNativeFS(home) );
  496. return true;
  497. }