x86UNIXFileio.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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. /* JMQ:
  23. Here's the scoop on unix file IO. The windows platform makes some
  24. assumptions about fileio: 1) the file system is case-insensitive, and
  25. 2) the platform can write to the directory in which
  26. the game is running. Both of these are usually false on linux. So, to
  27. compensate, we "route" created files and directories to the user's home
  28. directory (see GetPrefPath()). When a file is to be accessed, the code
  29. looks in the home directory first. If the file is not found there and the
  30. open mode is read only, the code will look in the game installation
  31. directory. Files are never created or modified in the game directory.
  32. For case-sensitivity, the MungePath code will test whether a given path
  33. specified by the engine exists. If not, it will use the ResolvePathCaseInsensitive function
  34. which will try to determine if an actual filesystem path matches the
  35. specified path case insensitive. If one is found, the actual path
  36. transparently (we hope) replaces the one requested by the engine.
  37. The preference directory is global to all torque executables with the same
  38. name. You should make sure you keep it clean if you build from multiple
  39. torque development trees.
  40. */
  41. // evil hack to get around insane X windows #define-happy header files
  42. #ifdef Status
  43. #undef Status
  44. #endif
  45. #include "platformX86UNIX/platformX86UNIX.h"
  46. #include "core/fileio.h"
  47. #include "core/util/tVector.h"
  48. #include "core/stringTable.h"
  49. #include "console/console.h"
  50. #include "core/strings/stringFunctions.h"
  51. #include "util/tempAlloc.h"
  52. #include "cinterface/c_controlInterface.h"
  53. #include "core/volume.h"
  54. #if defined(__FreeBSD__)
  55. #include <sys/types.h>
  56. #endif
  57. #include <utime.h>
  58. /* these are for reading directors, getting stats, etc. */
  59. #include <dirent.h>
  60. #include <sys/types.h>
  61. #include <sys/stat.h>
  62. #include <unistd.h>
  63. #include <fcntl.h>
  64. #include <errno.h>
  65. #include <stdlib.h>
  66. extern int x86UNIXOpen(const char *path, int oflag);
  67. extern int x86UNIXClose(int fd);
  68. extern ssize_t x86UNIXRead(int fd, void *buf, size_t nbytes);
  69. extern ssize_t x86UNIXWrite(int fd, const void *buf, size_t nbytes);
  70. const int MaxPath = PATH_MAX;
  71. namespace
  72. {
  73. const char sTempDir[] = "/tmp/";
  74. static char sBinPathName[MaxPath] = "";
  75. static char *sBinName = sBinPathName;
  76. bool sUseRedirect = true;
  77. }
  78. StringTableEntry osGetTemporaryDirectory()
  79. {
  80. return StringTable->insert(sTempDir);
  81. }
  82. // Various handy utility functions:
  83. //------------------------------------------------------------------------------
  84. // find all \ in a path and convert them in place to /
  85. static void ForwardSlash(char *str)
  86. {
  87. while(*str)
  88. {
  89. if(*str == '\\')
  90. *str = '/';
  91. str++;
  92. }
  93. }
  94. //------------------------------------------------------------------------------
  95. // copy a file from src to dest
  96. static bool CopyFile(const char* src, const char* dest)
  97. {
  98. S32 srcFd = x86UNIXOpen(src, O_RDONLY);
  99. S32 destFd = x86UNIXOpen(dest, O_WRONLY | O_CREAT | O_TRUNC);
  100. bool error = false;
  101. if (srcFd != -1 && destFd != -1)
  102. {
  103. const int BufSize = 8192;
  104. char buf[BufSize];
  105. S32 bytesRead = 0;
  106. while ((bytesRead = x86UNIXRead(srcFd, buf, BufSize)) > 0)
  107. {
  108. // write data
  109. if (x86UNIXWrite(destFd, buf, bytesRead) == -1)
  110. {
  111. error = true;
  112. break;
  113. }
  114. }
  115. if (bytesRead == -1)
  116. error = true;
  117. }
  118. if (srcFd != -1)
  119. x86UNIXClose(srcFd);
  120. if (destFd != -1)
  121. x86UNIXClose(destFd);
  122. if (error)
  123. {
  124. Con::errorf("Error copying file: %s, %s", src, dest);
  125. remove(dest);
  126. }
  127. return error;
  128. }
  129. bool dPathCopy(const char *fromName, const char *toName, bool nooverwrite)
  130. {
  131. return CopyFile(fromName,toName);
  132. }
  133. //-----------------------------------------------------------------------------
  134. static char sgPrefDir[MaxPath];
  135. static bool sgPrefDirInitialized = false;
  136. // get the "pref dir", which is where game output files are stored. the pref
  137. // dir is ~/PREF_DIR_ROOT/PREF_DIR_GAME_NAME
  138. static const char* GetPrefDir()
  139. {
  140. if (sgPrefDirInitialized)
  141. return sgPrefDir;
  142. if (sUseRedirect)
  143. {
  144. const char *home = getenv("HOME");
  145. AssertFatal(home, "HOME environment variable must be set");
  146. dSprintf(sgPrefDir, MaxPath, "%s/%s/%s",
  147. home, PREF_DIR_ROOT, PREF_DIR_GAME_NAME);
  148. }
  149. else
  150. {
  151. getcwd(sgPrefDir, MaxPath);
  152. }
  153. sgPrefDirInitialized = true;
  154. return sgPrefDir;
  155. }
  156. //-----------------------------------------------------------------------------
  157. // Returns true if the pathname exists, false otherwise. If isFile is true,
  158. // the pathname is assumed to be a file path, and only the directory part
  159. // will be examined (everything before last /)
  160. bool DirExists(char* pathname, bool isFile)
  161. {
  162. static char testpath[20000];
  163. dStrncpy(testpath, pathname, sizeof(testpath));
  164. if (isFile)
  165. {
  166. // find the last / and make it into null
  167. char* lastSlash = dStrrchr(testpath, '/');
  168. if (lastSlash != NULL)
  169. *lastSlash = 0;
  170. }
  171. return Platform::isDirectory(testpath);
  172. }
  173. //-----------------------------------------------------------------------------
  174. // Munge the specified path.
  175. static void MungePath(char* dest, S32 destSize,
  176. const char* src, const char* absolutePrefix)
  177. {
  178. char tempBuf[MaxPath];
  179. dStrncpy(dest, src, MaxPath);
  180. // translate all \ to /
  181. ForwardSlash(dest);
  182. // if it is relative, make it absolute with the absolutePrefix
  183. if (dest[0] != '/')
  184. {
  185. AssertFatal(absolutePrefix, "Absolute Prefix must not be NULL");
  186. dSprintf(tempBuf, MaxPath, "%s/%s",
  187. absolutePrefix, dest);
  188. // copy the result back into dest
  189. dStrncpy(dest, tempBuf, destSize);
  190. }
  191. // if the path exists, we're done
  192. struct stat filestat;
  193. if (stat(dest, &filestat) != -1)
  194. return;
  195. // otherwise munge the case of the path
  196. ResolvePathCaseInsensitive(dest, destSize, true);
  197. }
  198. //-----------------------------------------------------------------------------
  199. enum
  200. {
  201. TOUCH,
  202. DELETE
  203. };
  204. //-----------------------------------------------------------------------------
  205. // perform a modification on the specified file. allowed modifications are
  206. // specified in the enum above.
  207. bool ModifyFile(const char * name, S32 modType)
  208. {
  209. if(!name || (dStrlen(name) >= MaxPath) || dStrstr(name, "../") != NULL)
  210. return(false);
  211. // if its absolute skip it
  212. if (name[0]=='/' || name[0]=='\\')
  213. return(false);
  214. // only modify files in home directory
  215. char prefPathName[MaxPath];
  216. MungePath(prefPathName, MaxPath, name, GetPrefDir());
  217. if (modType == TOUCH)
  218. return(utime(prefPathName, 0) != -1);
  219. else if (modType == DELETE)
  220. return (remove(prefPathName) == 0);
  221. else
  222. AssertFatal(false, "Unknown File Mod type");
  223. return false;
  224. }
  225. //-----------------------------------------------------------------------------
  226. static bool RecurseDumpPath(const char *path, const char* relativePath, const char *pattern, Vector<Platform::FileInfo> &fileVector, S32 currentDepth = 0, S32 recurseDepth = -1)
  227. {
  228. char search[1024];
  229. dSprintf(search, sizeof(search), "%s", path, pattern);
  230. DIR *directory = opendir(search);
  231. if (directory == NULL)
  232. return false;
  233. struct dirent *fEntry;
  234. fEntry = readdir(directory); // read the first "file" in the directory
  235. if (fEntry == NULL)
  236. {
  237. closedir(directory);
  238. return false;
  239. }
  240. do
  241. {
  242. char filename[BUFSIZ+1];
  243. struct stat fStat;
  244. dSprintf(filename, sizeof(filename), "%s/%s", search, fEntry->d_name); // "construct" the file name
  245. stat(filename, &fStat); // get the file stats
  246. if ( (fStat.st_mode & S_IFMT) == S_IFDIR )
  247. {
  248. // Directory
  249. // skip . and .. directories
  250. if (dStrcmp(fEntry->d_name, ".") == 0 || dStrcmp(fEntry->d_name, "..") == 0)
  251. continue;
  252. // skip excluded directories
  253. if( Platform::isExcludedDirectory(fEntry->d_name))
  254. continue;
  255. char child[MaxPath];
  256. dSprintf(child, sizeof(child), "%s/%s", path, fEntry->d_name);
  257. char* childRelative = NULL;
  258. char childRelativeBuf[MaxPath];
  259. if (relativePath)
  260. {
  261. dSprintf(childRelativeBuf, sizeof(childRelativeBuf), "%s/%s",
  262. relativePath, fEntry->d_name);
  263. childRelative = childRelativeBuf;
  264. }
  265. if (currentDepth < recurseDepth || recurseDepth == -1 )
  266. RecurseDumpPath(child, childRelative, pattern, fileVector, currentDepth+1, recurseDepth);
  267. }
  268. else
  269. {
  270. // File
  271. // add it to the list
  272. fileVector.increment();
  273. Platform::FileInfo& rInfo = fileVector.last();
  274. if (relativePath)
  275. rInfo.pFullPath = StringTable->insert(relativePath);
  276. else
  277. rInfo.pFullPath = StringTable->insert(path);
  278. rInfo.pFileName = StringTable->insert(fEntry->d_name);
  279. rInfo.fileSize = fStat.st_size;
  280. //dPrintf("Adding file: %s/%s\n", rInfo.pFullPath, rInfo.pFileName);
  281. }
  282. } while( (fEntry = readdir(directory)) != NULL );
  283. closedir(directory);
  284. return true;
  285. }
  286. //-----------------------------------------------------------------------------
  287. bool dFileDelete(const char * name)
  288. {
  289. return ModifyFile(name, DELETE);
  290. }
  291. //-----------------------------------------------------------------------------
  292. bool dFileTouch(const char * name)
  293. {
  294. return ModifyFile(name, TOUCH);
  295. }
  296. bool dFileRename(const char *oldName, const char *newName)
  297. {
  298. AssertFatal( oldName != NULL && newName != NULL, "dFileRename - NULL file name" );
  299. // only modify files in home directory
  300. TempAlloc<char> oldPrefPathName(MaxPath);
  301. TempAlloc<char> newPrefPathName(MaxPath);
  302. MungePath(oldPrefPathName, MaxPath, oldName, GetPrefDir());
  303. MungePath(newPrefPathName, MaxPath, newName, GetPrefDir());
  304. return rename(oldPrefPathName, newPrefPathName) == 0;
  305. }
  306. //-----------------------------------------------------------------------------
  307. // Constructors & Destructor
  308. //-----------------------------------------------------------------------------
  309. //-----------------------------------------------------------------------------
  310. // After construction, the currentStatus will be Closed and the capabilities
  311. // will be 0.
  312. //-----------------------------------------------------------------------------
  313. File::File()
  314. : currentStatus(Closed), capability(0)
  315. {
  316. // AssertFatal(sizeof(int) == sizeof(void *), "File::File: cannot cast void* to int");
  317. handle = (void *)NULL;
  318. }
  319. //-----------------------------------------------------------------------------
  320. // insert a copy constructor here... (currently disabled)
  321. //-----------------------------------------------------------------------------
  322. //-----------------------------------------------------------------------------
  323. // Destructor
  324. //-----------------------------------------------------------------------------
  325. File::~File()
  326. {
  327. close();
  328. handle = (void *)NULL;
  329. }
  330. //-----------------------------------------------------------------------------
  331. // Open a file in the mode specified by openMode (Read, Write, or ReadWrite).
  332. // Truncate the file if the mode is either Write or ReadWrite and truncate is
  333. // true.
  334. //
  335. // Sets capability appropriate to the openMode.
  336. // Returns the currentStatus of the file.
  337. //-----------------------------------------------------------------------------
  338. File::FileStatus File::open(const char *filename, const AccessMode openMode)
  339. {
  340. AssertFatal(NULL != filename, "File::open: NULL filename");
  341. AssertWarn(NULL == handle, "File::open: handle already valid");
  342. // Close the file if it was already open...
  343. if (Closed != currentStatus)
  344. close();
  345. char prefPathName[MaxPath];
  346. char gamePathName[MaxPath];
  347. char cwd[MaxPath];
  348. getcwd(cwd, MaxPath);
  349. MungePath(prefPathName, MaxPath, filename, GetPrefDir());
  350. MungePath(gamePathName, MaxPath, filename, cwd);
  351. int oflag;
  352. struct stat filestat;
  353. handle = (void *)dRealMalloc(sizeof(int));
  354. switch (openMode)
  355. {
  356. case Read:
  357. oflag = O_RDONLY;
  358. break;
  359. case Write:
  360. oflag = O_WRONLY | O_CREAT | O_TRUNC;
  361. break;
  362. case ReadWrite:
  363. oflag = O_RDWR | O_CREAT;
  364. // if the file does not exist copy it before reading/writing
  365. if (stat(prefPathName, &filestat) == -1)
  366. bool ret = CopyFile(gamePathName, prefPathName);
  367. break;
  368. case WriteAppend:
  369. oflag = O_WRONLY | O_CREAT | O_APPEND;
  370. // if the file does not exist copy it before appending
  371. if (stat(prefPathName, &filestat) == -1)
  372. bool ret = CopyFile(gamePathName, prefPathName);
  373. break;
  374. default:
  375. AssertFatal(false, "File::open: bad access mode"); // impossible
  376. }
  377. // if we are writing, make sure output path exists
  378. if (openMode == Write || openMode == ReadWrite || openMode == WriteAppend)
  379. Platform::createPath(prefPathName);
  380. int fd = -1;
  381. fd = x86UNIXOpen(prefPathName, oflag);
  382. if (fd == -1 && openMode == Read)
  383. // for read only files we can use the gamePathName
  384. fd = x86UNIXOpen(gamePathName, oflag);
  385. dMemcpy(handle, &fd, sizeof(int));
  386. #ifdef DEBUG
  387. // fprintf(stdout,"fd = %d, handle = %d\n", fd, *((int *)handle));
  388. #endif
  389. if (*((int *)handle) == -1)
  390. {
  391. // handle not created successfully
  392. Con::errorf("Can't open file: %s", filename);
  393. return setStatus();
  394. }
  395. else
  396. {
  397. // successfully created file, so set the file capabilities...
  398. switch (openMode)
  399. {
  400. case Read:
  401. capability = U32(FileRead);
  402. break;
  403. case Write:
  404. case WriteAppend:
  405. capability = U32(FileWrite);
  406. break;
  407. case ReadWrite:
  408. capability = U32(FileRead) |
  409. U32(FileWrite);
  410. break;
  411. default:
  412. AssertFatal(false, "File::open: bad access mode");
  413. }
  414. return currentStatus = Ok; // success!
  415. }
  416. }
  417. //-----------------------------------------------------------------------------
  418. // Get the current position of the file pointer.
  419. //-----------------------------------------------------------------------------
  420. U32 File::getPosition() const
  421. {
  422. AssertFatal(Closed != currentStatus, "File::getPosition: file closed");
  423. AssertFatal(NULL != handle, "File::getPosition: invalid file handle");
  424. #ifdef DEBUG
  425. // fprintf(stdout, "handle = %d\n",*((int *)handle));fflush(stdout);
  426. #endif
  427. return (U32) lseek(*((int *)handle), 0, SEEK_CUR);
  428. }
  429. //-----------------------------------------------------------------------------
  430. // Set the position of the file pointer.
  431. // Absolute and relative positioning is supported via the absolutePos
  432. // parameter.
  433. //
  434. // If positioning absolutely, position MUST be positive - an IOError results if
  435. // position is negative.
  436. // Position can be negative if positioning relatively, however positioning
  437. // before the start of the file is an IOError.
  438. //
  439. // Returns the currentStatus of the file.
  440. //-----------------------------------------------------------------------------
  441. File::FileStatus File::setPosition(S32 position, bool absolutePos)
  442. {
  443. AssertFatal(Closed != currentStatus, "File::setPosition: file closed");
  444. AssertFatal(NULL != handle, "File::setPosition: invalid file handle");
  445. if (Ok != currentStatus && EOS != currentStatus)
  446. return currentStatus;
  447. U32 finalPos = 0;
  448. if (absolutePos)
  449. {
  450. AssertFatal(0 <= position, "File::setPosition: negative absolute position");
  451. // position beyond EOS is OK
  452. finalPos = lseek(*((int *)handle), position, SEEK_SET);
  453. }
  454. else
  455. {
  456. AssertFatal((getPosition() >= (U32)abs(position) && 0 > position) || 0 <= position, "File::setPosition: negative relative position");
  457. // position beyond EOS is OK
  458. finalPos = lseek(*((int *)handle), position, SEEK_CUR);
  459. }
  460. if (0xffffffff == finalPos)
  461. return setStatus(); // unsuccessful
  462. else if (finalPos >= getSize())
  463. return currentStatus = EOS; // success, at end of file
  464. else
  465. return currentStatus = Ok; // success!
  466. }
  467. //-----------------------------------------------------------------------------
  468. // Get the size of the file in bytes.
  469. // It is an error to query the file size for a Closed file, or for one with an
  470. // error status.
  471. //-----------------------------------------------------------------------------
  472. U32 File::getSize() const
  473. {
  474. AssertWarn(Closed != currentStatus, "File::getSize: file closed");
  475. AssertFatal(NULL != handle, "File::getSize: invalid file handle");
  476. if (Ok == currentStatus || EOS == currentStatus)
  477. {
  478. long currentOffset = getPosition(); // keep track of our current position
  479. long fileSize;
  480. lseek(*((int *)handle), 0, SEEK_END); // seek to the end of the file
  481. fileSize = getPosition(); // get the file size
  482. lseek(*((int *)handle), currentOffset, SEEK_SET); // seek back to our old offset
  483. return fileSize; // success!
  484. }
  485. else
  486. return 0; // unsuccessful
  487. }
  488. //-----------------------------------------------------------------------------
  489. // Flush the file.
  490. // It is an error to flush a read-only file.
  491. // Returns the currentStatus of the file.
  492. //-----------------------------------------------------------------------------
  493. File::FileStatus File::flush()
  494. {
  495. AssertFatal(Closed != currentStatus, "File::flush: file closed");
  496. AssertFatal(NULL != handle, "File::flush: invalid file handle");
  497. AssertFatal(true == hasCapability(FileWrite), "File::flush: cannot flush a read-only file");
  498. if (fsync(*((int *)handle)) == 0)
  499. return currentStatus = Ok; // success!
  500. else
  501. return setStatus(); // unsuccessful
  502. }
  503. //-----------------------------------------------------------------------------
  504. // Close the File.
  505. //
  506. // Returns the currentStatus
  507. //-----------------------------------------------------------------------------
  508. File::FileStatus File::close()
  509. {
  510. // if the handle is non-NULL, close it if necessary and free it
  511. if (NULL != handle)
  512. {
  513. // make a local copy of the handle value and
  514. // free the handle
  515. int handleVal = *((int *)handle);
  516. dRealFree(handle);
  517. handle = (void *)NULL;
  518. // close the handle if it is valid
  519. if (handleVal != -1 && x86UNIXClose(handleVal) != 0)
  520. return setStatus(); // unsuccessful
  521. }
  522. // Set the status to closed
  523. return currentStatus = Closed;
  524. }
  525. //-----------------------------------------------------------------------------
  526. // Self-explanatory.
  527. //-----------------------------------------------------------------------------
  528. File::FileStatus File::getStatus() const
  529. {
  530. return currentStatus;
  531. }
  532. //-----------------------------------------------------------------------------
  533. // Sets and returns the currentStatus when an error has been encountered.
  534. //-----------------------------------------------------------------------------
  535. File::FileStatus File::setStatus()
  536. {
  537. Con::printf("File IO error: %s", strerror(errno));
  538. return currentStatus = IOError;
  539. }
  540. //-----------------------------------------------------------------------------
  541. // Sets and returns the currentStatus to status.
  542. //-----------------------------------------------------------------------------
  543. File::FileStatus File::setStatus(File::FileStatus status)
  544. {
  545. return currentStatus = status;
  546. }
  547. //-----------------------------------------------------------------------------
  548. // Read from a file.
  549. // The number of bytes to read is passed in size, the data is returned in src.
  550. // The number of bytes read is available in bytesRead if a non-Null pointer is
  551. // provided.
  552. //-----------------------------------------------------------------------------
  553. File::FileStatus File::read(U32 size, char *dst, U32 *bytesRead)
  554. {
  555. #ifdef DEBUG
  556. // fprintf(stdout,"reading %d bytes\n",size);fflush(stdout);
  557. #endif
  558. AssertFatal(Closed != currentStatus, "File::read: file closed");
  559. AssertFatal(NULL != handle, "File::read: invalid file handle");
  560. AssertFatal(NULL != dst, "File::read: NULL destination pointer");
  561. AssertFatal(true == hasCapability(FileRead), "File::read: file lacks capability");
  562. AssertWarn(0 != size, "File::read: size of zero");
  563. /* show stats for this file */
  564. #ifdef DEBUG
  565. //struct stat st;
  566. //fstat(*((int *)handle), &st);
  567. //fprintf(stdout,"file size = %d\n", st.st_size);
  568. #endif
  569. /****************************/
  570. if (Ok != currentStatus || 0 == size)
  571. return currentStatus;
  572. else
  573. {
  574. long lastBytes;
  575. long *bytes = (NULL == bytesRead) ? &lastBytes : (long *)bytesRead;
  576. if ( (*((U32 *)bytes) = x86UNIXRead(*((int *)handle), dst, size)) == -1)
  577. {
  578. #ifdef DEBUG
  579. // fprintf(stdout,"unsuccessful: %d\n", *((U32 *)bytes));fflush(stdout);
  580. #endif
  581. return setStatus(); // unsuccessful
  582. } else {
  583. // dst[*((U32 *)bytes)] = '\0';
  584. if (*((U32 *)bytes) != size || *((U32 *)bytes) == 0) {
  585. #ifdef DEBUG
  586. // fprintf(stdout,"end of stream: %d\n", *((U32 *)bytes));fflush(stdout);
  587. #endif
  588. return currentStatus = EOS; // end of stream
  589. }
  590. }
  591. }
  592. // dst[*bytesRead] = '\0';
  593. #ifdef DEBUG
  594. //fprintf(stdout, "We read:\n");
  595. //fprintf(stdout, "====================================================\n");
  596. //fprintf(stdout, "%s\n",dst);
  597. //fprintf(stdout, "====================================================\n");
  598. //fprintf(stdout,"read ok: %d\n", *bytesRead);fflush(stdout);
  599. #endif
  600. return currentStatus = Ok; // successfully read size bytes
  601. }
  602. //-----------------------------------------------------------------------------
  603. // Write to a file.
  604. // The number of bytes to write is passed in size, the data is passed in src.
  605. // The number of bytes written is available in bytesWritten if a non-Null
  606. // pointer is provided.
  607. //-----------------------------------------------------------------------------
  608. File::FileStatus File::write(U32 size, const char *src, U32 *bytesWritten)
  609. {
  610. // JMQ: despite the U32 parameters, the maximum filesize supported by this
  611. // function is probably the max value of S32, due to the unix syscall
  612. // api.
  613. AssertFatal(Closed != currentStatus, "File::write: file closed");
  614. AssertFatal(NULL != handle, "File::write: invalid file handle");
  615. AssertFatal(NULL != src, "File::write: NULL source pointer");
  616. AssertFatal(true == hasCapability(FileWrite), "File::write: file lacks capability");
  617. AssertWarn(0 != size, "File::write: size of zero");
  618. if ((Ok != currentStatus && EOS != currentStatus) || 0 == size)
  619. return currentStatus;
  620. else
  621. {
  622. S32 numWritten = x86UNIXWrite(*((int *)handle), src, size);
  623. if (numWritten < 0)
  624. return setStatus();
  625. if (bytesWritten)
  626. *bytesWritten = static_cast<U32>(numWritten);
  627. return currentStatus = Ok;
  628. }
  629. }
  630. //-----------------------------------------------------------------------------
  631. // Self-explanatory. JMQ: No explanation needed. Move along. These aren't
  632. // the droids you're looking for.
  633. //-----------------------------------------------------------------------------
  634. bool File::hasCapability(Capability cap) const
  635. {
  636. return (0 != (U32(cap) & capability));
  637. }
  638. //-----------------------------------------------------------------------------
  639. S32 Platform::compareFileTimes(const FileTime &a, const FileTime &b)
  640. {
  641. if(a > b)
  642. return 1;
  643. if(a < b)
  644. return -1;
  645. return 0;
  646. }
  647. //-----------------------------------------------------------------------------
  648. static bool GetFileTimes(const char *filePath, FileTime *createTime, FileTime *modifyTime)
  649. {
  650. struct stat fStat;
  651. if (stat(filePath, &fStat) == -1)
  652. return false;
  653. if(createTime)
  654. {
  655. // no where does SysV/BSD UNIX keep a record of a file's
  656. // creation time. instead of creation time I'll just use
  657. // changed time for now.
  658. *createTime = fStat.st_ctime;
  659. }
  660. if(modifyTime)
  661. {
  662. *modifyTime = fStat.st_mtime;
  663. }
  664. return true;
  665. }
  666. //-----------------------------------------------------------------------------
  667. bool Platform::getFileTimes(const char *filePath, FileTime *createTime, FileTime *modifyTime)
  668. {
  669. char pathName[MaxPath];
  670. // if it starts with cwd, we need to strip that off so that we can look for
  671. // the file in the pref dir
  672. char cwd[MaxPath];
  673. getcwd(cwd, MaxPath);
  674. if (dStrstr(filePath, cwd) == filePath)
  675. filePath = filePath + dStrlen(cwd) + 1;
  676. // if its relative, first look in the pref dir
  677. if (filePath[0] != '/' && filePath[0] != '\\')
  678. {
  679. MungePath(pathName, MaxPath, filePath, GetPrefDir());
  680. if (GetFileTimes(pathName, createTime, modifyTime))
  681. return true;
  682. }
  683. // here if the path is absolute or not in the pref dir
  684. MungePath(pathName, MaxPath, filePath, cwd);
  685. return GetFileTimes(pathName, createTime, modifyTime);
  686. }
  687. //-----------------------------------------------------------------------------
  688. bool Platform::createPath(const char *file)
  689. {
  690. char pathbuf[MaxPath];
  691. const char *dir;
  692. pathbuf[0] = 0;
  693. U32 pathLen = 0;
  694. // all paths should be created in home directory
  695. char prefPathName[MaxPath];
  696. MungePath(prefPathName, MaxPath, file, GetPrefDir());
  697. file = prefPathName;
  698. // does the directory exist already?
  699. if (DirExists(prefPathName, true)) // true means that the path is a filepath
  700. return true;
  701. while((dir = dStrchr(file, '/')) != NULL)
  702. {
  703. dStrncpy(pathbuf + pathLen, file, dir - file);
  704. pathbuf[pathLen + dir-file] = 0;
  705. bool ret = mkdir(pathbuf, 0700);
  706. pathLen += dir - file;
  707. pathbuf[pathLen++] = '/';
  708. file = dir + 1;
  709. }
  710. return true;
  711. }
  712. // JMQ: Platform:cdFileExists in unimplemented
  713. //------------------------------------------------------------------------------
  714. // bool Platform::cdFileExists(const char *filePath, const char *volumeName,
  715. // S32 serialNum)
  716. // {
  717. // }
  718. //-----------------------------------------------------------------------------
  719. bool Platform::dumpPath(const char *path, Vector<Platform::FileInfo> &fileVector, int depth)
  720. {
  721. const char* pattern = "*";
  722. // if it is not absolute, dump the pref dir first
  723. if (path[0] != '/' && path[0] != '\\')
  724. {
  725. char prefPathName[MaxPath];
  726. MungePath(prefPathName, MaxPath, path, GetPrefDir());
  727. RecurseDumpPath(prefPathName, path, pattern, fileVector, 0, depth);
  728. }
  729. // munge the requested path and dump it
  730. char mungedPath[MaxPath];
  731. char cwd[MaxPath];
  732. getcwd(cwd, MaxPath);
  733. MungePath(mungedPath, MaxPath, path, cwd);
  734. return RecurseDumpPath(mungedPath, path, pattern, fileVector, 0, depth);
  735. }
  736. //-----------------------------------------------------------------------------
  737. StringTableEntry Platform::getCurrentDirectory()
  738. {
  739. char cwd_buf[2048];
  740. getcwd(cwd_buf, 2047);
  741. return StringTable->insert(cwd_buf);
  742. }
  743. //-----------------------------------------------------------------------------
  744. bool Platform::setCurrentDirectory(StringTableEntry newDir)
  745. {
  746. if (Platform::getWebDeployment())
  747. return true;
  748. TempAlloc< UTF8 > buf( dStrlen( newDir ) + 2 );
  749. dStrcpy( buf, newDir, buf.size );
  750. ForwardSlash( buf );
  751. return chdir( buf ) == 0;
  752. }
  753. //-----------------------------------------------------------------------------
  754. const char *Platform::getUserDataDirectory()
  755. {
  756. return StringTable->insert( GetPrefDir() );
  757. }
  758. //-----------------------------------------------------------------------------
  759. StringTableEntry Platform::getUserHomeDirectory()
  760. {
  761. char *home = getenv( "HOME" );
  762. return StringTable->insert( home );
  763. }
  764. StringTableEntry Platform::getExecutablePath()
  765. {
  766. if( !sBinPathName[0] )
  767. {
  768. const char *cpath;
  769. if( (cpath = torque_getexecutablepath()) )
  770. {
  771. dStrncpy(sBinPathName, cpath, sizeof(sBinPathName));
  772. chdir(sBinPathName);
  773. }
  774. else
  775. {
  776. getcwd(sBinPathName, sizeof(sBinPathName)-1);
  777. }
  778. }
  779. return StringTable->insert(sBinPathName);
  780. }
  781. //-----------------------------------------------------------------------------
  782. bool Platform::isFile(const char *pFilePath)
  783. {
  784. if (!pFilePath || !*pFilePath)
  785. return false;
  786. // Get file info
  787. struct stat fStat;
  788. if (stat(pFilePath, &fStat) < 0)
  789. {
  790. // Since file does not exist on disk see if it exists in a zip file loaded
  791. return Torque::FS::IsFile(pFilePath);
  792. }
  793. // if the file is a "regular file" then true
  794. if ( (fStat.st_mode & S_IFMT) == S_IFREG)
  795. return true;
  796. // must be some other file (directory, device, etc.)
  797. return false;
  798. }
  799. //-----------------------------------------------------------------------------
  800. S32 Platform::getFileSize(const char *pFilePath)
  801. {
  802. if (!pFilePath || !*pFilePath)
  803. return -1;
  804. // Get the file info
  805. struct stat fStat;
  806. if (stat(pFilePath, &fStat) < 0)
  807. return -1;
  808. // if the file is a "regular file" then return the size
  809. if ( (fStat.st_mode & S_IFMT) == S_IFREG)
  810. return fStat.st_size;
  811. // Must be something else or we can't read the file.
  812. return -1;
  813. }
  814. //-----------------------------------------------------------------------------
  815. bool Platform::isDirectory(const char *pDirPath)
  816. {
  817. if (!pDirPath || !*pDirPath)
  818. return false;
  819. // Get file info
  820. struct stat fStat;
  821. if (stat(pDirPath, &fStat) < 0)
  822. return false;
  823. // if the file is a Directory then true
  824. if ( (fStat.st_mode & S_IFMT) == S_IFDIR)
  825. return true;
  826. return false;
  827. }
  828. //-----------------------------------------------------------------------------
  829. bool Platform::isSubDirectory(const char *pParent, const char *pDir)
  830. {
  831. if (!pParent || !*pDir)
  832. return false;
  833. // this is somewhat of a brute force method but we need to be 100% sure
  834. // that the user cannot enter things like ../dir or /dir etc,...
  835. DIR *directory;
  836. directory = opendir(pParent);
  837. if (directory == NULL)
  838. return false;
  839. struct dirent *fEntry;
  840. fEntry = readdir(directory);
  841. if ( fEntry == NULL )
  842. {
  843. closedir(directory);
  844. return false;
  845. }
  846. do
  847. {
  848. char dirBuf[MaxPath];
  849. struct stat fStat;
  850. dSprintf(dirBuf, sizeof(dirBuf), "%s/%s", pParent, fEntry->d_name);
  851. if (stat(dirBuf, &fStat) < 0)
  852. continue;
  853. // if it is a directory...
  854. if ( (fStat.st_mode & S_IFMT) == S_IFDIR)
  855. {
  856. // and the names match
  857. if (dStrcmp(pDir, fEntry->d_name ) == 0)
  858. {
  859. // then we have a real sub directory
  860. closedir(directory);
  861. return true;
  862. }
  863. }
  864. } while( (fEntry = readdir(directory)) != NULL );
  865. closedir(directory);
  866. return false;
  867. }
  868. //-----------------------------------------------------------------------------
  869. // This is untested -- BJG
  870. bool Platform::fileTimeToString(FileTime * time, char * string, U32 strLen)
  871. {
  872. if(!time || !string)
  873. return(false);
  874. dSprintf(string, strLen, "%ld", *time);
  875. return(true);
  876. }
  877. bool Platform::stringToFileTime(const char * string, FileTime * time)
  878. {
  879. if(!time || !string)
  880. return(false);
  881. *time = dAtoi(string);
  882. return(true);
  883. }
  884. bool Platform::hasSubDirectory(const char *pPath)
  885. {
  886. if (!pPath)
  887. return false;
  888. struct dirent *d;
  889. DIR *dip;
  890. dip = opendir(pPath);
  891. if (dip == NULL)
  892. return false;
  893. while ((d = readdir(dip)))
  894. {
  895. bool isDir = false;
  896. if (d->d_type == DT_UNKNOWN)
  897. {
  898. char child [1024];
  899. if ((pPath[dStrlen(pPath) - 1] == '/'))
  900. dSprintf(child, 1024, "%s%s", pPath, d->d_name);
  901. else
  902. dSprintf(child, 1024, "%s/%s", pPath, d->d_name);
  903. isDir = Platform::isDirectory (child);
  904. }
  905. else if (d->d_type & DT_DIR)
  906. isDir = true;
  907. if( isDir )
  908. {
  909. // Skip the . and .. directories
  910. if (dStrcmp(d->d_name, ".") == 0 ||dStrcmp(d->d_name, "..") == 0)
  911. continue;
  912. if (Platform::isExcludedDirectory(d->d_name))
  913. continue;
  914. Platform::clearExcludedDirectories();
  915. closedir(dip);
  916. return true;
  917. }
  918. }
  919. closedir(dip);
  920. Platform::clearExcludedDirectories();
  921. return false;
  922. }
  923. bool Platform::fileDelete(const char * name)
  924. {
  925. return ModifyFile(name, DELETE);
  926. }
  927. static bool recurseDumpDirectories(const char *basePath, const char *subPath, Vector<StringTableEntry> &directoryVector, S32 currentDepth, S32 recurseDepth, bool noBasePath)
  928. {
  929. char Path[1024];
  930. DIR *dip;
  931. struct dirent *d;
  932. dsize_t trLen = basePath ? dStrlen(basePath) : 0;
  933. dsize_t subtrLen = subPath ? dStrlen(subPath) : 0;
  934. char trail = trLen > 0 ? basePath[trLen - 1] : '\0';
  935. char subTrail = subtrLen > 0 ? subPath[subtrLen - 1] : '\0';
  936. char subLead = subtrLen > 0 ? subPath[0] : '\0';
  937. if (trail == '/')
  938. {
  939. if (subPath && (dStrncmp(subPath, "", 1) != 0))
  940. {
  941. if (subTrail == '/')
  942. dSprintf(Path, 1024, "%s%s", basePath, subPath);
  943. else
  944. dSprintf(Path, 1024, "%s%s/", basePath, subPath);
  945. }
  946. else
  947. dSprintf(Path, 1024, "%s", basePath);
  948. }
  949. else
  950. {
  951. if (subPath && (dStrncmp(subPath, "", 1) != 0))
  952. {
  953. if (subTrail == '/')
  954. dSprintf(Path, 1024, "%s%s", basePath, subPath);
  955. else
  956. dSprintf(Path, 1024, "%s%s/", basePath, subPath);
  957. }
  958. else
  959. dSprintf(Path, 1024, "%s/", basePath);
  960. }
  961. dip = opendir(Path);
  962. if (dip == NULL)
  963. return false;
  964. //////////////////////////////////////////////////////////////////////////
  965. // add path to our return list ( provided it is valid )
  966. //////////////////////////////////////////////////////////////////////////
  967. if (!Platform::isExcludedDirectory(subPath))
  968. {
  969. if (noBasePath)
  970. {
  971. // We have a path and it's not an empty string or an excluded directory
  972. if ( (subPath && (dStrncmp (subPath, "", 1) != 0)) )
  973. directoryVector.push_back(StringTable->insert(subPath));
  974. }
  975. else
  976. {
  977. if ( (subPath && (dStrncmp(subPath, "", 1) != 0)) )
  978. {
  979. char szPath[1024];
  980. dMemset(szPath, 0, 1024);
  981. if (trail == '/')
  982. {
  983. if ((basePath[dStrlen(basePath) - 1]) != '/')
  984. dSprintf(szPath, 1024, "%s%s", basePath, &subPath[1]);
  985. else
  986. dSprintf(szPath, 1024, "%s%s", basePath, subPath);
  987. }
  988. else
  989. {
  990. if ((basePath[dStrlen(basePath) - 1]) != '/')
  991. dSprintf(szPath, 1024, "%s%s", basePath, subPath);
  992. else
  993. dSprintf(szPath, 1024, "%s/%s", basePath, subPath);
  994. }
  995. directoryVector.push_back(StringTable->insert(szPath));
  996. }
  997. else
  998. directoryVector.push_back(StringTable->insert(basePath));
  999. }
  1000. }
  1001. //////////////////////////////////////////////////////////////////////////
  1002. // Iterate through and grab valid directories
  1003. //////////////////////////////////////////////////////////////////////////
  1004. while ((d = readdir(dip)))
  1005. {
  1006. bool isDir;
  1007. isDir = false;
  1008. if (d->d_type == DT_UNKNOWN)
  1009. {
  1010. char child [1024];
  1011. if (Path[dStrlen(Path) - 1] == '/')
  1012. dSprintf(child, 1024, "%s%s", Path, d->d_name);
  1013. else
  1014. dSprintf(child, 1024, "%s/%s", Path, d->d_name);
  1015. isDir = Platform::isDirectory (child);
  1016. }
  1017. else if (d->d_type & DT_DIR)
  1018. isDir = true;
  1019. if ( isDir )
  1020. {
  1021. if (dStrcmp(d->d_name, ".") == 0 ||
  1022. dStrcmp(d->d_name, "..") == 0)
  1023. continue;
  1024. if (Platform::isExcludedDirectory(d->d_name))
  1025. continue;
  1026. if ( (subPath && (dStrncmp(subPath, "", 1) != 0)) )
  1027. {
  1028. char child[1024];
  1029. if ((subPath[dStrlen(subPath) - 1] == '/'))
  1030. dSprintf(child, 1024, "%s%s", subPath, d->d_name);
  1031. else
  1032. dSprintf(child, 1024, "%s/%s", subPath, d->d_name);
  1033. if (currentDepth < recurseDepth || recurseDepth == -1 )
  1034. recurseDumpDirectories(basePath, child, directoryVector,
  1035. currentDepth + 1, recurseDepth,
  1036. noBasePath);
  1037. }
  1038. else
  1039. {
  1040. char child[1024];
  1041. if ( (basePath[dStrlen(basePath) - 1]) == '/')
  1042. dStrcpy (child, d->d_name, 1024);
  1043. else
  1044. dSprintf(child, 1024, "/%s", d->d_name);
  1045. if (currentDepth < recurseDepth || recurseDepth == -1)
  1046. recurseDumpDirectories(basePath, child, directoryVector,
  1047. currentDepth + 1, recurseDepth,
  1048. noBasePath);
  1049. }
  1050. }
  1051. }
  1052. closedir(dip);
  1053. return true;
  1054. }
  1055. bool Platform::dumpDirectories(const char *path, Vector<StringTableEntry> &directoryVector, S32 depth, bool noBasePath)
  1056. {
  1057. #ifdef TORQUE_POSIX_PATH_CASE_INSENSITIVE
  1058. dsize_t pathLength = dStrlen(path);
  1059. char* caseSensitivePath = new char[pathLength + 1];
  1060. // Load path into temporary buffer
  1061. dMemcpy(caseSensitivePath, path, pathLength);
  1062. caseSensitivePath[pathLength] = 0x00;
  1063. ResolvePathCaseInsensitive(caseSensitivePath, pathLength, false);
  1064. #else
  1065. const char* caseSensitivePath = path;
  1066. #endif
  1067. bool retVal = recurseDumpDirectories(caseSensitivePath, "", directoryVector, -1, depth, noBasePath);
  1068. clearExcludedDirectories();
  1069. #ifdef TORQUE_POSIX_PATH_CASE_INSENSITIVE
  1070. delete[] caseSensitivePath;
  1071. #endif
  1072. return retVal;
  1073. }
  1074. StringTableEntry Platform::getExecutableName()
  1075. {
  1076. return StringTable->insert(sBinName);
  1077. }
  1078. extern "C"
  1079. {
  1080. void setExePathName(const char* exePathName)
  1081. {
  1082. if (exePathName == NULL)
  1083. sBinPathName[0] = '\0';
  1084. else
  1085. dStrncpy(sBinPathName, exePathName, sizeof(sBinPathName));
  1086. // set the base exe name field
  1087. char *binName = dStrrchr(sBinPathName, '/');
  1088. if( !binName )
  1089. binName = sBinPathName;
  1090. else
  1091. *binName++ = '\0';
  1092. sBinName = binName;
  1093. }
  1094. }