(my_systemv): cleanup unreachable-code warning.
[midnight-commander.git] / lib / utilunix.c
blobbe85567d9ccc17e04742ec4e930665d7fa417750
1 /*
2 Various utilities - Unix variants
4 Copyright (C) 1994-2016
5 Free Software Foundation, Inc.
7 Written by:
8 Miguel de Icaza, 1994, 1995, 1996
9 Janne Kukonlehto, 1994, 1995, 1996
10 Dugan Porter, 1994, 1995, 1996
11 Jakub Jelinek, 1994, 1995, 1996
12 Mauricio Plaza, 1994, 1995, 1996
14 The mc_realpath routine is mostly from uClibc package, written
15 by Rick Sladkey <jrs@world.std.com>
17 This file is part of the Midnight Commander.
19 The Midnight Commander is free software: you can redistribute it
20 and/or modify it under the terms of the GNU General Public License as
21 published by the Free Software Foundation, either version 3 of the License,
22 or (at your option) any later version.
24 The Midnight Commander is distributed in the hope that it will be useful,
25 but WITHOUT ANY WARRANTY; without even the implied warranty of
26 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 GNU General Public License for more details.
29 You should have received a copy of the GNU General Public License
30 along with this program. If not, see <http://www.gnu.org/licenses/>.
33 /** \file utilunix.c
34 * \brief Source: various utilities - Unix variant
37 #include <config.h>
39 #include <ctype.h>
40 #include <errno.h>
41 #include <limits.h>
42 #include <signal.h>
43 #include <stdarg.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #ifdef HAVE_SYS_PARAM_H
48 #include <sys/param.h>
49 #endif
50 #include <sys/types.h>
51 #include <sys/stat.h>
52 #ifdef HAVE_SYS_SELECT_H
53 #include <sys/select.h>
54 #endif
55 #include <sys/wait.h>
56 #ifdef HAVE_SYS_IOCTL_H
57 #include <sys/ioctl.h>
58 #endif
59 #ifdef HAVE_GET_PROCESS_STATS
60 #include <sys/procstats.h>
61 #endif
62 #include <pwd.h>
63 #include <grp.h>
65 #include "lib/global.h"
67 #include "lib/unixcompat.h"
68 #include "lib/vfs/vfs.h" /* VFS_ENCODING_PREFIX */
69 #include "lib/strutil.h" /* str_move() */
70 #include "lib/util.h"
71 #include "lib/widget.h" /* message() */
72 #include "lib/vfs/xdirentry.h"
74 #ifdef HAVE_CHARSET
75 #include "lib/charsets.h"
76 #endif
78 #include "utilunix.h"
80 /*** global variables ****************************************************************************/
82 struct sigaction startup_handler;
84 /*** file scope macro definitions ****************************************************************/
86 #define UID_CACHE_SIZE 200
87 #define GID_CACHE_SIZE 30
89 /* Pipes are guaranteed to be able to hold at least 4096 bytes */
90 /* More than that would be unportable */
91 #define MAX_PIPE_SIZE 4096
93 /*** file scope type declarations ****************************************************************/
95 typedef struct
97 int index;
98 char *string;
99 } int_cache;
101 typedef enum
103 FORK_ERROR = -1,
104 FORK_CHILD,
105 FORK_PARENT,
106 } my_fork_state_t;
108 typedef struct
110 struct sigaction intr;
111 struct sigaction quit;
112 struct sigaction stop;
113 } my_system_sigactions_t;
115 /*** file scope variables ************************************************************************/
117 static int_cache uid_cache[UID_CACHE_SIZE];
118 static int_cache gid_cache[GID_CACHE_SIZE];
120 static int error_pipe[2]; /* File descriptors of error pipe */
121 static int old_error; /* File descriptor of old standard error */
123 /*** file scope functions ************************************************************************/
124 /* --------------------------------------------------------------------------------------------- */
126 static char *
127 i_cache_match (int id, int_cache * cache, int size)
129 int i;
131 for (i = 0; i < size; i++)
132 if (cache[i].index == id)
133 return cache[i].string;
134 return 0;
137 /* --------------------------------------------------------------------------------------------- */
139 static void
140 i_cache_add (int id, int_cache * cache, int size, char *text, int *last)
142 g_free (cache[*last].string);
143 cache[*last].string = g_strdup (text);
144 cache[*last].index = id;
145 *last = ((*last) + 1) % size;
148 /* --------------------------------------------------------------------------------------------- */
150 static my_fork_state_t
151 my_fork (void)
153 pid_t pid;
155 pid = fork ();
157 if (pid < 0)
159 fprintf (stderr, "\n\nfork () = -1\n");
160 return FORK_ERROR;
163 if (pid == 0)
164 return FORK_CHILD;
166 while (TRUE)
168 int status = 0;
170 if (waitpid (pid, &status, 0) > 0)
171 return WEXITSTATUS (status) == 0 ? FORK_PARENT : FORK_ERROR;
173 if (errno != EINTR)
174 return FORK_ERROR;
178 /* --------------------------------------------------------------------------------------------- */
180 static void
181 my_system__save_sigaction_handlers (my_system_sigactions_t * sigactions)
183 struct sigaction ignore;
185 memset (&ignore, 0, sizeof (ignore));
186 ignore.sa_handler = SIG_IGN;
187 sigemptyset (&ignore.sa_mask);
189 sigaction (SIGINT, &ignore, &sigactions->intr);
190 sigaction (SIGQUIT, &ignore, &sigactions->quit);
192 /* Restore the original SIGTSTP handler, we don't want ncurses' */
193 /* handler messing the screen after the SIGCONT */
194 sigaction (SIGTSTP, &startup_handler, &sigactions->stop);
197 /* --------------------------------------------------------------------------------------------- */
199 static void
200 my_system__restore_sigaction_handlers (my_system_sigactions_t * sigactions)
202 sigaction (SIGINT, &sigactions->intr, NULL);
203 sigaction (SIGQUIT, &sigactions->quit, NULL);
204 sigaction (SIGTSTP, &sigactions->stop, NULL);
207 /* --------------------------------------------------------------------------------------------- */
209 static GPtrArray *
210 my_system_make_arg_array (int flags, const char *shell, char **execute_name)
212 GPtrArray *args_array;
214 args_array = g_ptr_array_new ();
216 if ((flags & EXECUTE_AS_SHELL) != 0)
218 g_ptr_array_add (args_array, (gpointer) shell);
219 g_ptr_array_add (args_array, (gpointer) "-c");
220 *execute_name = g_strdup (shell);
222 else
224 char *shell_token;
226 shell_token = shell != NULL ? strchr (shell, ' ') : NULL;
227 if (shell_token == NULL)
228 *execute_name = g_strdup (shell);
229 else
230 *execute_name = g_strndup (shell, (gsize) (shell_token - shell));
232 g_ptr_array_add (args_array, (gpointer) shell);
234 return args_array;
237 /* --------------------------------------------------------------------------------------------- */
239 static void
240 mc_pread_stream (mc_pipe_stream_t * ps, const fd_set * fds)
242 size_t buf_len;
243 ssize_t read_len;
245 if (!FD_ISSET (ps->fd, fds))
247 ps->len = MC_PIPE_STREAM_UNREAD;
248 return;
251 buf_len = (size_t) ps->len;
253 if (buf_len >= MC_PIPE_BUFSIZE)
254 buf_len = ps->null_term ? MC_PIPE_BUFSIZE - 1 : MC_PIPE_BUFSIZE;
258 read_len = read (ps->fd, ps->buf, buf_len);
260 while (read_len < 0 && errno == EINTR);
262 if (read_len < 0)
264 /* reading error */
265 ps->len = MC_PIPE_ERROR_READ;
266 ps->error = errno;
268 else if (read_len == 0)
269 /* EOF */
270 ps->len = MC_PIPE_STREAM_EOF;
271 else
273 /* success */
274 ps->len = read_len;
276 if (ps->null_term)
277 ps->buf[(size_t) ps->len] = '\0';
281 /* --------------------------------------------------------------------------------------------- */
282 /*** public functions ****************************************************************************/
283 /* --------------------------------------------------------------------------------------------- */
285 const char *
286 get_owner (uid_t uid)
288 struct passwd *pwd;
289 char *name;
290 static uid_t uid_last;
292 name = i_cache_match ((int) uid, uid_cache, UID_CACHE_SIZE);
293 if (name != NULL)
294 return name;
296 pwd = getpwuid (uid);
297 if (pwd != NULL)
299 i_cache_add ((int) uid, uid_cache, UID_CACHE_SIZE, pwd->pw_name, (int *) &uid_last);
300 return pwd->pw_name;
302 else
304 static char ibuf[10];
306 g_snprintf (ibuf, sizeof (ibuf), "%d", (int) uid);
307 return ibuf;
311 /* --------------------------------------------------------------------------------------------- */
313 const char *
314 get_group (gid_t gid)
316 struct group *grp;
317 char *name;
318 static gid_t gid_last;
320 name = i_cache_match ((int) gid, gid_cache, GID_CACHE_SIZE);
321 if (name != NULL)
322 return name;
324 grp = getgrgid (gid);
325 if (grp != NULL)
327 i_cache_add ((int) gid, gid_cache, GID_CACHE_SIZE, grp->gr_name, (int *) &gid_last);
328 return grp->gr_name;
330 else
332 static char gbuf[10];
334 g_snprintf (gbuf, sizeof (gbuf), "%d", (int) gid);
335 return gbuf;
339 /* --------------------------------------------------------------------------------------------- */
340 /* Since ncurses uses a handler that automatically refreshes the */
341 /* screen after a SIGCONT, and we don't want this behavior when */
342 /* spawning a child, we save the original handler here */
344 void
345 save_stop_handler (void)
347 sigaction (SIGTSTP, NULL, &startup_handler);
350 /* --------------------------------------------------------------------------------------------- */
352 * Wrapper for _exit() system call.
353 * The _exit() function has gcc's attribute 'noreturn', and this is reason why we can't
354 * mock the call.
356 * @param status exit code
359 void __attribute__ ((noreturn)) my_exit (int status)
361 _exit (status);
364 /* --------------------------------------------------------------------------------------------- */
366 * Call external programs.
368 * @parameter flags addition conditions for running external programs.
369 * @parameter shell shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
370 * Shell (or command) will be found in paths described in PATH variable
371 * (if shell parameter doesn't begin from path delimiter)
372 * @parameter command Command for shell (or first parameter for command, if flags contain EXECUTE_AS_SHELL)
373 * @return 0 if successfull, -1 otherwise
377 my_system (int flags, const char *shell, const char *command)
379 return my_systeml (flags, shell, command, NULL);
382 /* --------------------------------------------------------------------------------------------- */
384 * Call external programs with various parameters number.
386 * @parameter flags addition conditions for running external programs.
387 * @parameter shell shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
388 * Shell (or command) will be found in pathes described in PATH variable
389 * (if shell parameter doesn't begin from path delimiter)
390 * @parameter ... Command for shell with addition parameters for shell
391 * (or parameters for command, if flags contain EXECUTE_AS_SHELL).
392 * Should be NULL terminated.
393 * @return 0 if successfull, -1 otherwise
398 my_systeml (int flags, const char *shell, ...)
400 GPtrArray *args_array;
401 int status = 0;
402 va_list vargs;
403 char *one_arg;
405 args_array = g_ptr_array_new ();
407 va_start (vargs, shell);
408 while ((one_arg = va_arg (vargs, char *)) != NULL)
409 g_ptr_array_add (args_array, one_arg);
410 va_end (vargs);
412 g_ptr_array_add (args_array, NULL);
413 status = my_systemv_flags (flags, shell, (char *const *) args_array->pdata);
415 g_ptr_array_free (args_array, TRUE);
417 return status;
420 /* --------------------------------------------------------------------------------------------- */
422 * Call external programs with array of strings as parameters.
424 * @parameter command command to run. Command will be found in paths described in PATH variable
425 * (if command parameter doesn't begin from path delimiter)
426 * @parameter argv Array of strings (NULL-terminated) with parameters for command
427 * @return 0 if successfull, -1 otherwise
431 my_systemv (const char *command, char *const argv[])
433 my_fork_state_t fork_state;
434 int status = 0;
435 my_system_sigactions_t sigactions;
437 my_system__save_sigaction_handlers (&sigactions);
439 fork_state = my_fork ();
440 switch (fork_state)
442 case FORK_ERROR:
443 status = -1;
444 break;
445 case FORK_CHILD:
447 signal (SIGINT, SIG_DFL);
448 signal (SIGQUIT, SIG_DFL);
449 signal (SIGTSTP, SIG_DFL);
450 signal (SIGCHLD, SIG_DFL);
452 execvp (command, argv);
453 my_exit (127); /* Exec error */
455 /* no break here, or unreachable-code warning by no returning my_exit() */
456 default:
457 status = 0;
458 break;
460 my_system__restore_sigaction_handlers (&sigactions);
462 return status;
465 /* --------------------------------------------------------------------------------------------- */
467 * Call external programs with flags and with array of strings as parameters.
469 * @parameter flags addition conditions for running external programs.
470 * @parameter command shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
471 * Shell (or command) will be found in paths described in PATH variable
472 * (if shell parameter doesn't begin from path delimiter)
473 * @parameter argv Array of strings (NULL-terminated) with parameters for command
474 * @return 0 if successfull, -1 otherwise
478 my_systemv_flags (int flags, const char *command, char *const argv[])
480 char *execute_name = NULL;
481 GPtrArray *args_array;
482 int status = 0;
484 args_array = my_system_make_arg_array (flags, command, &execute_name);
486 for (; argv != NULL && *argv != NULL; argv++)
487 g_ptr_array_add (args_array, *argv);
489 g_ptr_array_add (args_array, NULL);
490 status = my_systemv (execute_name, (char *const *) args_array->pdata);
492 g_free (execute_name);
493 g_ptr_array_free (args_array, TRUE);
495 return status;
498 /* --------------------------------------------------------------------------------------------- */
500 * Create pipe and run child process.
502 * @parameter command command line of child process
503 * @paremeter error contains pointer to object to handle error code and message
505 * @return newly created object of mc_pipe_t class in success, NULL otherwise
508 mc_pipe_t *
509 mc_popen (const char *command, GError ** error)
511 mc_pipe_t *p;
512 const char *const argv[] = { "/bin/sh", "sh", "-c", command, NULL };
514 p = g_try_new (mc_pipe_t, 1);
515 if (p == NULL)
517 mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE, "%s",
518 _("Cannot create pipe descriptor"));
519 goto ret_err;
522 if (!g_spawn_async_with_pipes
523 (NULL, (gchar **) argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_FILE_AND_ARGV_ZERO,
524 NULL, NULL, &p->child_pid, NULL, &p->out.fd, &p->err.fd, error))
526 mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE_STREAM, "%s",
527 _("Cannot create pipe streams"));
528 goto ret_err;
531 p->out.buf[0] = '\0';
532 p->out.len = MC_PIPE_BUFSIZE;
533 p->out.null_term = FALSE;
535 p->err.buf[0] = '\0';
536 p->err.len = MC_PIPE_BUFSIZE;
537 p->err.null_term = FALSE;
539 return p;
541 ret_err:
542 g_free (p);
543 return NULL;
546 /* --------------------------------------------------------------------------------------------- */
548 * Read stdout and stderr of pipe asynchronously.
550 * @parameter p pipe descriptor
552 * The lengths of read data contain in p->out.len and p->err.len.
553 * Before read, p->xxx.len is an input:
554 * p->xxx.len > 0: do read stream p->xxx and store data in p->xxx.buf;
555 * p->xxx.len <= 0: do not read stream p->xxx.
557 * After read, p->xxx.len is an output and contains the following:
558 * p->xxx.len > 0: an actual length of read data stored in p->xxx.buf;
559 * p->xxx.len == MC_PIPE_STREAM_EOF: EOF of stream p->xxx;
560 * p->xxx.len == MC_PIPE_STREAM_UNREAD: stream p->xxx was not read;
561 * p->xxx.len == MC_PIPE_ERROR_READ: reading error, and p->xxx.errno is set appropriately.
563 * @paremeter error contains pointer to object to handle error code and message
566 void
567 mc_pread (mc_pipe_t * p, GError ** error)
569 gboolean read_out, read_err;
570 fd_set fds;
571 int maxfd = 0;
572 int res;
574 if (error != NULL)
575 *error = NULL;
577 read_out = p->out.fd >= 0 && p->out.len > 0;
578 read_err = p->err.fd >= 0 && p->err.len > 0;
580 if (!read_out && !read_err)
582 p->out.len = MC_PIPE_STREAM_UNREAD;
583 p->err.len = MC_PIPE_STREAM_UNREAD;
584 return;
587 FD_ZERO (&fds);
588 if (read_out)
590 FD_SET (p->out.fd, &fds);
591 maxfd = p->out.fd;
594 if (read_err)
596 FD_SET (p->err.fd, &fds);
597 maxfd = MAX (maxfd, p->err.fd);
600 /* no timeout */
601 res = select (maxfd + 1, &fds, NULL, NULL, NULL);
602 if (res < 0 && errno != EINTR)
604 mc_propagate_error (error, MC_PIPE_ERROR_READ,
606 ("Unexpected error in select() reading data from a child process:\n%s"),
607 unix_error_string (errno));
608 return;
611 if (read_out)
612 mc_pread_stream (&p->out, &fds);
613 else
614 p->out.len = MC_PIPE_STREAM_UNREAD;
616 if (read_err)
617 mc_pread_stream (&p->err, &fds);
618 else
619 p->err.len = MC_PIPE_STREAM_UNREAD;
622 /* --------------------------------------------------------------------------------------------- */
624 * Close pipe and destroy pipe descriptor.
626 * @paremeter p pipe descriptor
627 * @paremeter error contains pointer to object to handle error code and message
630 void
631 mc_pclose (mc_pipe_t * p, GError ** error)
633 int res;
635 if (p->out.fd >= 0)
636 res = close (p->out.fd);
637 if (p->err.fd >= 0)
638 res = close (p->err.fd);
642 int status;
644 res = waitpid (p->child_pid, &status, 0);
646 while (res < 0 && errno == EINTR);
648 if (res < 0)
649 mc_replace_error (error, MC_PIPE_ERROR_READ, _("Unexpected error in waitpid():\n%s"),
650 unix_error_string (errno));
652 g_free (p);
655 /* --------------------------------------------------------------------------------------------- */
658 * Perform tilde expansion if possible.
660 * @param directory pointer to the path
662 * @return newly allocated string, even if it's unchanged.
665 char *
666 tilde_expand (const char *directory)
668 struct passwd *passwd;
669 const char *p, *q;
671 if (*directory != '~')
672 return g_strdup (directory);
674 p = directory + 1;
676 /* d = "~" or d = "~/" */
677 if (*p == '\0' || IS_PATH_SEP (*p))
679 passwd = getpwuid (geteuid ());
680 q = IS_PATH_SEP (*p) ? p + 1 : "";
682 else
684 q = strchr (p, PATH_SEP);
685 if (!q)
687 passwd = getpwnam (p);
689 else
691 char *name;
693 name = g_strndup (p, q - p);
694 passwd = getpwnam (name);
695 q++;
696 g_free (name);
700 /* If we can't figure the user name, leave tilde unexpanded */
701 if (!passwd)
702 return g_strdup (directory);
704 return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
707 /* --------------------------------------------------------------------------------------------- */
709 * Creates a pipe to hold standard error for a later analysis.
710 * The pipe can hold 4096 bytes. Make sure no more is written
711 * or a deadlock might occur.
714 void
715 open_error_pipe (void)
717 if (pipe (error_pipe) < 0)
719 message (D_NORMAL, _("Warning"), _("Pipe failed"));
721 old_error = dup (STDERR_FILENO);
722 if (old_error < 0 || close (STDERR_FILENO) != 0 || dup (error_pipe[1]) != STDERR_FILENO)
724 message (D_NORMAL, _("Warning"), _("Dup failed"));
726 close (error_pipe[0]);
727 error_pipe[0] = -1;
729 else
732 * Settng stderr in nonblocking mode as we close it earlier, than
733 * program stops. We try to read some error at program startup,
734 * but we should not block on it.
736 * TODO: make piped stdin/stderr poll()/select()able to get rid
737 * of following hack.
739 int fd_flags;
740 fd_flags = fcntl (error_pipe[0], F_GETFL, NULL);
741 if (fd_flags != -1)
743 fd_flags |= O_NONBLOCK;
744 if (fcntl (error_pipe[0], F_SETFL, fd_flags) == -1)
746 /* TODO: handle it somehow */
750 /* we never write there */
751 close (error_pipe[1]);
752 error_pipe[1] = -1;
755 /* --------------------------------------------------------------------------------------------- */
757 * Close a pipe
759 * @param error '-1' - ignore errors, '0' - display warning, '1' - display error
760 * @param text is prepended to the error message from the pipe
762 * @return not 0 if an error was displayed
766 close_error_pipe (int error, const char *text)
768 const char *title;
769 char msg[MAX_PIPE_SIZE];
770 int len = 0;
772 /* already closed */
773 if (error_pipe[0] == -1)
774 return 0;
776 if (error < 0 || (error > 0 && (error & D_ERROR) != 0))
777 title = MSG_ERROR;
778 else
779 title = _("Warning");
780 if (old_error >= 0)
782 if (dup2 (old_error, STDERR_FILENO) == -1)
784 if (error < 0)
785 error = D_ERROR;
787 message (error, MSG_ERROR, _("Error dup'ing old error pipe"));
788 return 1;
790 close (old_error);
791 len = read (error_pipe[0], msg, sizeof (msg) - 1);
793 if (len >= 0)
794 msg[len] = 0;
795 close (error_pipe[0]);
796 error_pipe[0] = -1;
798 if (error < 0)
799 return 0; /* Just ignore error message */
800 if (text == NULL)
802 if (len <= 0)
803 return 0; /* Nothing to show */
805 /* Show message from pipe */
806 message (error, title, "%s", msg);
808 else
810 /* Show given text and possible message from pipe */
811 message (error, title, "%s\n%s", text, msg);
813 return 1;
816 /* --------------------------------------------------------------------------------------------- */
818 * Canonicalize path, and return a new path. Do everything in place.
819 * The new path differs from path in:
820 * Multiple '/'s are collapsed to a single '/'.
821 * Leading './'s and trailing '/.'s are removed.
822 * Trailing '/'s are removed.
823 * Non-leading '../'s and trailing '..'s are handled by removing
824 * portions of the path.
825 * Well formed UNC paths are modified only in the local part.
828 void
829 custom_canonicalize_pathname (char *path, CANON_PATH_FLAGS flags)
831 char *p, *s;
832 char *lpath = path; /* path without leading UNC part */
833 const size_t url_delim_len = strlen (VFS_PATH_URL_DELIMITER);
835 /* Detect and preserve UNC paths: //server/... */
836 if ((flags & CANON_PATH_GUARDUNC) != 0 && IS_PATH_SEP (path[0]) && IS_PATH_SEP (path[1]))
838 p = path + 2;
839 while (p[0] != '\0' && !IS_PATH_SEP (p[0]))
840 p++;
841 if (IS_PATH_SEP (p[0]) && p > path + 2)
842 lpath = p;
845 if (!lpath[0] || !lpath[1])
846 return;
848 if (flags & CANON_PATH_JOINSLASHES)
850 /* Collapse multiple slashes */
851 p = lpath;
852 while (*p)
854 if (IS_PATH_SEP (p[0]) && IS_PATH_SEP (p[1]) && (p == lpath || *(p - 1) != ':'))
856 s = p + 1;
857 while (IS_PATH_SEP (*(++s)))
859 str_move (p + 1, s);
861 p++;
865 if (flags & CANON_PATH_JOINSLASHES)
867 /* Collapse "/./" -> "/" */
868 p = lpath;
869 while (*p)
871 if (IS_PATH_SEP (p[0]) && p[1] == '.' && IS_PATH_SEP (p[2]))
872 str_move (p, p + 2);
873 else
874 p++;
878 if (flags & CANON_PATH_REMSLASHDOTS)
880 size_t len;
882 /* Remove trailing slashes */
883 p = lpath + strlen (lpath) - 1;
884 while (p > lpath && IS_PATH_SEP (*p))
886 if (p >= lpath + url_delim_len - 1
887 && strncmp (p - url_delim_len + 1, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
888 break;
889 *p-- = 0;
892 /* Remove leading "./" */
893 if (lpath[0] == '.' && IS_PATH_SEP (lpath[1]))
895 if (lpath[2] == 0)
897 lpath[1] = 0;
898 return;
900 else
902 str_move (lpath, lpath + 2);
906 /* Remove trailing "/" or "/." */
907 len = strlen (lpath);
908 if (len < 2)
909 return;
910 if (IS_PATH_SEP (lpath[len - 1])
911 && (len < url_delim_len
912 || strncmp (lpath + len - url_delim_len, VFS_PATH_URL_DELIMITER,
913 url_delim_len) != 0))
915 lpath[len - 1] = '\0';
917 else
919 if (lpath[len - 1] == '.' && IS_PATH_SEP (lpath[len - 2]))
921 if (len == 2)
923 lpath[1] = '\0';
924 return;
926 else
928 lpath[len - 2] = '\0';
934 if (flags & CANON_PATH_REMDOUBLEDOTS)
936 #ifdef HAVE_CHARSET
937 const size_t enc_prefix_len = strlen (VFS_ENCODING_PREFIX);
938 #endif /* HAVE_CHARSET */
940 /* Collapse "/.." with the previous part of path */
941 p = lpath;
942 while (p[0] && p[1] && p[2])
944 if (!IS_PATH_SEP (p[0]) || p[1] != '.' || p[2] != '.'
945 || (!IS_PATH_SEP (p[3]) && p[3] != '\0'))
947 p++;
948 continue;
951 /* search for the previous token */
952 s = p - 1;
953 if (s >= lpath + url_delim_len - 2
954 && strncmp (s - url_delim_len + 2, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
956 s -= (url_delim_len - 2);
957 while (s >= lpath && !IS_PATH_SEP (*s--))
961 while (s >= lpath)
963 if (s - url_delim_len > lpath
964 && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
966 char *vfs_prefix = s - url_delim_len;
967 vfs_class *vclass;
969 while (vfs_prefix > lpath && !IS_PATH_SEP (*--vfs_prefix))
971 if (IS_PATH_SEP (*vfs_prefix))
972 vfs_prefix++;
973 *(s - url_delim_len) = '\0';
975 vclass = vfs_prefix_to_class (vfs_prefix);
976 *(s - url_delim_len) = *VFS_PATH_URL_DELIMITER;
978 if (vclass != NULL)
980 struct vfs_s_subclass *sub = (struct vfs_s_subclass *) vclass->data;
981 if (sub != NULL && sub->flags & VFS_S_REMOTE)
983 s = vfs_prefix;
984 continue;
989 if (IS_PATH_SEP (*s))
990 break;
992 s--;
995 s++;
997 /* If the previous token is "..", we cannot collapse it */
998 if (s[0] == '.' && s[1] == '.' && s + 2 == p)
1000 p += 3;
1001 continue;
1004 if (p[3] != 0)
1006 if (s == lpath && IS_PATH_SEP (*s))
1008 /* "/../foo" -> "/foo" */
1009 str_move (s + 1, p + 4);
1011 else
1013 /* "token/../foo" -> "foo" */
1014 #ifdef HAVE_CHARSET
1015 if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
1016 && (is_supported_encoding (s + enc_prefix_len)))
1017 /* special case: remove encoding */
1018 str_move (s, p + 1);
1019 else
1020 #endif /* HAVE_CHARSET */
1021 str_move (s, p + 4);
1023 p = (s > lpath) ? s - 1 : s;
1024 continue;
1027 /* trailing ".." */
1028 if (s == lpath)
1030 /* "token/.." -> "." */
1031 if (!IS_PATH_SEP (lpath[0]))
1032 lpath[0] = '.';
1033 lpath[1] = '\0';
1035 else
1037 /* "foo/token/.." -> "foo" */
1038 if (s == lpath + 1)
1039 s[0] = '\0';
1040 #ifdef HAVE_CHARSET
1041 else if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
1042 && (is_supported_encoding (s + enc_prefix_len)))
1044 /* special case: remove encoding */
1045 s[0] = '.';
1046 s[1] = '.';
1047 s[2] = '\0';
1049 /* search for the previous token */
1050 /* IS_PATH_SEP (s[-1]) */
1051 p = s - 1;
1052 while (p >= lpath && !IS_PATH_SEP (*p))
1053 p--;
1055 if (p >= lpath)
1056 continue;
1058 #endif /* HAVE_CHARSET */
1059 else
1061 if (s >= lpath + url_delim_len
1062 && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
1063 *s = '\0';
1064 else
1065 s[-1] = '\0';
1069 break;
1074 /* --------------------------------------------------------------------------------------------- */
1076 void
1077 canonicalize_pathname (char *path)
1079 custom_canonicalize_pathname (path, CANON_PATH_ALL);
1082 /* --------------------------------------------------------------------------------------------- */
1084 #ifdef HAVE_GET_PROCESS_STATS
1086 gettimeofday (struct timeval *tp, void *tzp)
1088 return get_process_stats (tp, PS_SELF, 0, 0);
1090 #endif /* HAVE_GET_PROCESS_STATS */
1092 /* --------------------------------------------------------------------------------------------- */
1094 #ifndef HAVE_REALPATH
1095 char *
1096 mc_realpath (const char *path, char *resolved_path)
1098 char copy_path[PATH_MAX];
1099 char got_path[PATH_MAX];
1100 char *new_path = got_path;
1101 char *max_path;
1102 #ifdef S_IFLNK
1103 char link_path[PATH_MAX];
1104 int readlinks = 0;
1105 int n;
1106 #endif /* S_IFLNK */
1108 /* Make a copy of the source path since we may need to modify it. */
1109 if (strlen (path) >= PATH_MAX - 2)
1111 errno = ENAMETOOLONG;
1112 return NULL;
1114 strcpy (copy_path, path);
1115 path = copy_path;
1116 max_path = copy_path + PATH_MAX - 2;
1117 /* If it's a relative pathname use getwd for starters. */
1118 if (!IS_PATH_SEP (*path))
1120 new_path = g_get_current_dir ();
1121 if (new_path == NULL)
1123 strcpy (got_path, "");
1125 else
1127 g_snprintf (got_path, sizeof (got_path), "%s", new_path);
1128 g_free (new_path);
1129 new_path = got_path;
1132 new_path += strlen (got_path);
1133 if (!IS_PATH_SEP (new_path[-1]))
1134 *new_path++ = PATH_SEP;
1136 else
1138 *new_path++ = PATH_SEP;
1139 path++;
1141 /* Expand each slash-separated pathname component. */
1142 while (*path != '\0')
1144 /* Ignore stray "/". */
1145 if (IS_PATH_SEP (*path))
1147 path++;
1148 continue;
1150 if (*path == '.')
1152 /* Ignore ".". */
1153 if (path[1] == '\0' || IS_PATH_SEP (path[1]))
1155 path++;
1156 continue;
1158 if (path[1] == '.')
1160 if (path[2] == '\0' || IS_PATH_SEP (path[2]))
1162 path += 2;
1163 /* Ignore ".." at root. */
1164 if (new_path == got_path + 1)
1165 continue;
1166 /* Handle ".." by backing up. */
1167 while (!IS_PATH_SEP ((--new_path)[-1]))
1169 continue;
1173 /* Safely copy the next pathname component. */
1174 while (*path != '\0' && !IS_PATH_SEP (*path))
1176 if (path > max_path)
1178 errno = ENAMETOOLONG;
1179 return NULL;
1181 *new_path++ = *path++;
1183 #ifdef S_IFLNK
1184 /* Protect against infinite loops. */
1185 if (readlinks++ > MAXSYMLINKS)
1187 errno = ELOOP;
1188 return NULL;
1190 /* See if latest pathname component is a symlink. */
1191 *new_path = '\0';
1192 n = readlink (got_path, link_path, PATH_MAX - 1);
1193 if (n < 0)
1195 /* EINVAL means the file exists but isn't a symlink. */
1196 if (errno != EINVAL)
1198 /* Make sure it's null terminated. */
1199 *new_path = '\0';
1200 strcpy (resolved_path, got_path);
1201 return NULL;
1204 else
1206 /* Note: readlink doesn't add the null byte. */
1207 link_path[n] = '\0';
1208 if (IS_PATH_SEP (*link_path))
1209 /* Start over for an absolute symlink. */
1210 new_path = got_path;
1211 else
1212 /* Otherwise back up over this component. */
1213 while (!IS_PATH_SEP (*(--new_path)))
1215 /* Safe sex check. */
1216 if (strlen (path) + n >= PATH_MAX - 2)
1218 errno = ENAMETOOLONG;
1219 return NULL;
1221 /* Insert symlink contents into path. */
1222 strcat (link_path, path);
1223 strcpy (copy_path, link_path);
1224 path = copy_path;
1226 #endif /* S_IFLNK */
1227 *new_path++ = PATH_SEP;
1229 /* Delete trailing slash but don't whomp a lone slash. */
1230 if (new_path != got_path + 1 && IS_PATH_SEP (new_path[-1]))
1231 new_path--;
1232 /* Make sure it's null terminated. */
1233 *new_path = '\0';
1234 strcpy (resolved_path, got_path);
1235 return resolved_path;
1237 #endif /* HAVE_REALPATH */
1239 /* --------------------------------------------------------------------------------------------- */
1241 * Return the index of the permissions triplet
1246 get_user_permissions (struct stat *st)
1248 static gboolean initialized = FALSE;
1249 static gid_t *groups;
1250 static int ngroups;
1251 static uid_t uid;
1252 int i;
1254 if (!initialized)
1256 uid = geteuid ();
1258 ngroups = getgroups (0, NULL);
1259 if (ngroups == -1)
1260 ngroups = 0; /* ignore errors */
1262 /* allocate space for one element in addition to what
1263 * will be filled by getgroups(). */
1264 groups = g_new (gid_t, ngroups + 1);
1266 if (ngroups != 0)
1268 ngroups = getgroups (ngroups, groups);
1269 if (ngroups == -1)
1270 ngroups = 0; /* ignore errors */
1273 /* getgroups() may or may not return the effective group ID,
1274 * so we always include it at the end of the list. */
1275 groups[ngroups++] = getegid ();
1277 initialized = TRUE;
1280 if (st->st_uid == uid || uid == 0)
1281 return 0;
1283 for (i = 0; i < ngroups; i++)
1285 if (st->st_gid == groups[i])
1286 return 1;
1289 return 2;
1292 /* --------------------------------------------------------------------------------------------- */
1294 * Build filename from arguments.
1295 * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
1298 char *
1299 mc_build_filenamev (const char *first_element, va_list args)
1301 gboolean absolute;
1302 const char *element = first_element;
1303 GString *path;
1304 char *ret;
1306 if (element == NULL)
1307 return NULL;
1309 path = g_string_new ("");
1311 absolute = IS_PATH_SEP (*first_element);
1315 if (*element == '\0')
1316 element = va_arg (args, char *);
1317 else
1319 char *tmp_element;
1320 size_t len;
1321 const char *start;
1323 tmp_element = g_strdup (element);
1325 element = va_arg (args, char *);
1327 canonicalize_pathname (tmp_element);
1328 len = strlen (tmp_element);
1329 start = IS_PATH_SEP (tmp_element[0]) ? tmp_element + 1 : tmp_element;
1331 g_string_append (path, start);
1332 if (!IS_PATH_SEP (tmp_element[len - 1]) && element != NULL)
1333 g_string_append_c (path, PATH_SEP);
1335 g_free (tmp_element);
1338 while (element != NULL);
1340 if (absolute)
1341 g_string_prepend_c (path, PATH_SEP);
1343 ret = g_string_free (path, FALSE);
1344 canonicalize_pathname (ret);
1346 return ret;
1349 /* --------------------------------------------------------------------------------------------- */
1351 * Build filename from arguments.
1352 * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
1355 char *
1356 mc_build_filename (const char *first_element, ...)
1358 va_list args;
1359 char *ret;
1361 if (first_element == NULL)
1362 return NULL;
1364 va_start (args, first_element);
1365 ret = mc_build_filenamev (first_element, args);
1366 va_end (args);
1367 return ret;
1370 /* --------------------------------------------------------------------------------------------- */