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 "src/execute.h"
53 #include "src/wtools.h" /* message() */
55 struct sigaction startup_handler
;
57 #define UID_CACHE_SIZE 200
58 #define GID_CACHE_SIZE 30
66 static int_cache uid_cache
[UID_CACHE_SIZE
];
67 static int_cache gid_cache
[GID_CACHE_SIZE
];
70 i_cache_match (int id
, int_cache
* cache
, int size
)
74 for (i
= 0; i
< size
; i
++)
75 if (cache
[i
].index
== id
)
76 return cache
[i
].string
;
81 i_cache_add (int id
, int_cache
* cache
, int size
, char *text
, int *last
)
83 g_free (cache
[*last
].string
);
84 cache
[*last
].string
= g_strdup (text
);
85 cache
[*last
].index
= id
;
86 *last
= ((*last
) + 1) % size
;
97 name
= i_cache_match (uid
, uid_cache
, UID_CACHE_SIZE
);
101 pwd
= getpwuid (uid
);
104 i_cache_add (uid
, uid_cache
, UID_CACHE_SIZE
, pwd
->pw_name
, &uid_last
);
109 g_snprintf (ibuf
, sizeof (ibuf
), "%d", uid
);
118 static char gbuf
[10];
122 name
= i_cache_match (gid
, gid_cache
, GID_CACHE_SIZE
);
126 grp
= getgrgid (gid
);
129 i_cache_add (gid
, gid_cache
, GID_CACHE_SIZE
, grp
->gr_name
, &gid_last
);
134 g_snprintf (gbuf
, sizeof (gbuf
), "%d", gid
);
139 /* Since ncurses uses a handler that automatically refreshes the */
140 /* screen after a SIGCONT, and we don't want this behavior when */
141 /* spawning a child, we save the original handler here */
143 save_stop_handler (void)
145 sigaction (SIGTSTP
, NULL
, &startup_handler
);
149 my_system (int flags
, const char *shell
, const char *command
)
151 struct sigaction ignore
, save_intr
, save_quit
, save_stop
;
155 ignore
.sa_handler
= SIG_IGN
;
156 sigemptyset (&ignore
.sa_mask
);
159 sigaction (SIGINT
, &ignore
, &save_intr
);
160 sigaction (SIGQUIT
, &ignore
, &save_quit
);
162 /* Restore the original SIGTSTP handler, we don't want ncurses' */
163 /* handler messing the screen after the SIGCONT */
164 sigaction (SIGTSTP
, &startup_handler
, &save_stop
);
169 fprintf (stderr
, "\n\nfork () = -1\n");
174 signal (SIGINT
, SIG_DFL
);
175 signal (SIGQUIT
, SIG_DFL
);
176 signal (SIGTSTP
, SIG_DFL
);
177 signal (SIGCHLD
, SIG_DFL
);
179 if (flags
& EXECUTE_AS_SHELL
)
180 execl (shell
, shell
, "-c", command
, (char *) NULL
);
183 gchar
**shell_tokens
;
184 const gchar
*only_cmd
;
186 shell_tokens
= g_strsplit (shell
, " ", 2);
187 if (shell_tokens
== NULL
)
190 only_cmd
= (*shell_tokens
!= NULL
) ? *shell_tokens
: shell
;
192 execlp (only_cmd
, shell
, command
, (char *) NULL
);
195 execlp will replace current process,
196 therefore no sence in call of g_strfreev().
197 But this keeped for estetic reason :)
199 g_strfreev (shell_tokens
);
203 _exit (127); /* Exec error */
209 if (waitpid (pid
, &status
, 0) > 0)
211 status
= WEXITSTATUS(status
);
221 sigaction (SIGINT
, &save_intr
, NULL
);
222 sigaction (SIGQUIT
, &save_quit
, NULL
);
223 sigaction (SIGTSTP
, &save_stop
, NULL
);
230 * Perform tilde expansion if possible.
231 * Always return a newly allocated string, even if it's unchanged.
234 tilde_expand (const char *directory
)
236 struct passwd
*passwd
;
240 if (*directory
!= '~')
241 return g_strdup (directory
);
245 /* d = "~" or d = "~/" */
246 if (!(*p
) || (*p
== PATH_SEP
))
248 passwd
= getpwuid (geteuid ());
249 q
= (*p
== PATH_SEP
) ? p
+ 1 : "";
253 q
= strchr (p
, PATH_SEP
);
256 passwd
= getpwnam (p
);
260 name
= g_strndup (p
, q
- p
);
261 passwd
= getpwnam (name
);
267 /* If we can't figure the user name, leave tilde unexpanded */
269 return g_strdup (directory
);
271 return g_strconcat (passwd
->pw_dir
, PATH_SEP_STR
, q
, (char *) NULL
);
275 * Return the directory where mc should keep its temporary files.
276 * This directory is (in Bourne shell terms) "${TMPDIR=/tmp}/mc-$USER"
277 * When called the first time, the directory is created if needed.
278 * The first call should be done early, since we are using fprintf()
279 * and not message() to report possible problems.
284 static char buffer
[64];
285 static const char *tmpdir
;
289 const char *error
= NULL
;
291 /* Check if already correctly initialized */
292 if (tmpdir
&& lstat (tmpdir
, &st
) == 0 && S_ISDIR (st
.st_mode
) &&
293 st
.st_uid
== getuid () && (st
.st_mode
& 0777) == 0700)
296 sys_tmp
= getenv ("TMPDIR");
297 if (!sys_tmp
|| sys_tmp
[0] != '/')
299 sys_tmp
= TMPDIR_DEFAULT
;
302 pwd
= getpwuid (getuid ());
305 g_snprintf (buffer
, sizeof (buffer
), "%s/mc-%s", sys_tmp
, pwd
->pw_name
);
307 g_snprintf (buffer
, sizeof (buffer
), "%s/mc-%lu", sys_tmp
, (unsigned long) getuid ());
309 canonicalize_pathname (buffer
);
311 if (lstat (buffer
, &st
) == 0)
313 /* Sanity check for existing directory */
314 if (!S_ISDIR (st
.st_mode
))
315 error
= _("%s is not a directory\n");
316 else if (st
.st_uid
!= getuid ())
317 error
= _("Directory %s is not owned by you\n");
318 else if (((st
.st_mode
& 0777) != 0700) && (chmod (buffer
, 0700) != 0))
319 error
= _("Cannot set correct permissions for directory %s\n");
323 /* Need to create directory */
324 if (mkdir (buffer
, S_IRWXU
) != 0)
327 _("Cannot create temporary directory %s: %s\n"),
328 buffer
, unix_error_string (errno
));
336 char *test_fn
, *fallback_prefix
;
340 fprintf (stderr
, error
, buffer
);
342 /* Test if sys_tmp is suitable for temporary files */
343 fallback_prefix
= g_strdup_printf ("%s/mctest", sys_tmp
);
344 test_fd
= mc_mkstemps (&test_fn
, fallback_prefix
, NULL
);
345 g_free (fallback_prefix
);
349 test_fd
= open (test_fn
, O_RDONLY
);
360 fprintf (stderr
, _("Temporary files will be created in %s\n"), sys_tmp
);
361 g_snprintf (buffer
, sizeof (buffer
), "%s", sys_tmp
);
366 fprintf (stderr
, _("Temporary files will not be created\n"));
367 g_snprintf (buffer
, sizeof (buffer
), "%s", "/dev/null/");
370 fprintf (stderr
, "%s\n", _("Press any key to continue..."));
377 g_setenv ("MC_TMPDIR", tmpdir
, TRUE
);
383 /* Pipes are guaranteed to be able to hold at least 4096 bytes */
384 /* More than that would be unportable */
385 #define MAX_PIPE_SIZE 4096
387 static int error_pipe
[2]; /* File descriptors of error pipe */
388 static int old_error
; /* File descriptor of old standard error */
390 /* Creates a pipe to hold standard error for a later analysis. */
391 /* The pipe can hold 4096 bytes. Make sure no more is written */
392 /* or a deadlock might occur. */
394 open_error_pipe (void)
396 if (pipe (error_pipe
) < 0)
398 message (D_NORMAL
, _("Warning"), _("Pipe failed"));
401 if (old_error
< 0 || close (2) || dup (error_pipe
[1]) != 2)
403 message (D_NORMAL
, _("Warning"), _("Dup failed"));
405 close (error_pipe
[0]);
411 * Settng stderr in nonblocking mode as we close it earlier, than
412 * program stops. We try to read some error at program startup,
413 * but we should not block on it.
415 * TODO: make piped stdin/stderr poll()/select()able to get rid
419 fd_flags
= fcntl (error_pipe
[0], F_GETFL
, NULL
);
422 fd_flags
|= O_NONBLOCK
;
423 if (fcntl (error_pipe
[0], F_SETFL
, fd_flags
) == -1)
425 /* TODO: handle it somehow */
429 /* we never write there */
430 close (error_pipe
[1]);
435 * Returns true if an error was displayed
436 * error: -1 - ignore errors, 0 - display warning, 1 - display error
437 * text is prepended to the error message from the pipe
440 close_error_pipe (int error
, const char *text
)
443 char msg
[MAX_PIPE_SIZE
];
447 if (error_pipe
[0] == -1)
453 title
= _("Warning");
456 if (dup2 (old_error
, 2) == -1)
458 message (error
, MSG_ERROR
, _("Error dup'ing old error pipe"));
462 len
= read (error_pipe
[0], msg
, MAX_PIPE_SIZE
- 1);
466 close (error_pipe
[0]);
470 return 0; /* Just ignore error message */
474 return 0; /* Nothing to show */
476 /* Show message from pipe */
477 message (error
, title
, "%s", msg
);
481 /* Show given text and possible message from pipe */
482 message (error
, title
, "%s\n%s", text
, msg
);
488 * Canonicalize path, and return a new path. Do everything in place.
489 * The new path differs from path in:
490 * Multiple `/'s are collapsed to a single `/'.
491 * Leading `./'s and trailing `/.'s are removed.
492 * Trailing `/'s are removed.
493 * Non-leading `../'s and trailing `..'s are handled by removing
494 * portions of the path.
495 * Well formed UNC paths are modified only in the local part.
498 custom_canonicalize_pathname (char *path
, CANON_PATH_FLAGS flags
)
502 char *lpath
= path
; /* path without leading UNC part */
504 /* Detect and preserve UNC paths: //server/... */
505 if ((flags
& CANON_PATH_GUARDUNC
) && path
[0] == PATH_SEP
&& path
[1] == PATH_SEP
)
508 while (p
[0] && p
[0] != '/')
510 if (p
[0] == '/' && p
> path
+ 2)
514 if (!lpath
[0] || !lpath
[1])
517 if (flags
& CANON_PATH_JOINSLASHES
)
519 /* Collapse multiple slashes */
523 if (p
[0] == PATH_SEP
&& p
[1] == PATH_SEP
)
526 while (*(++s
) == PATH_SEP
);
533 if (flags
& CANON_PATH_JOINSLASHES
)
535 /* Collapse "/./" -> "/" */
539 if (p
[0] == PATH_SEP
&& p
[1] == '.' && p
[2] == PATH_SEP
)
546 if (flags
& CANON_PATH_REMSLASHDOTS
)
548 /* Remove trailing slashes */
549 p
= lpath
+ strlen (lpath
) - 1;
550 while (p
> lpath
&& *p
== PATH_SEP
)
553 /* Remove leading "./" */
554 if (lpath
[0] == '.' && lpath
[1] == PATH_SEP
)
563 str_move (lpath
, lpath
+ 2);
567 /* Remove trailing "/" or "/." */
568 len
= strlen (lpath
);
571 if (lpath
[len
- 1] == PATH_SEP
)
577 if (lpath
[len
- 1] == '.' && lpath
[len
- 2] == PATH_SEP
)
592 if (flags
& CANON_PATH_REMDOUBLEDOTS
)
594 /* Collapse "/.." with the previous part of path */
596 while (p
[0] && p
[1] && p
[2])
598 if ((p
[0] != PATH_SEP
|| p
[1] != '.' || p
[2] != '.') || (p
[3] != PATH_SEP
&& p
[3] != 0))
604 /* search for the previous token */
606 while (s
>= lpath
&& *s
!= PATH_SEP
)
611 /* If the previous token is "..", we cannot collapse it */
612 if (s
[0] == '.' && s
[1] == '.' && s
+ 2 == p
)
620 if (s
== lpath
&& *s
== PATH_SEP
)
622 /* "/../foo" -> "/foo" */
623 str_move (s
+ 1, p
+ 4);
627 /* "token/../foo" -> "foo" */
630 p
= (s
> lpath
) ? s
- 1 : s
;
637 /* "token/.." -> "." */
638 if (lpath
[0] != PATH_SEP
)
646 /* "foo/token/.." -> "foo" */
660 canonicalize_pathname (char *path
)
662 custom_canonicalize_pathname (path
, CANON_PATH_ALL
);
665 #ifdef HAVE_GET_PROCESS_STATS
666 # include <sys/procstats.h>
669 gettimeofday (struct timeval
*tp
, void *tzp
)
671 return get_process_stats (tp
, PS_SELF
, 0, 0);
673 #endif /* HAVE_GET_PROCESS_STATS */
675 #ifndef HAVE_REALPATH
677 mc_realpath (const char *path
, char *resolved_path
)
679 char copy_path
[PATH_MAX
];
680 char link_path
[PATH_MAX
];
681 char got_path
[PATH_MAX
];
682 char *new_path
= got_path
;
687 /* Make a copy of the source path since we may need to modify it. */
688 if (strlen (path
) >= PATH_MAX
- 2)
690 errno
= ENAMETOOLONG
;
693 strcpy (copy_path
, path
);
695 max_path
= copy_path
+ PATH_MAX
- 2;
696 /* If it's a relative pathname use getwd for starters. */
700 new_path
= g_get_current_dir ();
701 if (new_path
== NULL
)
703 strcpy (got_path
, "");
707 g_snprintf (got_path
, PATH_MAX
, "%s", new_path
);
712 new_path
+= strlen (got_path
);
713 if (new_path
[-1] != '/')
721 /* Expand each slash-separated pathname component. */
722 while (*path
!= '\0')
724 /* Ignore stray "/". */
733 if (path
[1] == '\0' || path
[1] == '/')
740 if (path
[2] == '\0' || path
[2] == '/')
743 /* Ignore ".." at root. */
744 if (new_path
== got_path
+ 1)
746 /* Handle ".." by backing up. */
747 while ((--new_path
)[-1] != '/');
752 /* Safely copy the next pathname component. */
753 while (*path
!= '\0' && *path
!= '/')
757 errno
= ENAMETOOLONG
;
760 *new_path
++ = *path
++;
763 /* Protect against infinite loops. */
764 if (readlinks
++ > MAXSYMLINKS
)
769 /* See if latest pathname component is a symlink. */
771 n
= readlink (got_path
, link_path
, PATH_MAX
- 1);
774 /* EINVAL means the file exists but isn't a symlink. */
777 /* Make sure it's null terminated. */
779 strcpy (resolved_path
, got_path
);
785 /* Note: readlink doesn't add the null byte. */
787 if (*link_path
== '/')
788 /* Start over for an absolute symlink. */
791 /* Otherwise back up over this component. */
792 while (*(--new_path
) != '/');
793 /* Safe sex check. */
794 if (strlen (path
) + n
>= PATH_MAX
- 2)
796 errno
= ENAMETOOLONG
;
799 /* Insert symlink contents into path. */
800 strcat (link_path
, path
);
801 strcpy (copy_path
, link_path
);
807 /* Delete trailing slash but don't whomp a lone slash. */
808 if (new_path
!= got_path
+ 1 && new_path
[-1] == '/')
810 /* Make sure it's null terminated. */
812 strcpy (resolved_path
, got_path
);
813 return resolved_path
;
815 #endif /* HAVE_REALPATH */
817 /* Return the index of the permissions triplet */
819 get_user_permissions (struct stat
*st
)
821 static gboolean initialized
= FALSE
;
822 static gid_t
*groups
;
831 ngroups
= getgroups (0, NULL
);
833 ngroups
= 0; /* ignore errors */
835 /* allocate space for one element in addition to what
836 * will be filled by getgroups(). */
837 groups
= g_new (gid_t
, ngroups
+ 1);
841 ngroups
= getgroups (ngroups
, groups
);
843 ngroups
= 0; /* ignore errors */
846 /* getgroups() may or may not return the effective group ID,
847 * so we always include it at the end of the list. */
848 groups
[ngroups
++] = getegid ();
853 if (st
->st_uid
== uid
|| uid
== 0)
856 for (i
= 0; i
< ngroups
; i
++)
858 if (st
->st_gid
== groups
[i
])