unix.c 14 KB

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