unix.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. if (IOMasterPort(MACH_PORT_NULL, &masterPort) != KERN_SUCCESS)
  135. BAIL_MACRO(ERR_OS_ERROR, /*return void*/);
  136. mounts = getmntinfo(&mntbufp, MNT_WAIT); /* NOT THREAD SAFE! */
  137. for (i = 0; i < mounts; i++)
  138. {
  139. char *dev = mntbufp[i].f_mntfromname;
  140. char *mnt = mntbufp[i].f_mntonname;
  141. if (strncmp(dev, devPrefix, prefixLen) != 0) /* a virtual device? */
  142. continue;
  143. dev += prefixLen;
  144. if (darwinIsMountedDisc(dev, masterPort))
  145. cb(data, mnt);
  146. } /* for */
  147. } /* __PHYSFS_platformDetectAvailableCDs */
  148. #elif (defined PHYSFS_HAVE_SYS_UCRED_H)
  149. void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
  150. {
  151. int i;
  152. struct statfs *mntbufp = NULL;
  153. int mounts = getmntinfo(&mntbufp, MNT_WAIT);
  154. for (i = 0; i < mounts; i++)
  155. {
  156. int add_it = 0;
  157. if (strcmp(mntbufp[i].f_fstypename, "iso9660") == 0)
  158. add_it = 1;
  159. else if (strcmp( mntbufp[i].f_fstypename, "cd9660") == 0)
  160. add_it = 1;
  161. /* add other mount types here */
  162. if (add_it)
  163. cb(data, mntbufp[i].f_mntonname);
  164. } /* for */
  165. } /* __PHYSFS_platformDetectAvailableCDs */
  166. #elif (defined PHYSFS_HAVE_MNTENT_H)
  167. void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
  168. {
  169. FILE *mounts = NULL;
  170. struct mntent *ent = NULL;
  171. mounts = setmntent("/etc/mtab", "r");
  172. BAIL_IF_MACRO(mounts == NULL, ERR_IO_ERROR, /*return void*/);
  173. while ( (ent = getmntent(mounts)) != NULL )
  174. {
  175. int add_it = 0;
  176. if (strcmp(ent->mnt_type, "iso9660") == 0)
  177. add_it = 1;
  178. /* add other mount types here */
  179. if (add_it)
  180. cb(data, ent->mnt_dir);
  181. } /* while */
  182. endmntent(mounts);
  183. } /* __PHYSFS_platformDetectAvailableCDs */
  184. #endif
  185. /* this is in posix.c ... */
  186. extern char *__PHYSFS_platformCopyEnvironmentVariable(const char *varname);
  187. /*
  188. * See where program (bin) resides in the $PATH specified by (envr).
  189. * returns a copy of the first element in envr that contains it, or NULL
  190. * if it doesn't exist or there were other problems. PHYSFS_SetError() is
  191. * called if we have a problem.
  192. *
  193. * (envr) will be scribbled over, and you are expected to free() the
  194. * return value when you're done with it.
  195. */
  196. static char *findBinaryInPath(const char *bin, char *envr)
  197. {
  198. size_t alloc_size = 0;
  199. char *exe = NULL;
  200. char *start = envr;
  201. char *ptr;
  202. BAIL_IF_MACRO(bin == NULL, ERR_INVALID_ARGUMENT, NULL);
  203. BAIL_IF_MACRO(envr == NULL, ERR_INVALID_ARGUMENT, NULL);
  204. do
  205. {
  206. size_t size;
  207. ptr = strchr(start, ':'); /* find next $PATH separator. */
  208. if (ptr)
  209. *ptr = '\0';
  210. size = strlen(start) + strlen(bin) + 2;
  211. if (size > alloc_size)
  212. {
  213. char *x = (char *) realloc(exe, size);
  214. if (x == NULL)
  215. {
  216. if (exe != NULL)
  217. free(exe);
  218. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  219. } /* if */
  220. alloc_size = size;
  221. exe = x;
  222. } /* if */
  223. /* build full binary path... */
  224. strcpy(exe, start);
  225. if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
  226. strcat(exe, "/");
  227. strcat(exe, bin);
  228. if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
  229. {
  230. strcpy(exe, start); /* i'm lazy. piss off. */
  231. return(exe);
  232. } /* if */
  233. start = ptr + 1; /* start points to beginning of next element. */
  234. } while (ptr != NULL);
  235. if (exe != NULL)
  236. free(exe);
  237. return(NULL); /* doesn't exist in path. */
  238. } /* findBinaryInPath */
  239. char *__PHYSFS_platformCalcBaseDir(const char *argv0)
  240. {
  241. /* If there isn't a path on argv0, then look through the $PATH for it. */
  242. char *retval;
  243. char *envr;
  244. if (strchr(argv0, '/') != NULL) /* default behaviour can handle this. */
  245. return(NULL);
  246. envr = __PHYSFS_platformCopyEnvironmentVariable("PATH");
  247. BAIL_IF_MACRO(!envr, NULL, NULL);
  248. retval = findBinaryInPath(argv0, envr);
  249. free(envr);
  250. return(retval);
  251. } /* __PHYSFS_platformCalcBaseDir */
  252. /* Much like my college days, try to sleep for 10 milliseconds at a time... */
  253. void __PHYSFS_platformTimeslice(void)
  254. {
  255. usleep( 10 * 1000 ); /* don't care if it fails. */
  256. } /* __PHYSFS_platformTimeslice */
  257. #if PHYSFS_DARWIN
  258. /*
  259. * This function is only for OSX. The problem is that Apple's applications
  260. * can actually be directory structures with the actual executable nested
  261. * several levels down. PhysFS computes the base directory from the Unix
  262. * executable, but this may not be the correct directory. Apple tries to
  263. * hide everything from the user, so from Finder, the user never sees the
  264. * Unix executable, and the directory package (bundle) is considered the
  265. * "executable". This means that the correct base directory is at the
  266. * level where the directory structure starts.
  267. * A typical bundle seems to look like this:
  268. * MyApp.app/ <-- top level...this is what the user sees in Finder
  269. * Contents/
  270. * MacOS/
  271. * MyApp <-- the actual executable
  272. *
  273. * Since anything below the app folder is considered hidden, most
  274. * application files need to be at the top level if you intend to
  275. * write portable software. Thus if the application resides in:
  276. * /Applications/MyProgram
  277. * and the executable is the bundle MyApp.app,
  278. * PhysFS computes the following as the base directory:
  279. * /Applications/MyProgram/MyApp.app/Contents/MacOS/
  280. * We need to strip off the MyApp.app/Contents/MacOS/
  281. *
  282. * However, there are corner cases. OSX applications can be traditional
  283. * Unix executables without the bundle. Also, it is not entirely clear
  284. * to me what kinds of permutations bundle structures can have.
  285. *
  286. * For now, this is a temporary hack until a better solution
  287. * can be made. This function will try to find a "/Contents/MacOS"
  288. * inside the path. If it succeeds, then the path will be truncated
  289. * to correct the directory. If it is not found, the path will be
  290. * left alone and will presume it is a traditional Unix execuatable.
  291. * Most programs also include the .app extention in the top level
  292. * folder, but it doesn't seem to be a requirement (Acrobat doesn't
  293. * have it). MacOS looks like it can also be MacOSClassic.
  294. * This function will test for MacOS and hope it captures any
  295. * other permutations.
  296. */
  297. static void stripAppleBundle(char *path)
  298. {
  299. char *sub_str = "/contents/macos";
  300. char *found_ptr = NULL;
  301. char *tempbuf = NULL;
  302. int i;
  303. /* Calloc will place the \0 character in the proper place for us */
  304. /* !!! FIXME: Can we stack-allocate this? --ryan. */
  305. tempbuf = (char*)calloc( (strlen(path)+1), sizeof(char) );
  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. 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. free(tempbuf);
  349. return;
  350. }
  351. #endif /* defined __MACH__ && defined __APPLE__ */
  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 *) malloc(strlen(resolved_path) + 1);
  359. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  360. strcpy(retval, resolved_path);
  361. #if defined(__MACH__) && defined(__APPLE__)
  362. stripAppleBundle(retval);
  363. #endif /* defined __MACH__ && defined __APPLE__ */
  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. /* Just in case; this is a panic value. */
  374. #if ((!defined SIZEOF_INT) || (SIZEOF_INT <= 0))
  375. # define SIZEOF_INT 4
  376. #endif
  377. #if (SIZEOF_INT == 4)
  378. # define PHTREAD_TO_UI64(thr) ( (PHYSFS_uint64) ((PHYSFS_uint32) (thr)) )
  379. #elif (SIZEOF_INT == 2)
  380. # define PHTREAD_TO_UI64(thr) ( (PHYSFS_uint64) ((PHYSFS_uint16) (thr)) )
  381. #elif (SIZEOF_INT == 1)
  382. # define PHTREAD_TO_UI64(thr) ( (PHYSFS_uint64) ((PHYSFS_uint8) (thr)) )
  383. #else
  384. # define PHTREAD_TO_UI64(thr) ((PHYSFS_uint64) (thr))
  385. #endif
  386. PHYSFS_uint64 __PHYSFS_platformGetThreadID(void)
  387. {
  388. return(PHTREAD_TO_UI64(pthread_self()));
  389. } /* __PHYSFS_platformGetThreadID */
  390. void *__PHYSFS_platformCreateMutex(void)
  391. {
  392. int rc;
  393. pthread_mutex_t *m = (pthread_mutex_t *) malloc(sizeof (pthread_mutex_t));
  394. BAIL_IF_MACRO(m == NULL, ERR_OUT_OF_MEMORY, NULL);
  395. rc = pthread_mutex_init(m, NULL);
  396. if (rc != 0)
  397. {
  398. free(m);
  399. BAIL_MACRO(strerror(rc), NULL);
  400. } /* if */
  401. return((void *) m);
  402. } /* __PHYSFS_platformCreateMutex */
  403. void __PHYSFS_platformDestroyMutex(void *mutex)
  404. {
  405. pthread_mutex_destroy((pthread_mutex_t *) mutex);
  406. free(mutex);
  407. } /* __PHYSFS_platformDestroyMutex */
  408. int __PHYSFS_platformGrabMutex(void *mutex)
  409. {
  410. return(pthread_mutex_lock((pthread_mutex_t *) mutex) == 0);
  411. } /* __PHYSFS_platformGrabMutex */
  412. void __PHYSFS_platformReleaseMutex(void *mutex)
  413. {
  414. pthread_mutex_unlock((pthread_mutex_t *) mutex);
  415. } /* __PHYSFS_platformReleaseMutex */
  416. #endif /* !PHYSFS_NO_PTHREADS_SUPPORT */
  417. #endif /* !defined __BEOS__ && !defined WIN32 */
  418. /* end of unix.c ... */