mceditor: refactoring.
[midnight-commander.git] / lib / utilunix.c
blobcec0dab414de8ddc72e52aee5b926cf020a8f41a
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 #include "utilunix.h"
75 /*** global variables ****************************************************************************/
77 struct sigaction startup_handler;
79 /*** file scope macro definitions ****************************************************************/
81 #define UID_CACHE_SIZE 200
82 #define GID_CACHE_SIZE 30
84 /*** file scope type declarations ****************************************************************/
86 typedef struct
88 int index;
89 char *string;
90 } int_cache;
92 typedef enum
94 FORK_ERROR = -1,
95 FORK_CHILD,
96 FORK_PARENT,
97 } my_fork_state_t;
99 typedef struct
101 struct sigaction intr;
102 struct sigaction quit;
103 struct sigaction stop;
104 } my_system_sigactions_t;
106 /*** forward declarations (file scope functions) *************************************************/
108 /*** file scope variables ************************************************************************/
110 static int_cache uid_cache[UID_CACHE_SIZE];
111 static int_cache gid_cache[GID_CACHE_SIZE];
113 /* --------------------------------------------------------------------------------------------- */
114 /*** file scope functions ************************************************************************/
115 /* --------------------------------------------------------------------------------------------- */
117 static char *
118 i_cache_match (int id, int_cache * cache, int size)
120 int i;
122 for (i = 0; i < size; i++)
123 if (cache[i].index == id)
124 return cache[i].string;
125 return 0;
128 /* --------------------------------------------------------------------------------------------- */
130 static void
131 i_cache_add (int id, int_cache * cache, int size, char *text, int *last)
133 g_free (cache[*last].string);
134 cache[*last].string = g_strdup (text);
135 cache[*last].index = id;
136 *last = ((*last) + 1) % size;
139 /* --------------------------------------------------------------------------------------------- */
141 static my_fork_state_t
142 my_fork (void)
144 pid_t pid;
146 pid = fork ();
148 if (pid < 0)
150 fprintf (stderr, "\n\nfork () = -1\n");
151 return FORK_ERROR;
154 if (pid == 0)
155 return FORK_CHILD;
157 while (TRUE)
159 int status = 0;
161 if (waitpid (pid, &status, 0) > 0)
162 return WEXITSTATUS (status) == 0 ? FORK_PARENT : FORK_ERROR;
164 if (errno != EINTR)
165 return FORK_ERROR;
169 /* --------------------------------------------------------------------------------------------- */
171 static void
172 my_system__save_sigaction_handlers (my_system_sigactions_t * sigactions)
174 struct sigaction ignore;
176 memset (&ignore, 0, sizeof (ignore));
177 ignore.sa_handler = SIG_IGN;
178 sigemptyset (&ignore.sa_mask);
180 sigaction (SIGINT, &ignore, &sigactions->intr);
181 sigaction (SIGQUIT, &ignore, &sigactions->quit);
183 /* Restore the original SIGTSTP handler, we don't want ncurses' */
184 /* handler messing the screen after the SIGCONT */
185 sigaction (SIGTSTP, &startup_handler, &sigactions->stop);
188 /* --------------------------------------------------------------------------------------------- */
190 static void
191 my_system__restore_sigaction_handlers (my_system_sigactions_t * sigactions)
193 sigaction (SIGINT, &sigactions->intr, NULL);
194 sigaction (SIGQUIT, &sigactions->quit, NULL);
195 sigaction (SIGTSTP, &sigactions->stop, NULL);
198 /* --------------------------------------------------------------------------------------------- */
200 static GPtrArray *
201 my_system_make_arg_array (int flags, const char *shell)
203 GPtrArray *args_array;
205 if ((flags & EXECUTE_AS_SHELL) != 0)
207 args_array = g_ptr_array_new ();
208 g_ptr_array_add (args_array, (gpointer) shell);
209 g_ptr_array_add (args_array, (gpointer) "-c");
211 else if (shell == NULL || *shell == '\0')
213 args_array = g_ptr_array_new ();
214 g_ptr_array_add (args_array, NULL);
216 else
217 args_array = str_tokenize (shell);
219 return args_array;
222 /* --------------------------------------------------------------------------------------------- */
224 static void
225 mc_pread_stream (mc_pipe_stream_t * ps, const fd_set * fds)
227 size_t buf_len;
228 ssize_t read_len;
230 if (!FD_ISSET (ps->fd, fds))
232 ps->len = MC_PIPE_STREAM_UNREAD;
233 return;
236 buf_len = (size_t) ps->len;
238 if (buf_len >= MC_PIPE_BUFSIZE)
239 buf_len = ps->null_term ? MC_PIPE_BUFSIZE - 1 : MC_PIPE_BUFSIZE;
243 read_len = read (ps->fd, ps->buf, buf_len);
245 while (read_len < 0 && errno == EINTR);
247 if (read_len < 0)
249 /* reading error */
250 ps->len = MC_PIPE_ERROR_READ;
251 ps->error = errno;
253 else if (read_len == 0)
254 /* EOF */
255 ps->len = MC_PIPE_STREAM_EOF;
256 else
258 /* success */
259 ps->len = read_len;
261 if (ps->null_term)
262 ps->buf[(size_t) ps->len] = '\0';
265 ps->pos = 0;
268 /* --------------------------------------------------------------------------------------------- */
269 /*** public functions ****************************************************************************/
270 /* --------------------------------------------------------------------------------------------- */
272 const char *
273 get_owner (uid_t uid)
275 struct passwd *pwd;
276 char *name;
277 static uid_t uid_last;
279 name = i_cache_match ((int) uid, uid_cache, UID_CACHE_SIZE);
280 if (name != NULL)
281 return name;
283 pwd = getpwuid (uid);
284 if (pwd != NULL)
286 i_cache_add ((int) uid, uid_cache, UID_CACHE_SIZE, pwd->pw_name, (int *) &uid_last);
287 return pwd->pw_name;
289 else
291 static char ibuf[10];
293 g_snprintf (ibuf, sizeof (ibuf), "%d", (int) uid);
294 return ibuf;
298 /* --------------------------------------------------------------------------------------------- */
300 const char *
301 get_group (gid_t gid)
303 struct group *grp;
304 char *name;
305 static gid_t gid_last;
307 name = i_cache_match ((int) gid, gid_cache, GID_CACHE_SIZE);
308 if (name != NULL)
309 return name;
311 grp = getgrgid (gid);
312 if (grp != NULL)
314 i_cache_add ((int) gid, gid_cache, GID_CACHE_SIZE, grp->gr_name, (int *) &gid_last);
315 return grp->gr_name;
317 else
319 static char gbuf[10];
321 g_snprintf (gbuf, sizeof (gbuf), "%d", (int) gid);
322 return gbuf;
326 /* --------------------------------------------------------------------------------------------- */
327 /* Since ncurses uses a handler that automatically refreshes the */
328 /* screen after a SIGCONT, and we don't want this behavior when */
329 /* spawning a child, we save the original handler here */
331 void
332 save_stop_handler (void)
334 sigaction (SIGTSTP, NULL, &startup_handler);
337 /* --------------------------------------------------------------------------------------------- */
339 * Wrapper for _exit() system call.
340 * The _exit() function has gcc's attribute 'noreturn', and this is reason why we can't
341 * mock the call.
343 * @param status exit code
346 void
347 /* __attribute__ ((noreturn)) */
348 my_exit (int status)
350 _exit (status);
353 /* --------------------------------------------------------------------------------------------- */
355 * Call external programs.
357 * @parameter flags addition conditions for running external programs.
358 * @parameter shell shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
359 * Shell (or command) will be found in paths described in PATH variable
360 * (if shell parameter doesn't begin from path delimiter)
361 * @parameter command Command for shell (or first parameter for command, if flags contain EXECUTE_AS_SHELL)
362 * @return 0 if successful, -1 otherwise
366 my_system (int flags, const char *shell, const char *command)
368 return my_systeml (flags, shell, command, NULL);
371 /* --------------------------------------------------------------------------------------------- */
373 * Call external programs with various parameters number.
375 * @parameter flags addition conditions for running external programs.
376 * @parameter shell shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
377 * Shell (or command) will be found in paths described in PATH variable
378 * (if shell parameter doesn't begin from path delimiter)
379 * @parameter ... Command for shell with addition parameters for shell
380 * (or parameters for command, if flags contain EXECUTE_AS_SHELL).
381 * Should be NULL terminated.
382 * @return 0 if successful, -1 otherwise
386 my_systeml (int flags, const char *shell, ...)
388 GPtrArray *args_array;
389 int status = 0;
390 va_list vargs;
391 char *one_arg;
393 args_array = g_ptr_array_new ();
395 va_start (vargs, shell);
396 while ((one_arg = va_arg (vargs, char *)) != NULL)
397 g_ptr_array_add (args_array, one_arg);
398 va_end (vargs);
400 g_ptr_array_add (args_array, NULL);
401 status = my_systemv_flags (flags, shell, (char *const *) args_array->pdata);
403 g_ptr_array_free (args_array, TRUE);
405 return status;
408 /* --------------------------------------------------------------------------------------------- */
410 * Call external programs with array of strings as parameters.
412 * @parameter command command to run. Command will be found in paths described in PATH variable
413 * (if command parameter doesn't begin from path delimiter)
414 * @parameter argv Array of strings (NULL-terminated) with parameters for command
415 * @return 0 if successful, -1 otherwise
419 my_systemv (const char *command, char *const argv[])
421 my_fork_state_t fork_state;
422 int status = 0;
423 my_system_sigactions_t sigactions;
425 my_system__save_sigaction_handlers (&sigactions);
427 fork_state = my_fork ();
428 switch (fork_state)
430 case FORK_ERROR:
431 status = -1;
432 break;
433 case FORK_CHILD:
435 signal (SIGINT, SIG_DFL);
436 signal (SIGQUIT, SIG_DFL);
437 signal (SIGTSTP, SIG_DFL);
438 signal (SIGCHLD, SIG_DFL);
440 execvp (command, argv);
441 my_exit (127); /* Exec error */
443 MC_FALLTHROUGH;
444 /* no break here, or unreachable-code warning by no returning my_exit() */
445 default:
446 status = 0;
447 break;
449 my_system__restore_sigaction_handlers (&sigactions);
451 return status;
454 /* --------------------------------------------------------------------------------------------- */
456 * Call external programs with flags and with array of strings as parameters.
458 * @parameter flags addition conditions for running external programs.
459 * @parameter command shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
460 * Shell (or command) will be found in paths described in PATH variable
461 * (if shell parameter doesn't begin from path delimiter)
462 * @parameter argv Array of strings (NULL-terminated) with parameters for command
463 * @return 0 if successful, -1 otherwise
467 my_systemv_flags (int flags, const char *command, char *const argv[])
469 const char *execute_name;
470 GPtrArray *args_array;
471 int status = 0;
473 args_array = my_system_make_arg_array (flags, command);
475 execute_name = g_ptr_array_index (args_array, 0);
477 for (; argv != NULL && *argv != NULL; argv++)
478 g_ptr_array_add (args_array, *argv);
480 g_ptr_array_add (args_array, NULL);
481 status = my_systemv (execute_name, (char *const *) args_array->pdata);
483 g_ptr_array_free (args_array, TRUE);
485 return status;
488 /* --------------------------------------------------------------------------------------------- */
490 * Create pipe and run child process.
492 * @parameter command command line of child process
493 * @parameter read_out do or don't read the stdout of child process
494 * @parameter read_err do or don't read the stderr of child process
495 * @parameter error contains pointer to object to handle error code and message
497 * @return newly created object of mc_pipe_t class in success, NULL otherwise
500 mc_pipe_t *
501 mc_popen (const char *command, gboolean read_out, gboolean read_err, GError ** error)
503 mc_pipe_t *p;
504 const char *const argv[] = { "/bin/sh", "sh", "-c", command, NULL };
506 p = g_try_new (mc_pipe_t, 1);
507 if (p == NULL)
509 mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE, "%s",
510 _("Cannot create pipe descriptor"));
511 goto ret_err;
514 p->out.fd = -1;
515 p->err.fd = -1;
517 if (!g_spawn_async_with_pipes
518 (NULL, (gchar **) argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_FILE_AND_ARGV_ZERO, NULL,
519 NULL, &p->child_pid, NULL, read_out ? &p->out.fd : NULL, read_err ? &p->err.fd : NULL,
520 error))
522 mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE_STREAM, "%s",
523 _("Cannot create pipe streams"));
524 goto ret_err;
527 p->out.buf[0] = '\0';
528 p->out.len = MC_PIPE_BUFSIZE;
529 p->out.null_term = FALSE;
531 p->err.buf[0] = '\0';
532 p->err.len = MC_PIPE_BUFSIZE;
533 p->err.null_term = FALSE;
535 return p;
537 ret_err:
538 g_free (p);
539 return NULL;
542 /* --------------------------------------------------------------------------------------------- */
544 * Read stdout and stderr of pipe asynchronously.
546 * @parameter p pipe descriptor
548 * The lengths of read data contain in p->out.len and p->err.len.
550 * Before read, p->xxx.len is an input. It defines the number of data to read.
551 * Should not be greater than MC_PIPE_BUFSIZE.
553 * After read, p->xxx.len is an output and contains the following:
554 * p->xxx.len > 0: an actual length of read data stored in p->xxx.buf;
555 * p->xxx.len == MC_PIPE_STREAM_EOF: EOF of stream p->xxx;
556 * p->xxx.len == MC_PIPE_STREAM_UNREAD: stream p->xxx was not read;
557 * p->xxx.len == MC_PIPE_ERROR_READ: reading error, and p->xxx.errno is set appropriately.
559 * @parameter error contains pointer to object to handle error code and message
562 void
563 mc_pread (mc_pipe_t * p, GError ** error)
565 gboolean read_out, read_err;
566 fd_set fds;
567 int maxfd = 0;
568 int res;
570 if (error != NULL)
571 *error = NULL;
573 read_out = p->out.fd >= 0;
574 read_err = p->err.fd >= 0;
576 if (!read_out && !read_err)
578 p->out.len = MC_PIPE_STREAM_UNREAD;
579 p->err.len = MC_PIPE_STREAM_UNREAD;
580 return;
583 FD_ZERO (&fds);
584 if (read_out)
586 FD_SET (p->out.fd, &fds);
587 maxfd = p->out.fd;
590 if (read_err)
592 FD_SET (p->err.fd, &fds);
593 maxfd = MAX (maxfd, p->err.fd);
596 /* no timeout */
597 res = select (maxfd + 1, &fds, NULL, NULL, NULL);
598 if (res < 0 && errno != EINTR)
600 mc_propagate_error (error, MC_PIPE_ERROR_READ,
602 ("Unexpected error in select() reading data from a child process:\n%s"),
603 unix_error_string (errno));
604 return;
607 if (read_out)
608 mc_pread_stream (&p->out, &fds);
609 else
610 p->out.len = MC_PIPE_STREAM_UNREAD;
612 if (read_err)
613 mc_pread_stream (&p->err, &fds);
614 else
615 p->err.len = MC_PIPE_STREAM_UNREAD;
618 /* --------------------------------------------------------------------------------------------- */
620 * Reads a line from @stream. Reading stops after an EOL or a newline. If a newline is read,
621 * it is appended to the line.
623 * @stream mc_pipe_stream_t object
625 * @return newly created GString or NULL in case of EOL;
628 GString *
629 mc_pstream_get_string (mc_pipe_stream_t * ps)
631 char *s;
632 size_t size, i;
633 gboolean escape = FALSE;
635 g_return_val_if_fail (ps != NULL, NULL);
637 if (ps->len < 0)
638 return NULL;
640 size = ps->len - ps->pos;
642 if (size == 0)
643 return NULL;
645 s = ps->buf + ps->pos;
647 if (s[0] == '\0')
648 return NULL;
650 /* find '\0' or unescaped '\n' */
651 for (i = 0; i < size && !(s[i] == '\0' || (s[i] == '\n' && !escape)); i++)
652 escape = s[i] == '\\' ? !escape : FALSE;
654 if (i != size && s[i] == '\n')
655 i++;
657 ps->pos += i;
659 return g_string_new_len (s, i);
662 /* --------------------------------------------------------------------------------------------- */
664 * Close pipe and destroy pipe descriptor.
666 * @parameter p pipe descriptor
667 * @parameter error contains pointer to object to handle error code and message
670 void
671 mc_pclose (mc_pipe_t * p, GError ** error)
673 int res;
675 if (p == NULL)
677 mc_replace_error (error, MC_PIPE_ERROR_READ, "%s",
678 _("Cannot close pipe descriptor (p == NULL)"));
679 return;
682 if (p->out.fd >= 0)
683 res = close (p->out.fd);
684 if (p->err.fd >= 0)
685 res = close (p->err.fd);
689 int status;
691 res = waitpid (p->child_pid, &status, 0);
693 while (res < 0 && errno == EINTR);
695 if (res < 0)
696 mc_replace_error (error, MC_PIPE_ERROR_READ, _("Unexpected error in waitpid():\n%s"),
697 unix_error_string (errno));
699 g_free (p);
702 /* --------------------------------------------------------------------------------------------- */
705 * Perform tilde expansion if possible.
707 * @param directory pointer to the path
709 * @return newly allocated string, even if it's unchanged.
712 char *
713 tilde_expand (const char *directory)
715 struct passwd *passwd;
716 const char *p, *q;
718 if (*directory != '~')
719 return g_strdup (directory);
721 p = directory + 1;
723 /* d = "~" or d = "~/" */
724 if (*p == '\0' || IS_PATH_SEP (*p))
726 passwd = getpwuid (geteuid ());
727 q = IS_PATH_SEP (*p) ? p + 1 : "";
729 else
731 q = strchr (p, PATH_SEP);
732 if (q == NULL)
733 passwd = getpwnam (p);
734 else
736 char *name;
738 name = g_strndup (p, q - p);
739 passwd = getpwnam (name);
740 q++;
741 g_free (name);
745 /* If we can't figure the user name, leave tilde unexpanded */
746 if (passwd == NULL)
747 return g_strdup (directory);
749 return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
752 /* --------------------------------------------------------------------------------------------- */
754 * Canonicalize path.
756 * @param path path to file
757 * @param flags canonicalization flags
759 * All modifications of @path are made in place.
760 * Well formed UNC paths are modified only in the local part.
763 void
764 canonicalize_pathname_custom (char *path, canon_path_flags_t flags)
766 char *p, *s;
767 char *lpath = path; /* path without leading UNC part */
768 const size_t url_delim_len = strlen (VFS_PATH_URL_DELIMITER);
770 /* Detect and preserve UNC paths: //server/... */
771 if ((flags & CANON_PATH_GUARDUNC) != 0 && IS_PATH_SEP (path[0]) && IS_PATH_SEP (path[1]))
773 for (p = path + 2; p[0] != '\0' && !IS_PATH_SEP (p[0]); p++)
775 if (IS_PATH_SEP (p[0]) && p > path + 2)
776 lpath = p;
779 if (lpath[0] == '\0' || lpath[1] == '\0')
780 return;
782 if ((flags & CANON_PATH_JOINSLASHES) != 0)
784 /* Collapse multiple slashes */
785 for (p = lpath; *p != '\0'; p++)
786 if (IS_PATH_SEP (p[0]) && IS_PATH_SEP (p[1]) && (p == lpath || *(p - 1) != ':'))
788 s = p + 1;
789 while (IS_PATH_SEP (*(++s)))
791 str_move (p + 1, s);
794 /* Collapse "/./" -> "/" */
795 for (p = lpath; *p != '\0';)
796 if (IS_PATH_SEP (p[0]) && p[1] == '.' && IS_PATH_SEP (p[2]))
797 str_move (p, p + 2);
798 else
799 p++;
802 if ((flags & CANON_PATH_REMSLASHDOTS) != 0)
804 size_t len;
806 /* Remove trailing slashes */
807 for (p = lpath + strlen (lpath) - 1; p > lpath && IS_PATH_SEP (*p); p--)
809 if (p >= lpath + url_delim_len - 1
810 && strncmp (p - url_delim_len + 1, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
811 break;
812 *p = '\0';
815 /* Remove leading "./" */
816 if (lpath[0] == '.' && IS_PATH_SEP (lpath[1]))
818 if (lpath[2] == '\0')
820 lpath[1] = '\0';
821 return;
824 str_move (lpath, lpath + 2);
827 /* Remove trailing "/" or "/." */
828 len = strlen (lpath);
829 if (len < 2)
830 return;
832 if (IS_PATH_SEP (lpath[len - 1])
833 && (len < url_delim_len
834 || strncmp (lpath + len - url_delim_len, VFS_PATH_URL_DELIMITER,
835 url_delim_len) != 0))
836 lpath[len - 1] = '\0';
837 else if (lpath[len - 1] == '.' && IS_PATH_SEP (lpath[len - 2]))
839 if (len == 2)
841 lpath[1] = '\0';
842 return;
845 lpath[len - 2] = '\0';
849 /* Collapse "/.." with the previous part of path */
850 if ((flags & CANON_PATH_REMDOUBLEDOTS) != 0)
852 #ifdef HAVE_CHARSET
853 const size_t enc_prefix_len = strlen (VFS_ENCODING_PREFIX);
854 #endif /* HAVE_CHARSET */
856 for (p = lpath; p[0] != '\0' && p[1] != '\0' && p[2] != '\0';)
858 if (!IS_PATH_SEP (p[0]) || p[1] != '.' || p[2] != '.'
859 || (!IS_PATH_SEP (p[3]) && p[3] != '\0'))
861 p++;
862 continue;
865 /* search for the previous token */
866 s = p - 1;
867 if (s >= lpath + url_delim_len - 2
868 && strncmp (s - url_delim_len + 2, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
870 s -= (url_delim_len - 2);
871 while (s >= lpath && !IS_PATH_SEP (*s--))
875 while (s >= lpath)
877 if (s - url_delim_len > lpath
878 && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
880 char *vfs_prefix = s - url_delim_len;
881 vfs_class *vclass;
883 while (vfs_prefix > lpath && !IS_PATH_SEP (*--vfs_prefix))
885 if (IS_PATH_SEP (*vfs_prefix))
886 vfs_prefix++;
887 *(s - url_delim_len) = '\0';
889 vclass = vfs_prefix_to_class (vfs_prefix);
890 *(s - url_delim_len) = *VFS_PATH_URL_DELIMITER;
892 if (vclass != NULL && (vclass->flags & VFSF_REMOTE) != 0)
894 s = vfs_prefix;
895 continue;
899 if (IS_PATH_SEP (*s))
900 break;
902 s--;
905 s++;
907 /* If the previous token is "..", we cannot collapse it */
908 if (s[0] == '.' && s[1] == '.' && s + 2 == p)
910 p += 3;
911 continue;
914 if (p[3] != '\0')
916 if (s == lpath && IS_PATH_SEP (*s))
918 /* "/../foo" -> "/foo" */
919 str_move (s + 1, p + 4);
921 else
923 /* "token/../foo" -> "foo" */
924 #ifdef HAVE_CHARSET
925 if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
926 && (is_supported_encoding (s + enc_prefix_len)))
927 /* special case: remove encoding */
928 str_move (s, p + 1);
929 else
930 #endif /* HAVE_CHARSET */
931 str_move (s, p + 4);
934 p = s > lpath ? s - 1 : s;
935 continue;
938 /* trailing ".." */
939 if (s == lpath)
941 /* "token/.." -> "." */
942 if (!IS_PATH_SEP (lpath[0]))
943 lpath[0] = '.';
944 lpath[1] = '\0';
946 else
948 /* "foo/token/.." -> "foo" */
949 if (s == lpath + 1)
950 s[0] = '\0';
951 #ifdef HAVE_CHARSET
952 else if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
953 && (is_supported_encoding (s + enc_prefix_len)))
955 /* special case: remove encoding */
956 s[0] = '.';
957 s[1] = '.';
958 s[2] = '\0';
960 /* search for the previous token */
961 /* IS_PATH_SEP (s[-1]) */
962 for (p = s - 1; p >= lpath && !IS_PATH_SEP (*p); p--)
965 if (p >= lpath)
966 continue;
968 #endif /* HAVE_CHARSET */
969 else
971 if (s >= lpath + url_delim_len
972 && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
973 *s = '\0';
974 else
975 s[-1] = '\0';
979 break;
984 /* --------------------------------------------------------------------------------------------- */
986 char *
987 mc_realpath (const char *path, char *resolved_path)
989 #ifdef HAVE_CHARSET
990 const char *p = path;
991 gboolean absolute_path = FALSE;
993 if (IS_PATH_SEP (*p))
995 absolute_path = TRUE;
996 p++;
999 /* ignore encoding: skip "#enc:" */
1000 if (g_str_has_prefix (p, VFS_ENCODING_PREFIX))
1002 p += strlen (VFS_ENCODING_PREFIX);
1003 p = strchr (p, PATH_SEP);
1004 if (p != NULL)
1006 if (!absolute_path && p[1] != '\0')
1007 p++;
1009 path = p;
1012 #endif /* HAVE_CHARSET */
1014 #ifdef HAVE_REALPATH
1015 return realpath (path, resolved_path);
1016 #else
1018 char copy_path[PATH_MAX];
1019 char got_path[PATH_MAX];
1020 char *new_path = got_path;
1021 char *max_path;
1022 #ifdef S_IFLNK
1023 char link_path[PATH_MAX];
1024 int readlinks = 0;
1025 int n;
1026 #endif /* S_IFLNK */
1028 /* Make a copy of the source path since we may need to modify it. */
1029 if (strlen (path) >= PATH_MAX - 2)
1031 errno = ENAMETOOLONG;
1032 return NULL;
1035 strcpy (copy_path, path);
1036 path = copy_path;
1037 max_path = copy_path + PATH_MAX - 2;
1038 /* If it's a relative pathname use getwd for starters. */
1039 if (!IS_PATH_SEP (*path))
1041 new_path = g_get_current_dir ();
1042 if (new_path == NULL)
1043 strcpy (got_path, "");
1044 else
1046 g_snprintf (got_path, sizeof (got_path), "%s", new_path);
1047 g_free (new_path);
1048 new_path = got_path;
1051 new_path += strlen (got_path);
1052 if (!IS_PATH_SEP (new_path[-1]))
1053 *new_path++ = PATH_SEP;
1055 else
1057 *new_path++ = PATH_SEP;
1058 path++;
1060 /* Expand each slash-separated pathname component. */
1061 while (*path != '\0')
1063 /* Ignore stray "/". */
1064 if (IS_PATH_SEP (*path))
1066 path++;
1067 continue;
1069 if (*path == '.')
1071 /* Ignore ".". */
1072 if (path[1] == '\0' || IS_PATH_SEP (path[1]))
1074 path++;
1075 continue;
1077 if (path[1] == '.')
1079 if (path[2] == '\0' || IS_PATH_SEP (path[2]))
1081 path += 2;
1082 /* Ignore ".." at root. */
1083 if (new_path == got_path + 1)
1084 continue;
1085 /* Handle ".." by backing up. */
1086 while (!IS_PATH_SEP ((--new_path)[-1]))
1088 continue;
1092 /* Safely copy the next pathname component. */
1093 while (*path != '\0' && !IS_PATH_SEP (*path))
1095 if (path > max_path)
1097 errno = ENAMETOOLONG;
1098 return NULL;
1100 *new_path++ = *path++;
1102 #ifdef S_IFLNK
1103 /* Protect against infinite loops. */
1104 if (readlinks++ > MAXSYMLINKS)
1106 errno = ELOOP;
1107 return NULL;
1109 /* See if latest pathname component is a symlink. */
1110 *new_path = '\0';
1111 n = readlink (got_path, link_path, PATH_MAX - 1);
1112 if (n < 0)
1114 /* EINVAL means the file exists but isn't a symlink. */
1115 if (errno != EINVAL)
1117 /* Make sure it's null terminated. */
1118 *new_path = '\0';
1119 strcpy (resolved_path, got_path);
1120 return NULL;
1123 else
1125 /* Note: readlink doesn't add the null byte. */
1126 link_path[n] = '\0';
1127 if (IS_PATH_SEP (*link_path))
1128 /* Start over for an absolute symlink. */
1129 new_path = got_path;
1130 else
1131 /* Otherwise back up over this component. */
1132 while (!IS_PATH_SEP (*(--new_path)))
1134 /* Safe sex check. */
1135 if (strlen (path) + n >= PATH_MAX - 2)
1137 errno = ENAMETOOLONG;
1138 return NULL;
1140 /* Insert symlink contents into path. */
1141 strcat (link_path, path);
1142 strcpy (copy_path, link_path);
1143 path = copy_path;
1145 #endif /* S_IFLNK */
1146 *new_path++ = PATH_SEP;
1148 /* Delete trailing slash but don't whomp a lone slash. */
1149 if (new_path != got_path + 1 && IS_PATH_SEP (new_path[-1]))
1150 new_path--;
1151 /* Make sure it's null terminated. */
1152 *new_path = '\0';
1153 strcpy (resolved_path, got_path);
1154 return resolved_path;
1156 #endif /* HAVE_REALPATH */
1159 /* --------------------------------------------------------------------------------------------- */
1161 * Return the index of the permissions triplet
1166 get_user_permissions (struct stat *st)
1168 static gboolean initialized = FALSE;
1169 static gid_t *groups;
1170 static int ngroups;
1171 static uid_t uid;
1172 int i;
1174 if (!initialized)
1176 uid = geteuid ();
1178 ngroups = getgroups (0, NULL);
1179 if (ngroups == -1)
1180 ngroups = 0; /* ignore errors */
1182 /* allocate space for one element in addition to what
1183 * will be filled by getgroups(). */
1184 groups = g_new (gid_t, ngroups + 1);
1186 if (ngroups != 0)
1188 ngroups = getgroups (ngroups, groups);
1189 if (ngroups == -1)
1190 ngroups = 0; /* ignore errors */
1193 /* getgroups() may or may not return the effective group ID,
1194 * so we always include it at the end of the list. */
1195 groups[ngroups++] = getegid ();
1197 initialized = TRUE;
1200 if (st->st_uid == uid || uid == 0)
1201 return 0;
1203 for (i = 0; i < ngroups; i++)
1204 if (st->st_gid == groups[i])
1205 return 1;
1207 return 2;
1210 /* --------------------------------------------------------------------------------------------- */
1212 * Build filename from arguments.
1213 * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
1216 char *
1217 mc_build_filenamev (const char *first_element, va_list args)
1219 gboolean absolute;
1220 const char *element = first_element;
1221 GString *path;
1222 char *ret;
1224 if (first_element == NULL)
1225 return NULL;
1227 absolute = IS_PATH_SEP (*first_element);
1229 path = g_string_new (absolute ? PATH_SEP_STR : "");
1233 if (*element == '\0')
1234 element = va_arg (args, char *);
1235 else
1237 char *tmp_element;
1238 const char *start;
1240 tmp_element = g_strdup (element);
1242 element = va_arg (args, char *);
1244 canonicalize_pathname (tmp_element);
1245 start = IS_PATH_SEP (tmp_element[0]) ? tmp_element + 1 : tmp_element;
1247 g_string_append (path, start);
1248 if (!IS_PATH_SEP (path->str[path->len - 1]) && element != NULL)
1249 g_string_append_c (path, PATH_SEP);
1251 g_free (tmp_element);
1254 while (element != NULL);
1256 ret = g_string_free (path, FALSE);
1257 canonicalize_pathname (ret);
1259 return ret;
1262 /* --------------------------------------------------------------------------------------------- */
1264 * Build filename from arguments.
1265 * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
1268 char *
1269 mc_build_filename (const char *first_element, ...)
1271 va_list args;
1272 char *ret;
1274 if (first_element == NULL)
1275 return NULL;
1277 va_start (args, first_element);
1278 ret = mc_build_filenamev (first_element, args);
1279 va_end (args);
1280 return ret;
1283 /* --------------------------------------------------------------------------------------------- */