utilunix.c 25 KB

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