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_pclose
  19. tilde_expand
  20. open_error_pipe
  21. close_error_pipe
  22. custom_canonicalize_pathname
  23. canonicalize_pathname
  24. gettimeofday
  25. mc_realpath
  26. get_user_permissions
  27. mc_build_filenamev
  28. mc_build_filename

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

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