unix.c 16 KB

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