posixVolume.cpp 14 KB

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