Created macro VFS_ENCODING_PREFIX for "#enc:" encoding prefix.
[pantumic.git] / lib / utilunix.c
blob2252933dc18bde9cc34fcf8584adb49608f0e2e9
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 #include <unistd.h>
48 #include <pwd.h>
49 #include <grp.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
62 typedef struct
64 int index;
65 char *string;
66 } int_cache;
68 static int_cache uid_cache[UID_CACHE_SIZE];
69 static int_cache gid_cache[GID_CACHE_SIZE];
71 static char *
72 i_cache_match (int id, int_cache * cache, int size)
74 int i;
76 for (i = 0; i < size; i++)
77 if (cache[i].index == id)
78 return cache[i].string;
79 return 0;
82 static void
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;
91 char *
92 get_owner (int uid)
94 struct passwd *pwd;
95 static char ibuf[10];
96 char *name;
97 static int uid_last;
99 name = i_cache_match (uid, uid_cache, UID_CACHE_SIZE);
100 if (name != NULL)
101 return name;
103 pwd = getpwuid (uid);
104 if (pwd != NULL)
106 i_cache_add (uid, uid_cache, UID_CACHE_SIZE, pwd->pw_name, &uid_last);
107 return pwd->pw_name;
109 else
111 g_snprintf (ibuf, sizeof (ibuf), "%d", uid);
112 return ibuf;
116 char *
117 get_group (int gid)
119 struct group *grp;
120 static char gbuf[10];
121 char *name;
122 static int gid_last;
124 name = i_cache_match (gid, gid_cache, GID_CACHE_SIZE);
125 if (name != NULL)
126 return name;
128 grp = getgrgid (gid);
129 if (grp != NULL)
131 i_cache_add (gid, gid_cache, GID_CACHE_SIZE, grp->gr_name, &gid_last);
132 return grp->gr_name;
134 else
136 g_snprintf (gbuf, sizeof (gbuf), "%d", gid);
137 return gbuf;
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 */
144 void
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;
154 pid_t pid;
155 int status = 0;
157 ignore.sa_handler = SIG_IGN;
158 sigemptyset (&ignore.sa_mask);
159 ignore.sa_flags = 0;
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);
168 pid = fork ();
169 if (pid < 0)
171 fprintf (stderr, "\n\nfork () = -1\n");
172 status = -1;
174 else if (pid == 0)
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);
183 else
185 gchar **shell_tokens;
186 const gchar *only_cmd;
188 shell_tokens = g_strsplit (shell, " ", 2);
189 if (shell_tokens == NULL)
190 only_cmd = shell;
191 else
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 */
207 else
209 while (TRUE)
211 if (waitpid (pid, &status, 0) > 0)
213 status = WEXITSTATUS(status);
214 break;
216 if (errno != EINTR)
218 status = -1;
219 break;
223 sigaction (SIGINT, &save_intr, NULL);
224 sigaction (SIGQUIT, &save_quit, NULL);
225 sigaction (SIGTSTP, &save_stop, NULL);
227 return status;
232 * Perform tilde expansion if possible.
233 * Always return a newly allocated string, even if it's unchanged.
235 char *
236 tilde_expand (const char *directory)
238 struct passwd *passwd;
239 const char *p, *q;
240 char *name;
242 if (*directory != '~')
243 return g_strdup (directory);
245 p = directory + 1;
247 /* d = "~" or d = "~/" */
248 if (!(*p) || (*p == PATH_SEP))
250 passwd = getpwuid (geteuid ());
251 q = (*p == PATH_SEP) ? p + 1 : "";
253 else
255 q = strchr (p, PATH_SEP);
256 if (!q)
258 passwd = getpwnam (p);
260 else
262 name = g_strndup (p, q - p);
263 passwd = getpwnam (name);
264 q++;
265 g_free (name);
269 /* If we can't figure the user name, leave tilde unexpanded */
270 if (!passwd)
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.
283 const char *
284 mc_tmpdir (void)
286 static char buffer[64];
287 static const char *tmpdir;
288 const char *sys_tmp;
289 struct passwd *pwd;
290 struct stat st;
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)
296 return tmpdir;
298 sys_tmp = getenv ("TMPDIR");
299 if (!sys_tmp || sys_tmp[0] != '/')
301 sys_tmp = TMPDIR_DEFAULT;
304 pwd = getpwuid (getuid ());
306 if (pwd)
307 g_snprintf (buffer, sizeof (buffer), "%s/mc-%s", sys_tmp, pwd->pw_name);
308 else
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");
323 else
325 /* Need to create directory */
326 if (mkdir (buffer, S_IRWXU) != 0)
328 fprintf (stderr,
329 _("Cannot create temporary directory %s: %s\n"),
330 buffer, unix_error_string (errno));
331 error = "";
335 if (error != NULL)
337 int test_fd;
338 char *test_fn, *fallback_prefix;
339 int fallback_ok = 0;
341 if (*error)
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);
348 if (test_fd != -1)
350 close (test_fd);
351 test_fd = open (test_fn, O_RDONLY);
352 if (test_fd != -1)
354 close (test_fd);
355 unlink (test_fn);
356 fallback_ok = 1;
360 if (fallback_ok)
362 fprintf (stderr, _("Temporary files will be created in %s\n"), sys_tmp);
363 g_snprintf (buffer, sizeof (buffer), "%s", sys_tmp);
364 error = NULL;
366 else
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..."));
373 getc (stdin);
376 tmpdir = buffer;
378 if (!error)
379 g_setenv ("MC_TMPDIR", tmpdir, TRUE);
381 return tmpdir;
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. */
395 void
396 open_error_pipe (void)
398 if (pipe (error_pipe) < 0)
400 message (D_NORMAL, _("Warning"), _("Pipe failed"));
402 old_error = dup (2);
403 if (old_error < 0 || close (2) || dup (error_pipe[1]) != 2)
405 message (D_NORMAL, _("Warning"), _("Dup failed"));
407 close (error_pipe[0]);
408 error_pipe[0] = -1;
410 else
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
418 * of following hack.
420 int fd_flags;
421 fd_flags = fcntl (error_pipe[0], F_GETFL, NULL);
422 if (fd_flags != -1)
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]);
433 error_pipe[1] = -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)
444 const char *title;
445 char msg[MAX_PIPE_SIZE];
446 int len = 0;
448 /* already closed */
449 if (error_pipe[0] == -1)
450 return 0;
452 if (error)
453 title = MSG_ERROR;
454 else
455 title = _("Warning");
456 if (old_error >= 0)
458 if (dup2 (old_error, 2) == -1)
460 message (error, MSG_ERROR, _("Error dup'ing old error pipe"));
461 return 1;
463 close (old_error);
464 len = read (error_pipe[0], msg, MAX_PIPE_SIZE - 1);
466 if (len >= 0)
467 msg[len] = 0;
468 close (error_pipe[0]);
469 error_pipe[0] = -1;
471 if (error < 0)
472 return 0; /* Just ignore error message */
473 if (text == NULL)
475 if (len <= 0)
476 return 0; /* Nothing to show */
478 /* Show message from pipe */
479 message (error, title, "%s", msg);
481 else
483 /* Show given text and possible message from pipe */
484 message (error, title, "%s\n%s", text, msg);
486 return 1;
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.
499 void
500 custom_canonicalize_pathname (char *path, CANON_PATH_FLAGS flags)
502 char *p, *s;
503 int len;
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)
509 p = path + 2;
510 while (p[0] && p[0] != '/')
511 p++;
512 if (p[0] == '/' && p > path + 2)
513 lpath = p;
516 if (!lpath[0] || !lpath[1])
517 return;
519 if (flags & CANON_PATH_JOINSLASHES)
521 /* Collapse multiple slashes */
522 p = lpath;
523 while (*p)
525 if (p[0] == PATH_SEP && p[1] == PATH_SEP)
527 s = p + 1;
528 while (*(++s) == PATH_SEP);
529 str_move (p + 1, s);
531 p++;
535 if (flags & CANON_PATH_JOINSLASHES)
537 /* Collapse "/./" -> "/" */
538 p = lpath;
539 while (*p)
541 if (p[0] == PATH_SEP && p[1] == '.' && p[2] == PATH_SEP)
542 str_move (p, p + 2);
543 else
544 p++;
548 if (flags & CANON_PATH_REMSLASHDOTS)
550 /* Remove trailing slashes */
551 p = lpath + strlen (lpath) - 1;
552 while (p > lpath && *p == PATH_SEP)
553 *p-- = 0;
555 /* Remove leading "./" */
556 if (lpath[0] == '.' && lpath[1] == PATH_SEP)
558 if (lpath[2] == 0)
560 lpath[1] = 0;
561 return;
563 else
565 str_move (lpath, lpath + 2);
569 /* Remove trailing "/" or "/." */
570 len = strlen (lpath);
571 if (len < 2)
572 return;
573 if (lpath[len - 1] == PATH_SEP)
575 lpath[len - 1] = 0;
577 else
579 if (lpath[len - 1] == '.' && lpath[len - 2] == PATH_SEP)
581 if (len == 2)
583 lpath[1] = 0;
584 return;
586 else
588 lpath[len - 2] = 0;
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 */
599 p = lpath;
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))
604 p++;
605 continue;
608 /* search for the previous token */
609 s = p - 1;
610 while (s >= lpath && *s != PATH_SEP)
611 s--;
613 s++;
615 /* If the previous token is "..", we cannot collapse it */
616 if (s[0] == '.' && s[1] == '.' && s + 2 == p)
618 p += 3;
619 continue;
622 if (p[3] != 0)
624 if (s == lpath && *s == PATH_SEP)
626 /* "/../foo" -> "/foo" */
627 str_move (s + 1, p + 4);
629 else
631 /* "token/../foo" -> "foo" */
632 #if HAVE_CHARSET
633 if (strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
634 /* special case: remove encoding */
635 str_move (s, p + 1);
636 else
637 #endif /* HAVE_CHARSET */
638 str_move (s, p + 4);
640 p = (s > lpath) ? s - 1 : s;
641 continue;
644 /* trailing ".." */
645 if (s == lpath)
647 /* "token/.." -> "." */
648 if (lpath[0] != PATH_SEP)
650 lpath[0] = '.';
652 lpath[1] = 0;
654 else
656 /* "foo/token/.." -> "foo" */
657 if (s == lpath + 1)
658 s[0] = 0;
659 #if HAVE_CHARSET
660 else if (strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
662 /* special case: remove encoding */
663 s[0] = '.';
664 s[1] = '.';
665 s[2] = '\0';
667 /* search for the previous token */
668 /* s[-1] == PATH_SEP */
669 p = s - 1;
670 while (p >= lpath && *p != PATH_SEP)
671 p--;
673 if (p != NULL)
674 continue;
676 #endif /* HAVE_CHARSET */
677 else
678 s[-1] = 0;
679 break;
682 break;
687 void
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
704 char *
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;
711 char *max_path;
712 int readlinks = 0;
713 int n;
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;
719 return NULL;
721 strcpy (copy_path, path);
722 path = copy_path;
723 max_path = copy_path + PATH_MAX - 2;
724 /* If it's a relative pathname use getwd for starters. */
725 if (*path != '/')
728 new_path = g_get_current_dir ();
729 if (new_path == NULL)
731 strcpy (got_path, "");
733 else
735 g_snprintf (got_path, PATH_MAX, "%s", new_path);
736 g_free (new_path);
737 new_path = got_path;
740 new_path += strlen (got_path);
741 if (new_path[-1] != '/')
742 *new_path++ = '/';
744 else
746 *new_path++ = '/';
747 path++;
749 /* Expand each slash-separated pathname component. */
750 while (*path != '\0')
752 /* Ignore stray "/". */
753 if (*path == '/')
755 path++;
756 continue;
758 if (*path == '.')
760 /* Ignore ".". */
761 if (path[1] == '\0' || path[1] == '/')
763 path++;
764 continue;
766 if (path[1] == '.')
768 if (path[2] == '\0' || path[2] == '/')
770 path += 2;
771 /* Ignore ".." at root. */
772 if (new_path == got_path + 1)
773 continue;
774 /* Handle ".." by backing up. */
775 while ((--new_path)[-1] != '/');
776 continue;
780 /* Safely copy the next pathname component. */
781 while (*path != '\0' && *path != '/')
783 if (path > max_path)
785 errno = ENAMETOOLONG;
786 return NULL;
788 *new_path++ = *path++;
790 #ifdef S_IFLNK
791 /* Protect against infinite loops. */
792 if (readlinks++ > MAXSYMLINKS)
794 errno = ELOOP;
795 return NULL;
797 /* See if latest pathname component is a symlink. */
798 *new_path = '\0';
799 n = readlink (got_path, link_path, PATH_MAX - 1);
800 if (n < 0)
802 /* EINVAL means the file exists but isn't a symlink. */
803 if (errno != EINVAL)
805 /* Make sure it's null terminated. */
806 *new_path = '\0';
807 strcpy (resolved_path, got_path);
808 return NULL;
811 else
813 /* Note: readlink doesn't add the null byte. */
814 link_path[n] = '\0';
815 if (*link_path == '/')
816 /* Start over for an absolute symlink. */
817 new_path = got_path;
818 else
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;
825 return NULL;
827 /* Insert symlink contents into path. */
828 strcat (link_path, path);
829 strcpy (copy_path, link_path);
830 path = copy_path;
832 #endif /* S_IFLNK */
833 *new_path++ = '/';
835 /* Delete trailing slash but don't whomp a lone slash. */
836 if (new_path != got_path + 1 && new_path[-1] == '/')
837 new_path--;
838 /* Make sure it's null terminated. */
839 *new_path = '\0';
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;
851 static int ngroups;
852 static uid_t uid;
853 int i;
855 if (!initialized)
857 uid = geteuid ();
859 ngroups = getgroups (0, NULL);
860 if (ngroups == -1)
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);
867 if (ngroups != 0)
869 ngroups = getgroups (ngroups, groups);
870 if (ngroups == -1)
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 ();
878 initialized = TRUE;
881 if (st->st_uid == uid || uid == 0)
882 return 0;
884 for (i = 0; i < ngroups; i++)
886 if (st->st_gid == groups[i])
887 return 1;
890 return 2;