Check whether VFS provides an open_archive() method.
[midnight-commander.git] / lib / utilunix.c
blob354a9b3b73a2a5d36810cb59c2d16ad3f7e914e3
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() */
60 #ifdef HAVE_CHARSET
61 #include "lib/charsets.h"
62 #endif
64 #include "utilunix.h"
66 /*** global variables ****************************************************************************/
68 struct sigaction startup_handler;
70 /*** file scope macro definitions ****************************************************************/
72 #define UID_CACHE_SIZE 200
73 #define GID_CACHE_SIZE 30
75 /* Pipes are guaranteed to be able to hold at least 4096 bytes */
76 /* More than that would be unportable */
77 #define MAX_PIPE_SIZE 4096
79 /*** file scope type declarations ****************************************************************/
81 typedef struct
83 int index;
84 char *string;
85 } int_cache;
87 /*** file scope variables ************************************************************************/
89 static int_cache uid_cache[UID_CACHE_SIZE];
90 static int_cache gid_cache[GID_CACHE_SIZE];
92 static int error_pipe[2]; /* File descriptors of error pipe */
93 static int old_error; /* File descriptor of old standard error */
95 /*** file scope functions ************************************************************************/
96 /* --------------------------------------------------------------------------------------------- */
98 static char *
99 i_cache_match (int id, int_cache * cache, int size)
101 int i;
103 for (i = 0; i < size; i++)
104 if (cache[i].index == id)
105 return cache[i].string;
106 return 0;
109 /* --------------------------------------------------------------------------------------------- */
111 static void
112 i_cache_add (int id, int_cache * cache, int size, char *text, int *last)
114 g_free (cache[*last].string);
115 cache[*last].string = g_strdup (text);
116 cache[*last].index = id;
117 *last = ((*last) + 1) % size;
120 /* --------------------------------------------------------------------------------------------- */
121 /*** public functions ****************************************************************************/
122 /* --------------------------------------------------------------------------------------------- */
124 char *
125 get_owner (int uid)
127 struct passwd *pwd;
128 static char ibuf[10];
129 char *name;
130 static int uid_last;
132 name = i_cache_match (uid, uid_cache, UID_CACHE_SIZE);
133 if (name != NULL)
134 return name;
136 pwd = getpwuid (uid);
137 if (pwd != NULL)
139 i_cache_add (uid, uid_cache, UID_CACHE_SIZE, pwd->pw_name, &uid_last);
140 return pwd->pw_name;
142 else
144 g_snprintf (ibuf, sizeof (ibuf), "%d", uid);
145 return ibuf;
149 /* --------------------------------------------------------------------------------------------- */
151 char *
152 get_group (int gid)
154 struct group *grp;
155 static char gbuf[10];
156 char *name;
157 static int gid_last;
159 name = i_cache_match (gid, gid_cache, GID_CACHE_SIZE);
160 if (name != NULL)
161 return name;
163 grp = getgrgid (gid);
164 if (grp != NULL)
166 i_cache_add (gid, gid_cache, GID_CACHE_SIZE, grp->gr_name, &gid_last);
167 return grp->gr_name;
169 else
171 g_snprintf (gbuf, sizeof (gbuf), "%d", gid);
172 return gbuf;
176 /* --------------------------------------------------------------------------------------------- */
177 /* Since ncurses uses a handler that automatically refreshes the */
178 /* screen after a SIGCONT, and we don't want this behavior when */
179 /* spawning a child, we save the original handler here */
181 void
182 save_stop_handler (void)
184 sigaction (SIGTSTP, NULL, &startup_handler);
187 /* --------------------------------------------------------------------------------------------- */
190 my_system (int flags, const char *shell, const char *command)
192 struct sigaction ignore, save_intr, save_quit, save_stop;
193 pid_t pid;
194 int status = 0;
196 ignore.sa_handler = SIG_IGN;
197 sigemptyset (&ignore.sa_mask);
198 ignore.sa_flags = 0;
200 sigaction (SIGINT, &ignore, &save_intr);
201 sigaction (SIGQUIT, &ignore, &save_quit);
203 /* Restore the original SIGTSTP handler, we don't want ncurses' */
204 /* handler messing the screen after the SIGCONT */
205 sigaction (SIGTSTP, &startup_handler, &save_stop);
207 pid = fork ();
208 if (pid < 0)
210 fprintf (stderr, "\n\nfork () = -1\n");
211 status = -1;
213 else if (pid == 0)
215 signal (SIGINT, SIG_DFL);
216 signal (SIGQUIT, SIG_DFL);
217 signal (SIGTSTP, SIG_DFL);
218 signal (SIGCHLD, SIG_DFL);
220 if (flags & EXECUTE_AS_SHELL)
221 execl (shell, shell, "-c", command, (char *) NULL);
222 else
224 gchar **shell_tokens;
225 const gchar *only_cmd;
227 shell_tokens = g_strsplit (shell, " ", 2);
228 if (shell_tokens == NULL)
229 only_cmd = shell;
230 else
231 only_cmd = (*shell_tokens != NULL) ? *shell_tokens : shell;
233 execlp (only_cmd, shell, command, (char *) NULL);
236 execlp will replace current process,
237 therefore no sence in call of g_strfreev().
238 But this keeped for estetic reason :)
240 g_strfreev (shell_tokens);
244 _exit (127); /* Exec error */
246 else
248 while (TRUE)
250 if (waitpid (pid, &status, 0) > 0)
252 status = WEXITSTATUS (status);
253 break;
255 if (errno != EINTR)
257 status = -1;
258 break;
262 sigaction (SIGINT, &save_intr, NULL);
263 sigaction (SIGQUIT, &save_quit, NULL);
264 sigaction (SIGTSTP, &save_stop, NULL);
266 return status;
270 /* --------------------------------------------------------------------------------------------- */
272 * Perform tilde expansion if possible.
273 * Always return a newly allocated string, even if it's unchanged.
276 char *
277 tilde_expand (const char *directory)
279 struct passwd *passwd;
280 const char *p, *q;
281 char *name;
283 if (*directory != '~')
284 return g_strdup (directory);
286 p = directory + 1;
288 /* d = "~" or d = "~/" */
289 if (!(*p) || (*p == PATH_SEP))
291 passwd = getpwuid (geteuid ());
292 q = (*p == PATH_SEP) ? p + 1 : "";
294 else
296 q = strchr (p, PATH_SEP);
297 if (!q)
299 passwd = getpwnam (p);
301 else
303 name = g_strndup (p, q - p);
304 passwd = getpwnam (name);
305 q++;
306 g_free (name);
310 /* If we can't figure the user name, leave tilde unexpanded */
311 if (!passwd)
312 return g_strdup (directory);
314 return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
317 /* --------------------------------------------------------------------------------------------- */
319 * Return the directory where mc should keep its temporary files.
320 * This directory is (in Bourne shell terms) "${TMPDIR=/tmp}/mc-$USER"
321 * When called the first time, the directory is created if needed.
322 * The first call should be done early, since we are using fprintf()
323 * and not message() to report possible problems.
326 const char *
327 mc_tmpdir (void)
329 static char buffer[64];
330 static const char *tmpdir;
331 const char *sys_tmp;
332 struct passwd *pwd;
333 struct stat st;
334 const char *error = NULL;
336 /* Check if already correctly initialized */
337 if (tmpdir && lstat (tmpdir, &st) == 0 && S_ISDIR (st.st_mode) &&
338 st.st_uid == getuid () && (st.st_mode & 0777) == 0700)
339 return tmpdir;
341 sys_tmp = getenv ("TMPDIR");
342 if (!sys_tmp || sys_tmp[0] != '/')
344 sys_tmp = TMPDIR_DEFAULT;
347 pwd = getpwuid (getuid ());
349 if (pwd)
350 g_snprintf (buffer, sizeof (buffer), "%s/mc-%s", sys_tmp, pwd->pw_name);
351 else
352 g_snprintf (buffer, sizeof (buffer), "%s/mc-%lu", sys_tmp, (unsigned long) getuid ());
354 canonicalize_pathname (buffer);
356 if (lstat (buffer, &st) == 0)
358 /* Sanity check for existing directory */
359 if (!S_ISDIR (st.st_mode))
360 error = _("%s is not a directory\n");
361 else if (st.st_uid != getuid ())
362 error = _("Directory %s is not owned by you\n");
363 else if (((st.st_mode & 0777) != 0700) && (chmod (buffer, 0700) != 0))
364 error = _("Cannot set correct permissions for directory %s\n");
366 else
368 /* Need to create directory */
369 if (mkdir (buffer, S_IRWXU) != 0)
371 fprintf (stderr,
372 _("Cannot create temporary directory %s: %s\n"),
373 buffer, unix_error_string (errno));
374 error = "";
378 if (error != NULL)
380 int test_fd;
381 char *test_fn, *fallback_prefix;
382 int fallback_ok = 0;
384 if (*error)
385 fprintf (stderr, error, buffer);
387 /* Test if sys_tmp is suitable for temporary files */
388 fallback_prefix = g_strdup_printf ("%s/mctest", sys_tmp);
389 test_fd = mc_mkstemps (&test_fn, fallback_prefix, NULL);
390 g_free (fallback_prefix);
391 if (test_fd != -1)
393 close (test_fd);
394 test_fd = open (test_fn, O_RDONLY);
395 if (test_fd != -1)
397 close (test_fd);
398 unlink (test_fn);
399 fallback_ok = 1;
403 if (fallback_ok)
405 fprintf (stderr, _("Temporary files will be created in %s\n"), sys_tmp);
406 g_snprintf (buffer, sizeof (buffer), "%s", sys_tmp);
407 error = NULL;
409 else
411 fprintf (stderr, _("Temporary files will not be created\n"));
412 g_snprintf (buffer, sizeof (buffer), "%s", "/dev/null/");
415 fprintf (stderr, "%s\n", _("Press any key to continue..."));
416 getc (stdin);
419 tmpdir = buffer;
421 if (!error)
422 g_setenv ("MC_TMPDIR", tmpdir, TRUE);
424 return tmpdir;
427 /* --------------------------------------------------------------------------------------------- */
429 * Creates a pipe to hold standard error for a later analysis.
430 * The pipe can hold 4096 bytes. Make sure no more is written
431 * or a deadlock might occur.
434 void
435 open_error_pipe (void)
437 if (pipe (error_pipe) < 0)
439 message (D_NORMAL, _("Warning"), _("Pipe failed"));
441 old_error = dup (2);
442 if (old_error < 0 || close (2) || dup (error_pipe[1]) != 2)
444 message (D_NORMAL, _("Warning"), _("Dup failed"));
446 close (error_pipe[0]);
447 error_pipe[0] = -1;
449 else
452 * Settng stderr in nonblocking mode as we close it earlier, than
453 * program stops. We try to read some error at program startup,
454 * but we should not block on it.
456 * TODO: make piped stdin/stderr poll()/select()able to get rid
457 * of following hack.
459 int fd_flags;
460 fd_flags = fcntl (error_pipe[0], F_GETFL, NULL);
461 if (fd_flags != -1)
463 fd_flags |= O_NONBLOCK;
464 if (fcntl (error_pipe[0], F_SETFL, fd_flags) == -1)
466 /* TODO: handle it somehow */
470 /* we never write there */
471 close (error_pipe[1]);
472 error_pipe[1] = -1;
475 /* --------------------------------------------------------------------------------------------- */
477 * Returns true if an error was displayed
478 * error: -1 - ignore errors, 0 - display warning, 1 - display error
479 * text is prepended to the error message from the pipe
483 close_error_pipe (int error, const char *text)
485 const char *title;
486 char msg[MAX_PIPE_SIZE];
487 int len = 0;
489 /* already closed */
490 if (error_pipe[0] == -1)
491 return 0;
493 if (error)
494 title = MSG_ERROR;
495 else
496 title = _("Warning");
497 if (old_error >= 0)
499 if (dup2 (old_error, 2) == -1)
501 message (error, MSG_ERROR, _("Error dup'ing old error pipe"));
502 return 1;
504 close (old_error);
505 len = read (error_pipe[0], msg, MAX_PIPE_SIZE - 1);
507 if (len >= 0)
508 msg[len] = 0;
509 close (error_pipe[0]);
510 error_pipe[0] = -1;
512 if (error < 0)
513 return 0; /* Just ignore error message */
514 if (text == NULL)
516 if (len <= 0)
517 return 0; /* Nothing to show */
519 /* Show message from pipe */
520 message (error, title, "%s", msg);
522 else
524 /* Show given text and possible message from pipe */
525 message (error, title, "%s\n%s", text, msg);
527 return 1;
530 /* --------------------------------------------------------------------------------------------- */
532 * Canonicalize path, and return a new path. Do everything in place.
533 * The new path differs from path in:
534 * Multiple `/'s are collapsed to a single `/'.
535 * Leading `./'s and trailing `/.'s are removed.
536 * Trailing `/'s are removed.
537 * Non-leading `../'s and trailing `..'s are handled by removing
538 * portions of the path.
539 * Well formed UNC paths are modified only in the local part.
542 void
543 custom_canonicalize_pathname (char *path, CANON_PATH_FLAGS flags)
545 char *p, *s;
546 int len;
547 char *lpath = path; /* path without leading UNC part */
549 /* Detect and preserve UNC paths: //server/... */
550 if ((flags & CANON_PATH_GUARDUNC) && path[0] == PATH_SEP && path[1] == PATH_SEP)
552 p = path + 2;
553 while (p[0] && p[0] != '/')
554 p++;
555 if (p[0] == '/' && p > path + 2)
556 lpath = p;
559 if (!lpath[0] || !lpath[1])
560 return;
562 if (flags & CANON_PATH_JOINSLASHES)
564 /* Collapse multiple slashes */
565 p = lpath;
566 while (*p)
568 if (p[0] == PATH_SEP && p[1] == PATH_SEP)
570 s = p + 1;
571 while (*(++s) == PATH_SEP);
572 str_move (p + 1, s);
574 p++;
578 if (flags & CANON_PATH_JOINSLASHES)
580 /* Collapse "/./" -> "/" */
581 p = lpath;
582 while (*p)
584 if (p[0] == PATH_SEP && p[1] == '.' && p[2] == PATH_SEP)
585 str_move (p, p + 2);
586 else
587 p++;
591 if (flags & CANON_PATH_REMSLASHDOTS)
593 /* Remove trailing slashes */
594 p = lpath + strlen (lpath) - 1;
595 while (p > lpath && *p == PATH_SEP)
596 *p-- = 0;
598 /* Remove leading "./" */
599 if (lpath[0] == '.' && lpath[1] == PATH_SEP)
601 if (lpath[2] == 0)
603 lpath[1] = 0;
604 return;
606 else
608 str_move (lpath, lpath + 2);
612 /* Remove trailing "/" or "/." */
613 len = strlen (lpath);
614 if (len < 2)
615 return;
616 if (lpath[len - 1] == PATH_SEP)
618 lpath[len - 1] = 0;
620 else
622 if (lpath[len - 1] == '.' && lpath[len - 2] == PATH_SEP)
624 if (len == 2)
626 lpath[1] = 0;
627 return;
629 else
631 lpath[len - 2] = 0;
637 if (flags & CANON_PATH_REMDOUBLEDOTS)
639 const size_t enc_prefix_len = strlen (VFS_ENCODING_PREFIX);
641 /* Collapse "/.." with the previous part of path */
642 p = lpath;
643 while (p[0] && p[1] && p[2])
645 if ((p[0] != PATH_SEP || p[1] != '.' || p[2] != '.') || (p[3] != PATH_SEP && p[3] != 0))
647 p++;
648 continue;
651 /* search for the previous token */
652 s = p - 1;
653 while (s >= lpath && *s != PATH_SEP)
654 s--;
656 s++;
658 /* If the previous token is "..", we cannot collapse it */
659 if (s[0] == '.' && s[1] == '.' && s + 2 == p)
661 p += 3;
662 continue;
665 if (p[3] != 0)
667 if (s == lpath && *s == PATH_SEP)
669 /* "/../foo" -> "/foo" */
670 str_move (s + 1, p + 4);
672 else
674 /* "token/../foo" -> "foo" */
675 #if HAVE_CHARSET
676 if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
677 && (is_supported_encoding (s + enc_prefix_len)))
678 /* special case: remove encoding */
679 str_move (s, p + 1);
680 else
681 #endif /* HAVE_CHARSET */
682 str_move (s, p + 4);
684 p = (s > lpath) ? s - 1 : s;
685 continue;
688 /* trailing ".." */
689 if (s == lpath)
691 /* "token/.." -> "." */
692 if (lpath[0] != PATH_SEP)
694 lpath[0] = '.';
696 lpath[1] = 0;
698 else
700 /* "foo/token/.." -> "foo" */
701 if (s == lpath + 1)
702 s[0] = 0;
703 #if HAVE_CHARSET
704 else if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
705 && (is_supported_encoding (s + enc_prefix_len)))
707 /* special case: remove encoding */
708 s[0] = '.';
709 s[1] = '.';
710 s[2] = '\0';
712 /* search for the previous token */
713 /* s[-1] == PATH_SEP */
714 p = s - 1;
715 while (p >= lpath && *p != PATH_SEP)
716 p--;
718 if (p != NULL)
719 continue;
721 #endif /* HAVE_CHARSET */
722 else
723 s[-1] = 0;
724 break;
727 break;
732 /* --------------------------------------------------------------------------------------------- */
734 void
735 canonicalize_pathname (char *path)
737 custom_canonicalize_pathname (path, CANON_PATH_ALL);
740 /* --------------------------------------------------------------------------------------------- */
742 #ifdef HAVE_GET_PROCESS_STATS
744 gettimeofday (struct timeval *tp, void *tzp)
746 return get_process_stats (tp, PS_SELF, 0, 0);
748 #endif /* HAVE_GET_PROCESS_STATS */
750 /* --------------------------------------------------------------------------------------------- */
752 #ifndef HAVE_REALPATH
753 char *
754 mc_realpath (const char *path, char *resolved_path)
756 char copy_path[PATH_MAX];
757 char link_path[PATH_MAX];
758 char got_path[PATH_MAX];
759 char *new_path = got_path;
760 char *max_path;
761 int readlinks = 0;
762 int n;
764 /* Make a copy of the source path since we may need to modify it. */
765 if (strlen (path) >= PATH_MAX - 2)
767 errno = ENAMETOOLONG;
768 return NULL;
770 strcpy (copy_path, path);
771 path = copy_path;
772 max_path = copy_path + PATH_MAX - 2;
773 /* If it's a relative pathname use getwd for starters. */
774 if (*path != '/')
777 new_path = g_get_current_dir ();
778 if (new_path == NULL)
780 strcpy (got_path, "");
782 else
784 g_snprintf (got_path, PATH_MAX, "%s", new_path);
785 g_free (new_path);
786 new_path = got_path;
789 new_path += strlen (got_path);
790 if (new_path[-1] != '/')
791 *new_path++ = '/';
793 else
795 *new_path++ = '/';
796 path++;
798 /* Expand each slash-separated pathname component. */
799 while (*path != '\0')
801 /* Ignore stray "/". */
802 if (*path == '/')
804 path++;
805 continue;
807 if (*path == '.')
809 /* Ignore ".". */
810 if (path[1] == '\0' || path[1] == '/')
812 path++;
813 continue;
815 if (path[1] == '.')
817 if (path[2] == '\0' || path[2] == '/')
819 path += 2;
820 /* Ignore ".." at root. */
821 if (new_path == got_path + 1)
822 continue;
823 /* Handle ".." by backing up. */
824 while ((--new_path)[-1] != '/');
825 continue;
829 /* Safely copy the next pathname component. */
830 while (*path != '\0' && *path != '/')
832 if (path > max_path)
834 errno = ENAMETOOLONG;
835 return NULL;
837 *new_path++ = *path++;
839 #ifdef S_IFLNK
840 /* Protect against infinite loops. */
841 if (readlinks++ > MAXSYMLINKS)
843 errno = ELOOP;
844 return NULL;
846 /* See if latest pathname component is a symlink. */
847 *new_path = '\0';
848 n = readlink (got_path, link_path, PATH_MAX - 1);
849 if (n < 0)
851 /* EINVAL means the file exists but isn't a symlink. */
852 if (errno != EINVAL)
854 /* Make sure it's null terminated. */
855 *new_path = '\0';
856 strcpy (resolved_path, got_path);
857 return NULL;
860 else
862 /* Note: readlink doesn't add the null byte. */
863 link_path[n] = '\0';
864 if (*link_path == '/')
865 /* Start over for an absolute symlink. */
866 new_path = got_path;
867 else
868 /* Otherwise back up over this component. */
869 while (*(--new_path) != '/');
870 /* Safe sex check. */
871 if (strlen (path) + n >= PATH_MAX - 2)
873 errno = ENAMETOOLONG;
874 return NULL;
876 /* Insert symlink contents into path. */
877 strcat (link_path, path);
878 strcpy (copy_path, link_path);
879 path = copy_path;
881 #endif /* S_IFLNK */
882 *new_path++ = '/';
884 /* Delete trailing slash but don't whomp a lone slash. */
885 if (new_path != got_path + 1 && new_path[-1] == '/')
886 new_path--;
887 /* Make sure it's null terminated. */
888 *new_path = '\0';
889 strcpy (resolved_path, got_path);
890 return resolved_path;
892 #endif /* HAVE_REALPATH */
894 /* --------------------------------------------------------------------------------------------- */
896 * Return the index of the permissions triplet
901 get_user_permissions (struct stat *st)
903 static gboolean initialized = FALSE;
904 static gid_t *groups;
905 static int ngroups;
906 static uid_t uid;
907 int i;
909 if (!initialized)
911 uid = geteuid ();
913 ngroups = getgroups (0, NULL);
914 if (ngroups == -1)
915 ngroups = 0; /* ignore errors */
917 /* allocate space for one element in addition to what
918 * will be filled by getgroups(). */
919 groups = g_new (gid_t, ngroups + 1);
921 if (ngroups != 0)
923 ngroups = getgroups (ngroups, groups);
924 if (ngroups == -1)
925 ngroups = 0; /* ignore errors */
928 /* getgroups() may or may not return the effective group ID,
929 * so we always include it at the end of the list. */
930 groups[ngroups++] = getegid ();
932 initialized = TRUE;
935 if (st->st_uid == uid || uid == 0)
936 return 0;
938 for (i = 0; i < ngroups; i++)
940 if (st->st_gid == groups[i])
941 return 1;
944 return 2;
947 /* --------------------------------------------------------------------------------------------- */