utilunix.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  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. status = -1;
  144. }
  145. else 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 (TRUE)
  175. {
  176. if (waitpid (pid, &status, 0) > 0)
  177. {
  178. status = WEXITSTATUS(status);
  179. break;
  180. }
  181. if (errno != EINTR)
  182. {
  183. status = -1;
  184. break;
  185. }
  186. }
  187. }
  188. sigaction (SIGINT, &save_intr, NULL);
  189. sigaction (SIGQUIT, &save_quit, NULL);
  190. sigaction (SIGTSTP, &save_stop, NULL);
  191. return status;
  192. }
  193. /*
  194. * Perform tilde expansion if possible.
  195. * Always return a newly allocated string, even if it's unchanged.
  196. */
  197. char *
  198. tilde_expand (const char *directory)
  199. {
  200. struct passwd *passwd;
  201. const char *p, *q;
  202. char *name;
  203. if (*directory != '~')
  204. return g_strdup (directory);
  205. p = directory + 1;
  206. /* d = "~" or d = "~/" */
  207. if (!(*p) || (*p == PATH_SEP))
  208. {
  209. passwd = getpwuid (geteuid ());
  210. q = (*p == PATH_SEP) ? p + 1 : "";
  211. }
  212. else
  213. {
  214. q = strchr (p, PATH_SEP);
  215. if (!q)
  216. {
  217. passwd = getpwnam (p);
  218. }
  219. else
  220. {
  221. name = g_strndup (p, q - p);
  222. passwd = getpwnam (name);
  223. q++;
  224. g_free (name);
  225. }
  226. }
  227. /* If we can't figure the user name, leave tilde unexpanded */
  228. if (!passwd)
  229. return g_strdup (directory);
  230. return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
  231. }
  232. /*
  233. * Return the directory where mc should keep its temporary files.
  234. * This directory is (in Bourne shell terms) "${TMPDIR=/tmp}/mc-$USER"
  235. * When called the first time, the directory is created if needed.
  236. * The first call should be done early, since we are using fprintf()
  237. * and not message() to report possible problems.
  238. */
  239. const char *
  240. mc_tmpdir (void)
  241. {
  242. static char buffer[64];
  243. static const char *tmpdir;
  244. const char *sys_tmp;
  245. struct passwd *pwd;
  246. struct stat st;
  247. const char *error = NULL;
  248. /* Check if already correctly initialized */
  249. if (tmpdir && lstat (tmpdir, &st) == 0 && S_ISDIR (st.st_mode) &&
  250. st.st_uid == getuid () && (st.st_mode & 0777) == 0700)
  251. return tmpdir;
  252. sys_tmp = getenv ("TMPDIR");
  253. if (!sys_tmp || sys_tmp[0] != '/')
  254. {
  255. sys_tmp = TMPDIR_DEFAULT;
  256. }
  257. pwd = getpwuid (getuid ());
  258. if (pwd)
  259. g_snprintf (buffer, sizeof (buffer), "%s/mc-%s", sys_tmp, pwd->pw_name);
  260. else
  261. g_snprintf (buffer, sizeof (buffer), "%s/mc-%lu", sys_tmp, (unsigned long) getuid ());
  262. canonicalize_pathname (buffer);
  263. if (lstat (buffer, &st) == 0)
  264. {
  265. /* Sanity check for existing directory */
  266. if (!S_ISDIR (st.st_mode))
  267. error = _("%s is not a directory\n");
  268. else if (st.st_uid != getuid ())
  269. error = _("Directory %s is not owned by you\n");
  270. else if (((st.st_mode & 0777) != 0700) && (chmod (buffer, 0700) != 0))
  271. error = _("Cannot set correct permissions for directory %s\n");
  272. }
  273. else
  274. {
  275. /* Need to create directory */
  276. if (mkdir (buffer, S_IRWXU) != 0)
  277. {
  278. fprintf (stderr,
  279. _("Cannot create temporary directory %s: %s\n"),
  280. buffer, unix_error_string (errno));
  281. error = "";
  282. }
  283. }
  284. if (error != NULL)
  285. {
  286. int test_fd;
  287. char *test_fn, *fallback_prefix;
  288. int fallback_ok = 0;
  289. if (*error)
  290. fprintf (stderr, error, buffer);
  291. /* Test if sys_tmp is suitable for temporary files */
  292. fallback_prefix = g_strdup_printf ("%s/mctest", sys_tmp);
  293. test_fd = mc_mkstemps (&test_fn, fallback_prefix, NULL);
  294. g_free (fallback_prefix);
  295. if (test_fd != -1)
  296. {
  297. close (test_fd);
  298. test_fd = open (test_fn, O_RDONLY);
  299. if (test_fd != -1)
  300. {
  301. close (test_fd);
  302. unlink (test_fn);
  303. fallback_ok = 1;
  304. }
  305. }
  306. if (fallback_ok)
  307. {
  308. fprintf (stderr, _("Temporary files will be created in %s\n"), sys_tmp);
  309. g_snprintf (buffer, sizeof (buffer), "%s", sys_tmp);
  310. error = NULL;
  311. }
  312. else
  313. {
  314. fprintf (stderr, _("Temporary files will not be created\n"));
  315. g_snprintf (buffer, sizeof (buffer), "%s", "/dev/null/");
  316. }
  317. fprintf (stderr, "%s\n", _("Press any key to continue..."));
  318. getc (stdin);
  319. }
  320. tmpdir = buffer;
  321. if (!error)
  322. g_setenv ("MC_TMPDIR", tmpdir, TRUE);
  323. return tmpdir;
  324. }
  325. /* Pipes are guaranteed to be able to hold at least 4096 bytes */
  326. /* More than that would be unportable */
  327. #define MAX_PIPE_SIZE 4096
  328. static int error_pipe[2]; /* File descriptors of error pipe */
  329. static int old_error; /* File descriptor of old standard error */
  330. /* Creates a pipe to hold standard error for a later analysis. */
  331. /* The pipe can hold 4096 bytes. Make sure no more is written */
  332. /* or a deadlock might occur. */
  333. void
  334. open_error_pipe (void)
  335. {
  336. if (pipe (error_pipe) < 0)
  337. {
  338. message (D_NORMAL, _("Warning"), _("Pipe failed"));
  339. }
  340. old_error = dup (2);
  341. if (old_error < 0 || close (2) || dup (error_pipe[1]) != 2)
  342. {
  343. message (D_NORMAL, _("Warning"), _("Dup failed"));
  344. close (error_pipe[0]);
  345. error_pipe[0] = -1;
  346. }
  347. else
  348. {
  349. /*
  350. * Settng stderr in nonblocking mode as we close it earlier, than
  351. * program stops. We try to read some error at program startup,
  352. * but we should not block on it.
  353. *
  354. * TODO: make piped stdin/stderr poll()/select()able to get rid
  355. * of following hack.
  356. */
  357. int fd_flags;
  358. fd_flags = fcntl (error_pipe[0], F_GETFL, NULL);
  359. if (fd_flags != -1)
  360. {
  361. fd_flags |= O_NONBLOCK;
  362. if (fcntl (error_pipe[0], F_SETFL, fd_flags) == -1)
  363. {
  364. /* TODO: handle it somehow */
  365. }
  366. }
  367. }
  368. /* we never write there */
  369. close (error_pipe[1]);
  370. error_pipe[1] = -1;
  371. }
  372. /*
  373. * Returns true if an error was displayed
  374. * error: -1 - ignore errors, 0 - display warning, 1 - display error
  375. * text is prepended to the error message from the pipe
  376. */
  377. int
  378. close_error_pipe (int error, const char *text)
  379. {
  380. const char *title;
  381. char msg[MAX_PIPE_SIZE];
  382. int len = 0;
  383. /* already closed */
  384. if (error_pipe[0] == -1)
  385. return 0;
  386. if (error)
  387. title = MSG_ERROR;
  388. else
  389. title = _("Warning");
  390. if (old_error >= 0)
  391. {
  392. if (dup2 (old_error, 2) == -1)
  393. {
  394. message (error, MSG_ERROR, _("Error dup'ing old error pipe"));
  395. return 1;
  396. }
  397. close (old_error);
  398. len = read (error_pipe[0], msg, MAX_PIPE_SIZE - 1);
  399. if (len >= 0)
  400. msg[len] = 0;
  401. close (error_pipe[0]);
  402. error_pipe[0] = -1;
  403. }
  404. if (error < 0)
  405. return 0; /* Just ignore error message */
  406. if (text == NULL)
  407. {
  408. if (len <= 0)
  409. return 0; /* Nothing to show */
  410. /* Show message from pipe */
  411. message (error, title, "%s", msg);
  412. }
  413. else
  414. {
  415. /* Show given text and possible message from pipe */
  416. message (error, title, "%s\n%s", text, msg);
  417. }
  418. return 1;
  419. }
  420. /*
  421. * Canonicalize path, and return a new path. Do everything in place.
  422. * The new path differs from path in:
  423. * Multiple `/'s are collapsed to a single `/'.
  424. * Leading `./'s and trailing `/.'s are removed.
  425. * Trailing `/'s are removed.
  426. * Non-leading `../'s and trailing `..'s are handled by removing
  427. * portions of the path.
  428. * Well formed UNC paths are modified only in the local part.
  429. */
  430. void
  431. custom_canonicalize_pathname (char *path, CANON_PATH_FLAGS flags)
  432. {
  433. char *p, *s;
  434. int len;
  435. char *lpath = path; /* path without leading UNC part */
  436. /* Detect and preserve UNC paths: //server/... */
  437. if ((flags & CANON_PATH_GUARDUNC) && path[0] == PATH_SEP && path[1] == PATH_SEP)
  438. {
  439. p = path + 2;
  440. while (p[0] && p[0] != '/')
  441. p++;
  442. if (p[0] == '/' && p > path + 2)
  443. lpath = p;
  444. }
  445. if (!lpath[0] || !lpath[1])
  446. return;
  447. if (flags & CANON_PATH_JOINSLASHES)
  448. {
  449. /* Collapse multiple slashes */
  450. p = lpath;
  451. while (*p)
  452. {
  453. if (p[0] == PATH_SEP && p[1] == PATH_SEP)
  454. {
  455. s = p + 1;
  456. while (*(++s) == PATH_SEP);
  457. str_move (p + 1, s);
  458. }
  459. p++;
  460. }
  461. }
  462. if (flags & CANON_PATH_JOINSLASHES)
  463. {
  464. /* Collapse "/./" -> "/" */
  465. p = lpath;
  466. while (*p)
  467. {
  468. if (p[0] == PATH_SEP && p[1] == '.' && p[2] == PATH_SEP)
  469. str_move (p, p + 2);
  470. else
  471. p++;
  472. }
  473. }
  474. if (flags & CANON_PATH_REMSLASHDOTS)
  475. {
  476. /* Remove trailing slashes */
  477. p = lpath + strlen (lpath) - 1;
  478. while (p > lpath && *p == PATH_SEP)
  479. *p-- = 0;
  480. /* Remove leading "./" */
  481. if (lpath[0] == '.' && lpath[1] == PATH_SEP)
  482. {
  483. if (lpath[2] == 0)
  484. {
  485. lpath[1] = 0;
  486. return;
  487. }
  488. else
  489. {
  490. str_move (lpath, lpath + 2);
  491. }
  492. }
  493. /* Remove trailing "/" or "/." */
  494. len = strlen (lpath);
  495. if (len < 2)
  496. return;
  497. if (lpath[len - 1] == PATH_SEP)
  498. {
  499. lpath[len - 1] = 0;
  500. }
  501. else
  502. {
  503. if (lpath[len - 1] == '.' && lpath[len - 2] == PATH_SEP)
  504. {
  505. if (len == 2)
  506. {
  507. lpath[1] = 0;
  508. return;
  509. }
  510. else
  511. {
  512. lpath[len - 2] = 0;
  513. }
  514. }
  515. }
  516. }
  517. if (flags & CANON_PATH_REMDOUBLEDOTS)
  518. {
  519. /* Collapse "/.." with the previous part of path */
  520. p = lpath;
  521. while (p[0] && p[1] && p[2])
  522. {
  523. if ((p[0] != PATH_SEP || p[1] != '.' || p[2] != '.') || (p[3] != PATH_SEP && p[3] != 0))
  524. {
  525. p++;
  526. continue;
  527. }
  528. /* search for the previous token */
  529. s = p - 1;
  530. while (s >= lpath && *s != PATH_SEP)
  531. s--;
  532. s++;
  533. /* If the previous token is "..", we cannot collapse it */
  534. if (s[0] == '.' && s[1] == '.' && s + 2 == p)
  535. {
  536. p += 3;
  537. continue;
  538. }
  539. if (p[3] != 0)
  540. {
  541. if (s == lpath && *s == PATH_SEP)
  542. {
  543. /* "/../foo" -> "/foo" */
  544. str_move (s + 1, p + 4);
  545. }
  546. else
  547. {
  548. /* "token/../foo" -> "foo" */
  549. str_move (s, p + 4);
  550. }
  551. p = (s > lpath) ? s - 1 : s;
  552. continue;
  553. }
  554. /* trailing ".." */
  555. if (s == lpath)
  556. {
  557. /* "token/.." -> "." */
  558. if (lpath[0] != PATH_SEP)
  559. {
  560. lpath[0] = '.';
  561. }
  562. lpath[1] = 0;
  563. }
  564. else
  565. {
  566. /* "foo/token/.." -> "foo" */
  567. if (s == lpath + 1)
  568. s[0] = 0;
  569. else
  570. s[-1] = 0;
  571. break;
  572. }
  573. break;
  574. }
  575. }
  576. }
  577. void
  578. canonicalize_pathname (char *path)
  579. {
  580. custom_canonicalize_pathname (path, CANON_PATH_ALL);
  581. }
  582. #ifdef HAVE_GET_PROCESS_STATS
  583. # include <sys/procstats.h>
  584. int
  585. gettimeofday (struct timeval *tp, void *tzp)
  586. {
  587. return get_process_stats (tp, PS_SELF, 0, 0);
  588. }
  589. #endif /* HAVE_GET_PROCESS_STATS */
  590. #ifndef HAVE_REALPATH
  591. char *
  592. mc_realpath (const char *path, char *resolved_path)
  593. {
  594. char copy_path[PATH_MAX];
  595. char link_path[PATH_MAX];
  596. char got_path[PATH_MAX];
  597. char *new_path = got_path;
  598. char *max_path;
  599. int readlinks = 0;
  600. int n;
  601. /* Make a copy of the source path since we may need to modify it. */
  602. if (strlen (path) >= PATH_MAX - 2)
  603. {
  604. errno = ENAMETOOLONG;
  605. return NULL;
  606. }
  607. strcpy (copy_path, path);
  608. path = copy_path;
  609. max_path = copy_path + PATH_MAX - 2;
  610. /* If it's a relative pathname use getwd for starters. */
  611. if (*path != '/')
  612. {
  613. new_path = g_get_current_dir ();
  614. if (new_path == NULL)
  615. {
  616. strcpy (got_path, "");
  617. }
  618. else
  619. {
  620. g_snprintf (got_path, PATH_MAX, "%s", new_path);
  621. g_free (new_path);
  622. new_path = got_path;
  623. }
  624. new_path += strlen (got_path);
  625. if (new_path[-1] != '/')
  626. *new_path++ = '/';
  627. }
  628. else
  629. {
  630. *new_path++ = '/';
  631. path++;
  632. }
  633. /* Expand each slash-separated pathname component. */
  634. while (*path != '\0')
  635. {
  636. /* Ignore stray "/". */
  637. if (*path == '/')
  638. {
  639. path++;
  640. continue;
  641. }
  642. if (*path == '.')
  643. {
  644. /* Ignore ".". */
  645. if (path[1] == '\0' || path[1] == '/')
  646. {
  647. path++;
  648. continue;
  649. }
  650. if (path[1] == '.')
  651. {
  652. if (path[2] == '\0' || path[2] == '/')
  653. {
  654. path += 2;
  655. /* Ignore ".." at root. */
  656. if (new_path == got_path + 1)
  657. continue;
  658. /* Handle ".." by backing up. */
  659. while ((--new_path)[-1] != '/');
  660. continue;
  661. }
  662. }
  663. }
  664. /* Safely copy the next pathname component. */
  665. while (*path != '\0' && *path != '/')
  666. {
  667. if (path > max_path)
  668. {
  669. errno = ENAMETOOLONG;
  670. return NULL;
  671. }
  672. *new_path++ = *path++;
  673. }
  674. #ifdef S_IFLNK
  675. /* Protect against infinite loops. */
  676. if (readlinks++ > MAXSYMLINKS)
  677. {
  678. errno = ELOOP;
  679. return NULL;
  680. }
  681. /* See if latest pathname component is a symlink. */
  682. *new_path = '\0';
  683. n = readlink (got_path, link_path, PATH_MAX - 1);
  684. if (n < 0)
  685. {
  686. /* EINVAL means the file exists but isn't a symlink. */
  687. if (errno != EINVAL)
  688. {
  689. /* Make sure it's null terminated. */
  690. *new_path = '\0';
  691. strcpy (resolved_path, got_path);
  692. return NULL;
  693. }
  694. }
  695. else
  696. {
  697. /* Note: readlink doesn't add the null byte. */
  698. link_path[n] = '\0';
  699. if (*link_path == '/')
  700. /* Start over for an absolute symlink. */
  701. new_path = got_path;
  702. else
  703. /* Otherwise back up over this component. */
  704. while (*(--new_path) != '/');
  705. /* Safe sex check. */
  706. if (strlen (path) + n >= PATH_MAX - 2)
  707. {
  708. errno = ENAMETOOLONG;
  709. return NULL;
  710. }
  711. /* Insert symlink contents into path. */
  712. strcat (link_path, path);
  713. strcpy (copy_path, link_path);
  714. path = copy_path;
  715. }
  716. #endif /* S_IFLNK */
  717. *new_path++ = '/';
  718. }
  719. /* Delete trailing slash but don't whomp a lone slash. */
  720. if (new_path != got_path + 1 && new_path[-1] == '/')
  721. new_path--;
  722. /* Make sure it's null terminated. */
  723. *new_path = '\0';
  724. strcpy (resolved_path, got_path);
  725. return resolved_path;
  726. }
  727. #endif /* HAVE_REALPATH */
  728. /* Return the index of the permissions triplet */
  729. int
  730. get_user_permissions (struct stat *st)
  731. {
  732. static gboolean initialized = FALSE;
  733. static gid_t *groups;
  734. static int ngroups;
  735. static uid_t uid;
  736. int i;
  737. if (!initialized)
  738. {
  739. uid = geteuid ();
  740. ngroups = getgroups (0, NULL);
  741. if (ngroups == -1)
  742. ngroups = 0; /* ignore errors */
  743. /* allocate space for one element in addition to what
  744. * will be filled by getgroups(). */
  745. groups = g_new (gid_t, ngroups + 1);
  746. if (ngroups != 0)
  747. {
  748. ngroups = getgroups (ngroups, groups);
  749. if (ngroups == -1)
  750. ngroups = 0; /* ignore errors */
  751. }
  752. /* getgroups() may or may not return the effective group ID,
  753. * so we always include it at the end of the list. */
  754. groups[ngroups++] = getegid ();
  755. initialized = TRUE;
  756. }
  757. if (st->st_uid == uid || uid == 0)
  758. return 0;
  759. for (i = 0; i < ngroups; i++)
  760. {
  761. if (st->st_gid == groups[i])
  762. return 1;
  763. }
  764. return 2;
  765. }