m4.include/mc-use-termcap.m4: fixed const char* issue which triggers break on -Wall
[free-mc.git] / src / utilunix.c
blobfdaafaa08ba10c1179889855bf3baaab72551978
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 "global.h"
52 #include "execute.h"
53 #include "wtools.h" /* message() */
55 struct sigaction startup_handler;
57 #define UID_CACHE_SIZE 200
58 #define GID_CACHE_SIZE 30
60 typedef struct {
61 int index;
62 char *string;
63 } int_cache;
65 static int_cache uid_cache [UID_CACHE_SIZE];
66 static int_cache gid_cache [GID_CACHE_SIZE];
68 static char *i_cache_match (int id, int_cache *cache, int size)
70 int i;
72 for (i = 0; i < size; i++)
73 if (cache [i].index == id)
74 return cache [i].string;
75 return 0;
78 static void i_cache_add (int id, int_cache *cache, int size, char *text,
79 int *last)
81 g_free (cache [*last].string);
82 cache [*last].string = g_strdup (text);
83 cache [*last].index = id;
84 *last = ((*last)+1) % size;
87 char *get_owner (int uid)
89 struct passwd *pwd;
90 static char ibuf [10];
91 char *name;
92 static int uid_last;
94 if ((name = i_cache_match (uid, uid_cache, UID_CACHE_SIZE)) != NULL)
95 return name;
97 pwd = getpwuid (uid);
98 if (pwd){
99 i_cache_add (uid, uid_cache, UID_CACHE_SIZE, pwd->pw_name, &uid_last);
100 return pwd->pw_name;
102 else {
103 g_snprintf (ibuf, sizeof (ibuf), "%d", uid);
104 return ibuf;
108 char *get_group (int gid)
110 struct group *grp;
111 static char gbuf [10];
112 char *name;
113 static int gid_last;
115 if ((name = i_cache_match (gid, gid_cache, GID_CACHE_SIZE)) != NULL)
116 return name;
118 grp = getgrgid (gid);
119 if (grp){
120 i_cache_add (gid, gid_cache, GID_CACHE_SIZE, grp->gr_name, &gid_last);
121 return grp->gr_name;
122 } else {
123 g_snprintf (gbuf, sizeof (gbuf), "%d", gid);
124 return gbuf;
128 /* Since ncurses uses a handler that automatically refreshes the */
129 /* screen after a SIGCONT, and we don't want this behavior when */
130 /* spawning a child, we save the original handler here */
131 void save_stop_handler (void)
133 sigaction (SIGTSTP, NULL, &startup_handler);
136 int my_system (int flags, const char *shell, const char *command)
138 struct sigaction ignore, save_intr, save_quit, save_stop;
139 pid_t pid;
140 int status = 0;
142 ignore.sa_handler = SIG_IGN;
143 sigemptyset (&ignore.sa_mask);
144 ignore.sa_flags = 0;
146 sigaction (SIGINT, &ignore, &save_intr);
147 sigaction (SIGQUIT, &ignore, &save_quit);
149 /* Restore the original SIGTSTP handler, we don't want ncurses' */
150 /* handler messing the screen after the SIGCONT */
151 sigaction (SIGTSTP, &startup_handler, &save_stop);
153 if ((pid = fork ()) < 0){
154 fprintf (stderr, "\n\nfork () = -1\n");
155 return -1;
157 if (pid == 0){
158 signal (SIGINT, SIG_DFL);
159 signal (SIGQUIT, SIG_DFL);
160 signal (SIGTSTP, SIG_DFL);
161 signal (SIGCHLD, SIG_DFL);
163 if (flags & EXECUTE_AS_SHELL)
164 execl (shell, shell, "-c", command, (char *) NULL);
165 else
167 gchar **shell_tokens;
168 const gchar *only_cmd;
169 shell_tokens = g_strsplit(shell," ", 2);
171 if (shell_tokens == NULL)
172 only_cmd = shell;
173 else
174 only_cmd = (*shell_tokens) ? *shell_tokens: shell;
176 execlp (only_cmd, shell, command, (char *) NULL);
179 execlp will replace current process,
180 therefore no sence in call of g_strfreev().
181 But this keeped for estetic reason :)
183 g_strfreev(shell_tokens);
187 _exit (127); /* Exec error */
188 } else {
189 while (waitpid (pid, &status, 0) < 0)
190 if (errno != EINTR){
191 status = -1;
192 break;
195 sigaction (SIGINT, &save_intr, NULL);
196 sigaction (SIGQUIT, &save_quit, NULL);
197 sigaction (SIGTSTP, &save_stop, NULL);
199 return WEXITSTATUS(status);
204 * Perform tilde expansion if possible.
205 * Always return a newly allocated string, even if it's unchanged.
207 char *
208 tilde_expand (const char *directory)
210 struct passwd *passwd;
211 const char *p, *q;
212 char *name;
214 if (*directory != '~')
215 return g_strdup (directory);
217 p = directory + 1;
219 /* d = "~" or d = "~/" */
220 if (!(*p) || (*p == PATH_SEP)) {
221 passwd = getpwuid (geteuid ());
222 q = (*p == PATH_SEP) ? p + 1 : "";
223 } else {
224 q = strchr (p, PATH_SEP);
225 if (!q) {
226 passwd = getpwnam (p);
227 } else {
228 name = g_strndup (p, q - p);
229 passwd = getpwnam (name);
230 q++;
231 g_free (name);
235 /* If we can't figure the user name, leave tilde unexpanded */
236 if (!passwd)
237 return g_strdup (directory);
239 return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
242 static void
243 mc_setenv (const char *name, const char *value, int overwrite_flag)
245 #if defined(HAVE_SETENV)
246 setenv (name, value, overwrite_flag);
247 #else
248 if (overwrite_flag || getenv (name) == NULL)
249 putenv (g_strconcat (name, "=", value, (char *) NULL));
250 #endif
254 * Return the directory where mc should keep its temporary files.
255 * This directory is (in Bourne shell terms) "${TMPDIR=/tmp}/mc-$USER"
256 * When called the first time, the directory is created if needed.
257 * The first call should be done early, since we are using fprintf()
258 * and not message() to report possible problems.
260 const char *
261 mc_tmpdir (void)
263 static char buffer[64];
264 static const char *tmpdir;
265 const char *sys_tmp;
266 struct passwd *pwd;
267 struct stat st;
268 const char *error = NULL;
270 /* Check if already correctly initialized */
271 if (tmpdir && lstat (tmpdir, &st) == 0 && S_ISDIR (st.st_mode) &&
272 st.st_uid == getuid () && (st.st_mode & 0777) == 0700)
273 return tmpdir;
275 sys_tmp = getenv ("TMPDIR");
276 if (!sys_tmp || sys_tmp[0] != '/') {
277 sys_tmp = TMPDIR_DEFAULT;
280 pwd = getpwuid (getuid ());
282 if (pwd)
283 g_snprintf (buffer, sizeof (buffer), "%s/mc-%s", sys_tmp,
284 pwd->pw_name);
285 else
286 g_snprintf (buffer, sizeof (buffer), "%s/mc-%lu", sys_tmp,
287 (unsigned long) getuid ());
289 canonicalize_pathname (buffer);
291 if (lstat (buffer, &st) == 0) {
292 /* Sanity check for existing directory */
293 if (!S_ISDIR (st.st_mode))
294 error = _("%s is not a directory\n");
295 else if (st.st_uid != getuid ())
296 error = _("Directory %s is not owned by you\n");
297 else if (((st.st_mode & 0777) != 0700)
298 && (chmod (buffer, 0700) != 0))
299 error = _("Cannot set correct permissions for directory %s\n");
300 } else {
301 /* Need to create directory */
302 if (mkdir (buffer, S_IRWXU) != 0) {
303 fprintf (stderr,
304 _("Cannot create temporary directory %s: %s\n"),
305 buffer, unix_error_string (errno));
306 error = "";
310 if (error != NULL) {
311 int test_fd;
312 char *test_fn, *fallback_prefix;
313 int fallback_ok = 0;
315 if (*error)
316 fprintf (stderr, error, buffer);
318 /* Test if sys_tmp is suitable for temporary files */
319 fallback_prefix = g_strdup_printf ("%s/mctest", sys_tmp);
320 test_fd = mc_mkstemps (&test_fn, fallback_prefix, NULL);
321 g_free (fallback_prefix);
322 if (test_fd != -1) {
323 close (test_fd);
324 test_fd = open (test_fn, O_RDONLY);
325 if (test_fd != -1) {
326 close (test_fd);
327 unlink (test_fn);
328 fallback_ok = 1;
332 if (fallback_ok) {
333 fprintf (stderr, _("Temporary files will be created in %s\n"),
334 sys_tmp);
335 g_snprintf (buffer, sizeof (buffer), "%s", sys_tmp);
336 error = NULL;
337 } else {
338 fprintf (stderr, _("Temporary files will not be created\n"));
339 g_snprintf (buffer, sizeof (buffer), "%s", "/dev/null/");
342 fprintf (stderr, "%s\n", _("Press any key to continue..."));
343 getc (stdin);
346 tmpdir = buffer;
348 if (!error)
349 mc_setenv ("MC_TMPDIR", tmpdir, 1);
351 return tmpdir;
355 /* Pipes are guaranteed to be able to hold at least 4096 bytes */
356 /* More than that would be unportable */
357 #define MAX_PIPE_SIZE 4096
359 static int error_pipe[2]; /* File descriptors of error pipe */
360 static int old_error; /* File descriptor of old standard error */
362 /* Creates a pipe to hold standard error for a later analysis. */
363 /* The pipe can hold 4096 bytes. Make sure no more is written */
364 /* or a deadlock might occur. */
365 void open_error_pipe (void)
367 if (pipe (error_pipe) < 0){
368 message (D_NORMAL, _("Warning"), _(" Pipe failed "));
370 old_error = dup (2);
371 if(old_error < 0 || close(2) || dup (error_pipe[1]) != 2){
372 message (D_NORMAL, _("Warning"), _(" Dup failed "));
374 close (error_pipe[0]);
375 error_pipe[0] = -1;
377 else
380 * Settng stderr in nonblocking mode as we close it earlier, than
381 * program stops. We try to read some error at program startup,
382 * but we should not block on it.
384 * TODO: make piped stdin/stderr poll()/select()able to get rid
385 * of following hack.
387 int fd_flags;
388 fd_flags = fcntl (error_pipe[0], F_GETFL, NULL);
389 if (fd_flags != -1)
391 fd_flags |= O_NONBLOCK;
392 if (fcntl(error_pipe[0], F_SETFL, fd_flags) == -1)
394 /* TODO: handle it somehow */
398 /* we never write there */
399 close (error_pipe[1]);
400 error_pipe[1] = -1;
404 * Returns true if an error was displayed
405 * error: -1 - ignore errors, 0 - display warning, 1 - display error
406 * text is prepended to the error message from the pipe
409 close_error_pipe (int error, const char *text)
411 const char *title;
412 char msg[MAX_PIPE_SIZE];
413 int len = 0;
415 /* already closed */
416 if (error_pipe[0] == -1)
417 return 0;
419 if (error)
420 title = MSG_ERROR;
421 else
422 title = _("Warning");
423 if (old_error >= 0){
424 close (2);
425 dup (old_error);
426 close (old_error);
427 len = read (error_pipe[0], msg, MAX_PIPE_SIZE - 1);
429 if (len >= 0)
430 msg[len] = 0;
431 close (error_pipe[0]);
432 error_pipe[0] = -1;
434 if (error < 0)
435 return 0; /* Just ignore error message */
436 if (text == NULL){
437 if (len <= 0)
438 return 0; /* Nothing to show */
440 /* Show message from pipe */
441 message (error, title, "%s", msg);
442 } else {
443 /* Show given text and possible message from pipe */
444 message (error, title, " %s \n %s ", text, msg);
446 return 1;
450 * Canonicalize path, and return a new path. Do everything in place.
451 * The new path differs from path in:
452 * Multiple `/'s are collapsed to a single `/'.
453 * Leading `./'s and trailing `/.'s are removed.
454 * Trailing `/'s are removed.
455 * Non-leading `../'s and trailing `..'s are handled by removing
456 * portions of the path.
457 * Well formed UNC paths are modified only in the local part.
459 void
460 canonicalize_pathname (char *path)
462 char *p, *s;
463 int len;
464 char *lpath = path; /* path without leading UNC part */
466 /* Detect and preserve UNC paths: //server/... */
467 if (path[0] == PATH_SEP && path[1] == PATH_SEP) {
468 p = path + 2;
469 while (p[0] && p[0] != '/')
470 p++;
471 if (p[0] == '/' && p > path + 2)
472 lpath = p;
475 if (!lpath[0] || !lpath[1])
476 return;
478 /* Collapse multiple slashes */
479 p = lpath;
480 while (*p) {
481 if (p[0] == PATH_SEP && p[1] == PATH_SEP) {
482 s = p + 1;
483 while (*(++s) == PATH_SEP);
484 str_move (p + 1, s);
486 p++;
489 /* Collapse "/./" -> "/" */
490 p = lpath;
491 while (*p) {
492 if (p[0] == PATH_SEP && p[1] == '.' && p[2] == PATH_SEP)
493 str_move (p, p + 2);
494 else
495 p++;
498 /* Remove trailing slashes */
499 p = lpath + strlen (lpath) - 1;
500 while (p > lpath && *p == PATH_SEP)
501 *p-- = 0;
503 /* Remove leading "./" */
504 if (lpath[0] == '.' && lpath[1] == PATH_SEP) {
505 if (lpath[2] == 0) {
506 lpath[1] = 0;
507 return;
508 } else {
509 str_move (lpath, lpath + 2);
513 /* Remove trailing "/" or "/." */
514 len = strlen (lpath);
515 if (len < 2)
516 return;
517 if (lpath[len - 1] == PATH_SEP) {
518 lpath[len - 1] = 0;
519 } else {
520 if (lpath[len - 1] == '.' && lpath[len - 2] == PATH_SEP) {
521 if (len == 2) {
522 lpath[1] = 0;
523 return;
524 } else {
525 lpath[len - 2] = 0;
530 /* Collapse "/.." with the previous part of path */
531 p = lpath;
532 while (p[0] && p[1] && p[2]) {
533 if ((p[0] != PATH_SEP || p[1] != '.' || p[2] != '.')
534 || (p[3] != PATH_SEP && p[3] != 0)) {
535 p++;
536 continue;
539 /* search for the previous token */
540 s = p - 1;
541 while (s >= lpath && *s != PATH_SEP)
542 s--;
544 s++;
546 /* If the previous token is "..", we cannot collapse it */
547 if (s[0] == '.' && s[1] == '.' && s + 2 == p) {
548 p += 3;
549 continue;
552 if (p[3] != 0) {
553 if (s == lpath && *s == PATH_SEP) {
554 /* "/../foo" -> "/foo" */
555 str_move (s + 1, p + 4);
556 } else {
557 /* "token/../foo" -> "foo" */
558 str_move (s, p + 4);
560 p = (s > lpath) ? s - 1 : s;
561 continue;
564 /* trailing ".." */
565 if (s == lpath) {
566 /* "token/.." -> "." */
567 if (lpath[0] != PATH_SEP) {
568 lpath[0] = '.';
570 lpath[1] = 0;
571 } else {
572 /* "foo/token/.." -> "foo" */
573 if (s == lpath + 1)
574 s[0] = 0;
575 else
576 s[-1] = 0;
577 break;
580 break;
584 #ifdef HAVE_GET_PROCESS_STATS
585 # include <sys/procstats.h>
587 int gettimeofday (struct timeval *tp, void *tzp)
589 return get_process_stats(tp, PS_SELF, 0, 0);
591 #endif /* HAVE_GET_PROCESS_STATS */
593 #ifndef HAVE_PUTENV
595 /* The following piece of code was copied from the GNU C Library */
596 /* And is provided here for nextstep who lacks putenv */
598 extern char **environ;
600 #ifndef HAVE_GNU_LD
601 #define __environ environ
602 #endif
605 /* Put STRING, which is of the form "NAME=VALUE", in the environment. */
607 putenv (char *string)
609 const char *const name_end = strchr (string, '=');
610 register size_t size;
611 register char **ep;
613 if (name_end == NULL){
614 /* Remove the variable from the environment. */
615 size = strlen (string);
616 for (ep = __environ; *ep != NULL; ++ep)
617 if (!strncmp (*ep, string, size) && (*ep)[size] == '='){
618 while (ep[1] != NULL){
619 ep[0] = ep[1];
620 ++ep;
622 *ep = NULL;
623 return 0;
627 size = 0;
628 for (ep = __environ; *ep != NULL; ++ep)
629 if (!strncmp (*ep, string, name_end - string) &&
630 (*ep)[name_end - string] == '=')
631 break;
632 else
633 ++size;
635 if (*ep == NULL){
636 static char **last_environ = NULL;
637 char **new_environ = g_new (char *, size + 2);
638 if (new_environ == NULL)
639 return -1;
640 (void) memcpy ((void *) new_environ, (void *) __environ,
641 size * sizeof (char *));
642 new_environ[size] = (char *) string;
643 new_environ[size + 1] = NULL;
644 g_free ((void *) last_environ);
645 last_environ = new_environ;
646 __environ = new_environ;
648 else
649 *ep = (char *) string;
651 return 0;
653 #endif /* !HAVE_PUTENV */
655 char *
656 mc_realpath (const char *path, char resolved_path[])
658 #ifdef USE_SYSTEM_REALPATH
659 return realpath (path, resolved_path);
660 #else
661 char copy_path[PATH_MAX];
662 char link_path[PATH_MAX];
663 char got_path[PATH_MAX];
664 char *new_path = got_path;
665 char *max_path;
666 int readlinks = 0;
667 int n;
669 /* Make a copy of the source path since we may need to modify it. */
670 if (strlen (path) >= PATH_MAX - 2) {
671 errno = ENAMETOOLONG;
672 return NULL;
674 strcpy (copy_path, path);
675 path = copy_path;
676 max_path = copy_path + PATH_MAX - 2;
677 /* If it's a relative pathname use getwd for starters. */
678 if (*path != '/') {
679 /* Ohoo... */
680 #ifdef HAVE_GETCWD
681 getcwd (new_path, PATH_MAX - 1);
682 #else
683 getwd (new_path);
684 #endif
685 new_path += strlen (new_path);
686 if (new_path[-1] != '/')
687 *new_path++ = '/';
688 } else {
689 *new_path++ = '/';
690 path++;
692 /* Expand each slash-separated pathname component. */
693 while (*path != '\0') {
694 /* Ignore stray "/". */
695 if (*path == '/') {
696 path++;
697 continue;
699 if (*path == '.') {
700 /* Ignore ".". */
701 if (path[1] == '\0' || path[1] == '/') {
702 path++;
703 continue;
705 if (path[1] == '.') {
706 if (path[2] == '\0' || path[2] == '/') {
707 path += 2;
708 /* Ignore ".." at root. */
709 if (new_path == got_path + 1)
710 continue;
711 /* Handle ".." by backing up. */
712 while ((--new_path)[-1] != '/');
713 continue;
717 /* Safely copy the next pathname component. */
718 while (*path != '\0' && *path != '/') {
719 if (path > max_path) {
720 errno = ENAMETOOLONG;
721 return NULL;
723 *new_path++ = *path++;
725 #ifdef S_IFLNK
726 /* Protect against infinite loops. */
727 if (readlinks++ > MAXSYMLINKS) {
728 errno = ELOOP;
729 return NULL;
731 /* See if latest pathname component is a symlink. */
732 *new_path = '\0';
733 n = readlink (got_path, link_path, PATH_MAX - 1);
734 if (n < 0) {
735 /* EINVAL means the file exists but isn't a symlink. */
736 if (errno != EINVAL) {
737 /* Make sure it's null terminated. */
738 *new_path = '\0';
739 strcpy (resolved_path, got_path);
740 return NULL;
742 } else {
743 /* Note: readlink doesn't add the null byte. */
744 link_path[n] = '\0';
745 if (*link_path == '/')
746 /* Start over for an absolute symlink. */
747 new_path = got_path;
748 else
749 /* Otherwise back up over this component. */
750 while (*(--new_path) != '/');
751 /* Safe sex check. */
752 if (strlen (path) + n >= PATH_MAX - 2) {
753 errno = ENAMETOOLONG;
754 return NULL;
756 /* Insert symlink contents into path. */
757 strcat (link_path, path);
758 strcpy (copy_path, link_path);
759 path = copy_path;
761 #endif /* S_IFLNK */
762 *new_path++ = '/';
764 /* Delete trailing slash but don't whomp a lone slash. */
765 if (new_path != got_path + 1 && new_path[-1] == '/')
766 new_path--;
767 /* Make sure it's null terminated. */
768 *new_path = '\0';
769 strcpy (resolved_path, got_path);
770 return resolved_path;
771 #endif /* USE_SYSTEM_REALPATH */
774 /* Return the index of the permissions triplet */
776 get_user_permissions (struct stat *st) {
777 static gboolean initialized = FALSE;
778 static gid_t *groups;
779 static int ngroups;
780 static uid_t uid;
781 int i;
783 if (!initialized) {
784 uid = geteuid ();
786 ngroups = getgroups (0, NULL);
787 if (ngroups == -1)
788 ngroups = 0; /* ignore errors */
790 /* allocate space for one element in addition to what
791 * will be filled by getgroups(). */
792 groups = g_new (gid_t, ngroups + 1);
794 if (ngroups != 0) {
795 ngroups = getgroups (ngroups, groups);
796 if (ngroups == -1)
797 ngroups = 0; /* ignore errors */
800 /* getgroups() may or may not return the effective group ID,
801 * so we always include it at the end of the list. */
802 groups[ngroups++] = getegid ();
804 initialized = TRUE;
807 if (st->st_uid == uid || uid == 0)
808 return 0;
810 for (i = 0; i < ngroups; i++) {
811 if (st->st_gid == groups[i])
812 return 1;
815 return 2;