Direct cleanup in master branch
[midnight-commander.git] / lib / utilunix.c
blobf7835fb07d4a3118ed4d2a23c65ecdca28217d1c
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 "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
60 typedef struct
62 int index;
63 char *string;
64 } int_cache;
66 static int_cache uid_cache[UID_CACHE_SIZE];
67 static int_cache gid_cache[GID_CACHE_SIZE];
69 static char *
70 i_cache_match (int id, int_cache * cache, int size)
72 int i;
74 for (i = 0; i < size; i++)
75 if (cache[i].index == id)
76 return cache[i].string;
77 return 0;
80 static void
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;
89 char *
90 get_owner (int uid)
92 struct passwd *pwd;
93 static char ibuf[10];
94 char *name;
95 static int uid_last;
97 name = i_cache_match (uid, uid_cache, UID_CACHE_SIZE);
98 if (name != NULL)
99 return name;
101 pwd = getpwuid (uid);
102 if (pwd != NULL)
104 i_cache_add (uid, uid_cache, UID_CACHE_SIZE, pwd->pw_name, &uid_last);
105 return pwd->pw_name;
107 else
109 g_snprintf (ibuf, sizeof (ibuf), "%d", uid);
110 return ibuf;
114 char *
115 get_group (int gid)
117 struct group *grp;
118 static char gbuf[10];
119 char *name;
120 static int gid_last;
122 name = i_cache_match (gid, gid_cache, GID_CACHE_SIZE);
123 if (name != NULL)
124 return name;
126 grp = getgrgid (gid);
127 if (grp != NULL)
129 i_cache_add (gid, gid_cache, GID_CACHE_SIZE, grp->gr_name, &gid_last);
130 return grp->gr_name;
132 else
134 g_snprintf (gbuf, sizeof (gbuf), "%d", gid);
135 return gbuf;
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 */
142 void
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;
152 pid_t pid;
153 int status = 0;
155 ignore.sa_handler = SIG_IGN;
156 sigemptyset (&ignore.sa_mask);
157 ignore.sa_flags = 0;
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);
166 pid = fork ();
167 if (pid < 0)
169 fprintf (stderr, "\n\nfork () = -1\n");
170 return -1;
172 if (pid == 0)
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);
181 else
183 gchar **shell_tokens;
184 const gchar *only_cmd;
186 shell_tokens = g_strsplit (shell, " ", 2);
187 if (shell_tokens == NULL)
188 only_cmd = shell;
189 else
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 */
205 else
207 while (waitpid (pid, &status, 0) < 0)
208 if (errno != EINTR)
210 status = -1;
211 break;
214 sigaction (SIGINT, &save_intr, NULL);
215 sigaction (SIGQUIT, &save_quit, NULL);
216 sigaction (SIGTSTP, &save_stop, NULL);
218 return WEXITSTATUS (status);
223 * Perform tilde expansion if possible.
224 * Always return a newly allocated string, even if it's unchanged.
226 char *
227 tilde_expand (const char *directory)
229 struct passwd *passwd;
230 const char *p, *q;
231 char *name;
233 if (*directory != '~')
234 return g_strdup (directory);
236 p = directory + 1;
238 /* d = "~" or d = "~/" */
239 if (!(*p) || (*p == PATH_SEP))
241 passwd = getpwuid (geteuid ());
242 q = (*p == PATH_SEP) ? p + 1 : "";
244 else
246 q = strchr (p, PATH_SEP);
247 if (!q)
249 passwd = getpwnam (p);
251 else
253 name = g_strndup (p, q - p);
254 passwd = getpwnam (name);
255 q++;
256 g_free (name);
260 /* If we can't figure the user name, leave tilde unexpanded */
261 if (!passwd)
262 return g_strdup (directory);
264 return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
268 * Return the directory where mc should keep its temporary files.
269 * This directory is (in Bourne shell terms) "${TMPDIR=/tmp}/mc-$USER"
270 * When called the first time, the directory is created if needed.
271 * The first call should be done early, since we are using fprintf()
272 * and not message() to report possible problems.
274 const char *
275 mc_tmpdir (void)
277 static char buffer[64];
278 static const char *tmpdir;
279 const char *sys_tmp;
280 struct passwd *pwd;
281 struct stat st;
282 const char *error = NULL;
284 /* Check if already correctly initialized */
285 if (tmpdir && lstat (tmpdir, &st) == 0 && S_ISDIR (st.st_mode) &&
286 st.st_uid == getuid () && (st.st_mode & 0777) == 0700)
287 return tmpdir;
289 sys_tmp = getenv ("TMPDIR");
290 if (!sys_tmp || sys_tmp[0] != '/')
292 sys_tmp = TMPDIR_DEFAULT;
295 pwd = getpwuid (getuid ());
297 if (pwd)
298 g_snprintf (buffer, sizeof (buffer), "%s/mc-%s", sys_tmp, pwd->pw_name);
299 else
300 g_snprintf (buffer, sizeof (buffer), "%s/mc-%lu", sys_tmp, (unsigned long) getuid ());
302 canonicalize_pathname (buffer);
304 if (lstat (buffer, &st) == 0)
306 /* Sanity check for existing directory */
307 if (!S_ISDIR (st.st_mode))
308 error = _("%s is not a directory\n");
309 else if (st.st_uid != getuid ())
310 error = _("Directory %s is not owned by you\n");
311 else if (((st.st_mode & 0777) != 0700) && (chmod (buffer, 0700) != 0))
312 error = _("Cannot set correct permissions for directory %s\n");
314 else
316 /* Need to create directory */
317 if (mkdir (buffer, S_IRWXU) != 0)
319 fprintf (stderr,
320 _("Cannot create temporary directory %s: %s\n"),
321 buffer, unix_error_string (errno));
322 error = "";
326 if (error != NULL)
328 int test_fd;
329 char *test_fn, *fallback_prefix;
330 int fallback_ok = 0;
332 if (*error)
333 fprintf (stderr, error, buffer);
335 /* Test if sys_tmp is suitable for temporary files */
336 fallback_prefix = g_strdup_printf ("%s/mctest", sys_tmp);
337 test_fd = mc_mkstemps (&test_fn, fallback_prefix, NULL);
338 g_free (fallback_prefix);
339 if (test_fd != -1)
341 close (test_fd);
342 test_fd = open (test_fn, O_RDONLY);
343 if (test_fd != -1)
345 close (test_fd);
346 unlink (test_fn);
347 fallback_ok = 1;
351 if (fallback_ok)
353 fprintf (stderr, _("Temporary files will be created in %s\n"), sys_tmp);
354 g_snprintf (buffer, sizeof (buffer), "%s", sys_tmp);
355 error = NULL;
357 else
359 fprintf (stderr, _("Temporary files will not be created\n"));
360 g_snprintf (buffer, sizeof (buffer), "%s", "/dev/null/");
363 fprintf (stderr, "%s\n", _("Press any key to continue..."));
364 getc (stdin);
367 tmpdir = buffer;
369 if (!error)
370 g_setenv ("MC_TMPDIR", tmpdir, TRUE);
372 return tmpdir;
376 /* Pipes are guaranteed to be able to hold at least 4096 bytes */
377 /* More than that would be unportable */
378 #define MAX_PIPE_SIZE 4096
380 static int error_pipe[2]; /* File descriptors of error pipe */
381 static int old_error; /* File descriptor of old standard error */
383 /* Creates a pipe to hold standard error for a later analysis. */
384 /* The pipe can hold 4096 bytes. Make sure no more is written */
385 /* or a deadlock might occur. */
386 void
387 open_error_pipe (void)
389 if (pipe (error_pipe) < 0)
391 message (D_NORMAL, _("Warning"), _(" Pipe failed "));
393 old_error = dup (2);
394 if (old_error < 0 || close (2) || dup (error_pipe[1]) != 2)
396 message (D_NORMAL, _("Warning"), _(" Dup failed "));
398 close (error_pipe[0]);
399 error_pipe[0] = -1;
401 else
404 * Settng stderr in nonblocking mode as we close it earlier, than
405 * program stops. We try to read some error at program startup,
406 * but we should not block on it.
408 * TODO: make piped stdin/stderr poll()/select()able to get rid
409 * of following hack.
411 int fd_flags;
412 fd_flags = fcntl (error_pipe[0], F_GETFL, NULL);
413 if (fd_flags != -1)
415 fd_flags |= O_NONBLOCK;
416 if (fcntl (error_pipe[0], F_SETFL, fd_flags) == -1)
418 /* TODO: handle it somehow */
422 /* we never write there */
423 close (error_pipe[1]);
424 error_pipe[1] = -1;
428 * Returns true if an error was displayed
429 * error: -1 - ignore errors, 0 - display warning, 1 - display error
430 * text is prepended to the error message from the pipe
433 close_error_pipe (int error, const char *text)
435 const char *title;
436 char msg[MAX_PIPE_SIZE];
437 int len = 0;
439 /* already closed */
440 if (error_pipe[0] == -1)
441 return 0;
443 if (error)
444 title = MSG_ERROR;
445 else
446 title = _("Warning");
447 if (old_error >= 0)
449 if (dup2 (old_error, 2) == -1)
451 message (error, MSG_ERROR, "%s", _("Error dup'ing old error pipe"));
452 return 1;
454 close (old_error);
455 len = read (error_pipe[0], msg, MAX_PIPE_SIZE - 1);
457 if (len >= 0)
458 msg[len] = 0;
459 close (error_pipe[0]);
460 error_pipe[0] = -1;
462 if (error < 0)
463 return 0; /* Just ignore error message */
464 if (text == NULL)
466 if (len <= 0)
467 return 0; /* Nothing to show */
469 /* Show message from pipe */
470 message (error, title, "%s", msg);
472 else
474 /* Show given text and possible message from pipe */
475 message (error, title, " %s \n %s ", text, msg);
477 return 1;
481 * Canonicalize path, and return a new path. Do everything in place.
482 * The new path differs from path in:
483 * Multiple `/'s are collapsed to a single `/'.
484 * Leading `./'s and trailing `/.'s are removed.
485 * Trailing `/'s are removed.
486 * Non-leading `../'s and trailing `..'s are handled by removing
487 * portions of the path.
488 * Well formed UNC paths are modified only in the local part.
490 void
491 custom_canonicalize_pathname (char *path, CANON_PATH_FLAGS flags)
493 char *p, *s;
494 int len;
495 char *lpath = path; /* path without leading UNC part */
497 /* Detect and preserve UNC paths: //server/... */
498 if ((flags & CANON_PATH_GUARDUNC) && path[0] == PATH_SEP && path[1] == PATH_SEP)
500 p = path + 2;
501 while (p[0] && p[0] != '/')
502 p++;
503 if (p[0] == '/' && p > path + 2)
504 lpath = p;
507 if (!lpath[0] || !lpath[1])
508 return;
510 if (flags & CANON_PATH_JOINSLASHES)
512 /* Collapse multiple slashes */
513 p = lpath;
514 while (*p)
516 if (p[0] == PATH_SEP && p[1] == PATH_SEP)
518 s = p + 1;
519 while (*(++s) == PATH_SEP);
520 str_move (p + 1, s);
522 p++;
526 if (flags & CANON_PATH_JOINSLASHES)
528 /* Collapse "/./" -> "/" */
529 p = lpath;
530 while (*p)
532 if (p[0] == PATH_SEP && p[1] == '.' && p[2] == PATH_SEP)
533 str_move (p, p + 2);
534 else
535 p++;
539 if (flags & CANON_PATH_REMSLASHDOTS)
541 /* Remove trailing slashes */
542 p = lpath + strlen (lpath) - 1;
543 while (p > lpath && *p == PATH_SEP)
544 *p-- = 0;
546 /* Remove leading "./" */
547 if (lpath[0] == '.' && lpath[1] == PATH_SEP)
549 if (lpath[2] == 0)
551 lpath[1] = 0;
552 return;
554 else
556 str_move (lpath, lpath + 2);
560 /* Remove trailing "/" or "/." */
561 len = strlen (lpath);
562 if (len < 2)
563 return;
564 if (lpath[len - 1] == PATH_SEP)
566 lpath[len - 1] = 0;
568 else
570 if (lpath[len - 1] == '.' && lpath[len - 2] == PATH_SEP)
572 if (len == 2)
574 lpath[1] = 0;
575 return;
577 else
579 lpath[len - 2] = 0;
585 if (flags & CANON_PATH_REMDOUBLEDOTS)
587 /* Collapse "/.." with the previous part of path */
588 p = lpath;
589 while (p[0] && p[1] && p[2])
591 if ((p[0] != PATH_SEP || p[1] != '.' || p[2] != '.') || (p[3] != PATH_SEP && p[3] != 0))
593 p++;
594 continue;
597 /* search for the previous token */
598 s = p - 1;
599 while (s >= lpath && *s != PATH_SEP)
600 s--;
602 s++;
604 /* If the previous token is "..", we cannot collapse it */
605 if (s[0] == '.' && s[1] == '.' && s + 2 == p)
607 p += 3;
608 continue;
611 if (p[3] != 0)
613 if (s == lpath && *s == PATH_SEP)
615 /* "/../foo" -> "/foo" */
616 str_move (s + 1, p + 4);
618 else
620 /* "token/../foo" -> "foo" */
621 str_move (s, p + 4);
623 p = (s > lpath) ? s - 1 : s;
624 continue;
627 /* trailing ".." */
628 if (s == lpath)
630 /* "token/.." -> "." */
631 if (lpath[0] != PATH_SEP)
633 lpath[0] = '.';
635 lpath[1] = 0;
637 else
639 /* "foo/token/.." -> "foo" */
640 if (s == lpath + 1)
641 s[0] = 0;
642 else
643 s[-1] = 0;
644 break;
647 break;
652 void
653 canonicalize_pathname (char *path)
655 custom_canonicalize_pathname (path, CANON_PATH_ALL);
658 #ifdef HAVE_GET_PROCESS_STATS
659 # include <sys/procstats.h>
662 gettimeofday (struct timeval *tp, void *tzp)
664 return get_process_stats (tp, PS_SELF, 0, 0);
666 #endif /* HAVE_GET_PROCESS_STATS */
668 char *
669 mc_realpath (const char *path, char resolved_path[])
671 #ifdef USE_SYSTEM_REALPATH
672 return realpath (path, resolved_path);
673 #else
674 char copy_path[PATH_MAX];
675 char link_path[PATH_MAX];
676 char got_path[PATH_MAX];
677 char *new_path = got_path;
678 char *max_path;
679 int readlinks = 0;
680 int n;
682 /* Make a copy of the source path since we may need to modify it. */
683 if (strlen (path) >= PATH_MAX - 2)
685 errno = ENAMETOOLONG;
686 return NULL;
688 strcpy (copy_path, path);
689 path = copy_path;
690 max_path = copy_path + PATH_MAX - 2;
691 /* If it's a relative pathname use getwd for starters. */
692 if (*path != '/')
695 new_path = g_get_current_dir ();
696 if (new_path == NULL)
698 strcpy (got_path, "");
700 else
702 g_snprintf (got_path, PATH_MAX, "%s", new_path);
703 g_free (new_path);
704 new_path = got_path;
707 new_path += strlen (got_path);
708 if (new_path[-1] != '/')
709 *new_path++ = '/';
711 else
713 *new_path++ = '/';
714 path++;
716 /* Expand each slash-separated pathname component. */
717 while (*path != '\0')
719 /* Ignore stray "/". */
720 if (*path == '/')
722 path++;
723 continue;
725 if (*path == '.')
727 /* Ignore ".". */
728 if (path[1] == '\0' || path[1] == '/')
730 path++;
731 continue;
733 if (path[1] == '.')
735 if (path[2] == '\0' || path[2] == '/')
737 path += 2;
738 /* Ignore ".." at root. */
739 if (new_path == got_path + 1)
740 continue;
741 /* Handle ".." by backing up. */
742 while ((--new_path)[-1] != '/');
743 continue;
747 /* Safely copy the next pathname component. */
748 while (*path != '\0' && *path != '/')
750 if (path > max_path)
752 errno = ENAMETOOLONG;
753 return NULL;
755 *new_path++ = *path++;
757 #ifdef S_IFLNK
758 /* Protect against infinite loops. */
759 if (readlinks++ > MAXSYMLINKS)
761 errno = ELOOP;
762 return NULL;
764 /* See if latest pathname component is a symlink. */
765 *new_path = '\0';
766 n = readlink (got_path, link_path, PATH_MAX - 1);
767 if (n < 0)
769 /* EINVAL means the file exists but isn't a symlink. */
770 if (errno != EINVAL)
772 /* Make sure it's null terminated. */
773 *new_path = '\0';
774 strcpy (resolved_path, got_path);
775 return NULL;
778 else
780 /* Note: readlink doesn't add the null byte. */
781 link_path[n] = '\0';
782 if (*link_path == '/')
783 /* Start over for an absolute symlink. */
784 new_path = got_path;
785 else
786 /* Otherwise back up over this component. */
787 while (*(--new_path) != '/');
788 /* Safe sex check. */
789 if (strlen (path) + n >= PATH_MAX - 2)
791 errno = ENAMETOOLONG;
792 return NULL;
794 /* Insert symlink contents into path. */
795 strcat (link_path, path);
796 strcpy (copy_path, link_path);
797 path = copy_path;
799 #endif /* S_IFLNK */
800 *new_path++ = '/';
802 /* Delete trailing slash but don't whomp a lone slash. */
803 if (new_path != got_path + 1 && new_path[-1] == '/')
804 new_path--;
805 /* Make sure it's null terminated. */
806 *new_path = '\0';
807 strcpy (resolved_path, got_path);
808 return resolved_path;
809 #endif /* USE_SYSTEM_REALPATH */
812 /* Return the index of the permissions triplet */
814 get_user_permissions (struct stat *st)
816 static gboolean initialized = FALSE;
817 static gid_t *groups;
818 static int ngroups;
819 static uid_t uid;
820 int i;
822 if (!initialized)
824 uid = geteuid ();
826 ngroups = getgroups (0, NULL);
827 if (ngroups == -1)
828 ngroups = 0; /* ignore errors */
830 /* allocate space for one element in addition to what
831 * will be filled by getgroups(). */
832 groups = g_new (gid_t, ngroups + 1);
834 if (ngroups != 0)
836 ngroups = getgroups (ngroups, groups);
837 if (ngroups == -1)
838 ngroups = 0; /* ignore errors */
841 /* getgroups() may or may not return the effective group ID,
842 * so we always include it at the end of the list. */
843 groups[ngroups++] = getegid ();
845 initialized = TRUE;
848 if (st->st_uid == uid || uid == 0)
849 return 0;
851 for (i = 0; i < ngroups; i++)
853 if (st->st_gid == groups[i])
854 return 1;
857 return 2;