Ticket #1897: Build breaks on ignored return values
[midnight-commander.git] / lib / utilunix.c
blob8c2bb58e4aa2a722847857a63129a9cd759d8e26
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 {
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);
243 * Return the directory where mc should keep its temporary files.
244 * This directory is (in Bourne shell terms) "${TMPDIR=/tmp}/mc-$USER"
245 * When called the first time, the directory is created if needed.
246 * The first call should be done early, since we are using fprintf()
247 * and not message() to report possible problems.
249 const char *
250 mc_tmpdir (void)
252 static char buffer[64];
253 static const char *tmpdir;
254 const char *sys_tmp;
255 struct passwd *pwd;
256 struct stat st;
257 const char *error = NULL;
259 /* Check if already correctly initialized */
260 if (tmpdir && lstat (tmpdir, &st) == 0 && S_ISDIR (st.st_mode) &&
261 st.st_uid == getuid () && (st.st_mode & 0777) == 0700)
262 return tmpdir;
264 sys_tmp = getenv ("TMPDIR");
265 if (!sys_tmp || sys_tmp[0] != '/') {
266 sys_tmp = TMPDIR_DEFAULT;
269 pwd = getpwuid (getuid ());
271 if (pwd)
272 g_snprintf (buffer, sizeof (buffer), "%s/mc-%s", sys_tmp,
273 pwd->pw_name);
274 else
275 g_snprintf (buffer, sizeof (buffer), "%s/mc-%lu", sys_tmp,
276 (unsigned long) getuid ());
278 canonicalize_pathname (buffer);
280 if (lstat (buffer, &st) == 0) {
281 /* Sanity check for existing directory */
282 if (!S_ISDIR (st.st_mode))
283 error = _("%s is not a directory\n");
284 else if (st.st_uid != getuid ())
285 error = _("Directory %s is not owned by you\n");
286 else if (((st.st_mode & 0777) != 0700)
287 && (chmod (buffer, 0700) != 0))
288 error = _("Cannot set correct permissions for directory %s\n");
289 } else {
290 /* Need to create directory */
291 if (mkdir (buffer, S_IRWXU) != 0) {
292 fprintf (stderr,
293 _("Cannot create temporary directory %s: %s\n"),
294 buffer, unix_error_string (errno));
295 error = "";
299 if (error != NULL) {
300 int test_fd;
301 char *test_fn, *fallback_prefix;
302 int fallback_ok = 0;
304 if (*error)
305 fprintf (stderr, error, buffer);
307 /* Test if sys_tmp is suitable for temporary files */
308 fallback_prefix = g_strdup_printf ("%s/mctest", sys_tmp);
309 test_fd = mc_mkstemps (&test_fn, fallback_prefix, NULL);
310 g_free (fallback_prefix);
311 if (test_fd != -1) {
312 close (test_fd);
313 test_fd = open (test_fn, O_RDONLY);
314 if (test_fd != -1) {
315 close (test_fd);
316 unlink (test_fn);
317 fallback_ok = 1;
321 if (fallback_ok) {
322 fprintf (stderr, _("Temporary files will be created in %s\n"),
323 sys_tmp);
324 g_snprintf (buffer, sizeof (buffer), "%s", sys_tmp);
325 error = NULL;
326 } else {
327 fprintf (stderr, _("Temporary files will not be created\n"));
328 g_snprintf (buffer, sizeof (buffer), "%s", "/dev/null/");
331 fprintf (stderr, "%s\n", _("Press any key to continue..."));
332 getc (stdin);
335 tmpdir = buffer;
337 if (!error)
338 g_setenv ("MC_TMPDIR", tmpdir, TRUE);
340 return tmpdir;
344 /* Pipes are guaranteed to be able to hold at least 4096 bytes */
345 /* More than that would be unportable */
346 #define MAX_PIPE_SIZE 4096
348 static int error_pipe[2]; /* File descriptors of error pipe */
349 static int old_error; /* File descriptor of old standard error */
351 /* Creates a pipe to hold standard error for a later analysis. */
352 /* The pipe can hold 4096 bytes. Make sure no more is written */
353 /* or a deadlock might occur. */
354 void open_error_pipe (void)
356 if (pipe (error_pipe) < 0){
357 message (D_NORMAL, _("Warning"), _(" Pipe failed "));
359 old_error = dup (2);
360 if(old_error < 0 || close(2) || dup (error_pipe[1]) != 2){
361 message (D_NORMAL, _("Warning"), _(" Dup failed "));
363 close (error_pipe[0]);
364 error_pipe[0] = -1;
366 else
369 * Settng stderr in nonblocking mode as we close it earlier, than
370 * program stops. We try to read some error at program startup,
371 * but we should not block on it.
373 * TODO: make piped stdin/stderr poll()/select()able to get rid
374 * of following hack.
376 int fd_flags;
377 fd_flags = fcntl (error_pipe[0], F_GETFL, NULL);
378 if (fd_flags != -1)
380 fd_flags |= O_NONBLOCK;
381 if (fcntl(error_pipe[0], F_SETFL, fd_flags) == -1)
383 /* TODO: handle it somehow */
387 /* we never write there */
388 close (error_pipe[1]);
389 error_pipe[1] = -1;
393 * Returns true if an error was displayed
394 * error: -1 - ignore errors, 0 - display warning, 1 - display error
395 * text is prepended to the error message from the pipe
398 close_error_pipe (int error, const char *text)
400 const char *title;
401 char msg[MAX_PIPE_SIZE];
402 int len = 0;
404 /* already closed */
405 if (error_pipe[0] == -1)
406 return 0;
408 if (error)
409 title = MSG_ERROR;
410 else
411 title = _("Warning");
412 if (old_error >= 0){
413 if (dup2 (old_error, 2))
415 message (error, MSG_ERROR, "%s", _("Error dup'ing old error pipe"));
416 return 1;
418 close (old_error);
419 len = read (error_pipe[0], msg, MAX_PIPE_SIZE - 1);
421 if (len >= 0)
422 msg[len] = 0;
423 close (error_pipe[0]);
424 error_pipe[0] = -1;
426 if (error < 0)
427 return 0; /* Just ignore error message */
428 if (text == NULL){
429 if (len <= 0)
430 return 0; /* Nothing to show */
432 /* Show message from pipe */
433 message (error, title, "%s", msg);
434 } else {
435 /* Show given text and possible message from pipe */
436 message (error, title, " %s \n %s ", text, msg);
438 return 1;
442 * Canonicalize path, and return a new path. Do everything in place.
443 * The new path differs from path in:
444 * Multiple `/'s are collapsed to a single `/'.
445 * Leading `./'s and trailing `/.'s are removed.
446 * Trailing `/'s are removed.
447 * Non-leading `../'s and trailing `..'s are handled by removing
448 * portions of the path.
449 * Well formed UNC paths are modified only in the local part.
451 void
452 custom_canonicalize_pathname (char *path, CANON_PATH_FLAGS flags)
454 char *p, *s;
455 int len;
456 char *lpath = path; /* path without leading UNC part */
458 /* Detect and preserve UNC paths: //server/... */
459 if ( ( flags & CANON_PATH_GUARDUNC ) && path[0] == PATH_SEP && path[1] == PATH_SEP) {
460 p = path + 2;
461 while (p[0] && p[0] != '/')
462 p++;
463 if (p[0] == '/' && p > path + 2)
464 lpath = p;
467 if (!lpath[0] || !lpath[1])
468 return;
470 if ( flags & CANON_PATH_JOINSLASHES ) {
471 /* Collapse multiple slashes */
472 p = lpath;
473 while (*p) {
474 if (p[0] == PATH_SEP && p[1] == PATH_SEP) {
475 s = p + 1;
476 while (*(++s) == PATH_SEP);
477 str_move (p + 1, s);
479 p++;
483 if ( flags & CANON_PATH_JOINSLASHES ) {
484 /* Collapse "/./" -> "/" */
485 p = lpath;
486 while (*p) {
487 if (p[0] == PATH_SEP && p[1] == '.' && p[2] == PATH_SEP)
488 str_move (p, p + 2);
489 else
490 p++;
494 if ( flags & CANON_PATH_REMSLASHDOTS ) {
495 /* Remove trailing slashes */
496 p = lpath + strlen (lpath) - 1;
497 while (p > lpath && *p == PATH_SEP)
498 *p-- = 0;
500 /* Remove leading "./" */
501 if (lpath[0] == '.' && lpath[1] == PATH_SEP) {
502 if (lpath[2] == 0) {
503 lpath[1] = 0;
504 return;
505 } else {
506 str_move (lpath, lpath + 2);
510 /* Remove trailing "/" or "/." */
511 len = strlen (lpath);
512 if (len < 2)
513 return;
514 if (lpath[len - 1] == PATH_SEP) {
515 lpath[len - 1] = 0;
516 } else {
517 if (lpath[len - 1] == '.' && lpath[len - 2] == PATH_SEP) {
518 if (len == 2) {
519 lpath[1] = 0;
520 return;
521 } else {
522 lpath[len - 2] = 0;
528 if ( flags & CANON_PATH_REMDOUBLEDOTS ) {
529 /* Collapse "/.." with the previous part of path */
530 p = lpath;
531 while (p[0] && p[1] && p[2]) {
532 if ((p[0] != PATH_SEP || p[1] != '.' || p[2] != '.')
533 || (p[3] != PATH_SEP && p[3] != 0)) {
534 p++;
535 continue;
538 /* search for the previous token */
539 s = p - 1;
540 while (s >= lpath && *s != PATH_SEP)
541 s--;
543 s++;
545 /* If the previous token is "..", we cannot collapse it */
546 if (s[0] == '.' && s[1] == '.' && s + 2 == p) {
547 p += 3;
548 continue;
551 if (p[3] != 0) {
552 if (s == lpath && *s == PATH_SEP) {
553 /* "/../foo" -> "/foo" */
554 str_move (s + 1, p + 4);
555 } else {
556 /* "token/../foo" -> "foo" */
557 str_move (s, p + 4);
559 p = (s > lpath) ? s - 1 : s;
560 continue;
563 /* trailing ".." */
564 if (s == lpath) {
565 /* "token/.." -> "." */
566 if (lpath[0] != PATH_SEP) {
567 lpath[0] = '.';
569 lpath[1] = 0;
570 } else {
571 /* "foo/token/.." -> "foo" */
572 if (s == lpath + 1)
573 s[0] = 0;
574 else
575 s[-1] = 0;
576 break;
579 break;
584 void
585 canonicalize_pathname (char *path)
587 custom_canonicalize_pathname (path, CANON_PATH_ALL);
590 #ifdef HAVE_GET_PROCESS_STATS
591 # include <sys/procstats.h>
593 int gettimeofday (struct timeval *tp, void *tzp)
595 return get_process_stats(tp, PS_SELF, 0, 0);
597 #endif /* HAVE_GET_PROCESS_STATS */
599 char *
600 mc_realpath (const char *path, char resolved_path[])
602 #ifdef USE_SYSTEM_REALPATH
603 return realpath (path, resolved_path);
604 #else
605 char copy_path[PATH_MAX];
606 char link_path[PATH_MAX];
607 char got_path[PATH_MAX];
608 char *new_path = got_path;
609 char *max_path;
610 int readlinks = 0;
611 int n;
613 /* Make a copy of the source path since we may need to modify it. */
614 if (strlen (path) >= PATH_MAX - 2) {
615 errno = ENAMETOOLONG;
616 return NULL;
618 strcpy (copy_path, path);
619 path = copy_path;
620 max_path = copy_path + PATH_MAX - 2;
621 /* If it's a relative pathname use getwd for starters. */
622 if (*path != '/') {
624 new_path = g_get_current_dir ();
625 if (new_path == NULL)
627 strcpy(got_path, "");
629 else
631 g_snprintf(got_path, PATH_MAX, "%s", new_path);
632 g_free(new_path);
633 new_path = got_path;
636 new_path += strlen (got_path);
637 if (new_path[-1] != '/')
638 *new_path++ = '/';
639 } else {
640 *new_path++ = '/';
641 path++;
643 /* Expand each slash-separated pathname component. */
644 while (*path != '\0') {
645 /* Ignore stray "/". */
646 if (*path == '/') {
647 path++;
648 continue;
650 if (*path == '.') {
651 /* Ignore ".". */
652 if (path[1] == '\0' || path[1] == '/') {
653 path++;
654 continue;
656 if (path[1] == '.') {
657 if (path[2] == '\0' || path[2] == '/') {
658 path += 2;
659 /* Ignore ".." at root. */
660 if (new_path == got_path + 1)
661 continue;
662 /* Handle ".." by backing up. */
663 while ((--new_path)[-1] != '/');
664 continue;
668 /* Safely copy the next pathname component. */
669 while (*path != '\0' && *path != '/') {
670 if (path > max_path) {
671 errno = ENAMETOOLONG;
672 return NULL;
674 *new_path++ = *path++;
676 #ifdef S_IFLNK
677 /* Protect against infinite loops. */
678 if (readlinks++ > MAXSYMLINKS) {
679 errno = ELOOP;
680 return NULL;
682 /* See if latest pathname component is a symlink. */
683 *new_path = '\0';
684 n = readlink (got_path, link_path, PATH_MAX - 1);
685 if (n < 0) {
686 /* EINVAL means the file exists but isn't a symlink. */
687 if (errno != EINVAL) {
688 /* Make sure it's null terminated. */
689 *new_path = '\0';
690 strcpy (resolved_path, got_path);
691 return NULL;
693 } else {
694 /* Note: readlink doesn't add the null byte. */
695 link_path[n] = '\0';
696 if (*link_path == '/')
697 /* Start over for an absolute symlink. */
698 new_path = got_path;
699 else
700 /* Otherwise back up over this component. */
701 while (*(--new_path) != '/');
702 /* Safe sex check. */
703 if (strlen (path) + n >= PATH_MAX - 2) {
704 errno = ENAMETOOLONG;
705 return NULL;
707 /* Insert symlink contents into path. */
708 strcat (link_path, path);
709 strcpy (copy_path, link_path);
710 path = copy_path;
712 #endif /* S_IFLNK */
713 *new_path++ = '/';
715 /* Delete trailing slash but don't whomp a lone slash. */
716 if (new_path != got_path + 1 && new_path[-1] == '/')
717 new_path--;
718 /* Make sure it's null terminated. */
719 *new_path = '\0';
720 strcpy (resolved_path, got_path);
721 return resolved_path;
722 #endif /* USE_SYSTEM_REALPATH */
725 /* Return the index of the permissions triplet */
727 get_user_permissions (struct stat *st) {
728 static gboolean initialized = FALSE;
729 static gid_t *groups;
730 static int ngroups;
731 static uid_t uid;
732 int i;
734 if (!initialized) {
735 uid = geteuid ();
737 ngroups = getgroups (0, NULL);
738 if (ngroups == -1)
739 ngroups = 0; /* ignore errors */
741 /* allocate space for one element in addition to what
742 * will be filled by getgroups(). */
743 groups = g_new (gid_t, ngroups + 1);
745 if (ngroups != 0) {
746 ngroups = getgroups (ngroups, groups);
747 if (ngroups == -1)
748 ngroups = 0; /* ignore errors */
751 /* getgroups() may or may not return the effective group ID,
752 * so we always include it at the end of the list. */
753 groups[ngroups++] = getegid ();
755 initialized = TRUE;
758 if (st->st_uid == uid || uid == 0)
759 return 0;
761 for (i = 0; i < ngroups; i++) {
762 if (st->st_gid == groups[i])
763 return 1;
766 return 2;