Last bunch of reverts and removal of mhl/*
[midnight-commander.git] / src / utilunix.c
blobc2afdee2ba6b7c4e3da85ca048a1057ae8956308
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 #include <config.h>
27 #include <ctype.h>
28 #include <errno.h>
29 #include <limits.h>
30 #include <signal.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
36 #include <sys/param.h>
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #ifdef HAVE_SYS_IOCTL_H
40 # include <sys/ioctl.h>
41 #endif
42 #include <unistd.h>
44 #include "global.h"
45 #include "execute.h"
46 #include "wtools.h" /* message() */
48 struct sigaction startup_handler;
50 #define UID_CACHE_SIZE 200
51 #define GID_CACHE_SIZE 30
53 typedef struct {
54 int index;
55 char *string;
56 } int_cache;
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)
63 int i;
65 for (i = 0; i < size; i++)
66 if (cache [i].index == id)
67 return cache [i].string;
68 return 0;
71 static void i_cache_add (int id, int_cache *cache, int size, char *text,
72 int *last)
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)
82 struct passwd *pwd;
83 static char ibuf [10];
84 char *name;
85 static int uid_last;
87 if ((name = i_cache_match (uid, uid_cache, UID_CACHE_SIZE)) != NULL)
88 return name;
90 pwd = getpwuid (uid);
91 if (pwd){
92 i_cache_add (uid, uid_cache, UID_CACHE_SIZE, pwd->pw_name, &uid_last);
93 return pwd->pw_name;
95 else {
96 g_snprintf (ibuf, sizeof (ibuf), "%d", uid);
97 return ibuf;
101 char *get_group (int gid)
103 struct group *grp;
104 static char gbuf [10];
105 char *name;
106 static int gid_last;
108 if ((name = i_cache_match (gid, gid_cache, GID_CACHE_SIZE)) != NULL)
109 return name;
111 grp = getgrgid (gid);
112 if (grp){
113 i_cache_add (gid, gid_cache, GID_CACHE_SIZE, grp->gr_name, &gid_last);
114 return grp->gr_name;
115 } else {
116 g_snprintf (gbuf, sizeof (gbuf), "%d", gid);
117 return gbuf;
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;
132 pid_t pid;
133 int status = 0;
135 ignore.sa_handler = SIG_IGN;
136 sigemptyset (&ignore.sa_mask);
137 ignore.sa_flags = 0;
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");
148 return -1;
150 if (pid == 0){
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);
158 else
159 execlp (shell, shell, command, (char *) NULL);
161 _exit (127); /* Exec error */
162 } else {
163 while (waitpid (pid, &status, 0) < 0)
164 if (errno != EINTR){
165 status = -1;
166 break;
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.
181 char *
182 tilde_expand (const char *directory)
184 struct passwd *passwd;
185 const char *p, *q;
186 char *name;
188 if (*directory != '~')
189 return g_strdup (directory);
191 p = directory + 1;
193 /* d = "~" or d = "~/" */
194 if (!(*p) || (*p == PATH_SEP)) {
195 passwd = getpwuid (geteuid ());
196 q = (*p == PATH_SEP) ? p + 1 : "";
197 } else {
198 q = strchr (p, PATH_SEP);
199 if (!q) {
200 passwd = getpwnam (p);
201 } else {
202 name = g_strndup (p, q - p);
203 passwd = getpwnam (name);
204 q++;
205 g_free (name);
209 /* If we can't figure the user name, leave tilde unexpanded */
210 if (!passwd)
211 return g_strdup (directory);
213 return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
216 static void
217 mc_setenv (const char *name, const char *value, int overwrite_flag)
219 #if defined(HAVE_SETENV)
220 setenv (name, value, overwrite_flag);
221 #else
222 if (overwrite_flag || getenv (name) == NULL)
223 putenv (g_strconcat (name, "=", value, (char *) NULL));
224 #endif
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.
234 const char *
235 mc_tmpdir (void)
237 static char buffer[64];
238 static const char *tmpdir;
239 const char *sys_tmp;
240 struct passwd *pwd;
241 struct stat st;
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)
247 return tmpdir;
249 sys_tmp = getenv ("TMPDIR");
250 if (!sys_tmp || sys_tmp[0] != '/') {
251 sys_tmp = TMPDIR_DEFAULT;
254 pwd = getpwuid (getuid ());
256 if (pwd)
257 g_snprintf (buffer, sizeof (buffer), "%s/mc-%s", sys_tmp,
258 pwd->pw_name);
259 else
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");
274 } else {
275 /* Need to create directory */
276 if (mkdir (buffer, S_IRWXU) != 0) {
277 fprintf (stderr,
278 _("Cannot create temporary directory %s: %s\n"),
279 buffer, unix_error_string (errno));
280 error = "";
284 if (error != NULL) {
285 int test_fd;
286 char *test_fn, *fallback_prefix;
287 int fallback_ok = 0;
289 if (*error)
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);
296 if (test_fd != -1) {
297 close (test_fd);
298 test_fd = open (test_fn, O_RDONLY);
299 if (test_fd != -1) {
300 close (test_fd);
301 unlink (test_fn);
302 fallback_ok = 1;
306 if (fallback_ok) {
307 fprintf (stderr, _("Temporary files will be created in %s\n"),
308 sys_tmp);
309 g_snprintf (buffer, sizeof (buffer), "%s", sys_tmp);
310 error = NULL;
311 } else {
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..."));
317 getc (stdin);
320 tmpdir = buffer;
322 if (!error)
323 mc_setenv ("MC_TMPDIR", tmpdir, 1);
325 return tmpdir;
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 "));
344 old_error = dup (2);
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)
361 const char *title;
362 char msg[MAX_PIPE_SIZE];
363 int len = 0;
365 if (error)
366 title = MSG_ERROR;
367 else
368 title = _("Warning");
369 if (old_error >= 0){
370 close (2);
371 dup (old_error);
372 close (old_error);
373 len = read (error_pipe[0], msg, MAX_PIPE_SIZE - 1);
375 if (len >= 0)
376 msg[len] = 0;
377 close (error_pipe[0]);
379 if (error < 0)
380 return 0; /* Just ignore error message */
381 if (text == NULL){
382 if (len <= 0)
383 return 0; /* Nothing to show */
385 /* Show message from pipe */
386 message (error, title, "%s", msg);
387 } else {
388 /* Show given text and possible message from pipe */
389 message (error, title, " %s \n %s ", text, msg);
391 return 1;
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.
404 void
405 canonicalize_pathname (char *path)
407 char *p, *s;
408 int len;
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) {
413 p = path + 2;
414 while (p[0] && p[0] != '/')
415 p++;
416 if (p[0] == '/' && p > path + 2)
417 lpath = p;
420 if (!lpath[0] || !lpath[1])
421 return;
423 /* Collapse multiple slashes */
424 p = lpath;
425 while (*p) {
426 if (p[0] == PATH_SEP && p[1] == PATH_SEP) {
427 s = p + 1;
428 while (*(++s) == PATH_SEP);
429 str_move (p + 1, s);
431 p++;
434 /* Collapse "/./" -> "/" */
435 p = lpath;
436 while (*p) {
437 if (p[0] == PATH_SEP && p[1] == '.' && p[2] == PATH_SEP)
438 str_move (p, p + 2);
439 else
440 p++;
443 /* Remove trailing slashes */
444 p = lpath + strlen (lpath) - 1;
445 while (p > lpath && *p == PATH_SEP)
446 *p-- = 0;
448 /* Remove leading "./" */
449 if (lpath[0] == '.' && lpath[1] == PATH_SEP) {
450 if (lpath[2] == 0) {
451 lpath[1] = 0;
452 return;
453 } else {
454 str_move (lpath, lpath + 2);
458 /* Remove trailing "/" or "/." */
459 len = strlen (lpath);
460 if (len < 2)
461 return;
462 if (lpath[len - 1] == PATH_SEP) {
463 lpath[len - 1] = 0;
464 } else {
465 if (lpath[len - 1] == '.' && lpath[len - 2] == PATH_SEP) {
466 if (len == 2) {
467 lpath[1] = 0;
468 return;
469 } else {
470 lpath[len - 2] = 0;
475 /* Collapse "/.." with the previous part of path */
476 p = lpath;
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)) {
480 p++;
481 continue;
484 /* search for the previous token */
485 s = p - 1;
486 while (s >= lpath && *s != PATH_SEP)
487 s--;
489 s++;
491 /* If the previous token is "..", we cannot collapse it */
492 if (s[0] == '.' && s[1] == '.' && s + 2 == p) {
493 p += 3;
494 continue;
497 if (p[3] != 0) {
498 if (s == lpath && *s == PATH_SEP) {
499 /* "/../foo" -> "/foo" */
500 str_move (s + 1, p + 4);
501 } else {
502 /* "token/../foo" -> "foo" */
503 str_move (s, p + 4);
505 p = (s > lpath) ? s - 1 : s;
506 continue;
509 /* trailing ".." */
510 if (s == lpath) {
511 /* "token/.." -> "." */
512 if (lpath[0] != PATH_SEP) {
513 lpath[0] = '.';
515 lpath[1] = 0;
516 } else {
517 /* "foo/token/.." -> "foo" */
518 if (s == lpath + 1)
519 s[0] = 0;
520 else
521 s[-1] = 0;
522 break;
525 break;
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 */
538 #ifndef HAVE_PUTENV
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;
545 #ifndef HAVE_GNU_LD
546 #define __environ environ
547 #endif
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;
556 register char **ep;
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){
564 ep[0] = ep[1];
565 ++ep;
567 *ep = NULL;
568 return 0;
572 size = 0;
573 for (ep = __environ; *ep != NULL; ++ep)
574 if (!strncmp (*ep, string, name_end - string) &&
575 (*ep)[name_end - string] == '=')
576 break;
577 else
578 ++size;
580 if (*ep == NULL){
581 static char **last_environ = NULL;
582 char **new_environ = g_new (char *, size + 2);
583 if (new_environ == NULL)
584 return -1;
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;
593 else
594 *ep = (char *) string;
596 return 0;
598 #endif /* !HAVE_PUTENV */
600 char *
601 mc_realpath (const char *path, char resolved_path[])
603 #ifdef USE_SYSTEM_REALPATH
604 return realpath (path, resolved_path);
605 #else
606 char copy_path[PATH_MAX];
607 char link_path[PATH_MAX];
608 char got_path[PATH_MAX];
609 char *new_path = got_path;
610 char *max_path;
611 int readlinks = 0;
612 int n;
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;
617 return NULL;
619 strcpy (copy_path, path);
620 path = copy_path;
621 max_path = copy_path + PATH_MAX - 2;
622 /* If it's a relative pathname use getwd for starters. */
623 if (*path != '/') {
624 /* Ohoo... */
625 #ifdef HAVE_GETCWD
626 getcwd (new_path, PATH_MAX - 1);
627 #else
628 getwd (new_path);
629 #endif
630 new_path += strlen (new_path);
631 if (new_path[-1] != '/')
632 *new_path++ = '/';
633 } else {
634 *new_path++ = '/';
635 path++;
637 /* Expand each slash-separated pathname component. */
638 while (*path != '\0') {
639 /* Ignore stray "/". */
640 if (*path == '/') {
641 path++;
642 continue;
644 if (*path == '.') {
645 /* Ignore ".". */
646 if (path[1] == '\0' || path[1] == '/') {
647 path++;
648 continue;
650 if (path[1] == '.') {
651 if (path[2] == '\0' || path[2] == '/') {
652 path += 2;
653 /* Ignore ".." at root. */
654 if (new_path == got_path + 1)
655 continue;
656 /* Handle ".." by backing up. */
657 while ((--new_path)[-1] != '/');
658 continue;
662 /* Safely copy the next pathname component. */
663 while (*path != '\0' && *path != '/') {
664 if (path > max_path) {
665 errno = ENAMETOOLONG;
666 return NULL;
668 *new_path++ = *path++;
670 #ifdef S_IFLNK
671 /* Protect against infinite loops. */
672 if (readlinks++ > MAXSYMLINKS) {
673 errno = ELOOP;
674 return NULL;
676 /* See if latest pathname component is a symlink. */
677 *new_path = '\0';
678 n = readlink (got_path, link_path, PATH_MAX - 1);
679 if (n < 0) {
680 /* EINVAL means the file exists but isn't a symlink. */
681 if (errno != EINVAL) {
682 /* Make sure it's null terminated. */
683 *new_path = '\0';
684 strcpy (resolved_path, got_path);
685 return NULL;
687 } else {
688 /* Note: readlink doesn't add the null byte. */
689 link_path[n] = '\0';
690 if (*link_path == '/')
691 /* Start over for an absolute symlink. */
692 new_path = got_path;
693 else
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;
699 return NULL;
701 /* Insert symlink contents into path. */
702 strcat (link_path, path);
703 strcpy (copy_path, link_path);
704 path = copy_path;
706 #endif /* S_IFLNK */
707 *new_path++ = '/';
709 /* Delete trailing slash but don't whomp a lone slash. */
710 if (new_path != got_path + 1 && new_path[-1] == '/')
711 new_path--;
712 /* Make sure it's null terminated. */
713 *new_path = '\0';
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;
724 static int ngroups;
725 static uid_t uid;
726 int i;
728 if (!initialized) {
729 uid = geteuid ();
731 ngroups = getgroups (0, NULL);
732 if (ngroups == -1)
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);
739 if (ngroups != 0) {
740 ngroups = getgroups (ngroups, groups);
741 if (ngroups == -1)
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 ();
749 initialized = TRUE;
752 if (st->st_uid == uid || uid == 0)
753 return 0;
755 for (i = 0; i < ngroups; i++) {
756 if (st->st_gid == groups[i])
757 return 1;
760 return 2;