unix.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. /*
  2. * Unix support routines for PhysicsFS.
  3. *
  4. * Please see the file LICENSE in the source's root directory.
  5. *
  6. * This file written by Ryan C. Gordon.
  7. */
  8. /* BeOS uses beos.cpp and posix.c ... Cygwin and such use windows.c ... */
  9. #if ((!defined __BEOS__) && (!defined WIN32))
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <ctype.h>
  14. #include <unistd.h>
  15. #include <sys/types.h>
  16. #include <pwd.h>
  17. #include <sys/stat.h>
  18. #include <sys/param.h>
  19. #include <dirent.h>
  20. #include <time.h>
  21. #include <errno.h>
  22. #include <sys/mount.h>
  23. #ifndef PHYSFS_DARWIN
  24. # if defined(__MACH__) && defined(__APPLE__)
  25. # define PHYSFS_DARWIN 1
  26. # include <CoreFoundation/CoreFoundation.h>
  27. # include <CoreServices/CoreServices.h>
  28. # include <IOKit/IOKitLib.h>
  29. # include <IOKit/storage/IOMedia.h>
  30. # include <IOKit/storage/IOCDMedia.h>
  31. # include <IOKit/storage/IODVDMedia.h>
  32. # endif
  33. #endif
  34. #if (!defined PHYSFS_NO_PTHREADS_SUPPORT)
  35. #include <pthread.h>
  36. #endif
  37. #ifdef PHYSFS_HAVE_SYS_UCRED_H
  38. # ifdef PHYSFS_HAVE_MNTENT_H
  39. # undef PHYSFS_HAVE_MNTENT_H /* don't do both... */
  40. # endif
  41. # include <sys/ucred.h>
  42. #endif
  43. #ifdef PHYSFS_HAVE_MNTENT_H
  44. #include <mntent.h>
  45. #endif
  46. #define __PHYSICSFS_INTERNAL__
  47. #include "physfs_internal.h"
  48. /* Seems to get defined in some system header... */
  49. #ifdef Free
  50. #undef Free
  51. #endif
  52. const char *__PHYSFS_platformDirSeparator = "/";
  53. int __PHYSFS_platformInit(void)
  54. {
  55. return(1); /* always succeed. */
  56. } /* __PHYSFS_platformInit */
  57. int __PHYSFS_platformDeinit(void)
  58. {
  59. return(1); /* always succeed. */
  60. } /* __PHYSFS_platformDeinit */
  61. #ifdef PHYSFS_NO_CDROM_SUPPORT
  62. /* Stub version for platforms without CD-ROM support. */
  63. void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
  64. {
  65. } /* __PHYSFS_platformDetectAvailableCDs */
  66. #elif (defined PHYSFS_DARWIN) /* "Big Nasty." */
  67. /*
  68. * Code based on sample from Apple Developer Connection:
  69. * http://developer.apple.com/samplecode/Sample_Code/Devices_and_Hardware/Disks/VolumeToBSDNode/VolumeToBSDNode.c.htm
  70. */
  71. static int darwinIsWholeMedia(io_service_t service)
  72. {
  73. int retval = 0;
  74. CFTypeRef wholeMedia;
  75. if (!IOObjectConformsTo(service, kIOMediaClass))
  76. return(0);
  77. wholeMedia = IORegistryEntryCreateCFProperty(service,
  78. CFSTR(kIOMediaWholeKey),
  79. kCFAllocatorDefault, 0);
  80. if (wholeMedia == NULL)
  81. return(0);
  82. retval = CFBooleanGetValue(wholeMedia);
  83. CFRelease(wholeMedia);
  84. return retval;
  85. } /* darwinIsWholeMedia */
  86. static int darwinIsMountedDisc(char *bsdName, mach_port_t masterPort)
  87. {
  88. int retval = 0;
  89. CFMutableDictionaryRef matchingDict;
  90. kern_return_t rc;
  91. io_iterator_t iter;
  92. io_service_t service;
  93. if ((matchingDict = IOBSDNameMatching(masterPort, 0, bsdName)) == NULL)
  94. return(0);
  95. rc = IOServiceGetMatchingServices(masterPort, matchingDict, &iter);
  96. if ((rc != KERN_SUCCESS) || (!iter))
  97. return(0);
  98. service = IOIteratorNext(iter);
  99. IOObjectRelease(iter);
  100. if (!service)
  101. return(0);
  102. rc = IORegistryEntryCreateIterator(service, kIOServicePlane,
  103. kIORegistryIterateRecursively | kIORegistryIterateParents, &iter);
  104. if (!iter)
  105. return(0);
  106. if (rc != KERN_SUCCESS)
  107. {
  108. IOObjectRelease(iter);
  109. return(0);
  110. } /* if */
  111. IOObjectRetain(service); /* add an extra object reference... */
  112. do
  113. {
  114. if (darwinIsWholeMedia(service))
  115. {
  116. if ( (IOObjectConformsTo(service, kIOCDMediaClass)) ||
  117. (IOObjectConformsTo(service, kIODVDMediaClass)) )
  118. {
  119. retval = 1;
  120. } /* if */
  121. } /* if */
  122. IOObjectRelease(service);
  123. } while ((service = IOIteratorNext(iter)) && (!retval));
  124. IOObjectRelease(iter);
  125. IOObjectRelease(service);
  126. return(retval);
  127. } /* darwinIsMountedDisc */
  128. void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
  129. {
  130. const char *devPrefix = "/dev/";
  131. int prefixLen = strlen(devPrefix);
  132. mach_port_t masterPort = 0;
  133. struct statfs *mntbufp;
  134. int i, mounts;
  135. if (IOMasterPort(MACH_PORT_NULL, &masterPort) != KERN_SUCCESS)
  136. BAIL_MACRO(ERR_OS_ERROR, /*return void*/);
  137. mounts = getmntinfo(&mntbufp, MNT_WAIT); /* NOT THREAD SAFE! */
  138. for (i = 0; i < mounts; i++)
  139. {
  140. char *dev = mntbufp[i].f_mntfromname;
  141. char *mnt = mntbufp[i].f_mntonname;
  142. if (strncmp(dev, devPrefix, prefixLen) != 0) /* a virtual device? */
  143. continue;
  144. dev += prefixLen;
  145. if (darwinIsMountedDisc(dev, masterPort))
  146. cb(data, mnt);
  147. } /* for */
  148. } /* __PHYSFS_platformDetectAvailableCDs */
  149. #elif (defined PHYSFS_HAVE_SYS_UCRED_H)
  150. void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
  151. {
  152. int i;
  153. struct statfs *mntbufp = NULL;
  154. int mounts = getmntinfo(&mntbufp, MNT_WAIT);
  155. for (i = 0; i < mounts; i++)
  156. {
  157. int add_it = 0;
  158. if (strcmp(mntbufp[i].f_fstypename, "iso9660") == 0)
  159. add_it = 1;
  160. else if (strcmp( mntbufp[i].f_fstypename, "cd9660") == 0)
  161. add_it = 1;
  162. /* add other mount types here */
  163. if (add_it)
  164. cb(data, mntbufp[i].f_mntonname);
  165. } /* for */
  166. } /* __PHYSFS_platformDetectAvailableCDs */
  167. #elif (defined PHYSFS_HAVE_MNTENT_H)
  168. void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
  169. {
  170. FILE *mounts = NULL;
  171. struct mntent *ent = NULL;
  172. mounts = setmntent("/etc/mtab", "r");
  173. BAIL_IF_MACRO(mounts == NULL, ERR_IO_ERROR, /*return void*/);
  174. while ( (ent = getmntent(mounts)) != NULL )
  175. {
  176. int add_it = 0;
  177. if (strcmp(ent->mnt_type, "iso9660") == 0)
  178. add_it = 1;
  179. /* add other mount types here */
  180. if (add_it)
  181. cb(data, ent->mnt_dir);
  182. } /* while */
  183. endmntent(mounts);
  184. } /* __PHYSFS_platformDetectAvailableCDs */
  185. #endif
  186. /* this is in posix.c ... */
  187. extern char *__PHYSFS_platformCopyEnvironmentVariable(const char *varname);
  188. /*
  189. * See where program (bin) resides in the $PATH specified by (envr).
  190. * returns a copy of the first element in envr that contains it, or NULL
  191. * if it doesn't exist or there were other problems. PHYSFS_SetError() is
  192. * called if we have a problem.
  193. *
  194. * (envr) will be scribbled over, and you are expected to allocator.Free() the
  195. * return value when you're done with it.
  196. */
  197. static char *findBinaryInPath(const char *bin, char *envr)
  198. {
  199. size_t alloc_size = 0;
  200. char *exe = NULL;
  201. char *start = envr;
  202. char *ptr;
  203. BAIL_IF_MACRO(bin == NULL, ERR_INVALID_ARGUMENT, NULL);
  204. BAIL_IF_MACRO(envr == NULL, ERR_INVALID_ARGUMENT, NULL);
  205. do
  206. {
  207. size_t size;
  208. ptr = strchr(start, ':'); /* find next $PATH separator. */
  209. if (ptr)
  210. *ptr = '\0';
  211. size = strlen(start) + strlen(bin) + 2;
  212. if (size > alloc_size)
  213. {
  214. char *x = (char *) allocator.Realloc(exe, size);
  215. if (x == NULL)
  216. {
  217. if (exe != NULL)
  218. allocator.Free(exe);
  219. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  220. } /* if */
  221. alloc_size = size;
  222. exe = x;
  223. } /* if */
  224. /* build full binary path... */
  225. strcpy(exe, start);
  226. if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
  227. strcat(exe, "/");
  228. strcat(exe, bin);
  229. if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
  230. {
  231. strcpy(exe, start); /* i'm lazy. piss off. */
  232. return(exe);
  233. } /* if */
  234. start = ptr + 1; /* start points to beginning of next element. */
  235. } while (ptr != NULL);
  236. if (exe != NULL)
  237. allocator.Free(exe);
  238. return(NULL); /* doesn't exist in path. */
  239. } /* findBinaryInPath */
  240. char *__PHYSFS_platformCalcBaseDir(const char *argv0)
  241. {
  242. /* If there isn't a path on argv0, then look through the $PATH for it. */
  243. char *retval;
  244. char *envr;
  245. if (strchr(argv0, '/') != NULL) /* default behaviour can handle this. */
  246. return(NULL);
  247. envr = __PHYSFS_platformCopyEnvironmentVariable("PATH");
  248. BAIL_IF_MACRO(!envr, NULL, NULL);
  249. retval = findBinaryInPath(argv0, envr);
  250. allocator.Free(envr);
  251. return(retval);
  252. } /* __PHYSFS_platformCalcBaseDir */
  253. /* Much like my college days, try to sleep for 10 milliseconds at a time... */
  254. void __PHYSFS_platformTimeslice(void)
  255. {
  256. usleep( 10 * 1000 ); /* don't care if it fails. */
  257. } /* __PHYSFS_platformTimeslice */
  258. #if PHYSFS_DARWIN
  259. /*
  260. * This function is only for OSX. The problem is that Apple's applications
  261. * can actually be directory structures with the actual executable nested
  262. * several levels down. PhysFS computes the base directory from the Unix
  263. * executable, but this may not be the correct directory. Apple tries to
  264. * hide everything from the user, so from Finder, the user never sees the
  265. * Unix executable, and the directory package (bundle) is considered the
  266. * "executable". This means that the correct base directory is at the
  267. * level where the directory structure starts.
  268. * A typical bundle seems to look like this:
  269. * MyApp.app/ <-- top level...this is what the user sees in Finder
  270. * Contents/
  271. * MacOS/
  272. * MyApp <-- the actual executable
  273. *
  274. * Since anything below the app folder is considered hidden, most
  275. * application files need to be at the top level if you intend to
  276. * write portable software. Thus if the application resides in:
  277. * /Applications/MyProgram
  278. * and the executable is the bundle MyApp.app,
  279. * PhysFS computes the following as the base directory:
  280. * /Applications/MyProgram/MyApp.app/Contents/MacOS/
  281. * We need to strip off the MyApp.app/Contents/MacOS/
  282. *
  283. * However, there are corner cases. OSX applications can be traditional
  284. * Unix executables without the bundle. Also, it is not entirely clear
  285. * to me what kinds of permutations bundle structures can have.
  286. *
  287. * For now, this is a temporary hack until a better solution
  288. * can be made. This function will try to find a "/Contents/MacOS"
  289. * inside the path. If it succeeds, then the path will be truncated
  290. * to correct the directory. If it is not found, the path will be
  291. * left alone and will presume it is a traditional Unix execuatable.
  292. * Most programs also include the .app extention in the top level
  293. * folder, but it doesn't seem to be a requirement (Acrobat doesn't
  294. * have it). MacOS looks like it can also be MacOSClassic.
  295. * This function will test for MacOS and hope it captures any
  296. * other permutations.
  297. */
  298. static void stripAppleBundle(char *path)
  299. {
  300. char *sub_str = "/contents/macos";
  301. char *found_ptr = NULL;
  302. char *tempbuf = NULL;
  303. size_t len = strlen(path) + 1;
  304. int i;
  305. /* !!! FIXME: Can we stack-allocate this? --ryan. */
  306. tempbuf = (char *) allocator.Malloc(len);
  307. if (!tempbuf) return;
  308. memset(tempbuf, '\0', len);
  309. /* Unlike other Unix filesystems, HFS is case insensitive
  310. * It wouldn be nice to use strcasestr, but it doesn't seem
  311. * to be available in the OSX gcc library right now.
  312. * So we should make a lower case copy of the path to
  313. * compare against
  314. */
  315. for(i=0; i<strlen(path); i++)
  316. {
  317. /* convert to lower case */
  318. tempbuf[i] = tolower(path[i]);
  319. }
  320. /* See if we can find "/contents/macos" in the path */
  321. found_ptr = strstr(tempbuf, sub_str);
  322. if(NULL == found_ptr)
  323. {
  324. /* It doesn't look like a bundle so we can keep the
  325. * original path. Just return */
  326. allocator.Free(tempbuf);
  327. return;
  328. }
  329. /* We have a bundle, so let's backstep character by character
  330. * to erase the extra parts of the path. Quit when we hit
  331. * the preceding '/' character.
  332. */
  333. for(i=strlen(path)-strlen(found_ptr)-1; i>=0; i--)
  334. {
  335. if('/' == path[i])
  336. {
  337. break;
  338. }
  339. }
  340. /* Safety check */
  341. if(i<1)
  342. {
  343. /* This probably shouldn't happen. */
  344. path[0] = '\0';
  345. }
  346. else
  347. {
  348. /* Back up one more to remove trailing '/' and set the '\0' */
  349. path[i] = '\0';
  350. }
  351. allocator.Free(tempbuf);
  352. return;
  353. }
  354. #endif /* defined __MACH__ && defined __APPLE__ */
  355. char *__PHYSFS_platformRealPath(const char *path)
  356. {
  357. char resolved_path[MAXPATHLEN];
  358. char *retval = NULL;
  359. errno = 0;
  360. BAIL_IF_MACRO(!realpath(path, resolved_path), strerror(errno), NULL);
  361. retval = (char *) allocator.Malloc(strlen(resolved_path) + 1);
  362. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  363. strcpy(retval, resolved_path);
  364. #if defined(__MACH__) && defined(__APPLE__)
  365. stripAppleBundle(retval);
  366. #endif /* defined __MACH__ && defined __APPLE__ */
  367. return(retval);
  368. } /* __PHYSFS_platformRealPath */
  369. #if (defined PHYSFS_NO_PTHREADS_SUPPORT)
  370. PHYSFS_uint64 __PHYSFS_platformGetThreadID(void) { return(0x0001); }
  371. void *__PHYSFS_platformCreateMutex(void) { return((void *) 0x0001); }
  372. void __PHYSFS_platformDestroyMutex(void *mutex) {}
  373. int __PHYSFS_platformGrabMutex(void *mutex) { return(1); }
  374. void __PHYSFS_platformReleaseMutex(void *mutex) {}
  375. #else
  376. typedef struct
  377. {
  378. pthread_mutex_t mutex;
  379. pthread_t owner;
  380. PHYSFS_uint32 count;
  381. } PthreadMutex;
  382. /* Just in case; this is a panic value. */
  383. #if ((!defined SIZEOF_INT) || (SIZEOF_INT <= 0))
  384. # define SIZEOF_INT 4
  385. #endif
  386. #if (SIZEOF_INT == 4)
  387. # define PHTREAD_TO_UI64(thr) ( (PHYSFS_uint64) ((PHYSFS_uint32) (thr)) )
  388. #elif (SIZEOF_INT == 2)
  389. # define PHTREAD_TO_UI64(thr) ( (PHYSFS_uint64) ((PHYSFS_uint16) (thr)) )
  390. #elif (SIZEOF_INT == 1)
  391. # define PHTREAD_TO_UI64(thr) ( (PHYSFS_uint64) ((PHYSFS_uint8) (thr)) )
  392. #else
  393. # define PHTREAD_TO_UI64(thr) ((PHYSFS_uint64) (thr))
  394. #endif
  395. PHYSFS_uint64 __PHYSFS_platformGetThreadID(void)
  396. {
  397. return(PHTREAD_TO_UI64(pthread_self()));
  398. } /* __PHYSFS_platformGetThreadID */
  399. void *__PHYSFS_platformCreateMutex(void)
  400. {
  401. int rc;
  402. PthreadMutex *m = (PthreadMutex *) allocator.Malloc(sizeof (PthreadMutex));
  403. BAIL_IF_MACRO(m == NULL, ERR_OUT_OF_MEMORY, NULL);
  404. rc = pthread_mutex_init(&m->mutex, NULL);
  405. if (rc != 0)
  406. {
  407. allocator.Free(m);
  408. BAIL_MACRO(strerror(rc), NULL);
  409. } /* if */
  410. m->count = 0;
  411. m->owner = (pthread_t) 0xDEADBEEF;
  412. return((void *) m);
  413. } /* __PHYSFS_platformCreateMutex */
  414. void __PHYSFS_platformDestroyMutex(void *mutex)
  415. {
  416. PthreadMutex *m = (PthreadMutex *) mutex;
  417. /* Destroying a locked mutex is a bug, but we'll try to be helpful. */
  418. if ((m->owner == pthread_self()) && (m->count > 0))
  419. pthread_mutex_unlock(&m->mutex);
  420. pthread_mutex_destroy(&m->mutex);
  421. allocator.Free(m);
  422. } /* __PHYSFS_platformDestroyMutex */
  423. int __PHYSFS_platformGrabMutex(void *mutex)
  424. {
  425. PthreadMutex *m = (PthreadMutex *) mutex;
  426. pthread_t tid = pthread_self();
  427. if (m->owner != tid)
  428. {
  429. if (pthread_mutex_lock(&m->mutex) != 0)
  430. return(0);
  431. m->owner = tid;
  432. } /* if */
  433. m->count++;
  434. return(1);
  435. } /* __PHYSFS_platformGrabMutex */
  436. void __PHYSFS_platformReleaseMutex(void *mutex)
  437. {
  438. PthreadMutex *m = (PthreadMutex *) mutex;
  439. if (m->owner == pthread_self())
  440. {
  441. if (--m->count == 0)
  442. {
  443. m->owner = (pthread_t) 0xDEADBEEF;
  444. pthread_mutex_unlock(&m->mutex);
  445. } /* if */
  446. } /* if */
  447. } /* __PHYSFS_platformReleaseMutex */
  448. #endif /* !PHYSFS_NO_PTHREADS_SUPPORT */
  449. #endif /* !defined __BEOS__ && !defined WIN32 */
  450. /* end of unix.c ... */