unix.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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. /* If there isn't a path on argv0, then look through the $PATH for it. */
  240. char *retval;
  241. char *envr;
  242. if (strchr(argv0, '/') != NULL) /* default behaviour can handle this. */
  243. return(NULL);
  244. envr = __PHYSFS_platformCopyEnvironmentVariable("PATH");
  245. BAIL_IF_MACRO(!envr, NULL, NULL);
  246. retval = findBinaryInPath(argv0, envr);
  247. allocator.Free(envr);
  248. return(retval);
  249. } /* __PHYSFS_platformCalcBaseDir */
  250. /* Much like my college days, try to sleep for 10 milliseconds at a time... */
  251. void __PHYSFS_platformTimeslice(void)
  252. {
  253. usleep( 10 * 1000 ); /* don't care if it fails. */
  254. } /* __PHYSFS_platformTimeslice */
  255. #ifdef PHYSFS_PLATFORM_MACOSX
  256. /*
  257. * This function is only for OSX. The problem is that Apple's applications
  258. * can actually be directory structures with the actual executable nested
  259. * several levels down. PhysFS computes the base directory from the Unix
  260. * executable, but this may not be the correct directory. Apple tries to
  261. * hide everything from the user, so from Finder, the user never sees the
  262. * Unix executable, and the directory package (bundle) is considered the
  263. * "executable". This means that the correct base directory is at the
  264. * level where the directory structure starts.
  265. * A typical bundle seems to look like this:
  266. * MyApp.app/ <-- top level...this is what the user sees in Finder
  267. * Contents/
  268. * MacOS/
  269. * MyApp <-- the actual executable
  270. *
  271. * Since anything below the app folder is considered hidden, most
  272. * application files need to be at the top level if you intend to
  273. * write portable software. Thus if the application resides in:
  274. * /Applications/MyProgram
  275. * and the executable is the bundle MyApp.app,
  276. * PhysFS computes the following as the base directory:
  277. * /Applications/MyProgram/MyApp.app/Contents/MacOS/
  278. * We need to strip off the MyApp.app/Contents/MacOS/
  279. *
  280. * However, there are corner cases. OSX applications can be traditional
  281. * Unix executables without the bundle. Also, it is not entirely clear
  282. * to me what kinds of permutations bundle structures can have.
  283. *
  284. * For now, this is a temporary hack until a better solution
  285. * can be made. This function will try to find a "/Contents/MacOS"
  286. * inside the path. If it succeeds, then the path will be truncated
  287. * to correct the directory. If it is not found, the path will be
  288. * left alone and will presume it is a traditional Unix execuatable.
  289. * Most programs also include the .app extention in the top level
  290. * folder, but it doesn't seem to be a requirement (Acrobat doesn't
  291. * have it). MacOS looks like it can also be MacOSClassic.
  292. * This function will test for MacOS and hope it captures any
  293. * other permutations.
  294. */
  295. static void stripAppleBundle(char *path)
  296. {
  297. char *sub_str = "/contents/macos";
  298. char *found_ptr = NULL;
  299. char *tempbuf = NULL;
  300. size_t len = strlen(path) + 1;
  301. int i;
  302. /* !!! FIXME: Can we stack-allocate this? --ryan. */
  303. tempbuf = (char *) allocator.Malloc(len);
  304. if (!tempbuf) return;
  305. memset(tempbuf, '\0', len);
  306. /* Unlike other Unix filesystems, HFS is case insensitive
  307. * It wouldn be nice to use strcasestr, but it doesn't seem
  308. * to be available in the OSX gcc library right now.
  309. * So we should make a lower case copy of the path to
  310. * compare against
  311. */
  312. for(i=0; i<strlen(path); i++)
  313. {
  314. /* convert to lower case */
  315. tempbuf[i] = tolower(path[i]);
  316. }
  317. /* See if we can find "/contents/macos" in the path */
  318. found_ptr = strstr(tempbuf, sub_str);
  319. if(NULL == found_ptr)
  320. {
  321. /* It doesn't look like a bundle so we can keep the
  322. * original path. Just return */
  323. allocator.Free(tempbuf);
  324. return;
  325. }
  326. /* We have a bundle, so let's backstep character by character
  327. * to erase the extra parts of the path. Quit when we hit
  328. * the preceding '/' character.
  329. */
  330. for(i=strlen(path)-strlen(found_ptr)-1; i>=0; i--)
  331. {
  332. if('/' == path[i])
  333. {
  334. break;
  335. }
  336. }
  337. /* Safety check */
  338. if(i<1)
  339. {
  340. /* This probably shouldn't happen. */
  341. path[0] = '\0';
  342. }
  343. else
  344. {
  345. /* Back up one more to remove trailing '/' and set the '\0' */
  346. path[i] = '\0';
  347. }
  348. allocator.Free(tempbuf);
  349. return;
  350. }
  351. #endif
  352. char *__PHYSFS_platformRealPath(const char *path)
  353. {
  354. char resolved_path[MAXPATHLEN];
  355. char *retval = NULL;
  356. errno = 0;
  357. BAIL_IF_MACRO(!realpath(path, resolved_path), strerror(errno), NULL);
  358. retval = (char *) allocator.Malloc(strlen(resolved_path) + 1);
  359. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  360. strcpy(retval, resolved_path);
  361. #ifdef PHYSFS_PLATFORM_MACOSX
  362. stripAppleBundle(retval);
  363. #endif
  364. return(retval);
  365. } /* __PHYSFS_platformRealPath */
  366. #if (defined PHYSFS_NO_PTHREADS_SUPPORT)
  367. PHYSFS_uint64 __PHYSFS_platformGetThreadID(void) { return(0x0001); }
  368. void *__PHYSFS_platformCreateMutex(void) { return((void *) 0x0001); }
  369. void __PHYSFS_platformDestroyMutex(void *mutex) {}
  370. int __PHYSFS_platformGrabMutex(void *mutex) { return(1); }
  371. void __PHYSFS_platformReleaseMutex(void *mutex) {}
  372. #else
  373. typedef struct
  374. {
  375. pthread_mutex_t mutex;
  376. pthread_t owner;
  377. PHYSFS_uint32 count;
  378. } PthreadMutex;
  379. /* Just in case; this is a panic value. */
  380. #if ((!defined SIZEOF_INT) || (SIZEOF_INT <= 0))
  381. # define SIZEOF_INT 4
  382. #endif
  383. #if (SIZEOF_INT == 4)
  384. # define PHTREAD_TO_UI64(thr) ( (PHYSFS_uint64) ((PHYSFS_uint32) (thr)) )
  385. #elif (SIZEOF_INT == 2)
  386. # define PHTREAD_TO_UI64(thr) ( (PHYSFS_uint64) ((PHYSFS_uint16) (thr)) )
  387. #elif (SIZEOF_INT == 1)
  388. # define PHTREAD_TO_UI64(thr) ( (PHYSFS_uint64) ((PHYSFS_uint8) (thr)) )
  389. #else
  390. # define PHTREAD_TO_UI64(thr) ((PHYSFS_uint64) (thr))
  391. #endif
  392. PHYSFS_uint64 __PHYSFS_platformGetThreadID(void)
  393. {
  394. return(PHTREAD_TO_UI64(pthread_self()));
  395. } /* __PHYSFS_platformGetThreadID */
  396. void *__PHYSFS_platformCreateMutex(void)
  397. {
  398. int rc;
  399. PthreadMutex *m = (PthreadMutex *) allocator.Malloc(sizeof (PthreadMutex));
  400. BAIL_IF_MACRO(m == NULL, ERR_OUT_OF_MEMORY, NULL);
  401. rc = pthread_mutex_init(&m->mutex, NULL);
  402. if (rc != 0)
  403. {
  404. allocator.Free(m);
  405. BAIL_MACRO(strerror(rc), NULL);
  406. } /* if */
  407. m->count = 0;
  408. m->owner = (pthread_t) 0xDEADBEEF;
  409. return((void *) m);
  410. } /* __PHYSFS_platformCreateMutex */
  411. void __PHYSFS_platformDestroyMutex(void *mutex)
  412. {
  413. PthreadMutex *m = (PthreadMutex *) mutex;
  414. /* Destroying a locked mutex is a bug, but we'll try to be helpful. */
  415. if ((m->owner == pthread_self()) && (m->count > 0))
  416. pthread_mutex_unlock(&m->mutex);
  417. pthread_mutex_destroy(&m->mutex);
  418. allocator.Free(m);
  419. } /* __PHYSFS_platformDestroyMutex */
  420. int __PHYSFS_platformGrabMutex(void *mutex)
  421. {
  422. PthreadMutex *m = (PthreadMutex *) mutex;
  423. pthread_t tid = pthread_self();
  424. if (m->owner != tid)
  425. {
  426. if (pthread_mutex_lock(&m->mutex) != 0)
  427. return(0);
  428. m->owner = tid;
  429. } /* if */
  430. m->count++;
  431. return(1);
  432. } /* __PHYSFS_platformGrabMutex */
  433. void __PHYSFS_platformReleaseMutex(void *mutex)
  434. {
  435. PthreadMutex *m = (PthreadMutex *) mutex;
  436. if (m->owner == pthread_self())
  437. {
  438. if (--m->count == 0)
  439. {
  440. m->owner = (pthread_t) 0xDEADBEEF;
  441. pthread_mutex_unlock(&m->mutex);
  442. } /* if */
  443. } /* if */
  444. } /* __PHYSFS_platformReleaseMutex */
  445. #endif /* !PHYSFS_NO_PTHREADS_SUPPORT */
  446. #endif /* PHYSFS_PLATFORM_UNIX */
  447. /* end of unix.c ... */