unix.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. char **__PHYSFS_platformDetectAvailableCDs(void)
  63. {
  64. char **retval = (char **) malloc(sizeof (char *));
  65. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  66. *retval = NULL;
  67. return(retval);
  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. char **__PHYSFS_platformDetectAvailableCDs(void)
  132. {
  133. const char *devPrefix = "/dev/";
  134. int prefixLen = strlen(devPrefix);
  135. mach_port_t masterPort = 0;
  136. char **retval = (char **) malloc(sizeof (char *));
  137. int cd_count = 1; /* We count the NULL entry. */
  138. struct statfs *mntbufp;
  139. int i, mounts;
  140. retval[0] = NULL;
  141. if (IOMasterPort(MACH_PORT_NULL, &masterPort) != KERN_SUCCESS)
  142. return(retval);
  143. mounts = getmntinfo(&mntbufp, MNT_WAIT); /* NOT THREAD SAFE! */
  144. for (i = 0; i < mounts; i++)
  145. {
  146. char *dev = mntbufp[i].f_mntfromname;
  147. char *mnt = mntbufp[i].f_mntonname;
  148. if (strncmp(dev, devPrefix, prefixLen) != 0) /* a virtual device? */
  149. continue;
  150. dev += prefixLen;
  151. if (darwinIsMountedDisc(dev, masterPort))
  152. {
  153. char **tmp = realloc(retval, sizeof (char *) * (cd_count + 1));
  154. if (tmp)
  155. {
  156. retval = tmp;
  157. retval[cd_count - 1] = (char *) malloc(strlen(mnt) + 1);
  158. if (retval[cd_count - 1])
  159. {
  160. strcpy(retval[cd_count - 1], mnt);
  161. cd_count++;
  162. } /* if */
  163. } /* if */
  164. } /* if */
  165. } /* for */
  166. retval[cd_count - 1] = NULL;
  167. return(retval);
  168. } /* __PHYSFS_platformDetectAvailableCDs */
  169. #elif (defined PHYSFS_HAVE_SYS_UCRED_H)
  170. char **__PHYSFS_platformDetectAvailableCDs(void)
  171. {
  172. char **retval = (char **) malloc(sizeof (char *));
  173. int cd_count = 1; /* We count the NULL entry. */
  174. struct statfs *mntbufp = NULL;
  175. int mounts;
  176. int i;
  177. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  178. mounts = getmntinfo(&mntbufp, MNT_WAIT);
  179. for (i = 0; i < mounts; i++)
  180. {
  181. int add_it = 0;
  182. if (strcmp(mntbufp[i].f_fstypename, "iso9660") == 0)
  183. add_it = 1;
  184. else if (strcmp( mntbufp[i].f_fstypename, "cd9660") == 0)
  185. add_it = 1;
  186. /* add other mount types here */
  187. if (add_it)
  188. {
  189. char **tmp = realloc(retval, sizeof (char *) * (cd_count + 1));
  190. if (tmp)
  191. {
  192. retval = tmp;
  193. retval[cd_count - 1] = (char *)
  194. malloc(strlen(mntbufp[i].f_mntonname) + 1);
  195. if (retval[cd_count - 1])
  196. {
  197. strcpy(retval[cd_count - 1], mntbufp[i].f_mntonname);
  198. cd_count++;
  199. } /* if */
  200. } /* if */
  201. } /* if */
  202. } /* for */
  203. retval[cd_count - 1] = NULL;
  204. return(retval);
  205. } /* __PHYSFS_platformDetectAvailableCDs */
  206. #elif (defined PHYSFS_HAVE_MNTENT_H)
  207. char **__PHYSFS_platformDetectAvailableCDs(void)
  208. {
  209. char **retval = (char **) malloc(sizeof (char *));
  210. int cd_count = 1; /* We count the NULL entry. */
  211. FILE *mounts = NULL;
  212. struct mntent *ent = NULL;
  213. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  214. *retval = NULL;
  215. mounts = setmntent("/etc/mtab", "r");
  216. BAIL_IF_MACRO(mounts == NULL, ERR_IO_ERROR, retval);
  217. while ( (ent = getmntent(mounts)) != NULL )
  218. {
  219. int add_it = 0;
  220. if (strcmp(ent->mnt_type, "iso9660") == 0)
  221. add_it = 1;
  222. /* add other mount types here */
  223. if (add_it)
  224. {
  225. char **tmp = realloc(retval, sizeof (char *) * (cd_count + 1));
  226. if (tmp)
  227. {
  228. retval = tmp;
  229. retval[cd_count-1] = (char *) malloc(strlen(ent->mnt_dir) + 1);
  230. if (retval[cd_count - 1])
  231. {
  232. strcpy(retval[cd_count - 1], ent->mnt_dir);
  233. cd_count++;
  234. } /* if */
  235. } /* if */
  236. } /* if */
  237. } /* while */
  238. endmntent(mounts);
  239. retval[cd_count - 1] = NULL;
  240. return(retval);
  241. } /* __PHYSFS_platformDetectAvailableCDs */
  242. #endif
  243. /* this is in posix.c ... */
  244. extern char *__PHYSFS_platformCopyEnvironmentVariable(const char *varname);
  245. /*
  246. * See where program (bin) resides in the $PATH specified by (envr).
  247. * returns a copy of the first element in envr that contains it, or NULL
  248. * if it doesn't exist or there were other problems. PHYSFS_SetError() is
  249. * called if we have a problem.
  250. *
  251. * (envr) will be scribbled over, and you are expected to free() the
  252. * return value when you're done with it.
  253. */
  254. static char *findBinaryInPath(const char *bin, char *envr)
  255. {
  256. size_t alloc_size = 0;
  257. char *exe = NULL;
  258. char *start = envr;
  259. char *ptr;
  260. BAIL_IF_MACRO(bin == NULL, ERR_INVALID_ARGUMENT, NULL);
  261. BAIL_IF_MACRO(envr == NULL, ERR_INVALID_ARGUMENT, NULL);
  262. do
  263. {
  264. size_t size;
  265. ptr = strchr(start, ':'); /* find next $PATH separator. */
  266. if (ptr)
  267. *ptr = '\0';
  268. size = strlen(start) + strlen(bin) + 2;
  269. if (size > alloc_size)
  270. {
  271. char *x = (char *) realloc(exe, size);
  272. if (x == NULL)
  273. {
  274. if (exe != NULL)
  275. free(exe);
  276. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  277. } /* if */
  278. alloc_size = size;
  279. exe = x;
  280. } /* if */
  281. /* build full binary path... */
  282. strcpy(exe, start);
  283. if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
  284. strcat(exe, "/");
  285. strcat(exe, bin);
  286. if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
  287. {
  288. strcpy(exe, start); /* i'm lazy. piss off. */
  289. return(exe);
  290. } /* if */
  291. start = ptr + 1; /* start points to beginning of next element. */
  292. } while (ptr != NULL);
  293. if (exe != NULL)
  294. free(exe);
  295. return(NULL); /* doesn't exist in path. */
  296. } /* findBinaryInPath */
  297. char *__PHYSFS_platformCalcBaseDir(const char *argv0)
  298. {
  299. /* If there isn't a path on argv0, then look through the $PATH for it. */
  300. char *retval;
  301. char *envr;
  302. if (strchr(argv0, '/') != NULL) /* default behaviour can handle this. */
  303. return(NULL);
  304. envr = __PHYSFS_platformCopyEnvironmentVariable("PATH");
  305. BAIL_IF_MACRO(!envr, NULL, NULL);
  306. retval = findBinaryInPath(argv0, envr);
  307. free(envr);
  308. return(retval);
  309. } /* __PHYSFS_platformCalcBaseDir */
  310. /* Much like my college days, try to sleep for 10 milliseconds at a time... */
  311. void __PHYSFS_platformTimeslice(void)
  312. {
  313. usleep( 10 * 1000 ); /* don't care if it fails. */
  314. } /* __PHYSFS_platformTimeslice */
  315. #if PHYSFS_DARWIN
  316. /*
  317. * This function is only for OSX. The problem is that Apple's applications
  318. * can actually be directory structures with the actual executable nested
  319. * several levels down. PhysFS computes the base directory from the Unix
  320. * executable, but this may not be the correct directory. Apple tries to
  321. * hide everything from the user, so from Finder, the user never sees the
  322. * Unix executable, and the directory package (bundle) is considered the
  323. * "executable". This means that the correct base directory is at the
  324. * level where the directory structure starts.
  325. * A typical bundle seems to look like this:
  326. * MyApp.app/ <-- top level...this is what the user sees in Finder
  327. * Contents/
  328. * MacOS/
  329. * MyApp <-- the actual executable
  330. *
  331. * Since anything below the app folder is considered hidden, most
  332. * application files need to be at the top level if you intend to
  333. * write portable software. Thus if the application resides in:
  334. * /Applications/MyProgram
  335. * and the executable is the bundle MyApp.app,
  336. * PhysFS computes the following as the base directory:
  337. * /Applications/MyProgram/MyApp.app/Contents/MacOS/
  338. * We need to strip off the MyApp.app/Contents/MacOS/
  339. *
  340. * However, there are corner cases. OSX applications can be traditional
  341. * Unix executables without the bundle. Also, it is not entirely clear
  342. * to me what kinds of permutations bundle structures can have.
  343. *
  344. * For now, this is a temporary hack until a better solution
  345. * can be made. This function will try to find a "/Contents/MacOS"
  346. * inside the path. If it succeeds, then the path will be truncated
  347. * to correct the directory. If it is not found, the path will be
  348. * left alone and will presume it is a traditional Unix execuatable.
  349. * Most programs also include the .app extention in the top level
  350. * folder, but it doesn't seem to be a requirement (Acrobat doesn't
  351. * have it). MacOS looks like it can also be MacOSClassic.
  352. * This function will test for MacOS and hope it captures any
  353. * other permutations.
  354. */
  355. static void stripAppleBundle(char *path)
  356. {
  357. char *sub_str = "/contents/macos";
  358. char *found_ptr = NULL;
  359. char *tempbuf = NULL;
  360. int i;
  361. /* Calloc will place the \0 character in the proper place for us */
  362. /* !!! FIXME: Can we stack-allocate this? --ryan. */
  363. tempbuf = (char*)calloc( (strlen(path)+1), sizeof(char) );
  364. /* Unlike other Unix filesystems, HFS is case insensitive
  365. * It wouldn be nice to use strcasestr, but it doesn't seem
  366. * to be available in the OSX gcc library right now.
  367. * So we should make a lower case copy of the path to
  368. * compare against
  369. */
  370. for(i=0; i<strlen(path); i++)
  371. {
  372. /* convert to lower case */
  373. tempbuf[i] = tolower(path[i]);
  374. }
  375. /* See if we can find "/contents/macos" in the path */
  376. found_ptr = strstr(tempbuf, sub_str);
  377. if(NULL == found_ptr)
  378. {
  379. /* It doesn't look like a bundle so we can keep the
  380. * original path. Just return */
  381. free(tempbuf);
  382. return;
  383. }
  384. /* We have a bundle, so let's backstep character by character
  385. * to erase the extra parts of the path. Quit when we hit
  386. * the preceding '/' character.
  387. */
  388. for(i=strlen(path)-strlen(found_ptr)-1; i>=0; i--)
  389. {
  390. if('/' == path[i])
  391. {
  392. break;
  393. }
  394. }
  395. /* Safety check */
  396. if(i<1)
  397. {
  398. /* This probably shouldn't happen. */
  399. path[0] = '\0';
  400. }
  401. else
  402. {
  403. /* Back up one more to remove trailing '/' and set the '\0' */
  404. path[i] = '\0';
  405. }
  406. free(tempbuf);
  407. return;
  408. }
  409. #endif /* defined __MACH__ && defined __APPLE__ */
  410. char *__PHYSFS_platformRealPath(const char *path)
  411. {
  412. char resolved_path[MAXPATHLEN];
  413. char *retval = NULL;
  414. errno = 0;
  415. BAIL_IF_MACRO(!realpath(path, resolved_path), strerror(errno), NULL);
  416. retval = (char *) malloc(strlen(resolved_path) + 1);
  417. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  418. strcpy(retval, resolved_path);
  419. #if defined(__MACH__) && defined(__APPLE__)
  420. stripAppleBundle(retval);
  421. #endif /* defined __MACH__ && defined __APPLE__ */
  422. return(retval);
  423. } /* __PHYSFS_platformRealPath */
  424. #if (defined PHYSFS_NO_PTHREADS_SUPPORT)
  425. PHYSFS_uint64 __PHYSFS_platformGetThreadID(void) { return(0x0001); }
  426. void *__PHYSFS_platformCreateMutex(void) { return((void *) 0x0001); }
  427. void __PHYSFS_platformDestroyMutex(void *mutex) {}
  428. int __PHYSFS_platformGrabMutex(void *mutex) { return(1); }
  429. void __PHYSFS_platformReleaseMutex(void *mutex) {}
  430. #else
  431. /* Just in case; this is a panic value. */
  432. #if ((!defined SIZEOF_INT) || (SIZEOF_INT <= 0))
  433. # define SIZEOF_INT 4
  434. #endif
  435. #if (SIZEOF_INT == 4)
  436. # define PHTREAD_TO_UI64(thr) ( (PHYSFS_uint64) ((PHYSFS_uint32) (thr)) )
  437. #elif (SIZEOF_INT == 2)
  438. # define PHTREAD_TO_UI64(thr) ( (PHYSFS_uint64) ((PHYSFS_uint16) (thr)) )
  439. #elif (SIZEOF_INT == 1)
  440. # define PHTREAD_TO_UI64(thr) ( (PHYSFS_uint64) ((PHYSFS_uint8) (thr)) )
  441. #else
  442. # define PHTREAD_TO_UI64(thr) ((PHYSFS_uint64) (thr))
  443. #endif
  444. PHYSFS_uint64 __PHYSFS_platformGetThreadID(void)
  445. {
  446. return(PHTREAD_TO_UI64(pthread_self()));
  447. } /* __PHYSFS_platformGetThreadID */
  448. void *__PHYSFS_platformCreateMutex(void)
  449. {
  450. int rc;
  451. pthread_mutex_t *m = (pthread_mutex_t *) malloc(sizeof (pthread_mutex_t));
  452. BAIL_IF_MACRO(m == NULL, ERR_OUT_OF_MEMORY, NULL);
  453. rc = pthread_mutex_init(m, NULL);
  454. if (rc != 0)
  455. {
  456. free(m);
  457. BAIL_MACRO(strerror(rc), NULL);
  458. } /* if */
  459. return((void *) m);
  460. } /* __PHYSFS_platformCreateMutex */
  461. void __PHYSFS_platformDestroyMutex(void *mutex)
  462. {
  463. pthread_mutex_destroy((pthread_mutex_t *) mutex);
  464. free(mutex);
  465. } /* __PHYSFS_platformDestroyMutex */
  466. int __PHYSFS_platformGrabMutex(void *mutex)
  467. {
  468. return(pthread_mutex_lock((pthread_mutex_t *) mutex) == 0);
  469. } /* __PHYSFS_platformGrabMutex */
  470. void __PHYSFS_platformReleaseMutex(void *mutex)
  471. {
  472. pthread_mutex_unlock((pthread_mutex_t *) mutex);
  473. } /* __PHYSFS_platformReleaseMutex */
  474. #endif /* !PHYSFS_NO_PTHREADS_SUPPORT */
  475. #endif /* !defined __BEOS__ && !defined WIN32 */
  476. /* end of unix.c ... */