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. */
36 #include <sys/param.h>
37 #include <sys/types.h>
39 #ifdef HAVE_SYS_IOCTL_H
40 # include <sys/ioctl.h>
46 #include "wtools.h" /* message() */
48 struct sigaction startup_handler
;
50 #define UID_CACHE_SIZE 200
51 #define GID_CACHE_SIZE 30
58 static int_cache uid_cache
[UID_CACHE_SIZE
];
59 static int_cache gid_cache
[GID_CACHE_SIZE
];
61 static char *i_cache_match (int id
, int_cache
*cache
, int size
)
65 for (i
= 0; i
< size
; i
++)
66 if (cache
[i
].index
== id
)
67 return cache
[i
].string
;
71 static void i_cache_add (int id
, int_cache
*cache
, int size
, char *text
,
74 g_free (cache
[*last
].string
);
75 cache
[*last
].string
= g_strdup (text
);
76 cache
[*last
].index
= id
;
77 *last
= ((*last
)+1) % size
;
80 char *get_owner (int uid
)
83 static char ibuf
[10];
87 if ((name
= i_cache_match (uid
, uid_cache
, UID_CACHE_SIZE
)) != NULL
)
92 i_cache_add (uid
, uid_cache
, UID_CACHE_SIZE
, pwd
->pw_name
, &uid_last
);
96 g_snprintf (ibuf
, sizeof (ibuf
), "%d", uid
);
101 char *get_group (int gid
)
104 static char gbuf
[10];
108 if ((name
= i_cache_match (gid
, gid_cache
, GID_CACHE_SIZE
)) != NULL
)
111 grp
= getgrgid (gid
);
113 i_cache_add (gid
, gid_cache
, GID_CACHE_SIZE
, grp
->gr_name
, &gid_last
);
116 g_snprintf (gbuf
, sizeof (gbuf
), "%d", gid
);
121 /* Since ncurses uses a handler that automatically refreshes the */
122 /* screen after a SIGCONT, and we don't want this behavior when */
123 /* spawning a child, we save the original handler here */
124 void save_stop_handler (void)
126 sigaction (SIGTSTP
, NULL
, &startup_handler
);
129 int my_system (int flags
, const char *shell
, const char *command
)
131 struct sigaction ignore
, save_intr
, save_quit
, save_stop
;
135 ignore
.sa_handler
= SIG_IGN
;
136 sigemptyset (&ignore
.sa_mask
);
139 sigaction (SIGINT
, &ignore
, &save_intr
);
140 sigaction (SIGQUIT
, &ignore
, &save_quit
);
142 /* Restore the original SIGTSTP handler, we don't want ncurses' */
143 /* handler messing the screen after the SIGCONT */
144 sigaction (SIGTSTP
, &startup_handler
, &save_stop
);
146 if ((pid
= fork ()) < 0){
147 fprintf (stderr
, "\n\nfork () = -1\n");
151 signal (SIGINT
, SIG_DFL
);
152 signal (SIGQUIT
, SIG_DFL
);
153 signal (SIGTSTP
, SIG_DFL
);
154 signal (SIGCHLD
, SIG_DFL
);
156 if (flags
& EXECUTE_AS_SHELL
)
157 execl (shell
, shell
, "-c", command
, (char *) NULL
);
159 execlp (shell
, shell
, command
, (char *) NULL
);
161 _exit (127); /* Exec error */
163 while (waitpid (pid
, &status
, 0) < 0)
169 sigaction (SIGINT
, &save_intr
, NULL
);
170 sigaction (SIGQUIT
, &save_quit
, NULL
);
171 sigaction (SIGTSTP
, &save_stop
, NULL
);
173 return WEXITSTATUS(status
);
178 * Perform tilde expansion if possible.
179 * Always return a newly allocated string, even if it's unchanged.
182 tilde_expand (const char *directory
)
184 struct passwd
*passwd
;
188 if (*directory
!= '~')
189 return g_strdup (directory
);
193 /* d = "~" or d = "~/" */
194 if (!(*p
) || (*p
== PATH_SEP
)) {
195 passwd
= getpwuid (geteuid ());
196 q
= (*p
== PATH_SEP
) ? p
+ 1 : "";
198 q
= strchr (p
, PATH_SEP
);
200 passwd
= getpwnam (p
);
202 name
= g_strndup (p
, q
- p
);
203 passwd
= getpwnam (name
);
209 /* If we can't figure the user name, leave tilde unexpanded */
211 return g_strdup (directory
);
213 return g_strconcat (passwd
->pw_dir
, PATH_SEP_STR
, q
, (char *) NULL
);
217 mc_setenv (const char *name
, const char *value
, int overwrite_flag
)
219 #if defined(HAVE_SETENV)
220 setenv (name
, value
, overwrite_flag
);
222 if (overwrite_flag
|| getenv (name
) == NULL
)
223 putenv (g_strconcat (name
, "=", value
, (char *) NULL
));
228 * Return the directory where mc should keep its temporary files.
229 * This directory is (in Bourne shell terms) "${TMPDIR=/tmp}/mc-$USER"
230 * When called the first time, the directory is created if needed.
231 * The first call should be done early, since we are using fprintf()
232 * and not message() to report possible problems.
237 static char buffer
[64];
238 static const char *tmpdir
;
242 const char *error
= NULL
;
244 /* Check if already correctly initialized */
245 if (tmpdir
&& lstat (tmpdir
, &st
) == 0 && S_ISDIR (st
.st_mode
) &&
246 st
.st_uid
== getuid () && (st
.st_mode
& 0777) == 0700)
249 sys_tmp
= getenv ("TMPDIR");
250 if (!sys_tmp
|| sys_tmp
[0] != '/') {
251 sys_tmp
= TMPDIR_DEFAULT
;
254 pwd
= getpwuid (getuid ());
257 g_snprintf (buffer
, sizeof (buffer
), "%s/mc-%s", sys_tmp
,
260 g_snprintf (buffer
, sizeof (buffer
), "%s/mc-%lu", sys_tmp
,
261 (unsigned long) getuid ());
263 canonicalize_pathname (buffer
);
265 if (lstat (buffer
, &st
) == 0) {
266 /* Sanity check for existing directory */
267 if (!S_ISDIR (st
.st_mode
))
268 error
= _("%s is not a directory\n");
269 else if (st
.st_uid
!= getuid ())
270 error
= _("Directory %s is not owned by you\n");
271 else if (((st
.st_mode
& 0777) != 0700)
272 && (chmod (buffer
, 0700) != 0))
273 error
= _("Cannot set correct permissions for directory %s\n");
275 /* Need to create directory */
276 if (mkdir (buffer
, S_IRWXU
) != 0) {
278 _("Cannot create temporary directory %s: %s\n"),
279 buffer
, unix_error_string (errno
));
286 char *test_fn
, *fallback_prefix
;
290 fprintf (stderr
, error
, buffer
);
292 /* Test if sys_tmp is suitable for temporary files */
293 fallback_prefix
= g_strdup_printf ("%s/mctest", sys_tmp
);
294 test_fd
= mc_mkstemps (&test_fn
, fallback_prefix
, NULL
);
295 g_free (fallback_prefix
);
298 test_fd
= open (test_fn
, O_RDONLY
);
307 fprintf (stderr
, _("Temporary files will be created in %s\n"),
309 g_snprintf (buffer
, sizeof (buffer
), "%s", sys_tmp
);
312 fprintf (stderr
, _("Temporary files will not be created\n"));
313 g_snprintf (buffer
, sizeof (buffer
), "%s", "/dev/null/");
316 fprintf (stderr
, "%s\n", _("Press any key to continue..."));
323 mc_setenv ("MC_TMPDIR", tmpdir
, 1);
329 /* Pipes are guaranteed to be able to hold at least 4096 bytes */
330 /* More than that would be unportable */
331 #define MAX_PIPE_SIZE 4096
333 static int error_pipe
[2]; /* File descriptors of error pipe */
334 static int old_error
; /* File descriptor of old standard error */
336 /* Creates a pipe to hold standard error for a later analysis. */
337 /* The pipe can hold 4096 bytes. Make sure no more is written */
338 /* or a deadlock might occur. */
339 void open_error_pipe (void)
341 if (pipe (error_pipe
) < 0){
342 message (0, _("Warning"), _(" Pipe failed "));
345 if(old_error
< 0 || close(2) || dup (error_pipe
[1]) != 2){
346 message (0, _("Warning"), _(" Dup failed "));
347 close (error_pipe
[0]);
348 close (error_pipe
[1]);
350 close (error_pipe
[1]);
354 * Returns true if an error was displayed
355 * error: -1 - ignore errors, 0 - display warning, 1 - display error
356 * text is prepended to the error message from the pipe
359 close_error_pipe (int error
, const char *text
)
362 char msg
[MAX_PIPE_SIZE
];
368 title
= _("Warning");
373 len
= read (error_pipe
[0], msg
, MAX_PIPE_SIZE
- 1);
377 close (error_pipe
[0]);
380 return 0; /* Just ignore error message */
383 return 0; /* Nothing to show */
385 /* Show message from pipe */
386 message (error
, title
, "%s", msg
);
388 /* Show given text and possible message from pipe */
389 message (error
, title
, " %s \n %s ", text
, msg
);
395 * Canonicalize path, and return a new path. Do everything in place.
396 * The new path differs from path in:
397 * Multiple `/'s are collapsed to a single `/'.
398 * Leading `./'s and trailing `/.'s are removed.
399 * Trailing `/'s are removed.
400 * Non-leading `../'s and trailing `..'s are handled by removing
401 * portions of the path.
402 * Well formed UNC paths are modified only in the local part.
405 canonicalize_pathname (char *path
)
409 char *lpath
= path
; /* path without leading UNC part */
411 /* Detect and preserve UNC paths: //server/... */
412 if (path
[0] == PATH_SEP
&& path
[1] == PATH_SEP
) {
414 while (p
[0] && p
[0] != '/')
416 if (p
[0] == '/' && p
> path
+ 2)
420 if (!lpath
[0] || !lpath
[1])
423 /* Collapse multiple slashes */
426 if (p
[0] == PATH_SEP
&& p
[1] == PATH_SEP
) {
428 while (*(++s
) == PATH_SEP
);
434 /* Collapse "/./" -> "/" */
437 if (p
[0] == PATH_SEP
&& p
[1] == '.' && p
[2] == PATH_SEP
)
443 /* Remove trailing slashes */
444 p
= lpath
+ strlen (lpath
) - 1;
445 while (p
> lpath
&& *p
== PATH_SEP
)
448 /* Remove leading "./" */
449 if (lpath
[0] == '.' && lpath
[1] == PATH_SEP
) {
454 str_move (lpath
, lpath
+ 2);
458 /* Remove trailing "/" or "/." */
459 len
= strlen (lpath
);
462 if (lpath
[len
- 1] == PATH_SEP
) {
465 if (lpath
[len
- 1] == '.' && lpath
[len
- 2] == PATH_SEP
) {
475 /* Collapse "/.." with the previous part of path */
477 while (p
[0] && p
[1] && p
[2]) {
478 if ((p
[0] != PATH_SEP
|| p
[1] != '.' || p
[2] != '.')
479 || (p
[3] != PATH_SEP
&& p
[3] != 0)) {
484 /* search for the previous token */
486 while (s
>= lpath
&& *s
!= PATH_SEP
)
491 /* If the previous token is "..", we cannot collapse it */
492 if (s
[0] == '.' && s
[1] == '.' && s
+ 2 == p
) {
498 if (s
== lpath
&& *s
== PATH_SEP
) {
499 /* "/../foo" -> "/foo" */
500 str_move (s
+ 1, p
+ 4);
502 /* "token/../foo" -> "foo" */
505 p
= (s
> lpath
) ? s
- 1 : s
;
511 /* "token/.." -> "." */
512 if (lpath
[0] != PATH_SEP
) {
517 /* "foo/token/.." -> "foo" */
529 #ifdef HAVE_GET_PROCESS_STATS
530 # include <sys/procstats.h>
532 int gettimeofday (struct timeval
*tp
, void *tzp
)
534 return get_process_stats(tp
, PS_SELF
, 0, 0);
536 #endif /* HAVE_GET_PROCESS_STATS */
540 /* The following piece of code was copied from the GNU C Library */
541 /* And is provided here for nextstep who lacks putenv */
543 extern char **environ
;
546 #define __environ environ
550 /* Put STRING, which is of the form "NAME=VALUE", in the environment. */
552 putenv (char *string
)
554 const char *const name_end
= strchr (string
, '=');
555 register size_t size
;
558 if (name_end
== NULL
){
559 /* Remove the variable from the environment. */
560 size
= strlen (string
);
561 for (ep
= __environ
; *ep
!= NULL
; ++ep
)
562 if (!strncmp (*ep
, string
, size
) && (*ep
)[size
] == '='){
563 while (ep
[1] != NULL
){
573 for (ep
= __environ
; *ep
!= NULL
; ++ep
)
574 if (!strncmp (*ep
, string
, name_end
- string
) &&
575 (*ep
)[name_end
- string
] == '=')
581 static char **last_environ
= NULL
;
582 char **new_environ
= g_new (char *, size
+ 2);
583 if (new_environ
== NULL
)
585 (void) memcpy ((void *) new_environ
, (void *) __environ
,
586 size
* sizeof (char *));
587 new_environ
[size
] = (char *) string
;
588 new_environ
[size
+ 1] = NULL
;
589 g_free ((void *) last_environ
);
590 last_environ
= new_environ
;
591 __environ
= new_environ
;
594 *ep
= (char *) string
;
598 #endif /* !HAVE_PUTENV */
601 mc_realpath (const char *path
, char resolved_path
[])
603 #ifdef USE_SYSTEM_REALPATH
604 return realpath (path
, resolved_path
);
606 char copy_path
[PATH_MAX
];
607 char link_path
[PATH_MAX
];
608 char got_path
[PATH_MAX
];
609 char *new_path
= got_path
;
614 /* Make a copy of the source path since we may need to modify it. */
615 if (strlen (path
) >= PATH_MAX
- 2) {
616 errno
= ENAMETOOLONG
;
619 strcpy (copy_path
, path
);
621 max_path
= copy_path
+ PATH_MAX
- 2;
622 /* If it's a relative pathname use getwd for starters. */
626 getcwd (new_path
, PATH_MAX
- 1);
630 new_path
+= strlen (new_path
);
631 if (new_path
[-1] != '/')
637 /* Expand each slash-separated pathname component. */
638 while (*path
!= '\0') {
639 /* Ignore stray "/". */
646 if (path
[1] == '\0' || path
[1] == '/') {
650 if (path
[1] == '.') {
651 if (path
[2] == '\0' || path
[2] == '/') {
653 /* Ignore ".." at root. */
654 if (new_path
== got_path
+ 1)
656 /* Handle ".." by backing up. */
657 while ((--new_path
)[-1] != '/');
662 /* Safely copy the next pathname component. */
663 while (*path
!= '\0' && *path
!= '/') {
664 if (path
> max_path
) {
665 errno
= ENAMETOOLONG
;
668 *new_path
++ = *path
++;
671 /* Protect against infinite loops. */
672 if (readlinks
++ > MAXSYMLINKS
) {
676 /* See if latest pathname component is a symlink. */
678 n
= readlink (got_path
, link_path
, PATH_MAX
- 1);
680 /* EINVAL means the file exists but isn't a symlink. */
681 if (errno
!= EINVAL
) {
682 /* Make sure it's null terminated. */
684 strcpy (resolved_path
, got_path
);
688 /* Note: readlink doesn't add the null byte. */
690 if (*link_path
== '/')
691 /* Start over for an absolute symlink. */
694 /* Otherwise back up over this component. */
695 while (*(--new_path
) != '/');
696 /* Safe sex check. */
697 if (strlen (path
) + n
>= PATH_MAX
- 2) {
698 errno
= ENAMETOOLONG
;
701 /* Insert symlink contents into path. */
702 strcat (link_path
, path
);
703 strcpy (copy_path
, link_path
);
709 /* Delete trailing slash but don't whomp a lone slash. */
710 if (new_path
!= got_path
+ 1 && new_path
[-1] == '/')
712 /* Make sure it's null terminated. */
714 strcpy (resolved_path
, got_path
);
715 return resolved_path
;
716 #endif /* USE_SYSTEM_REALPATH */
719 /* Return the index of the permissions triplet */
721 get_user_permissions (struct stat
*st
) {
722 static gboolean initialized
= FALSE
;
723 static gid_t
*groups
;
731 ngroups
= getgroups (0, NULL
);
733 ngroups
= 0; /* ignore errors */
735 /* allocate space for one element in addition to what
736 * will be filled by getgroups(). */
737 groups
= g_new (gid_t
, ngroups
+ 1);
740 ngroups
= getgroups (ngroups
, groups
);
742 ngroups
= 0; /* ignore errors */
745 /* getgroups() may or may not return the effective group ID,
746 * so we always include it at the end of the list. */
747 groups
[ngroups
++] = getegid ();
752 if (st
->st_uid
== uid
|| uid
== 0)
755 for (i
= 0; i
< ngroups
; i
++) {
756 if (st
->st_gid
== groups
[i
])