vfs_path_to_str() now return URL string instead of old representation
[midnight-commander.git] / lib / utilunix.c
blobef284da3a7994001cb4c1449668f5a3911100de6
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.
8 The mc_realpath routine is mostly from uClibc package, written
9 by Rick Sladkey <jrs@world.std.com>
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 2 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software
23 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
25 /** \file utilunix.c
26 * \brief Source: various utilities - Unix variant
29 #include <config.h>
31 #include <ctype.h>
32 #include <errno.h>
33 #include <limits.h>
34 #include <signal.h>
35 #include <stdarg.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <fcntl.h>
40 #include <sys/param.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <sys/wait.h>
44 #ifdef HAVE_SYS_IOCTL_H
45 #include <sys/ioctl.h>
46 #endif
47 #ifdef HAVE_GET_PROCESS_STATS
48 #include <sys/procstats.h>
49 #endif
50 #include <unistd.h>
51 #include <pwd.h>
52 #include <grp.h>
54 #include "lib/global.h"
55 #include "lib/vfs/vfs.h" /* VFS_ENCODING_PREFIX */
56 #include "lib/strutil.h" /* str_move() */
57 #include "lib/util.h"
58 #include "lib/widget.h" /* message() */
59 #include "lib/vfs/xdirentry.h"
61 #ifdef HAVE_CHARSET
62 #include "lib/charsets.h"
63 #endif
65 #include "utilunix.h"
67 /*** global variables ****************************************************************************/
69 struct sigaction startup_handler;
71 /*** file scope macro definitions ****************************************************************/
73 #define UID_CACHE_SIZE 200
74 #define GID_CACHE_SIZE 30
76 /* Pipes are guaranteed to be able to hold at least 4096 bytes */
77 /* More than that would be unportable */
78 #define MAX_PIPE_SIZE 4096
80 /*** file scope type declarations ****************************************************************/
82 typedef struct
84 int index;
85 char *string;
86 } int_cache;
88 /*** file scope variables ************************************************************************/
90 static int_cache uid_cache[UID_CACHE_SIZE];
91 static int_cache gid_cache[GID_CACHE_SIZE];
93 static int error_pipe[2]; /* File descriptors of error pipe */
94 static int old_error; /* File descriptor of old standard error */
96 /*** file scope functions ************************************************************************/
97 /* --------------------------------------------------------------------------------------------- */
99 static char *
100 i_cache_match (int id, int_cache * cache, int size)
102 int i;
104 for (i = 0; i < size; i++)
105 if (cache[i].index == id)
106 return cache[i].string;
107 return 0;
110 /* --------------------------------------------------------------------------------------------- */
112 static void
113 i_cache_add (int id, int_cache * cache, int size, char *text, int *last)
115 g_free (cache[*last].string);
116 cache[*last].string = g_strdup (text);
117 cache[*last].index = id;
118 *last = ((*last) + 1) % size;
121 /* --------------------------------------------------------------------------------------------- */
122 /*** public functions ****************************************************************************/
123 /* --------------------------------------------------------------------------------------------- */
125 char *
126 get_owner (int uid)
128 struct passwd *pwd;
129 static char ibuf[10];
130 char *name;
131 static int uid_last;
133 name = i_cache_match (uid, uid_cache, UID_CACHE_SIZE);
134 if (name != NULL)
135 return name;
137 pwd = getpwuid (uid);
138 if (pwd != NULL)
140 i_cache_add (uid, uid_cache, UID_CACHE_SIZE, pwd->pw_name, &uid_last);
141 return pwd->pw_name;
143 else
145 g_snprintf (ibuf, sizeof (ibuf), "%d", uid);
146 return ibuf;
150 /* --------------------------------------------------------------------------------------------- */
152 char *
153 get_group (int gid)
155 struct group *grp;
156 static char gbuf[10];
157 char *name;
158 static int gid_last;
160 name = i_cache_match (gid, gid_cache, GID_CACHE_SIZE);
161 if (name != NULL)
162 return name;
164 grp = getgrgid (gid);
165 if (grp != NULL)
167 i_cache_add (gid, gid_cache, GID_CACHE_SIZE, grp->gr_name, &gid_last);
168 return grp->gr_name;
170 else
172 g_snprintf (gbuf, sizeof (gbuf), "%d", gid);
173 return gbuf;
177 /* --------------------------------------------------------------------------------------------- */
178 /* Since ncurses uses a handler that automatically refreshes the */
179 /* screen after a SIGCONT, and we don't want this behavior when */
180 /* spawning a child, we save the original handler here */
182 void
183 save_stop_handler (void)
185 sigaction (SIGTSTP, NULL, &startup_handler);
188 /* --------------------------------------------------------------------------------------------- */
191 my_system (int flags, const char *shell, const char *command)
193 struct sigaction ignore, save_intr, save_quit, save_stop;
194 pid_t pid;
195 int status = 0;
197 ignore.sa_handler = SIG_IGN;
198 sigemptyset (&ignore.sa_mask);
199 ignore.sa_flags = 0;
201 sigaction (SIGINT, &ignore, &save_intr);
202 sigaction (SIGQUIT, &ignore, &save_quit);
204 /* Restore the original SIGTSTP handler, we don't want ncurses' */
205 /* handler messing the screen after the SIGCONT */
206 sigaction (SIGTSTP, &startup_handler, &save_stop);
208 pid = fork ();
209 if (pid < 0)
211 fprintf (stderr, "\n\nfork () = -1\n");
212 status = -1;
214 else if (pid == 0)
216 signal (SIGINT, SIG_DFL);
217 signal (SIGQUIT, SIG_DFL);
218 signal (SIGTSTP, SIG_DFL);
219 signal (SIGCHLD, SIG_DFL);
221 if (flags & EXECUTE_AS_SHELL)
222 execl (shell, shell, "-c", command, (char *) NULL);
223 else
225 gchar **shell_tokens;
226 const gchar *only_cmd;
228 shell_tokens = g_strsplit (shell, " ", 2);
229 if (shell_tokens == NULL)
230 only_cmd = shell;
231 else
232 only_cmd = (*shell_tokens != NULL) ? *shell_tokens : shell;
234 execlp (only_cmd, shell, command, (char *) NULL);
237 execlp will replace current process,
238 therefore no sence in call of g_strfreev().
239 But this keeped for estetic reason :)
241 g_strfreev (shell_tokens);
245 _exit (127); /* Exec error */
247 else
249 while (TRUE)
251 if (waitpid (pid, &status, 0) > 0)
253 status = WEXITSTATUS (status);
254 break;
256 if (errno != EINTR)
258 status = -1;
259 break;
263 sigaction (SIGINT, &save_intr, NULL);
264 sigaction (SIGQUIT, &save_quit, NULL);
265 sigaction (SIGTSTP, &save_stop, NULL);
267 return status;
271 /* --------------------------------------------------------------------------------------------- */
273 * Perform tilde expansion if possible.
274 * Always return a newly allocated string, even if it's unchanged.
277 char *
278 tilde_expand (const char *directory)
280 struct passwd *passwd;
281 const char *p, *q;
282 char *name;
284 if (*directory != '~')
285 return g_strdup (directory);
287 p = directory + 1;
289 /* d = "~" or d = "~/" */
290 if (!(*p) || (*p == PATH_SEP))
292 passwd = getpwuid (geteuid ());
293 q = (*p == PATH_SEP) ? p + 1 : "";
295 else
297 q = strchr (p, PATH_SEP);
298 if (!q)
300 passwd = getpwnam (p);
302 else
304 name = g_strndup (p, q - p);
305 passwd = getpwnam (name);
306 q++;
307 g_free (name);
311 /* If we can't figure the user name, leave tilde unexpanded */
312 if (!passwd)
313 return g_strdup (directory);
315 return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
318 /* --------------------------------------------------------------------------------------------- */
320 * Return the directory where mc should keep its temporary files.
321 * This directory is (in Bourne shell terms) "${TMPDIR=/tmp}/mc-$USER"
322 * When called the first time, the directory is created if needed.
323 * The first call should be done early, since we are using fprintf()
324 * and not message() to report possible problems.
327 const char *
328 mc_tmpdir (void)
330 static char buffer[64];
331 static const char *tmpdir;
332 const char *sys_tmp;
333 struct passwd *pwd;
334 struct stat st;
335 const char *error = NULL;
337 /* Check if already correctly initialized */
338 if (tmpdir && lstat (tmpdir, &st) == 0 && S_ISDIR (st.st_mode) &&
339 st.st_uid == getuid () && (st.st_mode & 0777) == 0700)
340 return tmpdir;
342 sys_tmp = getenv ("TMPDIR");
343 if (!sys_tmp || sys_tmp[0] != '/')
345 sys_tmp = TMPDIR_DEFAULT;
348 pwd = getpwuid (getuid ());
350 if (pwd)
351 g_snprintf (buffer, sizeof (buffer), "%s/mc-%s", sys_tmp, pwd->pw_name);
352 else
353 g_snprintf (buffer, sizeof (buffer), "%s/mc-%lu", sys_tmp, (unsigned long) getuid ());
355 canonicalize_pathname (buffer);
357 if (lstat (buffer, &st) == 0)
359 /* Sanity check for existing directory */
360 if (!S_ISDIR (st.st_mode))
361 error = _("%s is not a directory\n");
362 else if (st.st_uid != getuid ())
363 error = _("Directory %s is not owned by you\n");
364 else if (((st.st_mode & 0777) != 0700) && (chmod (buffer, 0700) != 0))
365 error = _("Cannot set correct permissions for directory %s\n");
367 else
369 /* Need to create directory */
370 if (mkdir (buffer, S_IRWXU) != 0)
372 fprintf (stderr,
373 _("Cannot create temporary directory %s: %s\n"),
374 buffer, unix_error_string (errno));
375 error = "";
379 if (error != NULL)
381 int test_fd;
382 char *test_fn, *fallback_prefix;
383 int fallback_ok = 0;
385 if (*error)
386 fprintf (stderr, error, buffer);
388 /* Test if sys_tmp is suitable for temporary files */
389 fallback_prefix = g_strdup_printf ("%s/mctest", sys_tmp);
390 test_fd = mc_mkstemps (&test_fn, fallback_prefix, NULL);
391 g_free (fallback_prefix);
392 if (test_fd != -1)
394 close (test_fd);
395 test_fd = open (test_fn, O_RDONLY);
396 if (test_fd != -1)
398 close (test_fd);
399 unlink (test_fn);
400 fallback_ok = 1;
404 if (fallback_ok)
406 fprintf (stderr, _("Temporary files will be created in %s\n"), sys_tmp);
407 g_snprintf (buffer, sizeof (buffer), "%s", sys_tmp);
408 error = NULL;
410 else
412 fprintf (stderr, _("Temporary files will not be created\n"));
413 g_snprintf (buffer, sizeof (buffer), "%s", "/dev/null/");
416 fprintf (stderr, "%s\n", _("Press any key to continue..."));
417 getc (stdin);
420 tmpdir = buffer;
422 if (!error)
423 g_setenv ("MC_TMPDIR", tmpdir, TRUE);
425 return tmpdir;
428 /* --------------------------------------------------------------------------------------------- */
430 * Creates a pipe to hold standard error for a later analysis.
431 * The pipe can hold 4096 bytes. Make sure no more is written
432 * or a deadlock might occur.
435 void
436 open_error_pipe (void)
438 if (pipe (error_pipe) < 0)
440 message (D_NORMAL, _("Warning"), _("Pipe failed"));
442 old_error = dup (2);
443 if (old_error < 0 || close (2) || dup (error_pipe[1]) != 2)
445 message (D_NORMAL, _("Warning"), _("Dup failed"));
447 close (error_pipe[0]);
448 error_pipe[0] = -1;
450 else
453 * Settng stderr in nonblocking mode as we close it earlier, than
454 * program stops. We try to read some error at program startup,
455 * but we should not block on it.
457 * TODO: make piped stdin/stderr poll()/select()able to get rid
458 * of following hack.
460 int fd_flags;
461 fd_flags = fcntl (error_pipe[0], F_GETFL, NULL);
462 if (fd_flags != -1)
464 fd_flags |= O_NONBLOCK;
465 if (fcntl (error_pipe[0], F_SETFL, fd_flags) == -1)
467 /* TODO: handle it somehow */
471 /* we never write there */
472 close (error_pipe[1]);
473 error_pipe[1] = -1;
476 /* --------------------------------------------------------------------------------------------- */
478 * Returns true if an error was displayed
479 * error: -1 - ignore errors, 0 - display warning, 1 - display error
480 * text is prepended to the error message from the pipe
484 close_error_pipe (int error, const char *text)
486 const char *title;
487 char msg[MAX_PIPE_SIZE];
488 int len = 0;
490 /* already closed */
491 if (error_pipe[0] == -1)
492 return 0;
494 if (error)
495 title = MSG_ERROR;
496 else
497 title = _("Warning");
498 if (old_error >= 0)
500 if (dup2 (old_error, 2) == -1)
502 message (error, MSG_ERROR, _("Error dup'ing old error pipe"));
503 return 1;
505 close (old_error);
506 len = read (error_pipe[0], msg, MAX_PIPE_SIZE - 1);
508 if (len >= 0)
509 msg[len] = 0;
510 close (error_pipe[0]);
511 error_pipe[0] = -1;
513 if (error < 0)
514 return 0; /* Just ignore error message */
515 if (text == NULL)
517 if (len <= 0)
518 return 0; /* Nothing to show */
520 /* Show message from pipe */
521 message (error, title, "%s", msg);
523 else
525 /* Show given text and possible message from pipe */
526 message (error, title, "%s\n%s", text, msg);
528 return 1;
531 /* --------------------------------------------------------------------------------------------- */
533 * Canonicalize path, and return a new path. Do everything in place.
534 * The new path differs from path in:
535 * Multiple `/'s are collapsed to a single `/'.
536 * Leading `./'s and trailing `/.'s are removed.
537 * Trailing `/'s are removed.
538 * Non-leading `../'s and trailing `..'s are handled by removing
539 * portions of the path.
540 * Well formed UNC paths are modified only in the local part.
543 void
544 custom_canonicalize_pathname (char *path, CANON_PATH_FLAGS flags)
546 char *p, *s;
547 size_t len;
548 char *lpath = path; /* path without leading UNC part */
549 const size_t url_delim_len = strlen (VFS_PATH_URL_DELIMITER);
551 /* Detect and preserve UNC paths: //server/... */
552 if ((flags & CANON_PATH_GUARDUNC) && path[0] == PATH_SEP && path[1] == PATH_SEP)
554 p = path + 2;
555 while (p[0] && p[0] != '/')
556 p++;
557 if (p[0] == '/' && p > path + 2)
558 lpath = p;
561 if (!lpath[0] || !lpath[1])
562 return;
564 if (flags & CANON_PATH_JOINSLASHES)
566 /* Collapse multiple slashes */
567 p = lpath;
568 while (*p)
570 if (p[0] == PATH_SEP && p[1] == PATH_SEP && (p == lpath || *(p - 1) != ':'))
572 s = p + 1;
573 while (*(++s) == PATH_SEP);
574 str_move (p + 1, s);
576 p++;
580 if (flags & CANON_PATH_JOINSLASHES)
582 /* Collapse "/./" -> "/" */
583 p = lpath;
584 while (*p)
586 if (p[0] == PATH_SEP && p[1] == '.' && p[2] == PATH_SEP)
587 str_move (p, p + 2);
588 else
589 p++;
593 if (flags & CANON_PATH_REMSLASHDOTS)
595 /* Remove trailing slashes */
596 p = lpath + strlen (lpath) - 1;
597 while (p > lpath && *p == PATH_SEP)
599 if (p >= lpath - (url_delim_len + 1)
600 && strncmp (p - url_delim_len + 1, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
601 break;
602 *p-- = 0;
605 /* Remove leading "./" */
606 if (lpath[0] == '.' && lpath[1] == PATH_SEP)
608 if (lpath[2] == 0)
610 lpath[1] = 0;
611 return;
613 else
615 str_move (lpath, lpath + 2);
619 /* Remove trailing "/" or "/." */
620 len = strlen (lpath);
621 if (len < 2)
622 return;
623 if (lpath[len - 1] == PATH_SEP
624 && (len < url_delim_len
625 || strncmp (lpath + len - url_delim_len, VFS_PATH_URL_DELIMITER,
626 url_delim_len) != 0))
628 lpath[len - 1] = '\0';
630 else
632 if (lpath[len - 1] == '.' && lpath[len - 2] == PATH_SEP)
634 if (len == 2)
636 lpath[1] = '\0';
637 return;
639 else
641 lpath[len - 2] = '\0';
647 if (flags & CANON_PATH_REMDOUBLEDOTS)
649 const size_t enc_prefix_len = strlen (VFS_ENCODING_PREFIX);
651 /* Collapse "/.." with the previous part of path */
652 p = lpath;
653 while (p[0] && p[1] && p[2])
655 if ((p[0] != PATH_SEP || p[1] != '.' || p[2] != '.') || (p[3] != PATH_SEP && p[3] != 0))
657 p++;
658 continue;
661 /* search for the previous token */
662 s = p - 1;
663 if (s >= lpath + url_delim_len - 2
664 && strncmp (s - url_delim_len + 2, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
666 s -= (url_delim_len - 2);
667 while (s >= lpath && *s-- != PATH_SEP);
670 while (s >= lpath)
672 if (s - url_delim_len > lpath
673 && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
675 char *vfs_prefix = s - url_delim_len;
676 struct vfs_class *vclass;
678 while (vfs_prefix > lpath && *--vfs_prefix != PATH_SEP);
679 if (*vfs_prefix == PATH_SEP)
680 vfs_prefix++;
681 *(s - url_delim_len) = '\0';
683 vclass = vfs_prefix_to_class (vfs_prefix);
684 *(s - url_delim_len) = *VFS_PATH_URL_DELIMITER;
686 if (vclass != NULL)
688 struct vfs_s_subclass *sub = (struct vfs_s_subclass *) vclass->data;
689 if (sub != NULL && sub->flags & VFS_S_REMOTE)
691 s = vfs_prefix;
692 continue;
697 if (*s == PATH_SEP)
699 /* skip VFS prefix */
700 char *path_sep;
701 struct vfs_class *vclass;
703 /* old parser mode */
704 if (*(s + 1) != '#')
705 break;
707 path_sep = strchr (s + 1, PATH_SEP);
708 if (path_sep != NULL)
709 *path_sep = '\0';
711 vclass = vfs_prefix_to_class (s + 2);
712 if (path_sep != NULL)
713 *path_sep = PATH_SEP;
715 if (vclass == NULL)
716 break;
718 s--;
721 s++;
723 /* If the previous token is "..", we cannot collapse it */
724 if (s[0] == '.' && s[1] == '.' && s + 2 == p)
726 p += 3;
727 continue;
730 if (p[3] != 0)
732 if (s == lpath && *s == PATH_SEP)
734 /* "/../foo" -> "/foo" */
735 str_move (s + 1, p + 4);
737 else
739 /* "token/../foo" -> "foo" */
740 #if HAVE_CHARSET
741 if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
742 && (is_supported_encoding (s + enc_prefix_len)))
743 /* special case: remove encoding */
744 str_move (s, p + 1);
745 else
746 #endif /* HAVE_CHARSET */
747 str_move (s, p + 4);
749 p = (s > lpath) ? s - 1 : s;
750 continue;
753 /* trailing ".." */
754 if (s == lpath)
756 /* "token/.." -> "." */
757 if (lpath[0] != PATH_SEP)
759 lpath[0] = '.';
761 lpath[1] = 0;
763 else
765 /* "foo/token/.." -> "foo" */
766 if (s == lpath + 1)
767 s[0] = 0;
768 #if HAVE_CHARSET
769 else if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
770 && (is_supported_encoding (s + enc_prefix_len)))
772 /* special case: remove encoding */
773 s[0] = '.';
774 s[1] = '.';
775 s[2] = '\0';
777 /* search for the previous token */
778 /* s[-1] == PATH_SEP */
779 p = s - 1;
780 while (p >= lpath && *p != PATH_SEP)
781 p--;
783 if (p != NULL)
784 continue;
786 #endif /* HAVE_CHARSET */
787 else
789 if (s >= lpath + url_delim_len
790 && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
791 *s = '\0';
792 else
793 s[-1] = '\0';
795 break;
798 break;
803 /* --------------------------------------------------------------------------------------------- */
805 void
806 canonicalize_pathname (char *path)
808 custom_canonicalize_pathname (path, CANON_PATH_ALL);
811 /* --------------------------------------------------------------------------------------------- */
813 #ifdef HAVE_GET_PROCESS_STATS
815 gettimeofday (struct timeval *tp, void *tzp)
817 return get_process_stats (tp, PS_SELF, 0, 0);
819 #endif /* HAVE_GET_PROCESS_STATS */
821 /* --------------------------------------------------------------------------------------------- */
823 #ifndef HAVE_REALPATH
824 char *
825 mc_realpath (const char *path, char *resolved_path)
827 char copy_path[PATH_MAX];
828 char link_path[PATH_MAX];
829 char got_path[PATH_MAX];
830 char *new_path = got_path;
831 char *max_path;
832 int readlinks = 0;
833 int n;
835 /* Make a copy of the source path since we may need to modify it. */
836 if (strlen (path) >= PATH_MAX - 2)
838 errno = ENAMETOOLONG;
839 return NULL;
841 strcpy (copy_path, path);
842 path = copy_path;
843 max_path = copy_path + PATH_MAX - 2;
844 /* If it's a relative pathname use getwd for starters. */
845 if (*path != '/')
848 new_path = g_get_current_dir ();
849 if (new_path == NULL)
851 strcpy (got_path, "");
853 else
855 g_snprintf (got_path, PATH_MAX, "%s", new_path);
856 g_free (new_path);
857 new_path = got_path;
860 new_path += strlen (got_path);
861 if (new_path[-1] != '/')
862 *new_path++ = '/';
864 else
866 *new_path++ = '/';
867 path++;
869 /* Expand each slash-separated pathname component. */
870 while (*path != '\0')
872 /* Ignore stray "/". */
873 if (*path == '/')
875 path++;
876 continue;
878 if (*path == '.')
880 /* Ignore ".". */
881 if (path[1] == '\0' || path[1] == '/')
883 path++;
884 continue;
886 if (path[1] == '.')
888 if (path[2] == '\0' || path[2] == '/')
890 path += 2;
891 /* Ignore ".." at root. */
892 if (new_path == got_path + 1)
893 continue;
894 /* Handle ".." by backing up. */
895 while ((--new_path)[-1] != '/');
896 continue;
900 /* Safely copy the next pathname component. */
901 while (*path != '\0' && *path != '/')
903 if (path > max_path)
905 errno = ENAMETOOLONG;
906 return NULL;
908 *new_path++ = *path++;
910 #ifdef S_IFLNK
911 /* Protect against infinite loops. */
912 if (readlinks++ > MAXSYMLINKS)
914 errno = ELOOP;
915 return NULL;
917 /* See if latest pathname component is a symlink. */
918 *new_path = '\0';
919 n = readlink (got_path, link_path, PATH_MAX - 1);
920 if (n < 0)
922 /* EINVAL means the file exists but isn't a symlink. */
923 if (errno != EINVAL)
925 /* Make sure it's null terminated. */
926 *new_path = '\0';
927 strcpy (resolved_path, got_path);
928 return NULL;
931 else
933 /* Note: readlink doesn't add the null byte. */
934 link_path[n] = '\0';
935 if (*link_path == '/')
936 /* Start over for an absolute symlink. */
937 new_path = got_path;
938 else
939 /* Otherwise back up over this component. */
940 while (*(--new_path) != '/');
941 /* Safe sex check. */
942 if (strlen (path) + n >= PATH_MAX - 2)
944 errno = ENAMETOOLONG;
945 return NULL;
947 /* Insert symlink contents into path. */
948 strcat (link_path, path);
949 strcpy (copy_path, link_path);
950 path = copy_path;
952 #endif /* S_IFLNK */
953 *new_path++ = '/';
955 /* Delete trailing slash but don't whomp a lone slash. */
956 if (new_path != got_path + 1 && new_path[-1] == '/')
957 new_path--;
958 /* Make sure it's null terminated. */
959 *new_path = '\0';
960 strcpy (resolved_path, got_path);
961 return resolved_path;
963 #endif /* HAVE_REALPATH */
965 /* --------------------------------------------------------------------------------------------- */
967 * Return the index of the permissions triplet
972 get_user_permissions (struct stat *st)
974 static gboolean initialized = FALSE;
975 static gid_t *groups;
976 static int ngroups;
977 static uid_t uid;
978 int i;
980 if (!initialized)
982 uid = geteuid ();
984 ngroups = getgroups (0, NULL);
985 if (ngroups == -1)
986 ngroups = 0; /* ignore errors */
988 /* allocate space for one element in addition to what
989 * will be filled by getgroups(). */
990 groups = g_new (gid_t, ngroups + 1);
992 if (ngroups != 0)
994 ngroups = getgroups (ngroups, groups);
995 if (ngroups == -1)
996 ngroups = 0; /* ignore errors */
999 /* getgroups() may or may not return the effective group ID,
1000 * so we always include it at the end of the list. */
1001 groups[ngroups++] = getegid ();
1003 initialized = TRUE;
1006 if (st->st_uid == uid || uid == 0)
1007 return 0;
1009 for (i = 0; i < ngroups; i++)
1011 if (st->st_gid == groups[i])
1012 return 1;
1015 return 2;
1018 /* --------------------------------------------------------------------------------------------- */