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. */
26 * \brief Source: various utilities - Unix variant
40 #include <sys/param.h>
41 #include <sys/types.h>
44 #ifdef HAVE_SYS_IOCTL_H
45 # include <sys/ioctl.h>
51 #include "lib/global.h"
52 #include "lib/vfs/mc-vfs/vfs.h" /* VFS_ENCODING_PREFIX */
54 #include "src/execute.h"
55 #include "src/wtools.h" /* message() */
57 struct sigaction startup_handler
;
59 #define UID_CACHE_SIZE 200
60 #define GID_CACHE_SIZE 30
68 static int_cache uid_cache
[UID_CACHE_SIZE
];
69 static int_cache gid_cache
[GID_CACHE_SIZE
];
72 i_cache_match (int id
, int_cache
* cache
, int size
)
76 for (i
= 0; i
< size
; i
++)
77 if (cache
[i
].index
== id
)
78 return cache
[i
].string
;
83 i_cache_add (int id
, int_cache
* cache
, int size
, char *text
, int *last
)
85 g_free (cache
[*last
].string
);
86 cache
[*last
].string
= g_strdup (text
);
87 cache
[*last
].index
= id
;
88 *last
= ((*last
) + 1) % size
;
99 name
= i_cache_match (uid
, uid_cache
, UID_CACHE_SIZE
);
103 pwd
= getpwuid (uid
);
106 i_cache_add (uid
, uid_cache
, UID_CACHE_SIZE
, pwd
->pw_name
, &uid_last
);
111 g_snprintf (ibuf
, sizeof (ibuf
), "%d", uid
);
120 static char gbuf
[10];
124 name
= i_cache_match (gid
, gid_cache
, GID_CACHE_SIZE
);
128 grp
= getgrgid (gid
);
131 i_cache_add (gid
, gid_cache
, GID_CACHE_SIZE
, grp
->gr_name
, &gid_last
);
136 g_snprintf (gbuf
, sizeof (gbuf
), "%d", gid
);
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 */
145 save_stop_handler (void)
147 sigaction (SIGTSTP
, NULL
, &startup_handler
);
151 my_system (int flags
, const char *shell
, const char *command
)
153 struct sigaction ignore
, save_intr
, save_quit
, save_stop
;
157 ignore
.sa_handler
= SIG_IGN
;
158 sigemptyset (&ignore
.sa_mask
);
161 sigaction (SIGINT
, &ignore
, &save_intr
);
162 sigaction (SIGQUIT
, &ignore
, &save_quit
);
164 /* Restore the original SIGTSTP handler, we don't want ncurses' */
165 /* handler messing the screen after the SIGCONT */
166 sigaction (SIGTSTP
, &startup_handler
, &save_stop
);
171 fprintf (stderr
, "\n\nfork () = -1\n");
176 signal (SIGINT
, SIG_DFL
);
177 signal (SIGQUIT
, SIG_DFL
);
178 signal (SIGTSTP
, SIG_DFL
);
179 signal (SIGCHLD
, SIG_DFL
);
181 if (flags
& EXECUTE_AS_SHELL
)
182 execl (shell
, shell
, "-c", command
, (char *) NULL
);
185 gchar
**shell_tokens
;
186 const gchar
*only_cmd
;
188 shell_tokens
= g_strsplit (shell
, " ", 2);
189 if (shell_tokens
== NULL
)
192 only_cmd
= (*shell_tokens
!= NULL
) ? *shell_tokens
: shell
;
194 execlp (only_cmd
, shell
, command
, (char *) NULL
);
197 execlp will replace current process,
198 therefore no sence in call of g_strfreev().
199 But this keeped for estetic reason :)
201 g_strfreev (shell_tokens
);
205 _exit (127); /* Exec error */
211 if (waitpid (pid
, &status
, 0) > 0)
213 status
= WEXITSTATUS(status
);
223 sigaction (SIGINT
, &save_intr
, NULL
);
224 sigaction (SIGQUIT
, &save_quit
, NULL
);
225 sigaction (SIGTSTP
, &save_stop
, NULL
);
232 * Perform tilde expansion if possible.
233 * Always return a newly allocated string, even if it's unchanged.
236 tilde_expand (const char *directory
)
238 struct passwd
*passwd
;
242 if (*directory
!= '~')
243 return g_strdup (directory
);
247 /* d = "~" or d = "~/" */
248 if (!(*p
) || (*p
== PATH_SEP
))
250 passwd
= getpwuid (geteuid ());
251 q
= (*p
== PATH_SEP
) ? p
+ 1 : "";
255 q
= strchr (p
, PATH_SEP
);
258 passwd
= getpwnam (p
);
262 name
= g_strndup (p
, q
- p
);
263 passwd
= getpwnam (name
);
269 /* If we can't figure the user name, leave tilde unexpanded */
271 return g_strdup (directory
);
273 return g_strconcat (passwd
->pw_dir
, PATH_SEP_STR
, q
, (char *) NULL
);
277 * Return the directory where mc should keep its temporary files.
278 * This directory is (in Bourne shell terms) "${TMPDIR=/tmp}/mc-$USER"
279 * When called the first time, the directory is created if needed.
280 * The first call should be done early, since we are using fprintf()
281 * and not message() to report possible problems.
286 static char buffer
[64];
287 static const char *tmpdir
;
291 const char *error
= NULL
;
293 /* Check if already correctly initialized */
294 if (tmpdir
&& lstat (tmpdir
, &st
) == 0 && S_ISDIR (st
.st_mode
) &&
295 st
.st_uid
== getuid () && (st
.st_mode
& 0777) == 0700)
298 sys_tmp
= getenv ("TMPDIR");
299 if (!sys_tmp
|| sys_tmp
[0] != '/')
301 sys_tmp
= TMPDIR_DEFAULT
;
304 pwd
= getpwuid (getuid ());
307 g_snprintf (buffer
, sizeof (buffer
), "%s/mc-%s", sys_tmp
, pwd
->pw_name
);
309 g_snprintf (buffer
, sizeof (buffer
), "%s/mc-%lu", sys_tmp
, (unsigned long) getuid ());
311 canonicalize_pathname (buffer
);
313 if (lstat (buffer
, &st
) == 0)
315 /* Sanity check for existing directory */
316 if (!S_ISDIR (st
.st_mode
))
317 error
= _("%s is not a directory\n");
318 else if (st
.st_uid
!= getuid ())
319 error
= _("Directory %s is not owned by you\n");
320 else if (((st
.st_mode
& 0777) != 0700) && (chmod (buffer
, 0700) != 0))
321 error
= _("Cannot set correct permissions for directory %s\n");
325 /* Need to create directory */
326 if (mkdir (buffer
, S_IRWXU
) != 0)
329 _("Cannot create temporary directory %s: %s\n"),
330 buffer
, unix_error_string (errno
));
338 char *test_fn
, *fallback_prefix
;
342 fprintf (stderr
, error
, buffer
);
344 /* Test if sys_tmp is suitable for temporary files */
345 fallback_prefix
= g_strdup_printf ("%s/mctest", sys_tmp
);
346 test_fd
= mc_mkstemps (&test_fn
, fallback_prefix
, NULL
);
347 g_free (fallback_prefix
);
351 test_fd
= open (test_fn
, O_RDONLY
);
362 fprintf (stderr
, _("Temporary files will be created in %s\n"), sys_tmp
);
363 g_snprintf (buffer
, sizeof (buffer
), "%s", sys_tmp
);
368 fprintf (stderr
, _("Temporary files will not be created\n"));
369 g_snprintf (buffer
, sizeof (buffer
), "%s", "/dev/null/");
372 fprintf (stderr
, "%s\n", _("Press any key to continue..."));
379 g_setenv ("MC_TMPDIR", tmpdir
, TRUE
);
385 /* Pipes are guaranteed to be able to hold at least 4096 bytes */
386 /* More than that would be unportable */
387 #define MAX_PIPE_SIZE 4096
389 static int error_pipe
[2]; /* File descriptors of error pipe */
390 static int old_error
; /* File descriptor of old standard error */
392 /* Creates a pipe to hold standard error for a later analysis. */
393 /* The pipe can hold 4096 bytes. Make sure no more is written */
394 /* or a deadlock might occur. */
396 open_error_pipe (void)
398 if (pipe (error_pipe
) < 0)
400 message (D_NORMAL
, _("Warning"), _("Pipe failed"));
403 if (old_error
< 0 || close (2) || dup (error_pipe
[1]) != 2)
405 message (D_NORMAL
, _("Warning"), _("Dup failed"));
407 close (error_pipe
[0]);
413 * Settng stderr in nonblocking mode as we close it earlier, than
414 * program stops. We try to read some error at program startup,
415 * but we should not block on it.
417 * TODO: make piped stdin/stderr poll()/select()able to get rid
421 fd_flags
= fcntl (error_pipe
[0], F_GETFL
, NULL
);
424 fd_flags
|= O_NONBLOCK
;
425 if (fcntl (error_pipe
[0], F_SETFL
, fd_flags
) == -1)
427 /* TODO: handle it somehow */
431 /* we never write there */
432 close (error_pipe
[1]);
437 * Returns true if an error was displayed
438 * error: -1 - ignore errors, 0 - display warning, 1 - display error
439 * text is prepended to the error message from the pipe
442 close_error_pipe (int error
, const char *text
)
445 char msg
[MAX_PIPE_SIZE
];
449 if (error_pipe
[0] == -1)
455 title
= _("Warning");
458 if (dup2 (old_error
, 2) == -1)
460 message (error
, MSG_ERROR
, _("Error dup'ing old error pipe"));
464 len
= read (error_pipe
[0], msg
, MAX_PIPE_SIZE
- 1);
468 close (error_pipe
[0]);
472 return 0; /* Just ignore error message */
476 return 0; /* Nothing to show */
478 /* Show message from pipe */
479 message (error
, title
, "%s", msg
);
483 /* Show given text and possible message from pipe */
484 message (error
, title
, "%s\n%s", text
, msg
);
490 * Canonicalize path, and return a new path. Do everything in place.
491 * The new path differs from path in:
492 * Multiple `/'s are collapsed to a single `/'.
493 * Leading `./'s and trailing `/.'s are removed.
494 * Trailing `/'s are removed.
495 * Non-leading `../'s and trailing `..'s are handled by removing
496 * portions of the path.
497 * Well formed UNC paths are modified only in the local part.
500 custom_canonicalize_pathname (char *path
, CANON_PATH_FLAGS flags
)
504 char *lpath
= path
; /* path without leading UNC part */
506 /* Detect and preserve UNC paths: //server/... */
507 if ((flags
& CANON_PATH_GUARDUNC
) && path
[0] == PATH_SEP
&& path
[1] == PATH_SEP
)
510 while (p
[0] && p
[0] != '/')
512 if (p
[0] == '/' && p
> path
+ 2)
516 if (!lpath
[0] || !lpath
[1])
519 if (flags
& CANON_PATH_JOINSLASHES
)
521 /* Collapse multiple slashes */
525 if (p
[0] == PATH_SEP
&& p
[1] == PATH_SEP
)
528 while (*(++s
) == PATH_SEP
);
535 if (flags
& CANON_PATH_JOINSLASHES
)
537 /* Collapse "/./" -> "/" */
541 if (p
[0] == PATH_SEP
&& p
[1] == '.' && p
[2] == PATH_SEP
)
548 if (flags
& CANON_PATH_REMSLASHDOTS
)
550 /* Remove trailing slashes */
551 p
= lpath
+ strlen (lpath
) - 1;
552 while (p
> lpath
&& *p
== PATH_SEP
)
555 /* Remove leading "./" */
556 if (lpath
[0] == '.' && lpath
[1] == PATH_SEP
)
565 str_move (lpath
, lpath
+ 2);
569 /* Remove trailing "/" or "/." */
570 len
= strlen (lpath
);
573 if (lpath
[len
- 1] == PATH_SEP
)
579 if (lpath
[len
- 1] == '.' && lpath
[len
- 2] == PATH_SEP
)
594 if (flags
& CANON_PATH_REMDOUBLEDOTS
)
596 const size_t enc_prefix_len
= strlen (VFS_ENCODING_PREFIX
);
598 /* Collapse "/.." with the previous part of path */
600 while (p
[0] && p
[1] && p
[2])
602 if ((p
[0] != PATH_SEP
|| p
[1] != '.' || p
[2] != '.') || (p
[3] != PATH_SEP
&& p
[3] != 0))
608 /* search for the previous token */
610 while (s
>= lpath
&& *s
!= PATH_SEP
)
615 /* If the previous token is "..", we cannot collapse it */
616 if (s
[0] == '.' && s
[1] == '.' && s
+ 2 == p
)
624 if (s
== lpath
&& *s
== PATH_SEP
)
626 /* "/../foo" -> "/foo" */
627 str_move (s
+ 1, p
+ 4);
631 /* "token/../foo" -> "foo" */
633 if (strncmp (s
, VFS_ENCODING_PREFIX
, enc_prefix_len
) == 0)
634 /* special case: remove encoding */
637 #endif /* HAVE_CHARSET */
640 p
= (s
> lpath
) ? s
- 1 : s
;
647 /* "token/.." -> "." */
648 if (lpath
[0] != PATH_SEP
)
656 /* "foo/token/.." -> "foo" */
660 else if (strncmp (s
, VFS_ENCODING_PREFIX
, enc_prefix_len
) == 0)
662 /* special case: remove encoding */
667 /* search for the previous token */
668 /* s[-1] == PATH_SEP */
670 while (p
>= lpath
&& *p
!= PATH_SEP
)
676 #endif /* HAVE_CHARSET */
688 canonicalize_pathname (char *path
)
690 custom_canonicalize_pathname (path
, CANON_PATH_ALL
);
693 #ifdef HAVE_GET_PROCESS_STATS
694 # include <sys/procstats.h>
697 gettimeofday (struct timeval
*tp
, void *tzp
)
699 return get_process_stats (tp
, PS_SELF
, 0, 0);
701 #endif /* HAVE_GET_PROCESS_STATS */
703 #ifndef HAVE_REALPATH
705 mc_realpath (const char *path
, char *resolved_path
)
707 char copy_path
[PATH_MAX
];
708 char link_path
[PATH_MAX
];
709 char got_path
[PATH_MAX
];
710 char *new_path
= got_path
;
715 /* Make a copy of the source path since we may need to modify it. */
716 if (strlen (path
) >= PATH_MAX
- 2)
718 errno
= ENAMETOOLONG
;
721 strcpy (copy_path
, path
);
723 max_path
= copy_path
+ PATH_MAX
- 2;
724 /* If it's a relative pathname use getwd for starters. */
728 new_path
= g_get_current_dir ();
729 if (new_path
== NULL
)
731 strcpy (got_path
, "");
735 g_snprintf (got_path
, PATH_MAX
, "%s", new_path
);
740 new_path
+= strlen (got_path
);
741 if (new_path
[-1] != '/')
749 /* Expand each slash-separated pathname component. */
750 while (*path
!= '\0')
752 /* Ignore stray "/". */
761 if (path
[1] == '\0' || path
[1] == '/')
768 if (path
[2] == '\0' || path
[2] == '/')
771 /* Ignore ".." at root. */
772 if (new_path
== got_path
+ 1)
774 /* Handle ".." by backing up. */
775 while ((--new_path
)[-1] != '/');
780 /* Safely copy the next pathname component. */
781 while (*path
!= '\0' && *path
!= '/')
785 errno
= ENAMETOOLONG
;
788 *new_path
++ = *path
++;
791 /* Protect against infinite loops. */
792 if (readlinks
++ > MAXSYMLINKS
)
797 /* See if latest pathname component is a symlink. */
799 n
= readlink (got_path
, link_path
, PATH_MAX
- 1);
802 /* EINVAL means the file exists but isn't a symlink. */
805 /* Make sure it's null terminated. */
807 strcpy (resolved_path
, got_path
);
813 /* Note: readlink doesn't add the null byte. */
815 if (*link_path
== '/')
816 /* Start over for an absolute symlink. */
819 /* Otherwise back up over this component. */
820 while (*(--new_path
) != '/');
821 /* Safe sex check. */
822 if (strlen (path
) + n
>= PATH_MAX
- 2)
824 errno
= ENAMETOOLONG
;
827 /* Insert symlink contents into path. */
828 strcat (link_path
, path
);
829 strcpy (copy_path
, link_path
);
835 /* Delete trailing slash but don't whomp a lone slash. */
836 if (new_path
!= got_path
+ 1 && new_path
[-1] == '/')
838 /* Make sure it's null terminated. */
840 strcpy (resolved_path
, got_path
);
841 return resolved_path
;
843 #endif /* HAVE_REALPATH */
845 /* Return the index of the permissions triplet */
847 get_user_permissions (struct stat
*st
)
849 static gboolean initialized
= FALSE
;
850 static gid_t
*groups
;
859 ngroups
= getgroups (0, NULL
);
861 ngroups
= 0; /* ignore errors */
863 /* allocate space for one element in addition to what
864 * will be filled by getgroups(). */
865 groups
= g_new (gid_t
, ngroups
+ 1);
869 ngroups
= getgroups (ngroups
, groups
);
871 ngroups
= 0; /* ignore errors */
874 /* getgroups() may or may not return the effective group ID,
875 * so we always include it at the end of the list. */
876 groups
[ngroups
++] = getegid ();
881 if (st
->st_uid
== uid
|| uid
== 0)
884 for (i
= 0; i
< ngroups
; i
++)
886 if (st
->st_gid
== groups
[i
])