utilunix.c 23 KB

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