unix.c 15 KB

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