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. canonicalize_pathname
  23. mc_realpath
  24. get_user_permissions
  25. mc_build_filenamev
  26. mc_build_filename

   1 /*
   2    Various utilities - Unix variants
   3 
   4    Copyright (C) 1994-2022
   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 successfull, -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 pathes 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 successfull, -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 successfull, -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 successfull, -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  * @paremeter 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  * @paremeter 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  * @paremeter p pipe descriptor
 670  * @paremeter 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  * @return a new path
 763  *
 764  * All modifications of @path are made in place.
 765  * Well formed UNC paths are modified only in the local part.
 766  */
 767 
 768 void
 769 canonicalize_pathname_custom (char *path, canon_path_flags_t flags)
     /* [previous][next][first][last][top][bottom][index][help]  */
 770 {
 771     char *p, *s;
 772     char *lpath = path;         /* path without leading UNC part */
 773     const size_t url_delim_len = strlen (VFS_PATH_URL_DELIMITER);
 774 
 775     /* Detect and preserve UNC paths: //server/... */
 776     if ((flags & CANON_PATH_GUARDUNC) != 0 && IS_PATH_SEP (path[0]) && IS_PATH_SEP (path[1]))
 777     {
 778         for (p = path + 2; p[0] != '\0' && !IS_PATH_SEP (p[0]); p++)
 779             ;
 780         if (IS_PATH_SEP (p[0]) && p > path + 2)
 781             lpath = p;
 782     }
 783 
 784     if (lpath[0] == '\0' || lpath[1] == '\0')
 785         return;
 786 
 787     if ((flags & CANON_PATH_JOINSLASHES) != 0)
 788     {
 789         /* Collapse multiple slashes */
 790         for (p = lpath; *p != '\0'; p++)
 791             if (IS_PATH_SEP (p[0]) && IS_PATH_SEP (p[1]) && (p == lpath || *(p - 1) != ':'))
 792             {
 793                 s = p + 1;
 794                 while (IS_PATH_SEP (*(++s)))
 795                     ;
 796                 str_move (p + 1, s);
 797             }
 798 
 799         /* Collapse "/./" -> "/" */
 800         for (p = lpath; *p != '\0';)
 801             if (IS_PATH_SEP (p[0]) && p[1] == '.' && IS_PATH_SEP (p[2]))
 802                 str_move (p, p + 2);
 803             else
 804                 p++;
 805     }
 806 
 807     if ((flags & CANON_PATH_REMSLASHDOTS) != 0)
 808     {
 809         size_t len;
 810 
 811         /* Remove trailing slashes */
 812         for (p = lpath + strlen (lpath) - 1; p > lpath && IS_PATH_SEP (*p); p--)
 813         {
 814             if (p >= lpath + url_delim_len - 1
 815                 && strncmp (p - url_delim_len + 1, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
 816                 break;
 817             *p = '\0';
 818         }
 819 
 820         /* Remove leading "./" */
 821         if (lpath[0] == '.' && IS_PATH_SEP (lpath[1]))
 822         {
 823             if (lpath[2] == '\0')
 824             {
 825                 lpath[1] = '\0';
 826                 return;
 827             }
 828 
 829             str_move (lpath, lpath + 2);
 830         }
 831 
 832         /* Remove trailing "/" or "/." */
 833         len = strlen (lpath);
 834         if (len < 2)
 835             return;
 836 
 837         if (IS_PATH_SEP (lpath[len - 1])
 838             && (len < url_delim_len
 839                 || strncmp (lpath + len - url_delim_len, VFS_PATH_URL_DELIMITER,
 840                             url_delim_len) != 0))
 841             lpath[len - 1] = '\0';
 842         else if (lpath[len - 1] == '.' && IS_PATH_SEP (lpath[len - 2]))
 843         {
 844             if (len == 2)
 845             {
 846                 lpath[1] = '\0';
 847                 return;
 848             }
 849 
 850             lpath[len - 2] = '\0';
 851         }
 852     }
 853 
 854     /* Collapse "/.." with the previous part of path */
 855     if ((flags & CANON_PATH_REMDOUBLEDOTS) != 0)
 856     {
 857 #ifdef HAVE_CHARSET
 858         const size_t enc_prefix_len = strlen (VFS_ENCODING_PREFIX);
 859 #endif /* HAVE_CHARSET */
 860 
 861         for (p = lpath; p[0] != '\0' && p[1] != '\0' && p[2] != '\0';)
 862         {
 863             if (!IS_PATH_SEP (p[0]) || p[1] != '.' || p[2] != '.'
 864                 || (!IS_PATH_SEP (p[3]) && p[3] != '\0'))
 865             {
 866                 p++;
 867                 continue;
 868             }
 869 
 870             /* search for the previous token */
 871             s = p - 1;
 872             if (s >= lpath + url_delim_len - 2
 873                 && strncmp (s - url_delim_len + 2, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
 874             {
 875                 s -= (url_delim_len - 2);
 876                 while (s >= lpath && !IS_PATH_SEP (*s--))
 877                     ;
 878             }
 879 
 880             while (s >= lpath)
 881             {
 882                 if (s - url_delim_len > lpath
 883                     && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
 884                 {
 885                     char *vfs_prefix = s - url_delim_len;
 886                     vfs_class *vclass;
 887 
 888                     while (vfs_prefix > lpath && !IS_PATH_SEP (*--vfs_prefix))
 889                         ;
 890                     if (IS_PATH_SEP (*vfs_prefix))
 891                         vfs_prefix++;
 892                     *(s - url_delim_len) = '\0';
 893 
 894                     vclass = vfs_prefix_to_class (vfs_prefix);
 895                     *(s - url_delim_len) = *VFS_PATH_URL_DELIMITER;
 896 
 897                     if (vclass != NULL && (vclass->flags & VFSF_REMOTE) != 0)
 898                     {
 899                         s = vfs_prefix;
 900                         continue;
 901                     }
 902                 }
 903 
 904                 if (IS_PATH_SEP (*s))
 905                     break;
 906 
 907                 s--;
 908             }
 909 
 910             s++;
 911 
 912             /* If the previous token is "..", we cannot collapse it */
 913             if (s[0] == '.' && s[1] == '.' && s + 2 == p)
 914             {
 915                 p += 3;
 916                 continue;
 917             }
 918 
 919             if (p[3] != '\0')
 920             {
 921                 if (s == lpath && IS_PATH_SEP (*s))
 922                 {
 923                     /* "/../foo" -> "/foo" */
 924                     str_move (s + 1, p + 4);
 925                 }
 926                 else
 927                 {
 928                     /* "token/../foo" -> "foo" */
 929 #ifdef HAVE_CHARSET
 930                     if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
 931                         && (is_supported_encoding (s + enc_prefix_len)))
 932                         /* special case: remove encoding */
 933                         str_move (s, p + 1);
 934                     else
 935 #endif /* HAVE_CHARSET */
 936                         str_move (s, p + 4);
 937                 }
 938 
 939                 p = s > lpath ? s - 1 : s;
 940                 continue;
 941             }
 942 
 943             /* trailing ".." */
 944             if (s == lpath)
 945             {
 946                 /* "token/.." -> "." */
 947                 if (!IS_PATH_SEP (lpath[0]))
 948                     lpath[0] = '.';
 949                 lpath[1] = '\0';
 950             }
 951             else
 952             {
 953                 /* "foo/token/.." -> "foo" */
 954                 if (s == lpath + 1)
 955                     s[0] = '\0';
 956 #ifdef HAVE_CHARSET
 957                 else if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
 958                          && (is_supported_encoding (s + enc_prefix_len)))
 959                 {
 960                     /* special case: remove encoding */
 961                     s[0] = '.';
 962                     s[1] = '.';
 963                     s[2] = '\0';
 964 
 965                     /* search for the previous token */
 966                     /* IS_PATH_SEP (s[-1]) */
 967                     for (p = s - 1; p >= lpath && !IS_PATH_SEP (*p); p--)
 968                         ;
 969 
 970                     if (p >= lpath)
 971                         continue;
 972                 }
 973 #endif /* HAVE_CHARSET */
 974                 else
 975                 {
 976                     if (s >= lpath + url_delim_len
 977                         && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
 978                         *s = '\0';
 979                     else
 980                         s[-1] = '\0';
 981                 }
 982             }
 983 
 984             break;
 985         }
 986     }
 987 }
 988 
 989 /* --------------------------------------------------------------------------------------------- */
 990 /**
 991  * Canonicalize path with CANON_PATH_ALL.
 992  *
 993  * @param path path to file
 994  * @param flags canonicalization flags
 995  *
 996  * @return a new path
 997  *
 998  * All modifications of @path are made in place.
 999  * Well formed UNC paths are modified only in the local part.
1000  */
1001 
1002 void
1003 canonicalize_pathname (char *path)
     /* [previous][next][first][last][top][bottom][index][help]  */
1004 {
1005     canonicalize_pathname_custom (path, CANON_PATH_ALL);
1006 }
1007 
1008 /* --------------------------------------------------------------------------------------------- */
1009 
1010 char *
1011 mc_realpath (const char *path, char *resolved_path)
     /* [previous][next][first][last][top][bottom][index][help]  */
1012 {
1013 #ifdef HAVE_CHARSET
1014     const char *p = path;
1015     gboolean absolute_path = FALSE;
1016 
1017     if (IS_PATH_SEP (*p))
1018     {
1019         absolute_path = TRUE;
1020         p++;
1021     }
1022 
1023     /* ignore encoding: skip "#enc:" */
1024     if (g_str_has_prefix (p, VFS_ENCODING_PREFIX))
1025     {
1026         p += strlen (VFS_ENCODING_PREFIX);
1027         p = strchr (p, PATH_SEP);
1028         if (p != NULL)
1029         {
1030             if (!absolute_path && p[1] != '\0')
1031                 p++;
1032 
1033             path = p;
1034         }
1035     }
1036 #endif /* HAVE_CHARSET */
1037 
1038 #ifdef HAVE_REALPATH
1039     return realpath (path, resolved_path);
1040 #else
1041     {
1042         char copy_path[PATH_MAX];
1043         char got_path[PATH_MAX];
1044         char *new_path = got_path;
1045         char *max_path;
1046 #ifdef S_IFLNK
1047         char link_path[PATH_MAX];
1048         int readlinks = 0;
1049         int n;
1050 #endif /* S_IFLNK */
1051 
1052         /* Make a copy of the source path since we may need to modify it. */
1053         if (strlen (path) >= PATH_MAX - 2)
1054         {
1055             errno = ENAMETOOLONG;
1056             return NULL;
1057         }
1058 
1059         strcpy (copy_path, path);
1060         path = copy_path;
1061         max_path = copy_path + PATH_MAX - 2;
1062         /* If it's a relative pathname use getwd for starters. */
1063         if (!IS_PATH_SEP (*path))
1064         {
1065             new_path = g_get_current_dir ();
1066             if (new_path == NULL)
1067                 strcpy (got_path, "");
1068             else
1069             {
1070                 g_snprintf (got_path, sizeof (got_path), "%s", new_path);
1071                 g_free (new_path);
1072                 new_path = got_path;
1073             }
1074 
1075             new_path += strlen (got_path);
1076             if (!IS_PATH_SEP (new_path[-1]))
1077                 *new_path++ = PATH_SEP;
1078         }
1079         else
1080         {
1081             *new_path++ = PATH_SEP;
1082             path++;
1083         }
1084         /* Expand each slash-separated pathname component. */
1085         while (*path != '\0')
1086         {
1087             /* Ignore stray "/". */
1088             if (IS_PATH_SEP (*path))
1089             {
1090                 path++;
1091                 continue;
1092             }
1093             if (*path == '.')
1094             {
1095                 /* Ignore ".". */
1096                 if (path[1] == '\0' || IS_PATH_SEP (path[1]))
1097                 {
1098                     path++;
1099                     continue;
1100                 }
1101                 if (path[1] == '.')
1102                 {
1103                     if (path[2] == '\0' || IS_PATH_SEP (path[2]))
1104                     {
1105                         path += 2;
1106                         /* Ignore ".." at root. */
1107                         if (new_path == got_path + 1)
1108                             continue;
1109                         /* Handle ".." by backing up. */
1110                         while (!IS_PATH_SEP ((--new_path)[-1]))
1111                             ;
1112                         continue;
1113                     }
1114                 }
1115             }
1116             /* Safely copy the next pathname component. */
1117             while (*path != '\0' && !IS_PATH_SEP (*path))
1118             {
1119                 if (path > max_path)
1120                 {
1121                     errno = ENAMETOOLONG;
1122                     return NULL;
1123                 }
1124                 *new_path++ = *path++;
1125             }
1126 #ifdef S_IFLNK
1127             /* Protect against infinite loops. */
1128             if (readlinks++ > MAXSYMLINKS)
1129             {
1130                 errno = ELOOP;
1131                 return NULL;
1132             }
1133             /* See if latest pathname component is a symlink. */
1134             *new_path = '\0';
1135             n = readlink (got_path, link_path, PATH_MAX - 1);
1136             if (n < 0)
1137             {
1138                 /* EINVAL means the file exists but isn't a symlink. */
1139                 if (errno != EINVAL)
1140                 {
1141                     /* Make sure it's null terminated. */
1142                     *new_path = '\0';
1143                     strcpy (resolved_path, got_path);
1144                     return NULL;
1145                 }
1146             }
1147             else
1148             {
1149                 /* Note: readlink doesn't add the null byte. */
1150                 link_path[n] = '\0';
1151                 if (IS_PATH_SEP (*link_path))
1152                     /* Start over for an absolute symlink. */
1153                     new_path = got_path;
1154                 else
1155                     /* Otherwise back up over this component. */
1156                     while (!IS_PATH_SEP (*(--new_path)))
1157                         ;
1158                 /* Safe sex check. */
1159                 if (strlen (path) + n >= PATH_MAX - 2)
1160                 {
1161                     errno = ENAMETOOLONG;
1162                     return NULL;
1163                 }
1164                 /* Insert symlink contents into path. */
1165                 strcat (link_path, path);
1166                 strcpy (copy_path, link_path);
1167                 path = copy_path;
1168             }
1169 #endif /* S_IFLNK */
1170             *new_path++ = PATH_SEP;
1171         }
1172         /* Delete trailing slash but don't whomp a lone slash. */
1173         if (new_path != got_path + 1 && IS_PATH_SEP (new_path[-1]))
1174             new_path--;
1175         /* Make sure it's null terminated. */
1176         *new_path = '\0';
1177         strcpy (resolved_path, got_path);
1178         return resolved_path;
1179     }
1180 #endif /* HAVE_REALPATH */
1181 }
1182 
1183 /* --------------------------------------------------------------------------------------------- */
1184 /**
1185  * Return the index of the permissions triplet
1186  *
1187  */
1188 
1189 int
1190 get_user_permissions (struct stat *st)
     /* [previous][next][first][last][top][bottom][index][help]  */
1191 {
1192     static gboolean initialized = FALSE;
1193     static gid_t *groups;
1194     static int ngroups;
1195     static uid_t uid;
1196     int i;
1197 
1198     if (!initialized)
1199     {
1200         uid = geteuid ();
1201 
1202         ngroups = getgroups (0, NULL);
1203         if (ngroups == -1)
1204             ngroups = 0;        /* ignore errors */
1205 
1206         /* allocate space for one element in addition to what
1207          * will be filled by getgroups(). */
1208         groups = g_new (gid_t, ngroups + 1);
1209 
1210         if (ngroups != 0)
1211         {
1212             ngroups = getgroups (ngroups, groups);
1213             if (ngroups == -1)
1214                 ngroups = 0;    /* ignore errors */
1215         }
1216 
1217         /* getgroups() may or may not return the effective group ID,
1218          * so we always include it at the end of the list. */
1219         groups[ngroups++] = getegid ();
1220 
1221         initialized = TRUE;
1222     }
1223 
1224     if (st->st_uid == uid || uid == 0)
1225         return 0;
1226 
1227     for (i = 0; i < ngroups; i++)
1228         if (st->st_gid == groups[i])
1229             return 1;
1230 
1231     return 2;
1232 }
1233 
1234 /* --------------------------------------------------------------------------------------------- */
1235 /**
1236  * Build filename from arguments.
1237  * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
1238  */
1239 
1240 char *
1241 mc_build_filenamev (const char *first_element, va_list args)
     /* [previous][next][first][last][top][bottom][index][help]  */
1242 {
1243     gboolean absolute;
1244     const char *element = first_element;
1245     GString *path;
1246     char *ret;
1247 
1248     if (element == NULL)
1249         return NULL;
1250 
1251     path = g_string_new ("");
1252 
1253     absolute = IS_PATH_SEP (*first_element);
1254 
1255     do
1256     {
1257         if (*element == '\0')
1258             element = va_arg (args, char *);
1259         else
1260         {
1261             char *tmp_element;
1262             size_t len;
1263             const char *start;
1264 
1265             tmp_element = g_strdup (element);
1266 
1267             element = va_arg (args, char *);
1268 
1269             canonicalize_pathname (tmp_element);
1270             len = strlen (tmp_element);
1271             start = IS_PATH_SEP (tmp_element[0]) ? tmp_element + 1 : tmp_element;
1272 
1273             g_string_append (path, start);
1274             if (!IS_PATH_SEP (tmp_element[len - 1]) && element != NULL)
1275                 g_string_append_c (path, PATH_SEP);
1276 
1277             g_free (tmp_element);
1278         }
1279     }
1280     while (element != NULL);
1281 
1282     if (absolute)
1283         g_string_prepend_c (path, PATH_SEP);
1284 
1285     ret = g_string_free (path, FALSE);
1286     canonicalize_pathname (ret);
1287 
1288     return ret;
1289 }
1290 
1291 /* --------------------------------------------------------------------------------------------- */
1292 /**
1293  * Build filename from arguments.
1294  * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
1295  */
1296 
1297 char *
1298 mc_build_filename (const char *first_element, ...)
     /* [previous][next][first][last][top][bottom][index][help]  */
1299 {
1300     va_list args;
1301     char *ret;
1302 
1303     if (first_element == NULL)
1304         return NULL;
1305 
1306     va_start (args, first_element);
1307     ret = mc_build_filenamev (first_element, args);
1308     va_end (args);
1309     return ret;
1310 }
1311 
1312 /* --------------------------------------------------------------------------------------------- */

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