utilunix.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. /* Various utilities - Unix variants
  2. Copyright (C) 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003,
  3. 2004, 2005, 2007 Free Software Foundation, Inc.
  4. Written 1994, 1995, 1996 by:
  5. Miguel de Icaza, Janne Kukonlehto, Dugan Porter,
  6. Jakub Jelinek, Mauricio Plaza.
  7. The mc_realpath routine is mostly from uClibc package, written
  8. by Rick Sladkey <jrs@world.std.com>
  9. This program is free software; you can redistribute it and/or modify
  10. it under the terms of the GNU General Public License as published by
  11. the Free Software Foundation; either version 2 of the License, or
  12. (at your option) any later version.
  13. This program is distributed in the hope that it will be useful,
  14. but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. GNU General Public License for more details.
  17. You should have received a copy of the GNU General Public License
  18. along with this program; if not, write to the Free Software
  19. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  20. /** \file utilunix.c
  21. * \brief Source: various utilities - Unix variant
  22. */
  23. #include <config.h>
  24. #include <ctype.h>
  25. #include <errno.h>
  26. #include <limits.h>
  27. #include <signal.h>
  28. #include <stdarg.h>
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <fcntl.h>
  33. #include <sys/param.h>
  34. #include <sys/types.h>
  35. #include <sys/stat.h>
  36. #include <sys/wait.h>
  37. #ifdef HAVE_SYS_IOCTL_H
  38. # include <sys/ioctl.h>
  39. #endif
  40. #include <unistd.h>
  41. #include <pwd.h>
  42. #include <grp.h>
  43. #include "lib/global.h"
  44. #include "src/execute.h"
  45. #include "src/wtools.h" /* message() */
  46. struct sigaction startup_handler;
  47. #define UID_CACHE_SIZE 200
  48. #define GID_CACHE_SIZE 30
  49. typedef struct
  50. {
  51. int index;
  52. char *string;
  53. } int_cache;
  54. static int_cache uid_cache[UID_CACHE_SIZE];
  55. static int_cache gid_cache[GID_CACHE_SIZE];
  56. static char *
  57. i_cache_match (int id, int_cache * cache, int size)
  58. {
  59. int i;
  60. for (i = 0; i < size; i++)
  61. if (cache[i].index == id)
  62. return cache[i].string;
  63. return 0;
  64. }
  65. static void
  66. i_cache_add (int id, int_cache * cache, int size, char *text, int *last)
  67. {
  68. g_free (cache[*last].string);
  69. cache[*last].string = g_strdup (text);
  70. cache[*last].index = id;
  71. *last = ((*last) + 1) % size;
  72. }
  73. char *
  74. get_owner (int uid)
  75. {
  76. struct passwd *pwd;
  77. static char ibuf[10];
  78. char *name;
  79. static int uid_last;
  80. name = i_cache_match (uid, uid_cache, UID_CACHE_SIZE);
  81. if (name != NULL)
  82. return name;
  83. pwd = getpwuid (uid);
  84. if (pwd != NULL)
  85. {
  86. i_cache_add (uid, uid_cache, UID_CACHE_SIZE, pwd->pw_name, &uid_last);
  87. return pwd->pw_name;
  88. }
  89. else
  90. {
  91. g_snprintf (ibuf, sizeof (ibuf), "%d", uid);
  92. return ibuf;
  93. }
  94. }
  95. char *
  96. get_group (int gid)
  97. {
  98. struct group *grp;
  99. static char gbuf[10];
  100. char *name;
  101. static int gid_last;
  102. name = i_cache_match (gid, gid_cache, GID_CACHE_SIZE);
  103. if (name != NULL)
  104. return name;
  105. grp = getgrgid (gid);
  106. if (grp != NULL)
  107. {
  108. i_cache_add (gid, gid_cache, GID_CACHE_SIZE, grp->gr_name, &gid_last);
  109. return grp->gr_name;
  110. }
  111. else
  112. {
  113. g_snprintf (gbuf, sizeof (gbuf), "%d", gid);
  114. return gbuf;
  115. }
  116. }
  117. /* Since ncurses uses a handler that automatically refreshes the */
  118. /* screen after a SIGCONT, and we don't want this behavior when */
  119. /* spawning a child, we save the original handler here */
  120. void
  121. save_stop_handler (void)
  122. {
  123. sigaction (SIGTSTP, NULL, &startup_handler);
  124. }
  125. int
  126. my_system (int flags, const char *shell, const char *command)
  127. {
  128. struct sigaction ignore, save_intr, save_quit, save_stop;
  129. pid_t pid;
  130. int status = 0;
  131. ignore.sa_handler = SIG_IGN;
  132. sigemptyset (&ignore.sa_mask);
  133. ignore.sa_flags = 0;
  134. sigaction (SIGINT, &ignore, &save_intr);
  135. sigaction (SIGQUIT, &ignore, &save_quit);
  136. /* Restore the original SIGTSTP handler, we don't want ncurses' */
  137. /* handler messing the screen after the SIGCONT */
  138. sigaction (SIGTSTP, &startup_handler, &save_stop);
  139. pid = fork ();
  140. if (pid < 0)
  141. {
  142. fprintf (stderr, "\n\nfork () = -1\n");
  143. return -1;
  144. }
  145. if (pid == 0)
  146. {
  147. signal (SIGINT, SIG_DFL);
  148. signal (SIGQUIT, SIG_DFL);
  149. signal (SIGTSTP, SIG_DFL);
  150. signal (SIGCHLD, SIG_DFL);
  151. if (flags & EXECUTE_AS_SHELL)
  152. execl (shell, shell, "-c", command, (char *) NULL);
  153. else
  154. {
  155. gchar **shell_tokens;
  156. const gchar *only_cmd;
  157. shell_tokens = g_strsplit (shell, " ", 2);
  158. if (shell_tokens == NULL)
  159. only_cmd = shell;
  160. else
  161. only_cmd = (*shell_tokens != NULL) ? *shell_tokens : shell;
  162. execlp (only_cmd, shell, command, (char *) NULL);
  163. /*
  164. execlp will replace current process,
  165. therefore no sence in call of g_strfreev().
  166. But this keeped for estetic reason :)
  167. */
  168. g_strfreev (shell_tokens);
  169. }
  170. _exit (127); /* Exec error */
  171. }
  172. else
  173. {
  174. while (waitpid (pid, &status, 0) < 0)
  175. if (errno != EINTR)
  176. {
  177. status = -1;
  178. break;
  179. }
  180. }
  181. sigaction (SIGINT, &save_intr, NULL);
  182. sigaction (SIGQUIT, &save_quit, NULL);
  183. sigaction (SIGTSTP, &save_stop, NULL);
  184. return WEXITSTATUS (status);
  185. }
  186. /*
  187. * Perform tilde expansion if possible.
  188. * Always return a newly allocated string, even if it's unchanged.
  189. */
  190. char *
  191. tilde_expand (const char *directory)
  192. {
  193. struct passwd *passwd;
  194. const char *p, *q;
  195. char *name;
  196. if (*directory != '~')
  197. return g_strdup (directory);
  198. p = directory + 1;
  199. /* d = "~" or d = "~/" */
  200. if (!(*p) || (*p == PATH_SEP))
  201. {
  202. passwd = getpwuid (geteuid ());
  203. q = (*p == PATH_SEP) ? p + 1 : "";
  204. }
  205. else
  206. {
  207. q = strchr (p, PATH_SEP);
  208. if (!q)
  209. {
  210. passwd = getpwnam (p);
  211. }
  212. else
  213. {
  214. name = g_strndup (p, q - p);
  215. passwd = getpwnam (name);
  216. q++;
  217. g_free (name);
  218. }
  219. }
  220. /* If we can't figure the user name, leave tilde unexpanded */
  221. if (!passwd)
  222. return g_strdup (directory);
  223. return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
  224. }
  225. /*
  226. * Return the directory where mc should keep its temporary files.
  227. * This directory is (in Bourne shell terms) "${TMPDIR=/tmp}/mc-$USER"
  228. * When called the first time, the directory is created if needed.
  229. * The first call should be done early, since we are using fprintf()
  230. * and not message() to report possible problems.
  231. */
  232. const char *
  233. mc_tmpdir (void)
  234. {
  235. static char buffer[64];
  236. static const char *tmpdir;
  237. const char *sys_tmp;
  238. struct passwd *pwd;
  239. struct stat st;
  240. const char *error = NULL;
  241. /* Check if already correctly initialized */
  242. if (tmpdir && lstat (tmpdir, &st) == 0 && S_ISDIR (st.st_mode) &&
  243. st.st_uid == getuid () && (st.st_mode & 0777) == 0700)
  244. return tmpdir;
  245. sys_tmp = getenv ("TMPDIR");
  246. if (!sys_tmp || sys_tmp[0] != '/')
  247. {
  248. sys_tmp = TMPDIR_DEFAULT;
  249. }
  250. pwd = getpwuid (getuid ());
  251. if (pwd)
  252. g_snprintf (buffer, sizeof (buffer), "%s/mc-%s", sys_tmp, pwd->pw_name);
  253. else
  254. g_snprintf (buffer, sizeof (buffer), "%s/mc-%lu", sys_tmp, (unsigned long) getuid ());
  255. canonicalize_pathname (buffer);
  256. if (lstat (buffer, &st) == 0)
  257. {
  258. /* Sanity check for existing directory */
  259. if (!S_ISDIR (st.st_mode))
  260. error = _("%s is not a directory\n");
  261. else if (st.st_uid != getuid ())
  262. error = _("Directory %s is not owned by you\n");
  263. else if (((st.st_mode & 0777) != 0700) && (chmod (buffer, 0700) != 0))
  264. error = _("Cannot set correct permissions for directory %s\n");
  265. }
  266. else
  267. {
  268. /* Need to create directory */
  269. if (mkdir (buffer, S_IRWXU) != 0)
  270. {
  271. fprintf (stderr,
  272. _("Cannot create temporary directory %s: %s\n"),
  273. buffer, unix_error_string (errno));
  274. error = "";
  275. }
  276. }
  277. if (error != NULL)
  278. {
  279. int test_fd;
  280. char *test_fn, *fallback_prefix;
  281. int fallback_ok = 0;
  282. if (*error)
  283. fprintf (stderr, error, buffer);
  284. /* Test if sys_tmp is suitable for temporary files */
  285. fallback_prefix = g_strdup_printf ("%s/mctest", sys_tmp);
  286. test_fd = mc_mkstemps (&test_fn, fallback_prefix, NULL);
  287. g_free (fallback_prefix);
  288. if (test_fd != -1)
  289. {
  290. close (test_fd);
  291. test_fd = open (test_fn, O_RDONLY);
  292. if (test_fd != -1)
  293. {
  294. close (test_fd);
  295. unlink (test_fn);
  296. fallback_ok = 1;
  297. }
  298. }
  299. if (fallback_ok)
  300. {
  301. fprintf (stderr, _("Temporary files will be created in %s\n"), sys_tmp);
  302. g_snprintf (buffer, sizeof (buffer), "%s", sys_tmp);
  303. error = NULL;
  304. }
  305. else
  306. {
  307. fprintf (stderr, _("Temporary files will not be created\n"));
  308. g_snprintf (buffer, sizeof (buffer), "%s", "/dev/null/");
  309. }
  310. fprintf (stderr, "%s\n", _("Press any key to continue..."));
  311. getc (stdin);
  312. }
  313. tmpdir = buffer;
  314. if (!error)
  315. g_setenv ("MC_TMPDIR", tmpdir, TRUE);
  316. return tmpdir;
  317. }
  318. /* Pipes are guaranteed to be able to hold at least 4096 bytes */
  319. /* More than that would be unportable */
  320. #define MAX_PIPE_SIZE 4096
  321. static int error_pipe[2]; /* File descriptors of error pipe */
  322. static int old_error; /* File descriptor of old standard error */
  323. /* Creates a pipe to hold standard error for a later analysis. */
  324. /* The pipe can hold 4096 bytes. Make sure no more is written */
  325. /* or a deadlock might occur. */
  326. void
  327. open_error_pipe (void)
  328. {
  329. if (pipe (error_pipe) < 0)
  330. {
  331. message (D_NORMAL, _("Warning"), _("Pipe failed"));
  332. }
  333. old_error = dup (2);
  334. if (old_error < 0 || close (2) || dup (error_pipe[1]) != 2)
  335. {
  336. message (D_NORMAL, _("Warning"), _("Dup failed"));
  337. close (error_pipe[0]);
  338. error_pipe[0] = -1;
  339. }
  340. else
  341. {
  342. /*
  343. * Settng stderr in nonblocking mode as we close it earlier, than
  344. * program stops. We try to read some error at program startup,
  345. * but we should not block on it.
  346. *
  347. * TODO: make piped stdin/stderr poll()/select()able to get rid
  348. * of following hack.
  349. */
  350. int fd_flags;
  351. fd_flags = fcntl (error_pipe[0], F_GETFL, NULL);
  352. if (fd_flags != -1)
  353. {
  354. fd_flags |= O_NONBLOCK;
  355. if (fcntl (error_pipe[0], F_SETFL, fd_flags) == -1)
  356. {
  357. /* TODO: handle it somehow */
  358. }
  359. }
  360. }
  361. /* we never write there */
  362. close (error_pipe[1]);
  363. error_pipe[1] = -1;
  364. }
  365. /*
  366. * Returns true if an error was displayed
  367. * error: -1 - ignore errors, 0 - display warning, 1 - display error
  368. * text is prepended to the error message from the pipe
  369. */
  370. int
  371. close_error_pipe (int error, const char *text)
  372. {
  373. const char *title;
  374. char msg[MAX_PIPE_SIZE];
  375. int len = 0;
  376. /* already closed */
  377. if (error_pipe[0] == -1)
  378. return 0;
  379. if (error)
  380. title = MSG_ERROR;
  381. else
  382. title = _("Warning");
  383. if (old_error >= 0)
  384. {
  385. if (dup2 (old_error, 2) == -1)
  386. {
  387. message (error, MSG_ERROR, _("Error dup'ing old error pipe"));
  388. return 1;
  389. }
  390. close (old_error);
  391. len = read (error_pipe[0], msg, MAX_PIPE_SIZE - 1);
  392. if (len >= 0)
  393. msg[len] = 0;
  394. close (error_pipe[0]);
  395. error_pipe[0] = -1;
  396. }
  397. if (error < 0)
  398. return 0; /* Just ignore error message */
  399. if (text == NULL)
  400. {
  401. if (len <= 0)
  402. return 0; /* Nothing to show */
  403. /* Show message from pipe */
  404. message (error, title, "%s", msg);
  405. }
  406. else
  407. {
  408. /* Show given text and possible message from pipe */
  409. message (error, title, "%s\n%s", text, msg);
  410. }
  411. return 1;
  412. }
  413. /*
  414. * Canonicalize path, and return a new path. Do everything in place.
  415. * The new path differs from path in:
  416. * Multiple `/'s are collapsed to a single `/'.
  417. * Leading `./'s and trailing `/.'s are removed.
  418. * Trailing `/'s are removed.
  419. * Non-leading `../'s and trailing `..'s are handled by removing
  420. * portions of the path.
  421. * Well formed UNC paths are modified only in the local part.
  422. */
  423. void
  424. custom_canonicalize_pathname (char *path, CANON_PATH_FLAGS flags)
  425. {
  426. char *p, *s;
  427. int len;
  428. char *lpath = path; /* path without leading UNC part */
  429. /* Detect and preserve UNC paths: //server/... */
  430. if ((flags & CANON_PATH_GUARDUNC) && path[0] == PATH_SEP && path[1] == PATH_SEP)
  431. {
  432. p = path + 2;
  433. while (p[0] && p[0] != '/')
  434. p++;
  435. if (p[0] == '/' && p > path + 2)
  436. lpath = p;
  437. }
  438. if (!lpath[0] || !lpath[1])
  439. return;
  440. if (flags & CANON_PATH_JOINSLASHES)
  441. {
  442. /* Collapse multiple slashes */
  443. p = lpath;
  444. while (*p)
  445. {
  446. if (p[0] == PATH_SEP && p[1] == PATH_SEP)
  447. {
  448. s = p + 1;
  449. while (*(++s) == PATH_SEP);
  450. str_move (p + 1, s);
  451. }
  452. p++;
  453. }
  454. }
  455. if (flags & CANON_PATH_JOINSLASHES)
  456. {
  457. /* Collapse "/./" -> "/" */
  458. p = lpath;
  459. while (*p)
  460. {
  461. if (p[0] == PATH_SEP && p[1] == '.' && p[2] == PATH_SEP)
  462. str_move (p, p + 2);
  463. else
  464. p++;
  465. }
  466. }
  467. if (flags & CANON_PATH_REMSLASHDOTS)
  468. {
  469. /* Remove trailing slashes */
  470. p = lpath + strlen (lpath) - 1;
  471. while (p > lpath && *p == PATH_SEP)
  472. *p-- = 0;
  473. /* Remove leading "./" */
  474. if (lpath[0] == '.' && lpath[1] == PATH_SEP)
  475. {
  476. if (lpath[2] == 0)
  477. {
  478. lpath[1] = 0;
  479. return;
  480. }
  481. else
  482. {
  483. str_move (lpath, lpath + 2);
  484. }
  485. }
  486. /* Remove trailing "/" or "/." */
  487. len = strlen (lpath);
  488. if (len < 2)
  489. return;
  490. if (lpath[len - 1] == PATH_SEP)
  491. {
  492. lpath[len - 1] = 0;
  493. }
  494. else
  495. {
  496. if (lpath[len - 1] == '.' && lpath[len - 2] == PATH_SEP)
  497. {
  498. if (len == 2)
  499. {
  500. lpath[1] = 0;
  501. return;
  502. }
  503. else
  504. {
  505. lpath[len - 2] = 0;
  506. }
  507. }
  508. }
  509. }
  510. if (flags & CANON_PATH_REMDOUBLEDOTS)
  511. {
  512. /* Collapse "/.." with the previous part of path */
  513. p = lpath;
  514. while (p[0] && p[1] && p[2])
  515. {
  516. if ((p[0] != PATH_SEP || p[1] != '.' || p[2] != '.') || (p[3] != PATH_SEP && p[3] != 0))
  517. {
  518. p++;
  519. continue;
  520. }
  521. /* search for the previous token */
  522. s = p - 1;
  523. while (s >= lpath && *s != PATH_SEP)
  524. s--;
  525. s++;
  526. /* If the previous token is "..", we cannot collapse it */
  527. if (s[0] == '.' && s[1] == '.' && s + 2 == p)
  528. {
  529. p += 3;
  530. continue;
  531. }
  532. if (p[3] != 0)
  533. {
  534. if (s == lpath && *s == PATH_SEP)
  535. {
  536. /* "/../foo" -> "/foo" */
  537. str_move (s + 1, p + 4);
  538. }
  539. else
  540. {
  541. /* "token/../foo" -> "foo" */
  542. str_move (s, p + 4);
  543. }
  544. p = (s > lpath) ? s - 1 : s;
  545. continue;
  546. }
  547. /* trailing ".." */
  548. if (s == lpath)
  549. {
  550. /* "token/.." -> "." */
  551. if (lpath[0] != PATH_SEP)
  552. {
  553. lpath[0] = '.';
  554. }
  555. lpath[1] = 0;
  556. }
  557. else
  558. {
  559. /* "foo/token/.." -> "foo" */
  560. if (s == lpath + 1)
  561. s[0] = 0;
  562. else
  563. s[-1] = 0;
  564. break;
  565. }
  566. break;
  567. }
  568. }
  569. }
  570. void
  571. canonicalize_pathname (char *path)
  572. {
  573. custom_canonicalize_pathname (path, CANON_PATH_ALL);
  574. }
  575. #ifdef HAVE_GET_PROCESS_STATS
  576. # include <sys/procstats.h>
  577. int
  578. gettimeofday (struct timeval *tp, void *tzp)
  579. {
  580. return get_process_stats (tp, PS_SELF, 0, 0);
  581. }
  582. #endif /* HAVE_GET_PROCESS_STATS */
  583. #ifndef HAVE_REALPATH
  584. char *
  585. mc_realpath (const char *path, char *resolved_path)
  586. {
  587. char copy_path[PATH_MAX];
  588. char link_path[PATH_MAX];
  589. char got_path[PATH_MAX];
  590. char *new_path = got_path;
  591. char *max_path;
  592. int readlinks = 0;
  593. int n;
  594. /* Make a copy of the source path since we may need to modify it. */
  595. if (strlen (path) >= PATH_MAX - 2)
  596. {
  597. errno = ENAMETOOLONG;
  598. return NULL;
  599. }
  600. strcpy (copy_path, path);
  601. path = copy_path;
  602. max_path = copy_path + PATH_MAX - 2;
  603. /* If it's a relative pathname use getwd for starters. */
  604. if (*path != '/')
  605. {
  606. new_path = g_get_current_dir ();
  607. if (new_path == NULL)
  608. {
  609. strcpy (got_path, "");
  610. }
  611. else
  612. {
  613. g_snprintf (got_path, PATH_MAX, "%s", new_path);
  614. g_free (new_path);
  615. new_path = got_path;
  616. }
  617. new_path += strlen (got_path);
  618. if (new_path[-1] != '/')
  619. *new_path++ = '/';
  620. }
  621. else
  622. {
  623. *new_path++ = '/';
  624. path++;
  625. }
  626. /* Expand each slash-separated pathname component. */
  627. while (*path != '\0')
  628. {
  629. /* Ignore stray "/". */
  630. if (*path == '/')
  631. {
  632. path++;
  633. continue;
  634. }
  635. if (*path == '.')
  636. {
  637. /* Ignore ".". */
  638. if (path[1] == '\0' || path[1] == '/')
  639. {
  640. path++;
  641. continue;
  642. }
  643. if (path[1] == '.')
  644. {
  645. if (path[2] == '\0' || path[2] == '/')
  646. {
  647. path += 2;
  648. /* Ignore ".." at root. */
  649. if (new_path == got_path + 1)
  650. continue;
  651. /* Handle ".." by backing up. */
  652. while ((--new_path)[-1] != '/');
  653. continue;
  654. }
  655. }
  656. }
  657. /* Safely copy the next pathname component. */
  658. while (*path != '\0' && *path != '/')
  659. {
  660. if (path > max_path)
  661. {
  662. errno = ENAMETOOLONG;
  663. return NULL;
  664. }
  665. *new_path++ = *path++;
  666. }
  667. #ifdef S_IFLNK
  668. /* Protect against infinite loops. */
  669. if (readlinks++ > MAXSYMLINKS)
  670. {
  671. errno = ELOOP;
  672. return NULL;
  673. }
  674. /* See if latest pathname component is a symlink. */
  675. *new_path = '\0';
  676. n = readlink (got_path, link_path, PATH_MAX - 1);
  677. if (n < 0)
  678. {
  679. /* EINVAL means the file exists but isn't a symlink. */
  680. if (errno != EINVAL)
  681. {
  682. /* Make sure it's null terminated. */
  683. *new_path = '\0';
  684. strcpy (resolved_path, got_path);
  685. return NULL;
  686. }
  687. }
  688. else
  689. {
  690. /* Note: readlink doesn't add the null byte. */
  691. link_path[n] = '\0';
  692. if (*link_path == '/')
  693. /* Start over for an absolute symlink. */
  694. new_path = got_path;
  695. else
  696. /* Otherwise back up over this component. */
  697. while (*(--new_path) != '/');
  698. /* Safe sex check. */
  699. if (strlen (path) + n >= PATH_MAX - 2)
  700. {
  701. errno = ENAMETOOLONG;
  702. return NULL;
  703. }
  704. /* Insert symlink contents into path. */
  705. strcat (link_path, path);
  706. strcpy (copy_path, link_path);
  707. path = copy_path;
  708. }
  709. #endif /* S_IFLNK */
  710. *new_path++ = '/';
  711. }
  712. /* Delete trailing slash but don't whomp a lone slash. */
  713. if (new_path != got_path + 1 && new_path[-1] == '/')
  714. new_path--;
  715. /* Make sure it's null terminated. */
  716. *new_path = '\0';
  717. strcpy (resolved_path, got_path);
  718. return resolved_path;
  719. }
  720. #endif /* HAVE_REALPATH */
  721. /* Return the index of the permissions triplet */
  722. int
  723. get_user_permissions (struct stat *st)
  724. {
  725. static gboolean initialized = FALSE;
  726. static gid_t *groups;
  727. static int ngroups;
  728. static uid_t uid;
  729. int i;
  730. if (!initialized)
  731. {
  732. uid = geteuid ();
  733. ngroups = getgroups (0, NULL);
  734. if (ngroups == -1)
  735. ngroups = 0; /* ignore errors */
  736. /* allocate space for one element in addition to what
  737. * will be filled by getgroups(). */
  738. groups = g_new (gid_t, ngroups + 1);
  739. if (ngroups != 0)
  740. {
  741. ngroups = getgroups (ngroups, groups);
  742. if (ngroups == -1)
  743. ngroups = 0; /* ignore errors */
  744. }
  745. /* getgroups() may or may not return the effective group ID,
  746. * so we always include it at the end of the list. */
  747. groups[ngroups++] = getegid ();
  748. initialized = TRUE;
  749. }
  750. if (st->st_uid == uid || uid == 0)
  751. return 0;
  752. for (i = 0; i < ngroups; i++)
  753. {
  754. if (st->st_gid == groups[i])
  755. return 1;
  756. }
  757. return 2;
  758. }