Partially revert "VFS: (vfs_s_subclass): make the derived class from vfs_class."
[midnight-commander.git] / lib / utilunix.c
blob92ddd4cf946d81b630eb0105de753ce349f376b7
1 /*
2 Various utilities - Unix variants
4 Copyright (C) 1994-2018
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
360 /* __attribute__ ((noreturn)) */
361 my_exit (int status)
363 _exit (status);
366 /* --------------------------------------------------------------------------------------------- */
368 * Call external programs.
370 * @parameter flags addition conditions for running external programs.
371 * @parameter shell shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
372 * Shell (or command) will be found in paths described in PATH variable
373 * (if shell parameter doesn't begin from path delimiter)
374 * @parameter command Command for shell (or first parameter for command, if flags contain EXECUTE_AS_SHELL)
375 * @return 0 if successfull, -1 otherwise
379 my_system (int flags, const char *shell, const char *command)
381 return my_systeml (flags, shell, command, NULL);
384 /* --------------------------------------------------------------------------------------------- */
386 * Call external programs with various parameters number.
388 * @parameter flags addition conditions for running external programs.
389 * @parameter shell shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
390 * Shell (or command) will be found in pathes described in PATH variable
391 * (if shell parameter doesn't begin from path delimiter)
392 * @parameter ... Command for shell with addition parameters for shell
393 * (or parameters for command, if flags contain EXECUTE_AS_SHELL).
394 * Should be NULL terminated.
395 * @return 0 if successfull, -1 otherwise
400 my_systeml (int flags, const char *shell, ...)
402 GPtrArray *args_array;
403 int status = 0;
404 va_list vargs;
405 char *one_arg;
407 args_array = g_ptr_array_new ();
409 va_start (vargs, shell);
410 while ((one_arg = va_arg (vargs, char *)) != NULL)
411 g_ptr_array_add (args_array, one_arg);
412 va_end (vargs);
414 g_ptr_array_add (args_array, NULL);
415 status = my_systemv_flags (flags, shell, (char *const *) args_array->pdata);
417 g_ptr_array_free (args_array, TRUE);
419 return status;
422 /* --------------------------------------------------------------------------------------------- */
424 * Call external programs with array of strings as parameters.
426 * @parameter command command to run. Command will be found in paths described in PATH variable
427 * (if command parameter doesn't begin from path delimiter)
428 * @parameter argv Array of strings (NULL-terminated) with parameters for command
429 * @return 0 if successfull, -1 otherwise
433 my_systemv (const char *command, char *const argv[])
435 my_fork_state_t fork_state;
436 int status = 0;
437 my_system_sigactions_t sigactions;
439 my_system__save_sigaction_handlers (&sigactions);
441 fork_state = my_fork ();
442 switch (fork_state)
444 case FORK_ERROR:
445 status = -1;
446 break;
447 case FORK_CHILD:
449 signal (SIGINT, SIG_DFL);
450 signal (SIGQUIT, SIG_DFL);
451 signal (SIGTSTP, SIG_DFL);
452 signal (SIGCHLD, SIG_DFL);
454 execvp (command, argv);
455 my_exit (127); /* Exec error */
457 MC_FALLTHROUGH;
458 /* no break here, or unreachable-code warning by no returning my_exit() */
459 default:
460 status = 0;
461 break;
463 my_system__restore_sigaction_handlers (&sigactions);
465 return status;
468 /* --------------------------------------------------------------------------------------------- */
470 * Call external programs with flags and with array of strings as parameters.
472 * @parameter flags addition conditions for running external programs.
473 * @parameter command shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
474 * Shell (or command) will be found in paths described in PATH variable
475 * (if shell parameter doesn't begin from path delimiter)
476 * @parameter argv Array of strings (NULL-terminated) with parameters for command
477 * @return 0 if successfull, -1 otherwise
481 my_systemv_flags (int flags, const char *command, char *const argv[])
483 char *execute_name = NULL;
484 GPtrArray *args_array;
485 int status = 0;
487 args_array = my_system_make_arg_array (flags, command, &execute_name);
489 for (; argv != NULL && *argv != NULL; argv++)
490 g_ptr_array_add (args_array, *argv);
492 g_ptr_array_add (args_array, NULL);
493 status = my_systemv (execute_name, (char *const *) args_array->pdata);
495 g_free (execute_name);
496 g_ptr_array_free (args_array, TRUE);
498 return status;
501 /* --------------------------------------------------------------------------------------------- */
503 * Create pipe and run child process.
505 * @parameter command command line of child process
506 * @paremeter error contains pointer to object to handle error code and message
508 * @return newly created object of mc_pipe_t class in success, NULL otherwise
511 mc_pipe_t *
512 mc_popen (const char *command, GError ** error)
514 mc_pipe_t *p;
515 const char *const argv[] = { "/bin/sh", "sh", "-c", command, NULL };
517 p = g_try_new (mc_pipe_t, 1);
518 if (p == NULL)
520 mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE, "%s",
521 _("Cannot create pipe descriptor"));
522 goto ret_err;
525 if (!g_spawn_async_with_pipes
526 (NULL, (gchar **) argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_FILE_AND_ARGV_ZERO,
527 NULL, NULL, &p->child_pid, NULL, &p->out.fd, &p->err.fd, error))
529 mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE_STREAM, "%s",
530 _("Cannot create pipe streams"));
531 goto ret_err;
534 p->out.buf[0] = '\0';
535 p->out.len = MC_PIPE_BUFSIZE;
536 p->out.null_term = FALSE;
538 p->err.buf[0] = '\0';
539 p->err.len = MC_PIPE_BUFSIZE;
540 p->err.null_term = FALSE;
542 return p;
544 ret_err:
545 g_free (p);
546 return NULL;
549 /* --------------------------------------------------------------------------------------------- */
551 * Read stdout and stderr of pipe asynchronously.
553 * @parameter p pipe descriptor
555 * The lengths of read data contain in p->out.len and p->err.len.
556 * Before read, p->xxx.len is an input:
557 * p->xxx.len > 0: do read stream p->xxx and store data in p->xxx.buf;
558 * p->xxx.len <= 0: do not read stream p->xxx.
560 * After read, p->xxx.len is an output and contains the following:
561 * p->xxx.len > 0: an actual length of read data stored in p->xxx.buf;
562 * p->xxx.len == MC_PIPE_STREAM_EOF: EOF of stream p->xxx;
563 * p->xxx.len == MC_PIPE_STREAM_UNREAD: stream p->xxx was not read;
564 * p->xxx.len == MC_PIPE_ERROR_READ: reading error, and p->xxx.errno is set appropriately.
566 * @paremeter error contains pointer to object to handle error code and message
569 void
570 mc_pread (mc_pipe_t * p, GError ** error)
572 gboolean read_out, read_err;
573 fd_set fds;
574 int maxfd = 0;
575 int res;
577 if (error != NULL)
578 *error = NULL;
580 read_out = p->out.fd >= 0 && p->out.len > 0;
581 read_err = p->err.fd >= 0 && p->err.len > 0;
583 if (!read_out && !read_err)
585 p->out.len = MC_PIPE_STREAM_UNREAD;
586 p->err.len = MC_PIPE_STREAM_UNREAD;
587 return;
590 FD_ZERO (&fds);
591 if (read_out)
593 FD_SET (p->out.fd, &fds);
594 maxfd = p->out.fd;
597 if (read_err)
599 FD_SET (p->err.fd, &fds);
600 maxfd = MAX (maxfd, p->err.fd);
603 /* no timeout */
604 res = select (maxfd + 1, &fds, NULL, NULL, NULL);
605 if (res < 0 && errno != EINTR)
607 mc_propagate_error (error, MC_PIPE_ERROR_READ,
609 ("Unexpected error in select() reading data from a child process:\n%s"),
610 unix_error_string (errno));
611 return;
614 if (read_out)
615 mc_pread_stream (&p->out, &fds);
616 else
617 p->out.len = MC_PIPE_STREAM_UNREAD;
619 if (read_err)
620 mc_pread_stream (&p->err, &fds);
621 else
622 p->err.len = MC_PIPE_STREAM_UNREAD;
625 /* --------------------------------------------------------------------------------------------- */
627 * Close pipe and destroy pipe descriptor.
629 * @paremeter p pipe descriptor
630 * @paremeter error contains pointer to object to handle error code and message
633 void
634 mc_pclose (mc_pipe_t * p, GError ** error)
636 int res;
638 if (p->out.fd >= 0)
639 res = close (p->out.fd);
640 if (p->err.fd >= 0)
641 res = close (p->err.fd);
645 int status;
647 res = waitpid (p->child_pid, &status, 0);
649 while (res < 0 && errno == EINTR);
651 if (res < 0)
652 mc_replace_error (error, MC_PIPE_ERROR_READ, _("Unexpected error in waitpid():\n%s"),
653 unix_error_string (errno));
655 g_free (p);
658 /* --------------------------------------------------------------------------------------------- */
661 * Perform tilde expansion if possible.
663 * @param directory pointer to the path
665 * @return newly allocated string, even if it's unchanged.
668 char *
669 tilde_expand (const char *directory)
671 struct passwd *passwd;
672 const char *p, *q;
674 if (*directory != '~')
675 return g_strdup (directory);
677 p = directory + 1;
679 /* d = "~" or d = "~/" */
680 if (*p == '\0' || IS_PATH_SEP (*p))
682 passwd = getpwuid (geteuid ());
683 q = IS_PATH_SEP (*p) ? p + 1 : "";
685 else
687 q = strchr (p, PATH_SEP);
688 if (!q)
690 passwd = getpwnam (p);
692 else
694 char *name;
696 name = g_strndup (p, q - p);
697 passwd = getpwnam (name);
698 q++;
699 g_free (name);
703 /* If we can't figure the user name, leave tilde unexpanded */
704 if (!passwd)
705 return g_strdup (directory);
707 return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
710 /* --------------------------------------------------------------------------------------------- */
712 * Creates a pipe to hold standard error for a later analysis.
713 * The pipe can hold 4096 bytes. Make sure no more is written
714 * or a deadlock might occur.
717 void
718 open_error_pipe (void)
720 if (pipe (error_pipe) < 0)
722 message (D_NORMAL, _("Warning"), _("Pipe failed"));
724 old_error = dup (STDERR_FILENO);
725 if (old_error < 0 || close (STDERR_FILENO) != 0 || dup (error_pipe[1]) != STDERR_FILENO)
727 message (D_NORMAL, _("Warning"), _("Dup failed"));
729 close (error_pipe[0]);
730 error_pipe[0] = -1;
732 else
735 * Settng stderr in nonblocking mode as we close it earlier, than
736 * program stops. We try to read some error at program startup,
737 * but we should not block on it.
739 * TODO: make piped stdin/stderr poll()/select()able to get rid
740 * of following hack.
742 int fd_flags;
743 fd_flags = fcntl (error_pipe[0], F_GETFL, NULL);
744 if (fd_flags != -1)
746 fd_flags |= O_NONBLOCK;
747 if (fcntl (error_pipe[0], F_SETFL, fd_flags) == -1)
749 /* TODO: handle it somehow */
753 /* we never write there */
754 close (error_pipe[1]);
755 error_pipe[1] = -1;
758 /* --------------------------------------------------------------------------------------------- */
760 * Close a pipe
762 * @param error '-1' - ignore errors, '0' - display warning, '1' - display error
763 * @param text is prepended to the error message from the pipe
765 * @return not 0 if an error was displayed
769 close_error_pipe (int error, const char *text)
771 const char *title;
772 char msg[MAX_PIPE_SIZE];
773 int len = 0;
775 /* already closed */
776 if (error_pipe[0] == -1)
777 return 0;
779 if (error < 0 || (error > 0 && (error & D_ERROR) != 0))
780 title = MSG_ERROR;
781 else
782 title = _("Warning");
783 if (old_error >= 0)
785 if (dup2 (old_error, STDERR_FILENO) == -1)
787 if (error < 0)
788 error = D_ERROR;
790 message (error, MSG_ERROR, _("Error dup'ing old error pipe"));
791 return 1;
793 close (old_error);
794 len = read (error_pipe[0], msg, sizeof (msg) - 1);
796 if (len >= 0)
797 msg[len] = 0;
798 close (error_pipe[0]);
799 error_pipe[0] = -1;
801 if (error < 0)
802 return 0; /* Just ignore error message */
803 if (text == NULL)
805 if (len <= 0)
806 return 0; /* Nothing to show */
808 /* Show message from pipe */
809 message (error, title, "%s", msg);
811 else
813 /* Show given text and possible message from pipe */
814 message (error, title, "%s\n%s", text, msg);
816 return 1;
819 /* --------------------------------------------------------------------------------------------- */
821 * Canonicalize path, and return a new path. Do everything in place.
822 * The new path differs from path in:
823 * Multiple '/'s are collapsed to a single '/'.
824 * Leading './'s and trailing '/.'s are removed.
825 * Trailing '/'s are removed.
826 * Non-leading '../'s and trailing '..'s are handled by removing
827 * portions of the path.
828 * Well formed UNC paths are modified only in the local part.
831 void
832 custom_canonicalize_pathname (char *path, CANON_PATH_FLAGS flags)
834 char *p, *s;
835 char *lpath = path; /* path without leading UNC part */
836 const size_t url_delim_len = strlen (VFS_PATH_URL_DELIMITER);
838 /* Detect and preserve UNC paths: //server/... */
839 if ((flags & CANON_PATH_GUARDUNC) != 0 && IS_PATH_SEP (path[0]) && IS_PATH_SEP (path[1]))
841 p = path + 2;
842 while (p[0] != '\0' && !IS_PATH_SEP (p[0]))
843 p++;
844 if (IS_PATH_SEP (p[0]) && p > path + 2)
845 lpath = p;
848 if (!lpath[0] || !lpath[1])
849 return;
851 if (flags & CANON_PATH_JOINSLASHES)
853 /* Collapse multiple slashes */
854 p = lpath;
855 while (*p)
857 if (IS_PATH_SEP (p[0]) && IS_PATH_SEP (p[1]) && (p == lpath || *(p - 1) != ':'))
859 s = p + 1;
860 while (IS_PATH_SEP (*(++s)))
862 str_move (p + 1, s);
864 p++;
868 if (flags & CANON_PATH_JOINSLASHES)
870 /* Collapse "/./" -> "/" */
871 p = lpath;
872 while (*p)
874 if (IS_PATH_SEP (p[0]) && p[1] == '.' && IS_PATH_SEP (p[2]))
875 str_move (p, p + 2);
876 else
877 p++;
881 if (flags & CANON_PATH_REMSLASHDOTS)
883 size_t len;
885 /* Remove trailing slashes */
886 p = lpath + strlen (lpath) - 1;
887 while (p > lpath && IS_PATH_SEP (*p))
889 if (p >= lpath + url_delim_len - 1
890 && strncmp (p - url_delim_len + 1, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
891 break;
892 *p-- = 0;
895 /* Remove leading "./" */
896 if (lpath[0] == '.' && IS_PATH_SEP (lpath[1]))
898 if (lpath[2] == 0)
900 lpath[1] = 0;
901 return;
903 else
905 str_move (lpath, lpath + 2);
909 /* Remove trailing "/" or "/." */
910 len = strlen (lpath);
911 if (len < 2)
912 return;
913 if (IS_PATH_SEP (lpath[len - 1])
914 && (len < url_delim_len
915 || strncmp (lpath + len - url_delim_len, VFS_PATH_URL_DELIMITER,
916 url_delim_len) != 0))
918 lpath[len - 1] = '\0';
920 else
922 if (lpath[len - 1] == '.' && IS_PATH_SEP (lpath[len - 2]))
924 if (len == 2)
926 lpath[1] = '\0';
927 return;
929 else
931 lpath[len - 2] = '\0';
937 if (flags & CANON_PATH_REMDOUBLEDOTS)
939 #ifdef HAVE_CHARSET
940 const size_t enc_prefix_len = strlen (VFS_ENCODING_PREFIX);
941 #endif /* HAVE_CHARSET */
943 /* Collapse "/.." with the previous part of path */
944 p = lpath;
945 while (p[0] && p[1] && p[2])
947 if (!IS_PATH_SEP (p[0]) || p[1] != '.' || p[2] != '.'
948 || (!IS_PATH_SEP (p[3]) && p[3] != '\0'))
950 p++;
951 continue;
954 /* search for the previous token */
955 s = p - 1;
956 if (s >= lpath + url_delim_len - 2
957 && strncmp (s - url_delim_len + 2, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
959 s -= (url_delim_len - 2);
960 while (s >= lpath && !IS_PATH_SEP (*s--))
964 while (s >= lpath)
966 if (s - url_delim_len > lpath
967 && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
969 char *vfs_prefix = s - url_delim_len;
970 vfs_class *vclass;
972 while (vfs_prefix > lpath && !IS_PATH_SEP (*--vfs_prefix))
974 if (IS_PATH_SEP (*vfs_prefix))
975 vfs_prefix++;
976 *(s - url_delim_len) = '\0';
978 vclass = vfs_prefix_to_class (vfs_prefix);
979 *(s - url_delim_len) = *VFS_PATH_URL_DELIMITER;
981 if (vclass != NULL)
983 struct vfs_s_subclass *sub = (struct vfs_s_subclass *) vclass->data;
984 if (sub != NULL && sub->flags & VFS_S_REMOTE)
986 s = vfs_prefix;
987 continue;
992 if (IS_PATH_SEP (*s))
993 break;
995 s--;
998 s++;
1000 /* If the previous token is "..", we cannot collapse it */
1001 if (s[0] == '.' && s[1] == '.' && s + 2 == p)
1003 p += 3;
1004 continue;
1007 if (p[3] != 0)
1009 if (s == lpath && IS_PATH_SEP (*s))
1011 /* "/../foo" -> "/foo" */
1012 str_move (s + 1, p + 4);
1014 else
1016 /* "token/../foo" -> "foo" */
1017 #ifdef HAVE_CHARSET
1018 if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
1019 && (is_supported_encoding (s + enc_prefix_len)))
1020 /* special case: remove encoding */
1021 str_move (s, p + 1);
1022 else
1023 #endif /* HAVE_CHARSET */
1024 str_move (s, p + 4);
1026 p = (s > lpath) ? s - 1 : s;
1027 continue;
1030 /* trailing ".." */
1031 if (s == lpath)
1033 /* "token/.." -> "." */
1034 if (!IS_PATH_SEP (lpath[0]))
1035 lpath[0] = '.';
1036 lpath[1] = '\0';
1038 else
1040 /* "foo/token/.." -> "foo" */
1041 if (s == lpath + 1)
1042 s[0] = '\0';
1043 #ifdef HAVE_CHARSET
1044 else if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
1045 && (is_supported_encoding (s + enc_prefix_len)))
1047 /* special case: remove encoding */
1048 s[0] = '.';
1049 s[1] = '.';
1050 s[2] = '\0';
1052 /* search for the previous token */
1053 /* IS_PATH_SEP (s[-1]) */
1054 p = s - 1;
1055 while (p >= lpath && !IS_PATH_SEP (*p))
1056 p--;
1058 if (p >= lpath)
1059 continue;
1061 #endif /* HAVE_CHARSET */
1062 else
1064 if (s >= lpath + url_delim_len
1065 && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
1066 *s = '\0';
1067 else
1068 s[-1] = '\0';
1072 break;
1077 /* --------------------------------------------------------------------------------------------- */
1079 void
1080 canonicalize_pathname (char *path)
1082 custom_canonicalize_pathname (path, CANON_PATH_ALL);
1085 /* --------------------------------------------------------------------------------------------- */
1087 #ifdef HAVE_GET_PROCESS_STATS
1089 gettimeofday (struct timeval *tp, void *tzp)
1091 return get_process_stats (tp, PS_SELF, 0, 0);
1093 #endif /* HAVE_GET_PROCESS_STATS */
1095 /* --------------------------------------------------------------------------------------------- */
1097 char *
1098 mc_realpath (const char *path, char *resolved_path)
1100 #ifdef HAVE_CHARSET
1101 const char *p = path;
1102 gboolean absolute_path = FALSE;
1104 if (IS_PATH_SEP (*p))
1106 absolute_path = TRUE;
1107 p++;
1110 /* ignore encoding: skip "#enc:" */
1111 if (g_str_has_prefix (p, VFS_ENCODING_PREFIX))
1113 p += strlen (VFS_ENCODING_PREFIX);
1114 p = strchr (p, PATH_SEP);
1115 if (p != NULL)
1117 if (!absolute_path && p[1] != '\0')
1118 p++;
1120 path = p;
1123 #endif /* HAVE_CHARSET */
1125 #ifdef HAVE_REALPATH
1126 return realpath (path, resolved_path);
1127 #else
1129 char copy_path[PATH_MAX];
1130 char got_path[PATH_MAX];
1131 char *new_path = got_path;
1132 char *max_path;
1133 #ifdef S_IFLNK
1134 char link_path[PATH_MAX];
1135 int readlinks = 0;
1136 int n;
1137 #endif /* S_IFLNK */
1139 /* Make a copy of the source path since we may need to modify it. */
1140 if (strlen (path) >= PATH_MAX - 2)
1142 errno = ENAMETOOLONG;
1143 return NULL;
1145 strcpy (copy_path, path);
1146 path = copy_path;
1147 max_path = copy_path + PATH_MAX - 2;
1148 /* If it's a relative pathname use getwd for starters. */
1149 if (!IS_PATH_SEP (*path))
1151 new_path = g_get_current_dir ();
1152 if (new_path == NULL)
1154 strcpy (got_path, "");
1156 else
1158 g_snprintf (got_path, sizeof (got_path), "%s", new_path);
1159 g_free (new_path);
1160 new_path = got_path;
1163 new_path += strlen (got_path);
1164 if (!IS_PATH_SEP (new_path[-1]))
1165 *new_path++ = PATH_SEP;
1167 else
1169 *new_path++ = PATH_SEP;
1170 path++;
1172 /* Expand each slash-separated pathname component. */
1173 while (*path != '\0')
1175 /* Ignore stray "/". */
1176 if (IS_PATH_SEP (*path))
1178 path++;
1179 continue;
1181 if (*path == '.')
1183 /* Ignore ".". */
1184 if (path[1] == '\0' || IS_PATH_SEP (path[1]))
1186 path++;
1187 continue;
1189 if (path[1] == '.')
1191 if (path[2] == '\0' || IS_PATH_SEP (path[2]))
1193 path += 2;
1194 /* Ignore ".." at root. */
1195 if (new_path == got_path + 1)
1196 continue;
1197 /* Handle ".." by backing up. */
1198 while (!IS_PATH_SEP ((--new_path)[-1]))
1200 continue;
1204 /* Safely copy the next pathname component. */
1205 while (*path != '\0' && !IS_PATH_SEP (*path))
1207 if (path > max_path)
1209 errno = ENAMETOOLONG;
1210 return NULL;
1212 *new_path++ = *path++;
1214 #ifdef S_IFLNK
1215 /* Protect against infinite loops. */
1216 if (readlinks++ > MAXSYMLINKS)
1218 errno = ELOOP;
1219 return NULL;
1221 /* See if latest pathname component is a symlink. */
1222 *new_path = '\0';
1223 n = readlink (got_path, link_path, PATH_MAX - 1);
1224 if (n < 0)
1226 /* EINVAL means the file exists but isn't a symlink. */
1227 if (errno != EINVAL)
1229 /* Make sure it's null terminated. */
1230 *new_path = '\0';
1231 strcpy (resolved_path, got_path);
1232 return NULL;
1235 else
1237 /* Note: readlink doesn't add the null byte. */
1238 link_path[n] = '\0';
1239 if (IS_PATH_SEP (*link_path))
1240 /* Start over for an absolute symlink. */
1241 new_path = got_path;
1242 else
1243 /* Otherwise back up over this component. */
1244 while (!IS_PATH_SEP (*(--new_path)))
1246 /* Safe sex check. */
1247 if (strlen (path) + n >= PATH_MAX - 2)
1249 errno = ENAMETOOLONG;
1250 return NULL;
1252 /* Insert symlink contents into path. */
1253 strcat (link_path, path);
1254 strcpy (copy_path, link_path);
1255 path = copy_path;
1257 #endif /* S_IFLNK */
1258 *new_path++ = PATH_SEP;
1260 /* Delete trailing slash but don't whomp a lone slash. */
1261 if (new_path != got_path + 1 && IS_PATH_SEP (new_path[-1]))
1262 new_path--;
1263 /* Make sure it's null terminated. */
1264 *new_path = '\0';
1265 strcpy (resolved_path, got_path);
1266 return resolved_path;
1268 #endif /* HAVE_REALPATH */
1271 /* --------------------------------------------------------------------------------------------- */
1273 * Return the index of the permissions triplet
1278 get_user_permissions (struct stat *st)
1280 static gboolean initialized = FALSE;
1281 static gid_t *groups;
1282 static int ngroups;
1283 static uid_t uid;
1284 int i;
1286 if (!initialized)
1288 uid = geteuid ();
1290 ngroups = getgroups (0, NULL);
1291 if (ngroups == -1)
1292 ngroups = 0; /* ignore errors */
1294 /* allocate space for one element in addition to what
1295 * will be filled by getgroups(). */
1296 groups = g_new (gid_t, ngroups + 1);
1298 if (ngroups != 0)
1300 ngroups = getgroups (ngroups, groups);
1301 if (ngroups == -1)
1302 ngroups = 0; /* ignore errors */
1305 /* getgroups() may or may not return the effective group ID,
1306 * so we always include it at the end of the list. */
1307 groups[ngroups++] = getegid ();
1309 initialized = TRUE;
1312 if (st->st_uid == uid || uid == 0)
1313 return 0;
1315 for (i = 0; i < ngroups; i++)
1317 if (st->st_gid == groups[i])
1318 return 1;
1321 return 2;
1324 /* --------------------------------------------------------------------------------------------- */
1326 * Build filename from arguments.
1327 * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
1330 char *
1331 mc_build_filenamev (const char *first_element, va_list args)
1333 gboolean absolute;
1334 const char *element = first_element;
1335 GString *path;
1336 char *ret;
1338 if (element == NULL)
1339 return NULL;
1341 path = g_string_new ("");
1343 absolute = IS_PATH_SEP (*first_element);
1347 if (*element == '\0')
1348 element = va_arg (args, char *);
1349 else
1351 char *tmp_element;
1352 size_t len;
1353 const char *start;
1355 tmp_element = g_strdup (element);
1357 element = va_arg (args, char *);
1359 canonicalize_pathname (tmp_element);
1360 len = strlen (tmp_element);
1361 start = IS_PATH_SEP (tmp_element[0]) ? tmp_element + 1 : tmp_element;
1363 g_string_append (path, start);
1364 if (!IS_PATH_SEP (tmp_element[len - 1]) && element != NULL)
1365 g_string_append_c (path, PATH_SEP);
1367 g_free (tmp_element);
1370 while (element != NULL);
1372 if (absolute)
1373 g_string_prepend_c (path, PATH_SEP);
1375 ret = g_string_free (path, FALSE);
1376 canonicalize_pathname (ret);
1378 return ret;
1381 /* --------------------------------------------------------------------------------------------- */
1383 * Build filename from arguments.
1384 * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
1387 char *
1388 mc_build_filename (const char *first_element, ...)
1390 va_list args;
1391 char *ret;
1393 if (first_element == NULL)
1394 return NULL;
1396 va_start (args, first_element);
1397 ret = mc_build_filenamev (first_element, args);
1398 va_end (args);
1399 return ret;
1402 /* --------------------------------------------------------------------------------------------- */