tar: avoid strtoul().
[midnight-commander.git] / lib / utilunix.c
bloba2c22f9deeb7e47de2a595756fd4b7d02d7123c0
1 /*
2 Various utilities - Unix variants
4 Copyright (C) 1994-2024
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
13 Andrew Borodin <aborodin@vmail.ru> 2010-2024
15 The mc_realpath routine is mostly from uClibc package, written
16 by Rick Sladkey <jrs@world.std.com>
18 This file is part of the Midnight Commander.
20 The Midnight Commander is free software: you can redistribute it
21 and/or modify it under the terms of the GNU General Public License as
22 published by the Free Software Foundation, either version 3 of the License,
23 or (at your option) any later version.
25 The Midnight Commander is distributed in the hope that it will be useful,
26 but WITHOUT ANY WARRANTY; without even the implied warranty of
27 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 GNU General Public License for more details.
30 You should have received a copy of the GNU General Public License
31 along with this program. If not, see <http://www.gnu.org/licenses/>.
34 /** \file utilunix.c
35 * \brief Source: various utilities - Unix variant
38 #include <config.h>
40 #include <ctype.h>
41 #include <errno.h>
42 #include <limits.h>
43 #include <signal.h>
44 #include <stdarg.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #ifdef HAVE_SYS_PARAM_H
49 #include <sys/param.h>
50 #endif
51 #include <sys/types.h>
52 #include <sys/stat.h>
53 #ifdef HAVE_SYS_SELECT_H
54 #include <sys/select.h>
55 #endif
56 #include <sys/wait.h>
57 #include <pwd.h>
58 #include <grp.h>
60 #include "lib/global.h"
62 #include "lib/unixcompat.h"
63 #include "lib/vfs/vfs.h" /* VFS_ENCODING_PREFIX */
64 #include "lib/strutil.h" /* str_move(), str_tokenize() */
65 #include "lib/util.h"
66 #include "lib/widget.h" /* message() */
67 #include "lib/vfs/xdirentry.h"
69 #ifdef HAVE_CHARSET
70 #include "lib/charsets.h"
71 #endif
73 /*** global variables ****************************************************************************/
75 struct sigaction startup_handler;
77 /*** file scope macro definitions ****************************************************************/
79 #define UID_CACHE_SIZE 200
80 #define GID_CACHE_SIZE 30
82 /*** file scope type declarations ****************************************************************/
84 typedef struct
86 int index;
87 char *string;
88 } int_cache;
90 typedef enum
92 FORK_ERROR = -1,
93 FORK_CHILD,
94 FORK_PARENT,
95 } my_fork_state_t;
97 typedef struct
99 struct sigaction intr;
100 struct sigaction quit;
101 struct sigaction stop;
102 } my_system_sigactions_t;
104 /*** forward declarations (file scope functions) *************************************************/
106 /*** file scope variables ************************************************************************/
108 static int_cache uid_cache[UID_CACHE_SIZE];
109 static int_cache gid_cache[GID_CACHE_SIZE];
111 /* --------------------------------------------------------------------------------------------- */
112 /*** file scope functions ************************************************************************/
113 /* --------------------------------------------------------------------------------------------- */
115 static char *
116 i_cache_match (int id, int_cache *cache, int size)
118 int i;
120 for (i = 0; i < size; i++)
121 if (cache[i].index == id)
122 return cache[i].string;
123 return 0;
126 /* --------------------------------------------------------------------------------------------- */
128 static void
129 i_cache_add (int id, int_cache *cache, int size, char *text, int *last)
131 g_free (cache[*last].string);
132 cache[*last].string = g_strdup (text);
133 cache[*last].index = id;
134 *last = ((*last) + 1) % size;
137 /* --------------------------------------------------------------------------------------------- */
139 static my_fork_state_t
140 my_fork (void)
142 pid_t pid;
144 pid = fork ();
146 if (pid < 0)
148 fprintf (stderr, "\n\nfork () = -1\n");
149 return FORK_ERROR;
152 if (pid == 0)
153 return FORK_CHILD;
155 while (TRUE)
157 int status = 0;
159 if (waitpid (pid, &status, 0) > 0)
160 return WEXITSTATUS (status) == 0 ? FORK_PARENT : FORK_ERROR;
162 if (errno != EINTR)
163 return FORK_ERROR;
167 /* --------------------------------------------------------------------------------------------- */
169 static void
170 my_system__save_sigaction_handlers (my_system_sigactions_t *sigactions)
172 struct sigaction ignore;
174 memset (&ignore, 0, sizeof (ignore));
175 ignore.sa_handler = SIG_IGN;
176 sigemptyset (&ignore.sa_mask);
178 sigaction (SIGINT, &ignore, &sigactions->intr);
179 sigaction (SIGQUIT, &ignore, &sigactions->quit);
181 /* Restore the original SIGTSTP handler, we don't want ncurses' */
182 /* handler messing the screen after the SIGCONT */
183 sigaction (SIGTSTP, &startup_handler, &sigactions->stop);
186 /* --------------------------------------------------------------------------------------------- */
188 static void
189 my_system__restore_sigaction_handlers (my_system_sigactions_t *sigactions)
191 sigaction (SIGINT, &sigactions->intr, NULL);
192 sigaction (SIGQUIT, &sigactions->quit, NULL);
193 sigaction (SIGTSTP, &sigactions->stop, NULL);
196 /* --------------------------------------------------------------------------------------------- */
198 static GPtrArray *
199 my_system_make_arg_array (int flags, const char *shell)
201 GPtrArray *args_array;
203 if ((flags & EXECUTE_AS_SHELL) != 0)
205 args_array = g_ptr_array_new ();
206 g_ptr_array_add (args_array, (gpointer) shell);
207 g_ptr_array_add (args_array, (gpointer) "-c");
209 else if (shell == NULL || *shell == '\0')
211 args_array = g_ptr_array_new ();
212 g_ptr_array_add (args_array, NULL);
214 else
215 args_array = str_tokenize (shell);
217 return args_array;
220 /* --------------------------------------------------------------------------------------------- */
222 static void
223 mc_pread_stream (mc_pipe_stream_t *ps, const fd_set *fds)
225 size_t buf_len;
226 ssize_t read_len;
228 if (!FD_ISSET (ps->fd, fds))
230 ps->len = MC_PIPE_STREAM_UNREAD;
231 return;
234 buf_len = (size_t) ps->len;
236 if (buf_len >= MC_PIPE_BUFSIZE)
237 buf_len = ps->null_term ? MC_PIPE_BUFSIZE - 1 : MC_PIPE_BUFSIZE;
241 read_len = read (ps->fd, ps->buf, buf_len);
243 while (read_len < 0 && errno == EINTR);
245 if (read_len < 0)
247 /* reading error */
248 ps->len = MC_PIPE_ERROR_READ;
249 ps->error = errno;
251 else if (read_len == 0)
252 /* EOF */
253 ps->len = MC_PIPE_STREAM_EOF;
254 else
256 /* success */
257 ps->len = read_len;
259 if (ps->null_term)
260 ps->buf[(size_t) ps->len] = '\0';
263 ps->pos = 0;
266 /* --------------------------------------------------------------------------------------------- */
267 /*** public functions ****************************************************************************/
268 /* --------------------------------------------------------------------------------------------- */
270 const char *
271 get_owner (uid_t uid)
273 struct passwd *pwd;
274 char *name;
275 static uid_t uid_last;
277 name = i_cache_match ((int) uid, uid_cache, UID_CACHE_SIZE);
278 if (name != NULL)
279 return name;
281 pwd = getpwuid (uid);
282 if (pwd != NULL)
284 i_cache_add ((int) uid, uid_cache, UID_CACHE_SIZE, pwd->pw_name, (int *) &uid_last);
285 return pwd->pw_name;
287 else
289 static char ibuf[10];
291 g_snprintf (ibuf, sizeof (ibuf), "%d", (int) uid);
292 return ibuf;
296 /* --------------------------------------------------------------------------------------------- */
298 const char *
299 get_group (gid_t gid)
301 struct group *grp;
302 char *name;
303 static gid_t gid_last;
305 name = i_cache_match ((int) gid, gid_cache, GID_CACHE_SIZE);
306 if (name != NULL)
307 return name;
309 grp = getgrgid (gid);
310 if (grp != NULL)
312 i_cache_add ((int) gid, gid_cache, GID_CACHE_SIZE, grp->gr_name, (int *) &gid_last);
313 return grp->gr_name;
315 else
317 static char gbuf[10];
319 g_snprintf (gbuf, sizeof (gbuf), "%d", (int) gid);
320 return gbuf;
324 /* --------------------------------------------------------------------------------------------- */
325 /* Since ncurses uses a handler that automatically refreshes the */
326 /* screen after a SIGCONT, and we don't want this behavior when */
327 /* spawning a child, we save the original handler here */
329 void
330 save_stop_handler (void)
332 sigaction (SIGTSTP, NULL, &startup_handler);
335 /* --------------------------------------------------------------------------------------------- */
337 * Wrapper for _exit() system call.
338 * The _exit() function has gcc's attribute 'noreturn', and this is reason why we can't
339 * mock the call.
341 * @param status exit code
344 void
345 /* __attribute__ ((noreturn)) */
346 my_exit (int status)
348 _exit (status);
351 /* --------------------------------------------------------------------------------------------- */
353 * Call external programs.
355 * @parameter flags addition conditions for running external programs.
356 * @parameter shell shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
357 * Shell (or command) will be found in paths described in PATH variable
358 * (if shell parameter doesn't begin from path delimiter)
359 * @parameter command Command for shell (or first parameter for command, if flags contain EXECUTE_AS_SHELL)
360 * @return 0 if successful, -1 otherwise
364 my_system (int flags, const char *shell, const char *command)
366 return my_systeml (flags, shell, command, NULL);
369 /* --------------------------------------------------------------------------------------------- */
371 * Call external programs with various parameters number.
373 * @parameter flags addition conditions for running external programs.
374 * @parameter shell shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
375 * Shell (or command) will be found in paths described in PATH variable
376 * (if shell parameter doesn't begin from path delimiter)
377 * @parameter ... Command for shell with addition parameters for shell
378 * (or parameters for command, if flags contain EXECUTE_AS_SHELL).
379 * Should be NULL terminated.
380 * @return 0 if successful, -1 otherwise
384 my_systeml (int flags, const char *shell, ...)
386 GPtrArray *args_array;
387 int status = 0;
388 va_list vargs;
389 char *one_arg;
391 args_array = g_ptr_array_new ();
393 va_start (vargs, shell);
394 while ((one_arg = va_arg (vargs, char *)) != NULL)
395 g_ptr_array_add (args_array, one_arg);
396 va_end (vargs);
398 g_ptr_array_add (args_array, NULL);
399 status = my_systemv_flags (flags, shell, (char *const *) args_array->pdata);
401 g_ptr_array_free (args_array, TRUE);
403 return status;
406 /* --------------------------------------------------------------------------------------------- */
408 * Call external programs with array of strings as parameters.
410 * @parameter command command to run. Command will be found in paths described in PATH variable
411 * (if command parameter doesn't begin from path delimiter)
412 * @parameter argv Array of strings (NULL-terminated) with parameters for command
413 * @return 0 if successful, -1 otherwise
417 my_systemv (const char *command, char *const argv[])
419 my_fork_state_t fork_state;
420 int status = 0;
421 my_system_sigactions_t sigactions;
423 my_system__save_sigaction_handlers (&sigactions);
425 fork_state = my_fork ();
426 switch (fork_state)
428 case FORK_ERROR:
429 status = -1;
430 break;
431 case FORK_CHILD:
433 signal (SIGINT, SIG_DFL);
434 signal (SIGQUIT, SIG_DFL);
435 signal (SIGTSTP, SIG_DFL);
436 signal (SIGCHLD, SIG_DFL);
438 execvp (command, argv);
439 my_exit (127); /* Exec error */
441 MC_FALLTHROUGH;
442 /* no break here, or unreachable-code warning by no returning my_exit() */
443 default:
444 status = 0;
445 break;
447 my_system__restore_sigaction_handlers (&sigactions);
449 return status;
452 /* --------------------------------------------------------------------------------------------- */
454 * Call external programs with flags and with array of strings as parameters.
456 * @parameter flags addition conditions for running external programs.
457 * @parameter command shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
458 * Shell (or command) will be found in paths described in PATH variable
459 * (if shell parameter doesn't begin from path delimiter)
460 * @parameter argv Array of strings (NULL-terminated) with parameters for command
461 * @return 0 if successful, -1 otherwise
465 my_systemv_flags (int flags, const char *command, char *const argv[])
467 const char *execute_name;
468 GPtrArray *args_array;
469 int status = 0;
471 args_array = my_system_make_arg_array (flags, command);
473 execute_name = g_ptr_array_index (args_array, 0);
475 for (; argv != NULL && *argv != NULL; argv++)
476 g_ptr_array_add (args_array, *argv);
478 g_ptr_array_add (args_array, NULL);
479 status = my_systemv (execute_name, (char *const *) args_array->pdata);
481 g_ptr_array_free (args_array, TRUE);
483 return status;
486 /* --------------------------------------------------------------------------------------------- */
488 * Create pipe and run child process.
490 * @parameter command command line of child process
491 * @parameter read_out do or don't read the stdout of child process
492 * @parameter read_err do or don't read the stderr of child process
493 * @parameter error contains pointer to object to handle error code and message
495 * @return newly created object of mc_pipe_t class in success, NULL otherwise
498 mc_pipe_t *
499 mc_popen (const char *command, gboolean read_out, gboolean read_err, GError **error)
501 mc_pipe_t *p;
502 const char *const argv[] = { "/bin/sh", "sh", "-c", command, NULL };
504 p = g_try_new (mc_pipe_t, 1);
505 if (p == NULL)
507 mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE, "%s",
508 _("Cannot create pipe descriptor"));
509 goto ret_err;
512 p->out.fd = -1;
513 p->err.fd = -1;
515 if (!g_spawn_async_with_pipes
516 (NULL, (gchar **) argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_FILE_AND_ARGV_ZERO, NULL,
517 NULL, &p->child_pid, NULL, read_out ? &p->out.fd : NULL, read_err ? &p->err.fd : NULL,
518 error))
520 mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE_STREAM, "%s",
521 _("Cannot create pipe streams"));
522 goto ret_err;
525 p->out.buf[0] = '\0';
526 p->out.len = MC_PIPE_BUFSIZE;
527 p->out.null_term = FALSE;
529 p->err.buf[0] = '\0';
530 p->err.len = MC_PIPE_BUFSIZE;
531 p->err.null_term = FALSE;
533 return p;
535 ret_err:
536 g_free (p);
537 return NULL;
540 /* --------------------------------------------------------------------------------------------- */
542 * Read stdout and stderr of pipe asynchronously.
544 * @parameter p pipe descriptor
546 * The lengths of read data contain in p->out.len and p->err.len.
548 * Before read, p->xxx.len is an input. It defines the number of data to read.
549 * Should not be greater than MC_PIPE_BUFSIZE.
551 * After read, p->xxx.len is an output and contains the following:
552 * p->xxx.len > 0: an actual length of read data stored in p->xxx.buf;
553 * p->xxx.len == MC_PIPE_STREAM_EOF: EOF of stream p->xxx;
554 * p->xxx.len == MC_PIPE_STREAM_UNREAD: stream p->xxx was not read;
555 * p->xxx.len == MC_PIPE_ERROR_READ: reading error, and p->xxx.errno is set appropriately.
557 * @parameter error contains pointer to object to handle error code and message
560 void
561 mc_pread (mc_pipe_t *p, GError **error)
563 gboolean read_out, read_err;
564 fd_set fds;
565 int maxfd = 0;
566 int res;
568 if (error != NULL)
569 *error = NULL;
571 read_out = p->out.fd >= 0;
572 read_err = p->err.fd >= 0;
574 if (!read_out && !read_err)
576 p->out.len = MC_PIPE_STREAM_UNREAD;
577 p->err.len = MC_PIPE_STREAM_UNREAD;
578 return;
581 FD_ZERO (&fds);
582 if (read_out)
584 FD_SET (p->out.fd, &fds);
585 maxfd = p->out.fd;
588 if (read_err)
590 FD_SET (p->err.fd, &fds);
591 maxfd = MAX (maxfd, p->err.fd);
594 /* no timeout */
595 res = select (maxfd + 1, &fds, NULL, NULL, NULL);
596 if (res < 0 && errno != EINTR)
598 mc_propagate_error (error, MC_PIPE_ERROR_READ,
600 ("Unexpected error in select() reading data from a child process:\n%s"),
601 unix_error_string (errno));
602 return;
605 if (read_out)
606 mc_pread_stream (&p->out, &fds);
607 else
608 p->out.len = MC_PIPE_STREAM_UNREAD;
610 if (read_err)
611 mc_pread_stream (&p->err, &fds);
612 else
613 p->err.len = MC_PIPE_STREAM_UNREAD;
616 /* --------------------------------------------------------------------------------------------- */
618 * Reads a line from @stream. Reading stops after an EOL or a newline. If a newline is read,
619 * it is appended to the line.
621 * @stream mc_pipe_stream_t object
623 * @return newly created GString or NULL in case of EOL;
626 GString *
627 mc_pstream_get_string (mc_pipe_stream_t *ps)
629 char *s;
630 size_t size, i;
631 gboolean escape = FALSE;
633 g_return_val_if_fail (ps != NULL, NULL);
635 if (ps->len < 0)
636 return NULL;
638 size = ps->len - ps->pos;
640 if (size == 0)
641 return NULL;
643 s = ps->buf + ps->pos;
645 if (s[0] == '\0')
646 return NULL;
648 /* find '\0' or unescaped '\n' */
649 for (i = 0; i < size && !(s[i] == '\0' || (s[i] == '\n' && !escape)); i++)
650 escape = s[i] == '\\' ? !escape : FALSE;
652 if (i != size && s[i] == '\n')
653 i++;
655 ps->pos += i;
657 return g_string_new_len (s, i);
660 /* --------------------------------------------------------------------------------------------- */
662 * Close pipe and destroy pipe descriptor.
664 * @parameter p pipe descriptor
665 * @parameter error contains pointer to object to handle error code and message
668 void
669 mc_pclose (mc_pipe_t *p, GError **error)
671 int res;
673 if (p == NULL)
675 mc_replace_error (error, MC_PIPE_ERROR_READ, "%s",
676 _("Cannot close pipe descriptor (p == NULL)"));
677 return;
680 if (p->out.fd >= 0)
681 res = close (p->out.fd);
682 if (p->err.fd >= 0)
683 res = close (p->err.fd);
687 int status;
689 res = waitpid (p->child_pid, &status, 0);
691 while (res < 0 && errno == EINTR);
693 if (res < 0)
694 mc_replace_error (error, MC_PIPE_ERROR_READ, _("Unexpected error in waitpid():\n%s"),
695 unix_error_string (errno));
697 g_free (p);
700 /* --------------------------------------------------------------------------------------------- */
703 * Perform tilde expansion if possible.
705 * @param directory pointer to the path
707 * @return newly allocated string, even if it's unchanged.
710 char *
711 tilde_expand (const char *directory)
713 struct passwd *passwd;
714 const char *p, *q;
716 if (*directory != '~')
717 return g_strdup (directory);
719 p = directory + 1;
721 /* d = "~" or d = "~/" */
722 if (*p == '\0' || IS_PATH_SEP (*p))
724 passwd = getpwuid (geteuid ());
725 q = IS_PATH_SEP (*p) ? p + 1 : "";
727 else
729 q = strchr (p, PATH_SEP);
730 if (q == NULL)
731 passwd = getpwnam (p);
732 else
734 char *name;
736 name = g_strndup (p, q - p);
737 passwd = getpwnam (name);
738 q++;
739 g_free (name);
743 /* If we can't figure the user name, leave tilde unexpanded */
744 if (passwd == NULL)
745 return g_strdup (directory);
747 return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
750 /* --------------------------------------------------------------------------------------------- */
752 * Canonicalize path.
754 * @param path path to file
755 * @param flags canonicalization flags
757 * All modifications of @path are made in place.
758 * Well formed UNC paths are modified only in the local part.
761 void
762 canonicalize_pathname_custom (char *path, canon_path_flags_t flags)
764 char *p, *s;
765 char *lpath = path; /* path without leading UNC part */
766 const size_t url_delim_len = strlen (VFS_PATH_URL_DELIMITER);
768 /* Detect and preserve UNC paths: //server/... */
769 if ((flags & CANON_PATH_GUARDUNC) != 0 && IS_PATH_SEP (path[0]) && IS_PATH_SEP (path[1]))
771 for (p = path + 2; p[0] != '\0' && !IS_PATH_SEP (p[0]); p++)
773 if (IS_PATH_SEP (p[0]) && p > path + 2)
774 lpath = p;
777 if (lpath[0] == '\0' || lpath[1] == '\0')
778 return;
780 if ((flags & CANON_PATH_JOINSLASHES) != 0)
782 /* Collapse multiple slashes */
783 for (p = lpath; *p != '\0'; p++)
784 if (IS_PATH_SEP (p[0]) && IS_PATH_SEP (p[1]) && (p == lpath || *(p - 1) != ':'))
786 s = p + 1;
787 while (IS_PATH_SEP (*(++s)))
789 str_move (p + 1, s);
792 /* Collapse "/./" -> "/" */
793 for (p = lpath; *p != '\0';)
794 if (IS_PATH_SEP (p[0]) && p[1] == '.' && IS_PATH_SEP (p[2]))
795 str_move (p, p + 2);
796 else
797 p++;
800 if ((flags & CANON_PATH_REMSLASHDOTS) != 0)
802 size_t len;
804 /* Remove trailing slashes */
805 for (p = lpath + strlen (lpath) - 1; p > lpath && IS_PATH_SEP (*p); p--)
807 if (p >= lpath + url_delim_len - 1
808 && strncmp (p - url_delim_len + 1, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
809 break;
810 *p = '\0';
813 /* Remove leading "./" */
814 if (lpath[0] == '.' && IS_PATH_SEP (lpath[1]))
816 if (lpath[2] == '\0')
818 lpath[1] = '\0';
819 return;
822 str_move (lpath, lpath + 2);
825 /* Remove trailing "/" or "/." */
826 len = strlen (lpath);
827 if (len < 2)
828 return;
830 if (IS_PATH_SEP (lpath[len - 1])
831 && (len < url_delim_len
832 || strncmp (lpath + len - url_delim_len, VFS_PATH_URL_DELIMITER,
833 url_delim_len) != 0))
834 lpath[len - 1] = '\0';
835 else if (lpath[len - 1] == '.' && IS_PATH_SEP (lpath[len - 2]))
837 if (len == 2)
839 lpath[1] = '\0';
840 return;
843 lpath[len - 2] = '\0';
847 /* Collapse "/.." with the previous part of path */
848 if ((flags & CANON_PATH_REMDOUBLEDOTS) != 0)
850 #ifdef HAVE_CHARSET
851 const size_t enc_prefix_len = strlen (VFS_ENCODING_PREFIX);
852 #endif /* HAVE_CHARSET */
854 for (p = lpath; p[0] != '\0' && p[1] != '\0' && p[2] != '\0';)
856 if (!IS_PATH_SEP (p[0]) || p[1] != '.' || p[2] != '.'
857 || (!IS_PATH_SEP (p[3]) && p[3] != '\0'))
859 p++;
860 continue;
863 /* search for the previous token */
864 s = p - 1;
865 if (s >= lpath + url_delim_len - 2
866 && strncmp (s - url_delim_len + 2, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
868 s -= (url_delim_len - 2);
869 while (s >= lpath && !IS_PATH_SEP (*s--))
873 while (s >= lpath)
875 if (s - url_delim_len > lpath
876 && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
878 char *vfs_prefix = s - url_delim_len;
879 vfs_class *vclass;
881 while (vfs_prefix > lpath && !IS_PATH_SEP (*--vfs_prefix))
883 if (IS_PATH_SEP (*vfs_prefix))
884 vfs_prefix++;
885 *(s - url_delim_len) = '\0';
887 vclass = vfs_prefix_to_class (vfs_prefix);
888 *(s - url_delim_len) = *VFS_PATH_URL_DELIMITER;
890 if (vclass != NULL && (vclass->flags & VFSF_REMOTE) != 0)
892 s = vfs_prefix;
893 continue;
897 if (IS_PATH_SEP (*s))
898 break;
900 s--;
903 s++;
905 /* If the previous token is "..", we cannot collapse it */
906 if (s[0] == '.' && s[1] == '.' && s + 2 == p)
908 p += 3;
909 continue;
912 if (p[3] != '\0')
914 if (s == lpath && IS_PATH_SEP (*s))
916 /* "/../foo" -> "/foo" */
917 str_move (s + 1, p + 4);
919 else
921 /* "token/../foo" -> "foo" */
922 #ifdef HAVE_CHARSET
923 if (strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
925 char *enc;
927 enc = vfs_get_encoding (s, -1);
929 if (is_supported_encoding (enc))
930 /* special case: remove encoding */
931 str_move (s, p + 1);
932 else
933 str_move (s, p + 4);
935 g_free (enc);
937 else
938 #endif /* HAVE_CHARSET */
939 str_move (s, p + 4);
942 p = s > lpath ? s - 1 : s;
943 continue;
946 /* trailing ".." */
947 if (s == lpath)
949 /* "token/.." -> "." */
950 if (!IS_PATH_SEP (lpath[0]))
951 lpath[0] = '.';
952 lpath[1] = '\0';
954 else
956 /* "foo/token/.." -> "foo" */
957 if (s == lpath + 1)
958 s[0] = '\0';
959 #ifdef HAVE_CHARSET
960 else if (strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
962 char *enc;
963 gboolean ok;
965 enc = vfs_get_encoding (s, -1);
966 ok = is_supported_encoding (enc);
967 g_free (enc);
969 if (!ok)
970 goto last;
972 /* special case: remove encoding */
973 s[0] = '.';
974 s[1] = '.';
975 s[2] = '\0';
977 /* search for the previous token */
978 /* IS_PATH_SEP (s[-1]) */
979 for (p = s - 1; p >= lpath && !IS_PATH_SEP (*p); p--)
982 if (p >= lpath)
983 continue;
985 #endif /* HAVE_CHARSET */
986 else
988 last:
989 if (s >= lpath + url_delim_len
990 && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
991 *s = '\0';
992 else
993 s[-1] = '\0';
997 break;
1002 /* --------------------------------------------------------------------------------------------- */
1004 char *
1005 mc_realpath (const char *path, char *resolved_path)
1007 #ifdef HAVE_CHARSET
1008 const char *p = path;
1009 gboolean absolute_path = FALSE;
1011 if (IS_PATH_SEP (*p))
1013 absolute_path = TRUE;
1014 p++;
1017 /* ignore encoding: skip "#enc:" */
1018 if (g_str_has_prefix (p, VFS_ENCODING_PREFIX))
1020 p += strlen (VFS_ENCODING_PREFIX);
1021 p = strchr (p, PATH_SEP);
1022 if (p != NULL)
1024 if (!absolute_path && p[1] != '\0')
1025 p++;
1027 path = p;
1030 #endif /* HAVE_CHARSET */
1032 #ifdef HAVE_REALPATH
1033 return realpath (path, resolved_path);
1034 #else
1036 char copy_path[PATH_MAX];
1037 char got_path[PATH_MAX];
1038 char *new_path = got_path;
1039 char *max_path;
1040 #ifdef S_IFLNK
1041 char link_path[PATH_MAX];
1042 int readlinks = 0;
1043 int n;
1044 #endif /* S_IFLNK */
1046 /* Make a copy of the source path since we may need to modify it. */
1047 if (strlen (path) >= PATH_MAX - 2)
1049 errno = ENAMETOOLONG;
1050 return NULL;
1053 strcpy (copy_path, path);
1054 path = copy_path;
1055 max_path = copy_path + PATH_MAX - 2;
1056 /* If it's a relative pathname use getwd for starters. */
1057 if (!IS_PATH_SEP (*path))
1059 new_path = g_get_current_dir ();
1060 if (new_path == NULL)
1061 strcpy (got_path, "");
1062 else
1064 g_snprintf (got_path, sizeof (got_path), "%s", new_path);
1065 g_free (new_path);
1066 new_path = got_path;
1069 new_path += strlen (got_path);
1070 if (!IS_PATH_SEP (new_path[-1]))
1071 *new_path++ = PATH_SEP;
1073 else
1075 *new_path++ = PATH_SEP;
1076 path++;
1078 /* Expand each slash-separated pathname component. */
1079 while (*path != '\0')
1081 /* Ignore stray "/". */
1082 if (IS_PATH_SEP (*path))
1084 path++;
1085 continue;
1087 if (*path == '.')
1089 /* Ignore ".". */
1090 if (path[1] == '\0' || IS_PATH_SEP (path[1]))
1092 path++;
1093 continue;
1095 if (path[1] == '.')
1097 if (path[2] == '\0' || IS_PATH_SEP (path[2]))
1099 path += 2;
1100 /* Ignore ".." at root. */
1101 if (new_path == got_path + 1)
1102 continue;
1103 /* Handle ".." by backing up. */
1104 while (!IS_PATH_SEP ((--new_path)[-1]))
1106 continue;
1110 /* Safely copy the next pathname component. */
1111 while (*path != '\0' && !IS_PATH_SEP (*path))
1113 if (path > max_path)
1115 errno = ENAMETOOLONG;
1116 return NULL;
1118 *new_path++ = *path++;
1120 #ifdef S_IFLNK
1121 /* Protect against infinite loops. */
1122 if (readlinks++ > MAXSYMLINKS)
1124 errno = ELOOP;
1125 return NULL;
1127 /* See if latest pathname component is a symlink. */
1128 *new_path = '\0';
1129 n = readlink (got_path, link_path, PATH_MAX - 1);
1130 if (n < 0)
1132 /* EINVAL means the file exists but isn't a symlink. */
1133 if (errno != EINVAL)
1135 /* Make sure it's null terminated. */
1136 *new_path = '\0';
1137 strcpy (resolved_path, got_path);
1138 return NULL;
1141 else
1143 /* Note: readlink doesn't add the null byte. */
1144 link_path[n] = '\0';
1145 if (IS_PATH_SEP (*link_path))
1146 /* Start over for an absolute symlink. */
1147 new_path = got_path;
1148 else
1149 /* Otherwise back up over this component. */
1150 while (!IS_PATH_SEP (*(--new_path)))
1152 /* Safe sex check. */
1153 if (strlen (path) + n >= PATH_MAX - 2)
1155 errno = ENAMETOOLONG;
1156 return NULL;
1158 /* Insert symlink contents into path. */
1159 strcat (link_path, path);
1160 strcpy (copy_path, link_path);
1161 path = copy_path;
1163 #endif /* S_IFLNK */
1164 *new_path++ = PATH_SEP;
1166 /* Delete trailing slash but don't whomp a lone slash. */
1167 if (new_path != got_path + 1 && IS_PATH_SEP (new_path[-1]))
1168 new_path--;
1169 /* Make sure it's null terminated. */
1170 *new_path = '\0';
1171 strcpy (resolved_path, got_path);
1172 return resolved_path;
1174 #endif /* HAVE_REALPATH */
1177 /* --------------------------------------------------------------------------------------------- */
1179 * Return the index of the permissions triplet
1184 get_user_permissions (struct stat *st)
1186 static gboolean initialized = FALSE;
1187 static gid_t *groups;
1188 static int ngroups;
1189 static uid_t uid;
1190 int i;
1192 if (!initialized)
1194 uid = geteuid ();
1196 ngroups = getgroups (0, NULL);
1197 if (ngroups == -1)
1198 ngroups = 0; /* ignore errors */
1200 /* allocate space for one element in addition to what
1201 * will be filled by getgroups(). */
1202 groups = g_new (gid_t, ngroups + 1);
1204 if (ngroups != 0)
1206 ngroups = getgroups (ngroups, groups);
1207 if (ngroups == -1)
1208 ngroups = 0; /* ignore errors */
1211 /* getgroups() may or may not return the effective group ID,
1212 * so we always include it at the end of the list. */
1213 groups[ngroups++] = getegid ();
1215 initialized = TRUE;
1218 if (st->st_uid == uid || uid == 0)
1219 return 0;
1221 for (i = 0; i < ngroups; i++)
1222 if (st->st_gid == groups[i])
1223 return 1;
1225 return 2;
1228 /* --------------------------------------------------------------------------------------------- */
1230 * Build filename from arguments.
1231 * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
1234 char *
1235 mc_build_filenamev (const char *first_element, va_list args)
1237 gboolean absolute;
1238 const char *element = first_element;
1239 GString *path;
1240 char *ret;
1242 if (first_element == NULL)
1243 return NULL;
1245 absolute = IS_PATH_SEP (*first_element);
1247 path = g_string_new (absolute ? PATH_SEP_STR : "");
1251 if (*element == '\0')
1252 element = va_arg (args, char *);
1253 else
1255 char *tmp_element;
1256 const char *start;
1258 tmp_element = g_strdup (element);
1260 element = va_arg (args, char *);
1262 canonicalize_pathname (tmp_element);
1263 start = IS_PATH_SEP (tmp_element[0]) ? tmp_element + 1 : tmp_element;
1265 g_string_append (path, start);
1266 if (!IS_PATH_SEP (path->str[path->len - 1]) && element != NULL)
1267 g_string_append_c (path, PATH_SEP);
1269 g_free (tmp_element);
1272 while (element != NULL);
1274 ret = g_string_free (path, FALSE);
1275 canonicalize_pathname (ret);
1277 return ret;
1280 /* --------------------------------------------------------------------------------------------- */
1282 * Build filename from arguments.
1283 * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
1286 char *
1287 mc_build_filename (const char *first_element, ...)
1289 va_list args;
1290 char *ret;
1292 if (first_element == NULL)
1293 return NULL;
1295 va_start (args, first_element);
1296 ret = mc_build_filenamev (first_element, args);
1297 va_end (args);
1298 return ret;
1301 /* --------------------------------------------------------------------------------------------- */