utilunix.c 25 KB

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