Fixed up several comments
[midnight-commander.git] / lib / utilunix.c
blob806ad70a5f849a661596362a4250f4eac5866174
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() */
56 #ifdef HAVE_CHARSET
57 #include "src/charsets.h"
58 #endif
60 struct sigaction startup_handler;
62 #define UID_CACHE_SIZE 200
63 #define GID_CACHE_SIZE 30
65 typedef struct
67 int index;
68 char *string;
69 } int_cache;
71 static int_cache uid_cache[UID_CACHE_SIZE];
72 static int_cache gid_cache[GID_CACHE_SIZE];
74 static char *
75 i_cache_match (int id, int_cache * cache, int size)
77 int i;
79 for (i = 0; i < size; i++)
80 if (cache[i].index == id)
81 return cache[i].string;
82 return 0;
85 static void
86 i_cache_add (int id, int_cache * cache, int size, char *text, int *last)
88 g_free (cache[*last].string);
89 cache[*last].string = g_strdup (text);
90 cache[*last].index = id;
91 *last = ((*last) + 1) % size;
94 char *
95 get_owner (int uid)
97 struct passwd *pwd;
98 static char ibuf[10];
99 char *name;
100 static int uid_last;
102 name = i_cache_match (uid, uid_cache, UID_CACHE_SIZE);
103 if (name != NULL)
104 return name;
106 pwd = getpwuid (uid);
107 if (pwd != NULL)
109 i_cache_add (uid, uid_cache, UID_CACHE_SIZE, pwd->pw_name, &uid_last);
110 return pwd->pw_name;
112 else
114 g_snprintf (ibuf, sizeof (ibuf), "%d", uid);
115 return ibuf;
119 char *
120 get_group (int gid)
122 struct group *grp;
123 static char gbuf[10];
124 char *name;
125 static int gid_last;
127 name = i_cache_match (gid, gid_cache, GID_CACHE_SIZE);
128 if (name != NULL)
129 return name;
131 grp = getgrgid (gid);
132 if (grp != NULL)
134 i_cache_add (gid, gid_cache, GID_CACHE_SIZE, grp->gr_name, &gid_last);
135 return grp->gr_name;
137 else
139 g_snprintf (gbuf, sizeof (gbuf), "%d", gid);
140 return gbuf;
144 /* Since ncurses uses a handler that automatically refreshes the */
145 /* screen after a SIGCONT, and we don't want this behavior when */
146 /* spawning a child, we save the original handler here */
147 void
148 save_stop_handler (void)
150 sigaction (SIGTSTP, NULL, &startup_handler);
154 my_system (int flags, const char *shell, const char *command)
156 struct sigaction ignore, save_intr, save_quit, save_stop;
157 pid_t pid;
158 int status = 0;
160 ignore.sa_handler = SIG_IGN;
161 sigemptyset (&ignore.sa_mask);
162 ignore.sa_flags = 0;
164 sigaction (SIGINT, &ignore, &save_intr);
165 sigaction (SIGQUIT, &ignore, &save_quit);
167 /* Restore the original SIGTSTP handler, we don't want ncurses' */
168 /* handler messing the screen after the SIGCONT */
169 sigaction (SIGTSTP, &startup_handler, &save_stop);
171 pid = fork ();
172 if (pid < 0)
174 fprintf (stderr, "\n\nfork () = -1\n");
175 status = -1;
177 else if (pid == 0)
179 signal (SIGINT, SIG_DFL);
180 signal (SIGQUIT, SIG_DFL);
181 signal (SIGTSTP, SIG_DFL);
182 signal (SIGCHLD, SIG_DFL);
184 if (flags & EXECUTE_AS_SHELL)
185 execl (shell, shell, "-c", command, (char *) NULL);
186 else
188 gchar **shell_tokens;
189 const gchar *only_cmd;
191 shell_tokens = g_strsplit (shell, " ", 2);
192 if (shell_tokens == NULL)
193 only_cmd = shell;
194 else
195 only_cmd = (*shell_tokens != NULL) ? *shell_tokens : shell;
197 execlp (only_cmd, shell, command, (char *) NULL);
200 execlp will replace current process,
201 therefore no sence in call of g_strfreev().
202 But this keeped for estetic reason :)
204 g_strfreev (shell_tokens);
208 _exit (127); /* Exec error */
210 else
212 while (TRUE)
214 if (waitpid (pid, &status, 0) > 0)
216 status = WEXITSTATUS(status);
217 break;
219 if (errno != EINTR)
221 status = -1;
222 break;
226 sigaction (SIGINT, &save_intr, NULL);
227 sigaction (SIGQUIT, &save_quit, NULL);
228 sigaction (SIGTSTP, &save_stop, NULL);
230 return status;
235 * Perform tilde expansion if possible.
236 * Always return a newly allocated string, even if it's unchanged.
238 char *
239 tilde_expand (const char *directory)
241 struct passwd *passwd;
242 const char *p, *q;
243 char *name;
245 if (*directory != '~')
246 return g_strdup (directory);
248 p = directory + 1;
250 /* d = "~" or d = "~/" */
251 if (!(*p) || (*p == PATH_SEP))
253 passwd = getpwuid (geteuid ());
254 q = (*p == PATH_SEP) ? p + 1 : "";
256 else
258 q = strchr (p, PATH_SEP);
259 if (!q)
261 passwd = getpwnam (p);
263 else
265 name = g_strndup (p, q - p);
266 passwd = getpwnam (name);
267 q++;
268 g_free (name);
272 /* If we can't figure the user name, leave tilde unexpanded */
273 if (!passwd)
274 return g_strdup (directory);
276 return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
280 * Return the directory where mc should keep its temporary files.
281 * This directory is (in Bourne shell terms) "${TMPDIR=/tmp}/mc-$USER"
282 * When called the first time, the directory is created if needed.
283 * The first call should be done early, since we are using fprintf()
284 * and not message() to report possible problems.
286 const char *
287 mc_tmpdir (void)
289 static char buffer[64];
290 static const char *tmpdir;
291 const char *sys_tmp;
292 struct passwd *pwd;
293 struct stat st;
294 const char *error = NULL;
296 /* Check if already correctly initialized */
297 if (tmpdir && lstat (tmpdir, &st) == 0 && S_ISDIR (st.st_mode) &&
298 st.st_uid == getuid () && (st.st_mode & 0777) == 0700)
299 return tmpdir;
301 sys_tmp = getenv ("TMPDIR");
302 if (!sys_tmp || sys_tmp[0] != '/')
304 sys_tmp = TMPDIR_DEFAULT;
307 pwd = getpwuid (getuid ());
309 if (pwd)
310 g_snprintf (buffer, sizeof (buffer), "%s/mc-%s", sys_tmp, pwd->pw_name);
311 else
312 g_snprintf (buffer, sizeof (buffer), "%s/mc-%lu", sys_tmp, (unsigned long) getuid ());
314 canonicalize_pathname (buffer);
316 if (lstat (buffer, &st) == 0)
318 /* Sanity check for existing directory */
319 if (!S_ISDIR (st.st_mode))
320 error = _("%s is not a directory\n");
321 else if (st.st_uid != getuid ())
322 error = _("Directory %s is not owned by you\n");
323 else if (((st.st_mode & 0777) != 0700) && (chmod (buffer, 0700) != 0))
324 error = _("Cannot set correct permissions for directory %s\n");
326 else
328 /* Need to create directory */
329 if (mkdir (buffer, S_IRWXU) != 0)
331 fprintf (stderr,
332 _("Cannot create temporary directory %s: %s\n"),
333 buffer, unix_error_string (errno));
334 error = "";
338 if (error != NULL)
340 int test_fd;
341 char *test_fn, *fallback_prefix;
342 int fallback_ok = 0;
344 if (*error)
345 fprintf (stderr, error, buffer);
347 /* Test if sys_tmp is suitable for temporary files */
348 fallback_prefix = g_strdup_printf ("%s/mctest", sys_tmp);
349 test_fd = mc_mkstemps (&test_fn, fallback_prefix, NULL);
350 g_free (fallback_prefix);
351 if (test_fd != -1)
353 close (test_fd);
354 test_fd = open (test_fn, O_RDONLY);
355 if (test_fd != -1)
357 close (test_fd);
358 unlink (test_fn);
359 fallback_ok = 1;
363 if (fallback_ok)
365 fprintf (stderr, _("Temporary files will be created in %s\n"), sys_tmp);
366 g_snprintf (buffer, sizeof (buffer), "%s", sys_tmp);
367 error = NULL;
369 else
371 fprintf (stderr, _("Temporary files will not be created\n"));
372 g_snprintf (buffer, sizeof (buffer), "%s", "/dev/null/");
375 fprintf (stderr, "%s\n", _("Press any key to continue..."));
376 getc (stdin);
379 tmpdir = buffer;
381 if (!error)
382 g_setenv ("MC_TMPDIR", tmpdir, TRUE);
384 return tmpdir;
388 /* Pipes are guaranteed to be able to hold at least 4096 bytes */
389 /* More than that would be unportable */
390 #define MAX_PIPE_SIZE 4096
392 static int error_pipe[2]; /* File descriptors of error pipe */
393 static int old_error; /* File descriptor of old standard error */
395 /* Creates a pipe to hold standard error for a later analysis. */
396 /* The pipe can hold 4096 bytes. Make sure no more is written */
397 /* or a deadlock might occur. */
398 void
399 open_error_pipe (void)
401 if (pipe (error_pipe) < 0)
403 message (D_NORMAL, _("Warning"), _("Pipe failed"));
405 old_error = dup (2);
406 if (old_error < 0 || close (2) || dup (error_pipe[1]) != 2)
408 message (D_NORMAL, _("Warning"), _("Dup failed"));
410 close (error_pipe[0]);
411 error_pipe[0] = -1;
413 else
416 * Settng stderr in nonblocking mode as we close it earlier, than
417 * program stops. We try to read some error at program startup,
418 * but we should not block on it.
420 * TODO: make piped stdin/stderr poll()/select()able to get rid
421 * of following hack.
423 int fd_flags;
424 fd_flags = fcntl (error_pipe[0], F_GETFL, NULL);
425 if (fd_flags != -1)
427 fd_flags |= O_NONBLOCK;
428 if (fcntl (error_pipe[0], F_SETFL, fd_flags) == -1)
430 /* TODO: handle it somehow */
434 /* we never write there */
435 close (error_pipe[1]);
436 error_pipe[1] = -1;
440 * Returns true if an error was displayed
441 * error: -1 - ignore errors, 0 - display warning, 1 - display error
442 * text is prepended to the error message from the pipe
445 close_error_pipe (int error, const char *text)
447 const char *title;
448 char msg[MAX_PIPE_SIZE];
449 int len = 0;
451 /* already closed */
452 if (error_pipe[0] == -1)
453 return 0;
455 if (error)
456 title = MSG_ERROR;
457 else
458 title = _("Warning");
459 if (old_error >= 0)
461 if (dup2 (old_error, 2) == -1)
463 message (error, MSG_ERROR, _("Error dup'ing old error pipe"));
464 return 1;
466 close (old_error);
467 len = read (error_pipe[0], msg, MAX_PIPE_SIZE - 1);
469 if (len >= 0)
470 msg[len] = 0;
471 close (error_pipe[0]);
472 error_pipe[0] = -1;
474 if (error < 0)
475 return 0; /* Just ignore error message */
476 if (text == NULL)
478 if (len <= 0)
479 return 0; /* Nothing to show */
481 /* Show message from pipe */
482 message (error, title, "%s", msg);
484 else
486 /* Show given text and possible message from pipe */
487 message (error, title, "%s\n%s", text, msg);
489 return 1;
493 * Canonicalize path, and return a new path. Do everything in place.
494 * The new path differs from path in:
495 * Multiple `/'s are collapsed to a single `/'.
496 * Leading `./'s and trailing `/.'s are removed.
497 * Trailing `/'s are removed.
498 * Non-leading `../'s and trailing `..'s are handled by removing
499 * portions of the path.
500 * Well formed UNC paths are modified only in the local part.
502 void
503 custom_canonicalize_pathname (char *path, CANON_PATH_FLAGS flags)
505 char *p, *s;
506 int len;
507 char *lpath = path; /* path without leading UNC part */
509 /* Detect and preserve UNC paths: //server/... */
510 if ((flags & CANON_PATH_GUARDUNC) && path[0] == PATH_SEP && path[1] == PATH_SEP)
512 p = path + 2;
513 while (p[0] && p[0] != '/')
514 p++;
515 if (p[0] == '/' && p > path + 2)
516 lpath = p;
519 if (!lpath[0] || !lpath[1])
520 return;
522 if (flags & CANON_PATH_JOINSLASHES)
524 /* Collapse multiple slashes */
525 p = lpath;
526 while (*p)
528 if (p[0] == PATH_SEP && p[1] == PATH_SEP)
530 s = p + 1;
531 while (*(++s) == PATH_SEP);
532 str_move (p + 1, s);
534 p++;
538 if (flags & CANON_PATH_JOINSLASHES)
540 /* Collapse "/./" -> "/" */
541 p = lpath;
542 while (*p)
544 if (p[0] == PATH_SEP && p[1] == '.' && p[2] == PATH_SEP)
545 str_move (p, p + 2);
546 else
547 p++;
551 if (flags & CANON_PATH_REMSLASHDOTS)
553 /* Remove trailing slashes */
554 p = lpath + strlen (lpath) - 1;
555 while (p > lpath && *p == PATH_SEP)
556 *p-- = 0;
558 /* Remove leading "./" */
559 if (lpath[0] == '.' && lpath[1] == PATH_SEP)
561 if (lpath[2] == 0)
563 lpath[1] = 0;
564 return;
566 else
568 str_move (lpath, lpath + 2);
572 /* Remove trailing "/" or "/." */
573 len = strlen (lpath);
574 if (len < 2)
575 return;
576 if (lpath[len - 1] == PATH_SEP)
578 lpath[len - 1] = 0;
580 else
582 if (lpath[len - 1] == '.' && lpath[len - 2] == PATH_SEP)
584 if (len == 2)
586 lpath[1] = 0;
587 return;
589 else
591 lpath[len - 2] = 0;
597 if (flags & CANON_PATH_REMDOUBLEDOTS)
599 const size_t enc_prefix_len = strlen (VFS_ENCODING_PREFIX);
601 /* Collapse "/.." with the previous part of path */
602 p = lpath;
603 while (p[0] && p[1] && p[2])
605 if ((p[0] != PATH_SEP || p[1] != '.' || p[2] != '.') || (p[3] != PATH_SEP && p[3] != 0))
607 p++;
608 continue;
611 /* search for the previous token */
612 s = p - 1;
613 while (s >= lpath && *s != PATH_SEP)
614 s--;
616 s++;
618 /* If the previous token is "..", we cannot collapse it */
619 if (s[0] == '.' && s[1] == '.' && s + 2 == p)
621 p += 3;
622 continue;
625 if (p[3] != 0)
627 if (s == lpath && *s == PATH_SEP)
629 /* "/../foo" -> "/foo" */
630 str_move (s + 1, p + 4);
632 else
634 /* "token/../foo" -> "foo" */
635 #if HAVE_CHARSET
636 if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
637 && (is_supported_encoding (s + enc_prefix_len)))
638 /* special case: remove encoding */
639 str_move (s, p + 1);
640 else
641 #endif /* HAVE_CHARSET */
642 str_move (s, p + 4);
644 p = (s > lpath) ? s - 1 : s;
645 continue;
648 /* trailing ".." */
649 if (s == lpath)
651 /* "token/.." -> "." */
652 if (lpath[0] != PATH_SEP)
654 lpath[0] = '.';
656 lpath[1] = 0;
658 else
660 /* "foo/token/.." -> "foo" */
661 if (s == lpath + 1)
662 s[0] = 0;
663 #if HAVE_CHARSET
664 else if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
665 && (is_supported_encoding (s + enc_prefix_len)))
667 /* special case: remove encoding */
668 s[0] = '.';
669 s[1] = '.';
670 s[2] = '\0';
672 /* search for the previous token */
673 /* s[-1] == PATH_SEP */
674 p = s - 1;
675 while (p >= lpath && *p != PATH_SEP)
676 p--;
678 if (p != NULL)
679 continue;
681 #endif /* HAVE_CHARSET */
682 else
683 s[-1] = 0;
684 break;
687 break;
692 void
693 canonicalize_pathname (char *path)
695 custom_canonicalize_pathname (path, CANON_PATH_ALL);
698 #ifdef HAVE_GET_PROCESS_STATS
699 # include <sys/procstats.h>
702 gettimeofday (struct timeval *tp, void *tzp)
704 return get_process_stats (tp, PS_SELF, 0, 0);
706 #endif /* HAVE_GET_PROCESS_STATS */
708 #ifndef HAVE_REALPATH
709 char *
710 mc_realpath (const char *path, char *resolved_path)
712 char copy_path[PATH_MAX];
713 char link_path[PATH_MAX];
714 char got_path[PATH_MAX];
715 char *new_path = got_path;
716 char *max_path;
717 int readlinks = 0;
718 int n;
720 /* Make a copy of the source path since we may need to modify it. */
721 if (strlen (path) >= PATH_MAX - 2)
723 errno = ENAMETOOLONG;
724 return NULL;
726 strcpy (copy_path, path);
727 path = copy_path;
728 max_path = copy_path + PATH_MAX - 2;
729 /* If it's a relative pathname use getwd for starters. */
730 if (*path != '/')
733 new_path = g_get_current_dir ();
734 if (new_path == NULL)
736 strcpy (got_path, "");
738 else
740 g_snprintf (got_path, PATH_MAX, "%s", new_path);
741 g_free (new_path);
742 new_path = got_path;
745 new_path += strlen (got_path);
746 if (new_path[-1] != '/')
747 *new_path++ = '/';
749 else
751 *new_path++ = '/';
752 path++;
754 /* Expand each slash-separated pathname component. */
755 while (*path != '\0')
757 /* Ignore stray "/". */
758 if (*path == '/')
760 path++;
761 continue;
763 if (*path == '.')
765 /* Ignore ".". */
766 if (path[1] == '\0' || path[1] == '/')
768 path++;
769 continue;
771 if (path[1] == '.')
773 if (path[2] == '\0' || path[2] == '/')
775 path += 2;
776 /* Ignore ".." at root. */
777 if (new_path == got_path + 1)
778 continue;
779 /* Handle ".." by backing up. */
780 while ((--new_path)[-1] != '/');
781 continue;
785 /* Safely copy the next pathname component. */
786 while (*path != '\0' && *path != '/')
788 if (path > max_path)
790 errno = ENAMETOOLONG;
791 return NULL;
793 *new_path++ = *path++;
795 #ifdef S_IFLNK
796 /* Protect against infinite loops. */
797 if (readlinks++ > MAXSYMLINKS)
799 errno = ELOOP;
800 return NULL;
802 /* See if latest pathname component is a symlink. */
803 *new_path = '\0';
804 n = readlink (got_path, link_path, PATH_MAX - 1);
805 if (n < 0)
807 /* EINVAL means the file exists but isn't a symlink. */
808 if (errno != EINVAL)
810 /* Make sure it's null terminated. */
811 *new_path = '\0';
812 strcpy (resolved_path, got_path);
813 return NULL;
816 else
818 /* Note: readlink doesn't add the null byte. */
819 link_path[n] = '\0';
820 if (*link_path == '/')
821 /* Start over for an absolute symlink. */
822 new_path = got_path;
823 else
824 /* Otherwise back up over this component. */
825 while (*(--new_path) != '/');
826 /* Safe sex check. */
827 if (strlen (path) + n >= PATH_MAX - 2)
829 errno = ENAMETOOLONG;
830 return NULL;
832 /* Insert symlink contents into path. */
833 strcat (link_path, path);
834 strcpy (copy_path, link_path);
835 path = copy_path;
837 #endif /* S_IFLNK */
838 *new_path++ = '/';
840 /* Delete trailing slash but don't whomp a lone slash. */
841 if (new_path != got_path + 1 && new_path[-1] == '/')
842 new_path--;
843 /* Make sure it's null terminated. */
844 *new_path = '\0';
845 strcpy (resolved_path, got_path);
846 return resolved_path;
848 #endif /* HAVE_REALPATH */
850 /* Return the index of the permissions triplet */
852 get_user_permissions (struct stat *st)
854 static gboolean initialized = FALSE;
855 static gid_t *groups;
856 static int ngroups;
857 static uid_t uid;
858 int i;
860 if (!initialized)
862 uid = geteuid ();
864 ngroups = getgroups (0, NULL);
865 if (ngroups == -1)
866 ngroups = 0; /* ignore errors */
868 /* allocate space for one element in addition to what
869 * will be filled by getgroups(). */
870 groups = g_new (gid_t, ngroups + 1);
872 if (ngroups != 0)
874 ngroups = getgroups (ngroups, groups);
875 if (ngroups == -1)
876 ngroups = 0; /* ignore errors */
879 /* getgroups() may or may not return the effective group ID,
880 * so we always include it at the end of the list. */
881 groups[ngroups++] = getegid ();
883 initialized = TRUE;
886 if (st->st_uid == uid || uid == 0)
887 return 0;
889 for (i = 0; i < ngroups; i++)
891 if (st->st_gid == groups[i])
892 return 1;
895 return 2;