Extended shortcuts like 'ctrl-x x' are unavailable in editor.
[midnight-commander.git] / lib / utilunix.c
blob213adf3e3d6af48868ea3f984b0b535a4e96f686
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)
698 break;
700 s--;
703 s++;
705 /* If the previous token is "..", we cannot collapse it */
706 if (s[0] == '.' && s[1] == '.' && s + 2 == p)
708 p += 3;
709 continue;
712 if (p[3] != 0)
714 if (s == lpath && *s == PATH_SEP)
716 /* "/../foo" -> "/foo" */
717 str_move (s + 1, p + 4);
719 else
721 /* "token/../foo" -> "foo" */
722 #if HAVE_CHARSET
723 if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
724 && (is_supported_encoding (s + enc_prefix_len)))
725 /* special case: remove encoding */
726 str_move (s, p + 1);
727 else
728 #endif /* HAVE_CHARSET */
729 str_move (s, p + 4);
731 p = (s > lpath) ? s - 1 : s;
732 continue;
735 /* trailing ".." */
736 if (s == lpath)
738 /* "token/.." -> "." */
739 if (lpath[0] != PATH_SEP)
741 lpath[0] = '.';
743 lpath[1] = 0;
745 else
747 /* "foo/token/.." -> "foo" */
748 if (s == lpath + 1)
749 s[0] = 0;
750 #if HAVE_CHARSET
751 else if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
752 && (is_supported_encoding (s + enc_prefix_len)))
754 /* special case: remove encoding */
755 s[0] = '.';
756 s[1] = '.';
757 s[2] = '\0';
759 /* search for the previous token */
760 /* s[-1] == PATH_SEP */
761 p = s - 1;
762 while (p >= lpath && *p != PATH_SEP)
763 p--;
765 if (p != NULL)
766 continue;
768 #endif /* HAVE_CHARSET */
769 else
771 if (s >= lpath + url_delim_len
772 && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
773 *s = '\0';
774 else
775 s[-1] = '\0';
777 break;
780 break;
785 /* --------------------------------------------------------------------------------------------- */
787 void
788 canonicalize_pathname (char *path)
790 custom_canonicalize_pathname (path, CANON_PATH_ALL);
793 /* --------------------------------------------------------------------------------------------- */
795 #ifdef HAVE_GET_PROCESS_STATS
797 gettimeofday (struct timeval *tp, void *tzp)
799 return get_process_stats (tp, PS_SELF, 0, 0);
801 #endif /* HAVE_GET_PROCESS_STATS */
803 /* --------------------------------------------------------------------------------------------- */
805 #ifndef HAVE_REALPATH
806 char *
807 mc_realpath (const char *path, char *resolved_path)
809 char copy_path[PATH_MAX];
810 char link_path[PATH_MAX];
811 char got_path[PATH_MAX];
812 char *new_path = got_path;
813 char *max_path;
814 int readlinks = 0;
815 int n;
817 /* Make a copy of the source path since we may need to modify it. */
818 if (strlen (path) >= PATH_MAX - 2)
820 errno = ENAMETOOLONG;
821 return NULL;
823 strcpy (copy_path, path);
824 path = copy_path;
825 max_path = copy_path + PATH_MAX - 2;
826 /* If it's a relative pathname use getwd for starters. */
827 if (*path != '/')
830 new_path = g_get_current_dir ();
831 if (new_path == NULL)
833 strcpy (got_path, "");
835 else
837 g_snprintf (got_path, PATH_MAX, "%s", new_path);
838 g_free (new_path);
839 new_path = got_path;
842 new_path += strlen (got_path);
843 if (new_path[-1] != '/')
844 *new_path++ = '/';
846 else
848 *new_path++ = '/';
849 path++;
851 /* Expand each slash-separated pathname component. */
852 while (*path != '\0')
854 /* Ignore stray "/". */
855 if (*path == '/')
857 path++;
858 continue;
860 if (*path == '.')
862 /* Ignore ".". */
863 if (path[1] == '\0' || path[1] == '/')
865 path++;
866 continue;
868 if (path[1] == '.')
870 if (path[2] == '\0' || path[2] == '/')
872 path += 2;
873 /* Ignore ".." at root. */
874 if (new_path == got_path + 1)
875 continue;
876 /* Handle ".." by backing up. */
877 while ((--new_path)[-1] != '/');
878 continue;
882 /* Safely copy the next pathname component. */
883 while (*path != '\0' && *path != '/')
885 if (path > max_path)
887 errno = ENAMETOOLONG;
888 return NULL;
890 *new_path++ = *path++;
892 #ifdef S_IFLNK
893 /* Protect against infinite loops. */
894 if (readlinks++ > MAXSYMLINKS)
896 errno = ELOOP;
897 return NULL;
899 /* See if latest pathname component is a symlink. */
900 *new_path = '\0';
901 n = readlink (got_path, link_path, PATH_MAX - 1);
902 if (n < 0)
904 /* EINVAL means the file exists but isn't a symlink. */
905 if (errno != EINVAL)
907 /* Make sure it's null terminated. */
908 *new_path = '\0';
909 strcpy (resolved_path, got_path);
910 return NULL;
913 else
915 /* Note: readlink doesn't add the null byte. */
916 link_path[n] = '\0';
917 if (*link_path == '/')
918 /* Start over for an absolute symlink. */
919 new_path = got_path;
920 else
921 /* Otherwise back up over this component. */
922 while (*(--new_path) != '/');
923 /* Safe sex check. */
924 if (strlen (path) + n >= PATH_MAX - 2)
926 errno = ENAMETOOLONG;
927 return NULL;
929 /* Insert symlink contents into path. */
930 strcat (link_path, path);
931 strcpy (copy_path, link_path);
932 path = copy_path;
934 #endif /* S_IFLNK */
935 *new_path++ = '/';
937 /* Delete trailing slash but don't whomp a lone slash. */
938 if (new_path != got_path + 1 && new_path[-1] == '/')
939 new_path--;
940 /* Make sure it's null terminated. */
941 *new_path = '\0';
942 strcpy (resolved_path, got_path);
943 return resolved_path;
945 #endif /* HAVE_REALPATH */
947 /* --------------------------------------------------------------------------------------------- */
949 * Return the index of the permissions triplet
954 get_user_permissions (struct stat *st)
956 static gboolean initialized = FALSE;
957 static gid_t *groups;
958 static int ngroups;
959 static uid_t uid;
960 int i;
962 if (!initialized)
964 uid = geteuid ();
966 ngroups = getgroups (0, NULL);
967 if (ngroups == -1)
968 ngroups = 0; /* ignore errors */
970 /* allocate space for one element in addition to what
971 * will be filled by getgroups(). */
972 groups = g_new (gid_t, ngroups + 1);
974 if (ngroups != 0)
976 ngroups = getgroups (ngroups, groups);
977 if (ngroups == -1)
978 ngroups = 0; /* ignore errors */
981 /* getgroups() may or may not return the effective group ID,
982 * so we always include it at the end of the list. */
983 groups[ngroups++] = getegid ();
985 initialized = TRUE;
988 if (st->st_uid == uid || uid == 0)
989 return 0;
991 for (i = 0; i < ngroups; i++)
993 if (st->st_gid == groups[i])
994 return 1;
997 return 2;
1000 /* --------------------------------------------------------------------------------------------- */
1002 * Build filename from arguments.
1003 * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
1006 char *
1007 mc_build_filename (const char *first_element, ...)
1009 va_list args;
1010 const char *element = first_element;
1011 GString *path;
1012 char *ret;
1014 if (element == NULL)
1015 return NULL;
1017 path = g_string_new ("");
1018 va_start (args, first_element);
1022 char *tmp_element;
1023 size_t len;
1024 const char *start;
1026 tmp_element = g_strdup (element);
1028 element = va_arg (args, char *);
1030 canonicalize_pathname (tmp_element);
1031 len = strlen (tmp_element);
1032 start = (tmp_element[0] == PATH_SEP) ? tmp_element + 1 : tmp_element;
1034 g_string_append (path, start);
1035 if (tmp_element[len - 1] != PATH_SEP && element != NULL)
1036 g_string_append_c (path, PATH_SEP);
1038 g_free (tmp_element);
1040 while (element != NULL);
1042 va_end (args);
1044 g_string_prepend_c (path, PATH_SEP);
1046 ret = g_string_free (path, FALSE);
1047 canonicalize_pathname (ret);
1049 return ret;
1052 /* --------------------------------------------------------------------------------------------- */