root/lib/utilunix.c

/* [previous][next][first][last][top][bottom][index][help]  */

DEFINITIONS

This source file includes following definitions.
  1. i_cache_match
  2. i_cache_add
  3. my_fork
  4. my_system__save_sigaction_handlers
  5. my_system__restore_sigaction_handlers
  6. my_system_make_arg_array
  7. mc_pread_stream
  8. get_owner
  9. get_group
  10. save_stop_handler
  11. my_exit
  12. my_system
  13. my_systeml
  14. my_systemv
  15. my_systemv_flags
  16. mc_popen
  17. mc_pread
  18. mc_pstream_get_string
  19. mc_pclose
  20. tilde_expand
  21. canonicalize_pathname_custom
  22. mc_realpath
  23. get_user_permissions
  24. mc_build_filenamev
  25. mc_build_filename

   1 /*
   2    Various utilities - Unix variants
   3 
   4    Copyright (C) 1994-2023
   5    Free Software Foundation, Inc.
   6 
   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-2022
  14 
  15    The mc_realpath routine is mostly from uClibc package, written
  16    by Rick Sladkey <jrs@world.std.com>
  17 
  18    This file is part of the Midnight Commander.
  19 
  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.
  24 
  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.
  29 
  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/>.
  32  */
  33 
  34 /** \file utilunix.c
  35  *  \brief Source: various utilities - Unix variant
  36  */
  37 
  38 #include <config.h>
  39 
  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>
  59 
  60 #include "lib/global.h"
  61 
  62 #include "lib/unixcompat.h"
  63 #include "lib/vfs/vfs.h"        /* VFS_ENCODING_PREFIX */
  64 #include "lib/strutil.h"        /* str_move() */
  65 #include "lib/util.h"
  66 #include "lib/widget.h"         /* message() */
  67 #include "lib/vfs/xdirentry.h"
  68 
  69 #ifdef HAVE_CHARSET
  70 #include "lib/charsets.h"
  71 #endif
  72 
  73 #include "utilunix.h"
  74 
  75 /*** global variables ****************************************************************************/
  76 
  77 struct sigaction startup_handler;
  78 
  79 /*** file scope macro definitions ****************************************************************/
  80 
  81 #define UID_CACHE_SIZE 200
  82 #define GID_CACHE_SIZE 30
  83 
  84 /*** file scope type declarations ****************************************************************/
  85 
  86 typedef struct
  87 {
  88     int index;
  89     char *string;
  90 } int_cache;
  91 
  92 typedef enum
  93 {
  94     FORK_ERROR = -1,
  95     FORK_CHILD,
  96     FORK_PARENT,
  97 } my_fork_state_t;
  98 
  99 typedef struct
 100 {
 101     struct sigaction intr;
 102     struct sigaction quit;
 103     struct sigaction stop;
 104 } my_system_sigactions_t;
 105 
 106 /*** file scope variables ************************************************************************/
 107 
 108 static int_cache uid_cache[UID_CACHE_SIZE];
 109 static int_cache gid_cache[GID_CACHE_SIZE];
 110 
 111 /* --------------------------------------------------------------------------------------------- */
 112 /*** file scope functions ************************************************************************/
 113 /* --------------------------------------------------------------------------------------------- */
 114 
 115 static char *
 116 i_cache_match (int id, int_cache * cache, int size)
     /* [previous][next][first][last][top][bottom][index][help]  */
 117 {
 118     int i;
 119 
 120     for (i = 0; i < size; i++)
 121         if (cache[i].index == id)
 122             return cache[i].string;
 123     return 0;
 124 }
 125 
 126 /* --------------------------------------------------------------------------------------------- */
 127 
 128 static void
 129 i_cache_add (int id, int_cache * cache, int size, char *text, int *last)
     /* [previous][next][first][last][top][bottom][index][help]  */
 130 {
 131     g_free (cache[*last].string);
 132     cache[*last].string = g_strdup (text);
 133     cache[*last].index = id;
 134     *last = ((*last) + 1) % size;
 135 }
 136 
 137 /* --------------------------------------------------------------------------------------------- */
 138 
 139 static my_fork_state_t
 140 my_fork (void)
     /* [previous][next][first][last][top][bottom][index][help]  */
 141 {
 142     pid_t pid;
 143 
 144     pid = fork ();
 145 
 146     if (pid < 0)
 147     {
 148         fprintf (stderr, "\n\nfork () = -1\n");
 149         return FORK_ERROR;
 150     }
 151 
 152     if (pid == 0)
 153         return FORK_CHILD;
 154 
 155     while (TRUE)
 156     {
 157         int status = 0;
 158 
 159         if (waitpid (pid, &status, 0) > 0)
 160             return WEXITSTATUS (status) == 0 ? FORK_PARENT : FORK_ERROR;
 161 
 162         if (errno != EINTR)
 163             return FORK_ERROR;
 164     }
 165 }
 166 
 167 /* --------------------------------------------------------------------------------------------- */
 168 
 169 static void
 170 my_system__save_sigaction_handlers (my_system_sigactions_t * sigactions)
     /* [previous][next][first][last][top][bottom][index][help]  */
 171 {
 172     struct sigaction ignore;
 173 
 174     memset (&ignore, 0, sizeof (ignore));
 175     ignore.sa_handler = SIG_IGN;
 176     sigemptyset (&ignore.sa_mask);
 177 
 178     sigaction (SIGINT, &ignore, &sigactions->intr);
 179     sigaction (SIGQUIT, &ignore, &sigactions->quit);
 180 
 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);
 184 }
 185 
 186 /* --------------------------------------------------------------------------------------------- */
 187 
 188 static void
 189 my_system__restore_sigaction_handlers (my_system_sigactions_t * sigactions)
     /* [previous][next][first][last][top][bottom][index][help]  */
 190 {
 191     sigaction (SIGINT, &sigactions->intr, NULL);
 192     sigaction (SIGQUIT, &sigactions->quit, NULL);
 193     sigaction (SIGTSTP, &sigactions->stop, NULL);
 194 }
 195 
 196 /* --------------------------------------------------------------------------------------------- */
 197 
 198 static GPtrArray *
 199 my_system_make_arg_array (int flags, const char *shell, char **execute_name)
     /* [previous][next][first][last][top][bottom][index][help]  */
 200 {
 201     GPtrArray *args_array;
 202 
 203     args_array = g_ptr_array_new ();
 204 
 205     if ((flags & EXECUTE_AS_SHELL) != 0)
 206     {
 207         g_ptr_array_add (args_array, (gpointer) shell);
 208         g_ptr_array_add (args_array, (gpointer) "-c");
 209         *execute_name = g_strdup (shell);
 210     }
 211     else
 212     {
 213         char *shell_token;
 214 
 215         shell_token = shell != NULL ? strchr (shell, ' ') : NULL;
 216         if (shell_token == NULL)
 217             *execute_name = g_strdup (shell);
 218         else
 219             *execute_name = g_strndup (shell, (gsize) (shell_token - shell));
 220 
 221         g_ptr_array_add (args_array, (gpointer) shell);
 222     }
 223     return args_array;
 224 }
 225 
 226 /* --------------------------------------------------------------------------------------------- */
 227 
 228 static void
 229 mc_pread_stream (mc_pipe_stream_t * ps, const fd_set * fds)
     /* [previous][next][first][last][top][bottom][index][help]  */
 230 {
 231     size_t buf_len;
 232     ssize_t read_len;
 233 
 234     if (!FD_ISSET (ps->fd, fds))
 235     {
 236         ps->len = MC_PIPE_STREAM_UNREAD;
 237         return;
 238     }
 239 
 240     buf_len = (size_t) ps->len;
 241 
 242     if (buf_len >= MC_PIPE_BUFSIZE)
 243         buf_len = ps->null_term ? MC_PIPE_BUFSIZE - 1 : MC_PIPE_BUFSIZE;
 244 
 245     do
 246     {
 247         read_len = read (ps->fd, ps->buf, buf_len);
 248     }
 249     while (read_len < 0 && errno == EINTR);
 250 
 251     if (read_len < 0)
 252     {
 253         /* reading error */
 254         ps->len = MC_PIPE_ERROR_READ;
 255         ps->error = errno;
 256     }
 257     else if (read_len == 0)
 258         /* EOF */
 259         ps->len = MC_PIPE_STREAM_EOF;
 260     else
 261     {
 262         /* success */
 263         ps->len = read_len;
 264 
 265         if (ps->null_term)
 266             ps->buf[(size_t) ps->len] = '\0';
 267     }
 268 
 269     ps->pos = 0;
 270 }
 271 
 272 /* --------------------------------------------------------------------------------------------- */
 273 /*** public functions ****************************************************************************/
 274 /* --------------------------------------------------------------------------------------------- */
 275 
 276 const char *
 277 get_owner (uid_t uid)
     /* [previous][next][first][last][top][bottom][index][help]  */
 278 {
 279     struct passwd *pwd;
 280     char *name;
 281     static uid_t uid_last;
 282 
 283     name = i_cache_match ((int) uid, uid_cache, UID_CACHE_SIZE);
 284     if (name != NULL)
 285         return name;
 286 
 287     pwd = getpwuid (uid);
 288     if (pwd != NULL)
 289     {
 290         i_cache_add ((int) uid, uid_cache, UID_CACHE_SIZE, pwd->pw_name, (int *) &uid_last);
 291         return pwd->pw_name;
 292     }
 293     else
 294     {
 295         static char ibuf[10];
 296 
 297         g_snprintf (ibuf, sizeof (ibuf), "%d", (int) uid);
 298         return ibuf;
 299     }
 300 }
 301 
 302 /* --------------------------------------------------------------------------------------------- */
 303 
 304 const char *
 305 get_group (gid_t gid)
     /* [previous][next][first][last][top][bottom][index][help]  */
 306 {
 307     struct group *grp;
 308     char *name;
 309     static gid_t gid_last;
 310 
 311     name = i_cache_match ((int) gid, gid_cache, GID_CACHE_SIZE);
 312     if (name != NULL)
 313         return name;
 314 
 315     grp = getgrgid (gid);
 316     if (grp != NULL)
 317     {
 318         i_cache_add ((int) gid, gid_cache, GID_CACHE_SIZE, grp->gr_name, (int *) &gid_last);
 319         return grp->gr_name;
 320     }
 321     else
 322     {
 323         static char gbuf[10];
 324 
 325         g_snprintf (gbuf, sizeof (gbuf), "%d", (int) gid);
 326         return gbuf;
 327     }
 328 }
 329 
 330 /* --------------------------------------------------------------------------------------------- */
 331 /* Since ncurses uses a handler that automatically refreshes the */
 332 /* screen after a SIGCONT, and we don't want this behavior when */
 333 /* spawning a child, we save the original handler here */
 334 
 335 void
 336 save_stop_handler (void)
     /* [previous][next][first][last][top][bottom][index][help]  */
 337 {
 338     sigaction (SIGTSTP, NULL, &startup_handler);
 339 }
 340 
 341 /* --------------------------------------------------------------------------------------------- */
 342 /**
 343  * Wrapper for _exit() system call.
 344  * The _exit() function has gcc's attribute 'noreturn', and this is reason why we can't
 345  * mock the call.
 346  *
 347  * @param status exit code
 348  */
 349 
 350 void
 351 /* __attribute__ ((noreturn)) */
 352 my_exit (int status)
     /* [previous][next][first][last][top][bottom][index][help]  */
 353 {
 354     _exit (status);
 355 }
 356 
 357 /* --------------------------------------------------------------------------------------------- */
 358 /**
 359  * Call external programs.
 360  *
 361  * @parameter flags   addition conditions for running external programs.
 362  * @parameter shell   shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
 363  *                    Shell (or command) will be found in paths described in PATH variable
 364  *                    (if shell parameter doesn't begin from path delimiter)
 365  * @parameter command Command for shell (or first parameter for command, if flags contain EXECUTE_AS_SHELL)
 366  * @return 0 if successful, -1 otherwise
 367  */
 368 
 369 int
 370 my_system (int flags, const char *shell, const char *command)
     /* [previous][next][first][last][top][bottom][index][help]  */
 371 {
 372     return my_systeml (flags, shell, command, NULL);
 373 }
 374 
 375 /* --------------------------------------------------------------------------------------------- */
 376 /**
 377  * Call external programs with various parameters number.
 378  *
 379  * @parameter flags addition conditions for running external programs.
 380  * @parameter shell shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
 381  *                  Shell (or command) will be found in paths described in PATH variable
 382  *                  (if shell parameter doesn't begin from path delimiter)
 383  * @parameter ...   Command for shell with addition parameters for shell
 384  *                  (or parameters for command, if flags contain EXECUTE_AS_SHELL).
 385  *                  Should be NULL terminated.
 386  * @return 0 if successful, -1 otherwise
 387  */
 388 
 389 int
 390 my_systeml (int flags, const char *shell, ...)
     /* [previous][next][first][last][top][bottom][index][help]  */
 391 {
 392     GPtrArray *args_array;
 393     int status = 0;
 394     va_list vargs;
 395     char *one_arg;
 396 
 397     args_array = g_ptr_array_new ();
 398 
 399     va_start (vargs, shell);
 400     while ((one_arg = va_arg (vargs, char *)) != NULL)
 401           g_ptr_array_add (args_array, one_arg);
 402     va_end (vargs);
 403 
 404     g_ptr_array_add (args_array, NULL);
 405     status = my_systemv_flags (flags, shell, (char *const *) args_array->pdata);
 406 
 407     g_ptr_array_free (args_array, TRUE);
 408 
 409     return status;
 410 }
 411 
 412 /* --------------------------------------------------------------------------------------------- */
 413 /**
 414  * Call external programs with array of strings as parameters.
 415  *
 416  * @parameter command command to run. Command will be found in paths described in PATH variable
 417  *                    (if command parameter doesn't begin from path delimiter)
 418  * @parameter argv    Array of strings (NULL-terminated) with parameters for command
 419  * @return 0 if successful, -1 otherwise
 420  */
 421 
 422 int
 423 my_systemv (const char *command, char *const argv[])
     /* [previous][next][first][last][top][bottom][index][help]  */
 424 {
 425     my_fork_state_t fork_state;
 426     int status = 0;
 427     my_system_sigactions_t sigactions;
 428 
 429     my_system__save_sigaction_handlers (&sigactions);
 430 
 431     fork_state = my_fork ();
 432     switch (fork_state)
 433     {
 434     case FORK_ERROR:
 435         status = -1;
 436         break;
 437     case FORK_CHILD:
 438         {
 439             signal (SIGINT, SIG_DFL);
 440             signal (SIGQUIT, SIG_DFL);
 441             signal (SIGTSTP, SIG_DFL);
 442             signal (SIGCHLD, SIG_DFL);
 443 
 444             execvp (command, argv);
 445             my_exit (127);      /* Exec error */
 446         }
 447         MC_FALLTHROUGH;
 448         /* no break here, or unreachable-code warning by no returning my_exit() */
 449     default:
 450         status = 0;
 451         break;
 452     }
 453     my_system__restore_sigaction_handlers (&sigactions);
 454 
 455     return status;
 456 }
 457 
 458 /* --------------------------------------------------------------------------------------------- */
 459 /**
 460  * Call external programs with flags and with array of strings as parameters.
 461  *
 462  * @parameter flags   addition conditions for running external programs.
 463  * @parameter command shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
 464  *                    Shell (or command) will be found in paths described in PATH variable
 465  *                    (if shell parameter doesn't begin from path delimiter)
 466  * @parameter argv    Array of strings (NULL-terminated) with parameters for command
 467  * @return 0 if successful, -1 otherwise
 468  */
 469 
 470 int
 471 my_systemv_flags (int flags, const char *command, char *const argv[])
     /* [previous][next][first][last][top][bottom][index][help]  */
 472 {
 473     char *execute_name = NULL;
 474     GPtrArray *args_array;
 475     int status = 0;
 476 
 477     args_array = my_system_make_arg_array (flags, command, &execute_name);
 478 
 479     for (; argv != NULL && *argv != NULL; argv++)
 480         g_ptr_array_add (args_array, *argv);
 481 
 482     g_ptr_array_add (args_array, NULL);
 483     status = my_systemv (execute_name, (char *const *) args_array->pdata);
 484 
 485     g_free (execute_name);
 486     g_ptr_array_free (args_array, TRUE);
 487 
 488     return status;
 489 }
 490 
 491 /* --------------------------------------------------------------------------------------------- */
 492 /**
 493  * Create pipe and run child process.
 494  *
 495  * @parameter command command line of child process
 496  * @parameter read_out do or don't read the stdout of child process
 497  * @parameter read_err do or don't read the stderr of child process
 498  * @parameter error contains pointer to object to handle error code and message
 499  *
 500  * @return newly created object of mc_pipe_t class in success, NULL otherwise
 501  */
 502 
 503 mc_pipe_t *
 504 mc_popen (const char *command, gboolean read_out, gboolean read_err, GError ** error)
     /* [previous][next][first][last][top][bottom][index][help]  */
 505 {
 506     mc_pipe_t *p;
 507     const char *const argv[] = { "/bin/sh", "sh", "-c", command, NULL };
 508 
 509     p = g_try_new (mc_pipe_t, 1);
 510     if (p == NULL)
 511     {
 512         mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE, "%s",
 513                           _("Cannot create pipe descriptor"));
 514         goto ret_err;
 515     }
 516 
 517     p->out.fd = -1;
 518     p->err.fd = -1;
 519 
 520     if (!g_spawn_async_with_pipes
 521         (NULL, (gchar **) argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_FILE_AND_ARGV_ZERO, NULL,
 522          NULL, &p->child_pid, NULL, read_out ? &p->out.fd : NULL, read_err ? &p->err.fd : NULL,
 523          error))
 524     {
 525         mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE_STREAM, "%s",
 526                           _("Cannot create pipe streams"));
 527         goto ret_err;
 528     }
 529 
 530     p->out.buf[0] = '\0';
 531     p->out.len = MC_PIPE_BUFSIZE;
 532     p->out.null_term = FALSE;
 533 
 534     p->err.buf[0] = '\0';
 535     p->err.len = MC_PIPE_BUFSIZE;
 536     p->err.null_term = FALSE;
 537 
 538     return p;
 539 
 540   ret_err:
 541     g_free (p);
 542     return NULL;
 543 }
 544 
 545 /* --------------------------------------------------------------------------------------------- */
 546 /**
 547  * Read stdout and stderr of pipe asynchronously.
 548  *
 549  * @parameter p pipe descriptor
 550  *
 551  * The lengths of read data contain in p->out.len and p->err.len.
 552  *
 553  * Before read, p->xxx.len is an input. It defines the number of data to read.
 554  * Should not be greater than MC_PIPE_BUFSIZE.
 555  *
 556  * After read, p->xxx.len is an output and contains the following:
 557  *   p->xxx.len > 0: an actual length of read data stored in p->xxx.buf;
 558  *   p->xxx.len == MC_PIPE_STREAM_EOF: EOF of stream p->xxx;
 559  *   p->xxx.len == MC_PIPE_STREAM_UNREAD: stream p->xxx was not read;
 560  *   p->xxx.len == MC_PIPE_ERROR_READ: reading error, and p->xxx.errno is set appropriately.
 561  *
 562  * @parameter error contains pointer to object to handle error code and message
 563  */
 564 
 565 void
 566 mc_pread (mc_pipe_t * p, GError ** error)
     /* [previous][next][first][last][top][bottom][index][help]  */
 567 {
 568     gboolean read_out, read_err;
 569     fd_set fds;
 570     int maxfd = 0;
 571     int res;
 572 
 573     if (error != NULL)
 574         *error = NULL;
 575 
 576     read_out = p->out.fd >= 0;
 577     read_err = p->err.fd >= 0;
 578 
 579     if (!read_out && !read_err)
 580     {
 581         p->out.len = MC_PIPE_STREAM_UNREAD;
 582         p->err.len = MC_PIPE_STREAM_UNREAD;
 583         return;
 584     }
 585 
 586     FD_ZERO (&fds);
 587     if (read_out)
 588     {
 589         FD_SET (p->out.fd, &fds);
 590         maxfd = p->out.fd;
 591     }
 592 
 593     if (read_err)
 594     {
 595         FD_SET (p->err.fd, &fds);
 596         maxfd = MAX (maxfd, p->err.fd);
 597     }
 598 
 599     /* no timeout */
 600     res = select (maxfd + 1, &fds, NULL, NULL, NULL);
 601     if (res < 0 && errno != EINTR)
 602     {
 603         mc_propagate_error (error, MC_PIPE_ERROR_READ,
 604                             _
 605                             ("Unexpected error in select() reading data from a child process:\n%s"),
 606                             unix_error_string (errno));
 607         return;
 608     }
 609 
 610     if (read_out)
 611         mc_pread_stream (&p->out, &fds);
 612     else
 613         p->out.len = MC_PIPE_STREAM_UNREAD;
 614 
 615     if (read_err)
 616         mc_pread_stream (&p->err, &fds);
 617     else
 618         p->err.len = MC_PIPE_STREAM_UNREAD;
 619 }
 620 
 621 /* --------------------------------------------------------------------------------------------- */
 622 /**
 623  * Reads a line from @stream. Reading stops after an EOL or a newline. If a newline is read,
 624  * it is appended to the line.
 625  *
 626  * @stream mc_pipe_stream_t object
 627  *
 628  * @return newly created GString or NULL in case of EOL;
 629  */
 630 
 631 GString *
 632 mc_pstream_get_string (mc_pipe_stream_t * ps)
     /* [previous][next][first][last][top][bottom][index][help]  */
 633 {
 634     char *s;
 635     size_t size, i;
 636     gboolean escape = FALSE;
 637 
 638     g_return_val_if_fail (ps != NULL, NULL);
 639 
 640     if (ps->len < 0)
 641         return NULL;
 642 
 643     size = ps->len - ps->pos;
 644 
 645     if (size == 0)
 646         return NULL;
 647 
 648     s = ps->buf + ps->pos;
 649 
 650     if (s[0] == '\0')
 651         return NULL;
 652 
 653     /* find '\0' or unescaped '\n' */
 654     for (i = 0; i < size && !(s[i] == '\0' || (s[i] == '\n' && !escape)); i++)
 655         escape = s[i] == '\\' ? !escape : FALSE;
 656 
 657     if (i != size && s[i] == '\n')
 658         i++;
 659 
 660     ps->pos += i;
 661 
 662     return g_string_new_len (s, i);
 663 }
 664 
 665 /* --------------------------------------------------------------------------------------------- */
 666 /**
 667  * Close pipe and destroy pipe descriptor.
 668  *
 669  * @parameter p pipe descriptor
 670  * @parameter error contains pointer to object to handle error code and message
 671  */
 672 
 673 void
 674 mc_pclose (mc_pipe_t * p, GError ** error)
     /* [previous][next][first][last][top][bottom][index][help]  */
 675 {
 676     int res;
 677 
 678     if (p == NULL)
 679     {
 680         mc_replace_error (error, MC_PIPE_ERROR_READ, "%s",
 681                           _("Cannot close pipe descriptor (p == NULL)"));
 682         return;
 683     }
 684 
 685     if (p->out.fd >= 0)
 686         res = close (p->out.fd);
 687     if (p->err.fd >= 0)
 688         res = close (p->err.fd);
 689 
 690     do
 691     {
 692         int status;
 693 
 694         res = waitpid (p->child_pid, &status, 0);
 695     }
 696     while (res < 0 && errno == EINTR);
 697 
 698     if (res < 0)
 699         mc_replace_error (error, MC_PIPE_ERROR_READ, _("Unexpected error in waitpid():\n%s"),
 700                           unix_error_string (errno));
 701 
 702     g_free (p);
 703 }
 704 
 705 /* --------------------------------------------------------------------------------------------- */
 706 
 707 /**
 708  * Perform tilde expansion if possible.
 709  *
 710  * @param directory pointer to the path
 711  *
 712  * @return newly allocated string, even if it's unchanged.
 713  */
 714 
 715 char *
 716 tilde_expand (const char *directory)
     /* [previous][next][first][last][top][bottom][index][help]  */
 717 {
 718     struct passwd *passwd;
 719     const char *p, *q;
 720 
 721     if (*directory != '~')
 722         return g_strdup (directory);
 723 
 724     p = directory + 1;
 725 
 726     /* d = "~" or d = "~/" */
 727     if (*p == '\0' || IS_PATH_SEP (*p))
 728     {
 729         passwd = getpwuid (geteuid ());
 730         q = IS_PATH_SEP (*p) ? p + 1 : "";
 731     }
 732     else
 733     {
 734         q = strchr (p, PATH_SEP);
 735         if (q == NULL)
 736             passwd = getpwnam (p);
 737         else
 738         {
 739             char *name;
 740 
 741             name = g_strndup (p, q - p);
 742             passwd = getpwnam (name);
 743             q++;
 744             g_free (name);
 745         }
 746     }
 747 
 748     /* If we can't figure the user name, leave tilde unexpanded */
 749     if (passwd == NULL)
 750         return g_strdup (directory);
 751 
 752     return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
 753 }
 754 
 755 /* --------------------------------------------------------------------------------------------- */
 756 /**
 757  * Canonicalize path.
 758  *
 759  * @param path path to file
 760  * @param flags canonicalization flags
 761  *
 762  * All modifications of @path are made in place.
 763  * Well formed UNC paths are modified only in the local part.
 764  */
 765 
 766 void
 767 canonicalize_pathname_custom (char *path, canon_path_flags_t flags)
     /* [previous][next][first][last][top][bottom][index][help]  */
 768 {
 769     char *p, *s;
 770     char *lpath = path;         /* path without leading UNC part */
 771     const size_t url_delim_len = strlen (VFS_PATH_URL_DELIMITER);
 772 
 773     /* Detect and preserve UNC paths: //server/... */
 774     if ((flags & CANON_PATH_GUARDUNC) != 0 && IS_PATH_SEP (path[0]) && IS_PATH_SEP (path[1]))
 775     {
 776         for (p = path + 2; p[0] != '\0' && !IS_PATH_SEP (p[0]); p++)
 777             ;
 778         if (IS_PATH_SEP (p[0]) && p > path + 2)
 779             lpath = p;
 780     }
 781 
 782     if (lpath[0] == '\0' || lpath[1] == '\0')
 783         return;
 784 
 785     if ((flags & CANON_PATH_JOINSLASHES) != 0)
 786     {
 787         /* Collapse multiple slashes */
 788         for (p = lpath; *p != '\0'; p++)
 789             if (IS_PATH_SEP (p[0]) && IS_PATH_SEP (p[1]) && (p == lpath || *(p - 1) != ':'))
 790             {
 791                 s = p + 1;
 792                 while (IS_PATH_SEP (*(++s)))
 793                     ;
 794                 str_move (p + 1, s);
 795             }
 796 
 797         /* Collapse "/./" -> "/" */
 798         for (p = lpath; *p != '\0';)
 799             if (IS_PATH_SEP (p[0]) && p[1] == '.' && IS_PATH_SEP (p[2]))
 800                 str_move (p, p + 2);
 801             else
 802                 p++;
 803     }
 804 
 805     if ((flags & CANON_PATH_REMSLASHDOTS) != 0)
 806     {
 807         size_t len;
 808 
 809         /* Remove trailing slashes */
 810         for (p = lpath + strlen (lpath) - 1; p > lpath && IS_PATH_SEP (*p); p--)
 811         {
 812             if (p >= lpath + url_delim_len - 1
 813                 && strncmp (p - url_delim_len + 1, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
 814                 break;
 815             *p = '\0';
 816         }
 817 
 818         /* Remove leading "./" */
 819         if (lpath[0] == '.' && IS_PATH_SEP (lpath[1]))
 820         {
 821             if (lpath[2] == '\0')
 822             {
 823                 lpath[1] = '\0';
 824                 return;
 825             }
 826 
 827             str_move (lpath, lpath + 2);
 828         }
 829 
 830         /* Remove trailing "/" or "/." */
 831         len = strlen (lpath);
 832         if (len < 2)
 833             return;
 834 
 835         if (IS_PATH_SEP (lpath[len - 1])
 836             && (len < url_delim_len
 837                 || strncmp (lpath + len - url_delim_len, VFS_PATH_URL_DELIMITER,
 838                             url_delim_len) != 0))
 839             lpath[len - 1] = '\0';
 840         else if (lpath[len - 1] == '.' && IS_PATH_SEP (lpath[len - 2]))
 841         {
 842             if (len == 2)
 843             {
 844                 lpath[1] = '\0';
 845                 return;
 846             }
 847 
 848             lpath[len - 2] = '\0';
 849         }
 850     }
 851 
 852     /* Collapse "/.." with the previous part of path */
 853     if ((flags & CANON_PATH_REMDOUBLEDOTS) != 0)
 854     {
 855 #ifdef HAVE_CHARSET
 856         const size_t enc_prefix_len = strlen (VFS_ENCODING_PREFIX);
 857 #endif /* HAVE_CHARSET */
 858 
 859         for (p = lpath; p[0] != '\0' && p[1] != '\0' && p[2] != '\0';)
 860         {
 861             if (!IS_PATH_SEP (p[0]) || p[1] != '.' || p[2] != '.'
 862                 || (!IS_PATH_SEP (p[3]) && p[3] != '\0'))
 863             {
 864                 p++;
 865                 continue;
 866             }
 867 
 868             /* search for the previous token */
 869             s = p - 1;
 870             if (s >= lpath + url_delim_len - 2
 871                 && strncmp (s - url_delim_len + 2, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
 872             {
 873                 s -= (url_delim_len - 2);
 874                 while (s >= lpath && !IS_PATH_SEP (*s--))
 875                     ;
 876             }
 877 
 878             while (s >= lpath)
 879             {
 880                 if (s - url_delim_len > lpath
 881                     && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
 882                 {
 883                     char *vfs_prefix = s - url_delim_len;
 884                     vfs_class *vclass;
 885 
 886                     while (vfs_prefix > lpath && !IS_PATH_SEP (*--vfs_prefix))
 887                         ;
 888                     if (IS_PATH_SEP (*vfs_prefix))
 889                         vfs_prefix++;
 890                     *(s - url_delim_len) = '\0';
 891 
 892                     vclass = vfs_prefix_to_class (vfs_prefix);
 893                     *(s - url_delim_len) = *VFS_PATH_URL_DELIMITER;
 894 
 895                     if (vclass != NULL && (vclass->flags & VFSF_REMOTE) != 0)
 896                     {
 897                         s = vfs_prefix;
 898                         continue;
 899                     }
 900                 }
 901 
 902                 if (IS_PATH_SEP (*s))
 903                     break;
 904 
 905                 s--;
 906             }
 907 
 908             s++;
 909 
 910             /* If the previous token is "..", we cannot collapse it */
 911             if (s[0] == '.' && s[1] == '.' && s + 2 == p)
 912             {
 913                 p += 3;
 914                 continue;
 915             }
 916 
 917             if (p[3] != '\0')
 918             {
 919                 if (s == lpath && IS_PATH_SEP (*s))
 920                 {
 921                     /* "/../foo" -> "/foo" */
 922                     str_move (s + 1, p + 4);
 923                 }
 924                 else
 925                 {
 926                     /* "token/../foo" -> "foo" */
 927 #ifdef HAVE_CHARSET
 928                     if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
 929                         && (is_supported_encoding (s + enc_prefix_len)))
 930                         /* special case: remove encoding */
 931                         str_move (s, p + 1);
 932                     else
 933 #endif /* HAVE_CHARSET */
 934                         str_move (s, p + 4);
 935                 }
 936 
 937                 p = s > lpath ? s - 1 : s;
 938                 continue;
 939             }
 940 
 941             /* trailing ".." */
 942             if (s == lpath)
 943             {
 944                 /* "token/.." -> "." */
 945                 if (!IS_PATH_SEP (lpath[0]))
 946                     lpath[0] = '.';
 947                 lpath[1] = '\0';
 948             }
 949             else
 950             {
 951                 /* "foo/token/.." -> "foo" */
 952                 if (s == lpath + 1)
 953                     s[0] = '\0';
 954 #ifdef HAVE_CHARSET
 955                 else if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
 956                          && (is_supported_encoding (s + enc_prefix_len)))
 957                 {
 958                     /* special case: remove encoding */
 959                     s[0] = '.';
 960                     s[1] = '.';
 961                     s[2] = '\0';
 962 
 963                     /* search for the previous token */
 964                     /* IS_PATH_SEP (s[-1]) */
 965                     for (p = s - 1; p >= lpath && !IS_PATH_SEP (*p); p--)
 966                         ;
 967 
 968                     if (p >= lpath)
 969                         continue;
 970                 }
 971 #endif /* HAVE_CHARSET */
 972                 else
 973                 {
 974                     if (s >= lpath + url_delim_len
 975                         && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
 976                         *s = '\0';
 977                     else
 978                         s[-1] = '\0';
 979                 }
 980             }
 981 
 982             break;
 983         }
 984     }
 985 }
 986 
 987 /* --------------------------------------------------------------------------------------------- */
 988 
 989 char *
 990 mc_realpath (const char *path, char *resolved_path)
     /* [previous][next][first][last][top][bottom][index][help]  */
 991 {
 992 #ifdef HAVE_CHARSET
 993     const char *p = path;
 994     gboolean absolute_path = FALSE;
 995 
 996     if (IS_PATH_SEP (*p))
 997     {
 998         absolute_path = TRUE;
 999         p++;
1000     }
1001 
1002     /* ignore encoding: skip "#enc:" */
1003     if (g_str_has_prefix (p, VFS_ENCODING_PREFIX))
1004     {
1005         p += strlen (VFS_ENCODING_PREFIX);
1006         p = strchr (p, PATH_SEP);
1007         if (p != NULL)
1008         {
1009             if (!absolute_path && p[1] != '\0')
1010                 p++;
1011 
1012             path = p;
1013         }
1014     }
1015 #endif /* HAVE_CHARSET */
1016 
1017 #ifdef HAVE_REALPATH
1018     return realpath (path, resolved_path);
1019 #else
1020     {
1021         char copy_path[PATH_MAX];
1022         char got_path[PATH_MAX];
1023         char *new_path = got_path;
1024         char *max_path;
1025 #ifdef S_IFLNK
1026         char link_path[PATH_MAX];
1027         int readlinks = 0;
1028         int n;
1029 #endif /* S_IFLNK */
1030 
1031         /* Make a copy of the source path since we may need to modify it. */
1032         if (strlen (path) >= PATH_MAX - 2)
1033         {
1034             errno = ENAMETOOLONG;
1035             return NULL;
1036         }
1037 
1038         strcpy (copy_path, path);
1039         path = copy_path;
1040         max_path = copy_path + PATH_MAX - 2;
1041         /* If it's a relative pathname use getwd for starters. */
1042         if (!IS_PATH_SEP (*path))
1043         {
1044             new_path = g_get_current_dir ();
1045             if (new_path == NULL)
1046                 strcpy (got_path, "");
1047             else
1048             {
1049                 g_snprintf (got_path, sizeof (got_path), "%s", new_path);
1050                 g_free (new_path);
1051                 new_path = got_path;
1052             }
1053 
1054             new_path += strlen (got_path);
1055             if (!IS_PATH_SEP (new_path[-1]))
1056                 *new_path++ = PATH_SEP;
1057         }
1058         else
1059         {
1060             *new_path++ = PATH_SEP;
1061             path++;
1062         }
1063         /* Expand each slash-separated pathname component. */
1064         while (*path != '\0')
1065         {
1066             /* Ignore stray "/". */
1067             if (IS_PATH_SEP (*path))
1068             {
1069                 path++;
1070                 continue;
1071             }
1072             if (*path == '.')
1073             {
1074                 /* Ignore ".". */
1075                 if (path[1] == '\0' || IS_PATH_SEP (path[1]))
1076                 {
1077                     path++;
1078                     continue;
1079                 }
1080                 if (path[1] == '.')
1081                 {
1082                     if (path[2] == '\0' || IS_PATH_SEP (path[2]))
1083                     {
1084                         path += 2;
1085                         /* Ignore ".." at root. */
1086                         if (new_path == got_path + 1)
1087                             continue;
1088                         /* Handle ".." by backing up. */
1089                         while (!IS_PATH_SEP ((--new_path)[-1]))
1090                             ;
1091                         continue;
1092                     }
1093                 }
1094             }
1095             /* Safely copy the next pathname component. */
1096             while (*path != '\0' && !IS_PATH_SEP (*path))
1097             {
1098                 if (path > max_path)
1099                 {
1100                     errno = ENAMETOOLONG;
1101                     return NULL;
1102                 }
1103                 *new_path++ = *path++;
1104             }
1105 #ifdef S_IFLNK
1106             /* Protect against infinite loops. */
1107             if (readlinks++ > MAXSYMLINKS)
1108             {
1109                 errno = ELOOP;
1110                 return NULL;
1111             }
1112             /* See if latest pathname component is a symlink. */
1113             *new_path = '\0';
1114             n = readlink (got_path, link_path, PATH_MAX - 1);
1115             if (n < 0)
1116             {
1117                 /* EINVAL means the file exists but isn't a symlink. */
1118                 if (errno != EINVAL)
1119                 {
1120                     /* Make sure it's null terminated. */
1121                     *new_path = '\0';
1122                     strcpy (resolved_path, got_path);
1123                     return NULL;
1124                 }
1125             }
1126             else
1127             {
1128                 /* Note: readlink doesn't add the null byte. */
1129                 link_path[n] = '\0';
1130                 if (IS_PATH_SEP (*link_path))
1131                     /* Start over for an absolute symlink. */
1132                     new_path = got_path;
1133                 else
1134                     /* Otherwise back up over this component. */
1135                     while (!IS_PATH_SEP (*(--new_path)))
1136                         ;
1137                 /* Safe sex check. */
1138                 if (strlen (path) + n >= PATH_MAX - 2)
1139                 {
1140                     errno = ENAMETOOLONG;
1141                     return NULL;
1142                 }
1143                 /* Insert symlink contents into path. */
1144                 strcat (link_path, path);
1145                 strcpy (copy_path, link_path);
1146                 path = copy_path;
1147             }
1148 #endif /* S_IFLNK */
1149             *new_path++ = PATH_SEP;
1150         }
1151         /* Delete trailing slash but don't whomp a lone slash. */
1152         if (new_path != got_path + 1 && IS_PATH_SEP (new_path[-1]))
1153             new_path--;
1154         /* Make sure it's null terminated. */
1155         *new_path = '\0';
1156         strcpy (resolved_path, got_path);
1157         return resolved_path;
1158     }
1159 #endif /* HAVE_REALPATH */
1160 }
1161 
1162 /* --------------------------------------------------------------------------------------------- */
1163 /**
1164  * Return the index of the permissions triplet
1165  *
1166  */
1167 
1168 int
1169 get_user_permissions (struct stat *st)
     /* [previous][next][first][last][top][bottom][index][help]  */
1170 {
1171     static gboolean initialized = FALSE;
1172     static gid_t *groups;
1173     static int ngroups;
1174     static uid_t uid;
1175     int i;
1176 
1177     if (!initialized)
1178     {
1179         uid = geteuid ();
1180 
1181         ngroups = getgroups (0, NULL);
1182         if (ngroups == -1)
1183             ngroups = 0;        /* ignore errors */
1184 
1185         /* allocate space for one element in addition to what
1186          * will be filled by getgroups(). */
1187         groups = g_new (gid_t, ngroups + 1);
1188 
1189         if (ngroups != 0)
1190         {
1191             ngroups = getgroups (ngroups, groups);
1192             if (ngroups == -1)
1193                 ngroups = 0;    /* ignore errors */
1194         }
1195 
1196         /* getgroups() may or may not return the effective group ID,
1197          * so we always include it at the end of the list. */
1198         groups[ngroups++] = getegid ();
1199 
1200         initialized = TRUE;
1201     }
1202 
1203     if (st->st_uid == uid || uid == 0)
1204         return 0;
1205 
1206     for (i = 0; i < ngroups; i++)
1207         if (st->st_gid == groups[i])
1208             return 1;
1209 
1210     return 2;
1211 }
1212 
1213 /* --------------------------------------------------------------------------------------------- */
1214 /**
1215  * Build filename from arguments.
1216  * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
1217  */
1218 
1219 char *
1220 mc_build_filenamev (const char *first_element, va_list args)
     /* [previous][next][first][last][top][bottom][index][help]  */
1221 {
1222     gboolean absolute;
1223     const char *element = first_element;
1224     GString *path;
1225     char *ret;
1226 
1227     if (element == NULL)
1228         return NULL;
1229 
1230     path = g_string_new ("");
1231 
1232     absolute = IS_PATH_SEP (*first_element);
1233 
1234     do
1235     {
1236         if (*element == '\0')
1237             element = va_arg (args, char *);
1238         else
1239         {
1240             char *tmp_element;
1241             size_t len;
1242             const char *start;
1243 
1244             tmp_element = g_strdup (element);
1245 
1246             element = va_arg (args, char *);
1247 
1248             canonicalize_pathname (tmp_element);
1249             len = strlen (tmp_element);
1250             start = IS_PATH_SEP (tmp_element[0]) ? tmp_element + 1 : tmp_element;
1251 
1252             g_string_append (path, start);
1253             if (!IS_PATH_SEP (tmp_element[len - 1]) && element != NULL)
1254                 g_string_append_c (path, PATH_SEP);
1255 
1256             g_free (tmp_element);
1257         }
1258     }
1259     while (element != NULL);
1260 
1261     if (absolute)
1262         g_string_prepend_c (path, PATH_SEP);
1263 
1264     ret = g_string_free (path, FALSE);
1265     canonicalize_pathname (ret);
1266 
1267     return ret;
1268 }
1269 
1270 /* --------------------------------------------------------------------------------------------- */
1271 /**
1272  * Build filename from arguments.
1273  * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
1274  */
1275 
1276 char *
1277 mc_build_filename (const char *first_element, ...)
     /* [previous][next][first][last][top][bottom][index][help]  */
1278 {
1279     va_list args;
1280     char *ret;
1281 
1282     if (first_element == NULL)
1283         return NULL;
1284 
1285     va_start (args, first_element);
1286     ret = mc_build_filenamev (first_element, args);
1287     va_end (args);
1288     return ret;
1289 }
1290 
1291 /* --------------------------------------------------------------------------------------------- */

/* [previous][next][first][last][top][bottom][index][help]  */