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-2019
   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     if (pipe (error_pipe) < 0)
 719         message (D_NORMAL, _("Warning"), _("Pipe failed"));
 720 
 721     old_error = dup (STDERR_FILENO);
 722     if (old_error < 0 || close (STDERR_FILENO) != 0 || dup (error_pipe[1]) != STDERR_FILENO)
 723     {
 724         message (D_NORMAL, _("Warning"), _("Dup failed"));
 725 
 726         close (error_pipe[0]);
 727         error_pipe[0] = -1;
 728     }
 729     else
 730     {
 731         /*
 732          * Settng stderr in nonblocking mode as we close it earlier, than
 733          * program stops. We try to read some error at program startup,
 734          * but we should not block on it.
 735          *
 736          * TODO: make piped stdin/stderr poll()/select()able to get rid
 737          * of following hack.
 738          */
 739         int fd_flags;
 740 
 741         fd_flags = fcntl (error_pipe[0], F_GETFL, NULL);
 742         if (fd_flags != -1)
 743         {
 744             fd_flags |= O_NONBLOCK;
 745 
 746             if (fcntl (error_pipe[0], F_SETFL, fd_flags) == -1)
 747             {
 748                 /* TODO: handle it somehow */
 749             }
 750         }
 751     }
 752     /* we never write there */
 753     close (error_pipe[1]);
 754     error_pipe[1] = -1;
 755 }
 756 
 757 /* --------------------------------------------------------------------------------------------- */
 758 /**
 759  * Close a pipe
 760  *
 761  * @param error '-1' - ignore errors, '0' - display warning, '1' - display error
 762  * @param text is prepended to the error message from the pipe
 763  *
 764  * @return not 0 if an error was displayed
 765  */
 766 
 767 int
 768 close_error_pipe (int error, const char *text)
     /* [previous][next][first][last][top][bottom][index][help]  */
 769 {
 770     const char *title;
 771     char msg[MAX_PIPE_SIZE];
 772     int len = 0;
 773 
 774     /* already closed */
 775     if (error_pipe[0] == -1)
 776         return 0;
 777 
 778     if (error < 0 || (error > 0 && (error & D_ERROR) != 0))
 779         title = MSG_ERROR;
 780     else
 781         title = _("Warning");
 782     if (old_error >= 0)
 783     {
 784         if (dup2 (old_error, STDERR_FILENO) == -1)
 785         {
 786             if (error < 0)
 787                 error = D_ERROR;
 788 
 789             message (error, MSG_ERROR, _("Error dup'ing old error pipe"));
 790             return 1;
 791         }
 792         close (old_error);
 793         len = read (error_pipe[0], msg, sizeof (msg) - 1);
 794 
 795         if (len >= 0)
 796             msg[len] = 0;
 797         close (error_pipe[0]);
 798         error_pipe[0] = -1;
 799     }
 800     if (error < 0)
 801         return 0;               /* Just ignore error message */
 802     if (text == NULL)
 803     {
 804         if (len <= 0)
 805             return 0;           /* Nothing to show */
 806 
 807         /* Show message from pipe */
 808         message (error, title, "%s", msg);
 809     }
 810     else
 811     {
 812         /* Show given text and possible message from pipe */
 813         message (error, title, "%s\n%s", text, msg);
 814     }
 815     return 1;
 816 }
 817 
 818 /* --------------------------------------------------------------------------------------------- */
 819 /**
 820  * Canonicalize path, and return a new path.  Do everything in place.
 821  * The new path differs from path in:
 822  *      Multiple '/'s are collapsed to a single '/'.
 823  *      Leading './'s and trailing '/.'s are removed.
 824  *      Trailing '/'s are removed.
 825  *      Non-leading '../'s and trailing '..'s are handled by removing
 826  *      portions of the path.
 827  * Well formed UNC paths are modified only in the local part.
 828  */
 829 
 830 void
 831 custom_canonicalize_pathname (char *path, CANON_PATH_FLAGS flags)
     /* [previous][next][first][last][top][bottom][index][help]  */
 832 {
 833     char *p, *s;
 834     char *lpath = path;         /* path without leading UNC part */
 835     const size_t url_delim_len = strlen (VFS_PATH_URL_DELIMITER);
 836 
 837     /* Detect and preserve UNC paths: //server/... */
 838     if ((flags & CANON_PATH_GUARDUNC) != 0 && IS_PATH_SEP (path[0]) && IS_PATH_SEP (path[1]))
 839     {
 840         for (p = path + 2; p[0] != '\0' && !IS_PATH_SEP (p[0]); p++)
 841             ;
 842         if (IS_PATH_SEP (p[0]) && p > path + 2)
 843             lpath = p;
 844     }
 845 
 846     if (lpath[0] == '\0' || lpath[1] == '\0')
 847         return;
 848 
 849     if ((flags & CANON_PATH_JOINSLASHES) != 0)
 850     {
 851         /* Collapse multiple slashes */
 852         for (p = lpath; *p != '\0'; p++)
 853             if (IS_PATH_SEP (p[0]) && IS_PATH_SEP (p[1]) && (p == lpath || *(p - 1) != ':'))
 854             {
 855                 s = p + 1;
 856                 while (IS_PATH_SEP (*(++s)))
 857                     ;
 858                 str_move (p + 1, s);
 859             }
 860 
 861         /* Collapse "/./" -> "/" */
 862         for (p = lpath; *p != '\0';)
 863             if (IS_PATH_SEP (p[0]) && p[1] == '.' && IS_PATH_SEP (p[2]))
 864                 str_move (p, p + 2);
 865             else
 866                 p++;
 867     }
 868 
 869     if ((flags & CANON_PATH_REMSLASHDOTS) != 0)
 870     {
 871         size_t len;
 872 
 873         /* Remove trailing slashes */
 874         for (p = lpath + strlen (lpath) - 1; p > lpath && IS_PATH_SEP (*p); p--)
 875         {
 876             if (p >= lpath + url_delim_len - 1
 877                 && strncmp (p - url_delim_len + 1, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
 878                 break;
 879             *p = '\0';
 880         }
 881 
 882         /* Remove leading "./" */
 883         if (lpath[0] == '.' && IS_PATH_SEP (lpath[1]))
 884         {
 885             if (lpath[2] == '\0')
 886             {
 887                 lpath[1] = '\0';
 888                 return;
 889             }
 890 
 891             str_move (lpath, lpath + 2);
 892         }
 893 
 894         /* Remove trailing "/" or "/." */
 895         len = strlen (lpath);
 896         if (len < 2)
 897             return;
 898 
 899         if (IS_PATH_SEP (lpath[len - 1])
 900             && (len < url_delim_len
 901                 || strncmp (lpath + len - url_delim_len, VFS_PATH_URL_DELIMITER,
 902                             url_delim_len) != 0))
 903             lpath[len - 1] = '\0';
 904         else if (lpath[len - 1] == '.' && IS_PATH_SEP (lpath[len - 2]))
 905         {
 906             if (len == 2)
 907             {
 908                 lpath[1] = '\0';
 909                 return;
 910             }
 911 
 912             lpath[len - 2] = '\0';
 913         }
 914     }
 915 
 916     /* Collapse "/.." with the previous part of path */
 917     if ((flags & CANON_PATH_REMDOUBLEDOTS) != 0)
 918     {
 919 #ifdef HAVE_CHARSET
 920         const size_t enc_prefix_len = strlen (VFS_ENCODING_PREFIX);
 921 #endif /* HAVE_CHARSET */
 922 
 923         for (p = lpath; p[0] != '\0' && p[1] != '\0' && p[2] != '\0';)
 924         {
 925             if (!IS_PATH_SEP (p[0]) || p[1] != '.' || p[2] != '.'
 926                 || (!IS_PATH_SEP (p[3]) && p[3] != '\0'))
 927             {
 928                 p++;
 929                 continue;
 930             }
 931 
 932             /* search for the previous token */
 933             s = p - 1;
 934             if (s >= lpath + url_delim_len - 2
 935                 && strncmp (s - url_delim_len + 2, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
 936             {
 937                 s -= (url_delim_len - 2);
 938                 while (s >= lpath && !IS_PATH_SEP (*s--))
 939                     ;
 940             }
 941 
 942             while (s >= lpath)
 943             {
 944                 if (s - url_delim_len > lpath
 945                     && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
 946                 {
 947                     char *vfs_prefix = s - url_delim_len;
 948                     vfs_class *vclass;
 949 
 950                     while (vfs_prefix > lpath && !IS_PATH_SEP (*--vfs_prefix))
 951                         ;
 952                     if (IS_PATH_SEP (*vfs_prefix))
 953                         vfs_prefix++;
 954                     *(s - url_delim_len) = '\0';
 955 
 956                     vclass = vfs_prefix_to_class (vfs_prefix);
 957                     *(s - url_delim_len) = *VFS_PATH_URL_DELIMITER;
 958 
 959                     if (vclass != NULL && (vclass->flags & VFS_REMOTE) != 0)
 960                     {
 961                         s = vfs_prefix;
 962                         continue;
 963                     }
 964                 }
 965 
 966                 if (IS_PATH_SEP (*s))
 967                     break;
 968 
 969                 s--;
 970             }
 971 
 972             s++;
 973 
 974             /* If the previous token is "..", we cannot collapse it */
 975             if (s[0] == '.' && s[1] == '.' && s + 2 == p)
 976             {
 977                 p += 3;
 978                 continue;
 979             }
 980 
 981             if (p[3] != '\0')
 982             {
 983                 if (s == lpath && IS_PATH_SEP (*s))
 984                 {
 985                     /* "/../foo" -> "/foo" */
 986                     str_move (s + 1, p + 4);
 987                 }
 988                 else
 989                 {
 990                     /* "token/../foo" -> "foo" */
 991 #ifdef HAVE_CHARSET
 992                     if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
 993                         && (is_supported_encoding (s + enc_prefix_len)))
 994                         /* special case: remove encoding */
 995                         str_move (s, p + 1);
 996                     else
 997 #endif /* HAVE_CHARSET */
 998                         str_move (s, p + 4);
 999                 }
1000 
1001                 p = s > lpath ? s - 1 : s;
1002                 continue;
1003             }
1004 
1005             /* trailing ".." */
1006             if (s == lpath)
1007             {
1008                 /* "token/.." -> "." */
1009                 if (!IS_PATH_SEP (lpath[0]))
1010                     lpath[0] = '.';
1011                 lpath[1] = '\0';
1012             }
1013             else
1014             {
1015                 /* "foo/token/.." -> "foo" */
1016                 if (s == lpath + 1)
1017                     s[0] = '\0';
1018 #ifdef HAVE_CHARSET
1019                 else if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
1020                          && (is_supported_encoding (s + enc_prefix_len)))
1021                 {
1022                     /* special case: remove encoding */
1023                     s[0] = '.';
1024                     s[1] = '.';
1025                     s[2] = '\0';
1026 
1027                     /* search for the previous token */
1028                     /* IS_PATH_SEP (s[-1]) */
1029                     for (p = s - 1; p >= lpath && !IS_PATH_SEP (*p); p--)
1030                         ;
1031 
1032                     if (p >= lpath)
1033                         continue;
1034                 }
1035 #endif /* HAVE_CHARSET */
1036                 else
1037                 {
1038                     if (s >= lpath + url_delim_len
1039                         && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
1040                         *s = '\0';
1041                     else
1042                         s[-1] = '\0';
1043                 }
1044             }
1045 
1046             break;
1047         }
1048     }
1049 }
1050 
1051 /* --------------------------------------------------------------------------------------------- */
1052 
1053 void
1054 canonicalize_pathname (char *path)
     /* [previous][next][first][last][top][bottom][index][help]  */
1055 {
1056     custom_canonicalize_pathname (path, CANON_PATH_ALL);
1057 }
1058 
1059 /* --------------------------------------------------------------------------------------------- */
1060 
1061 #ifdef HAVE_GET_PROCESS_STATS
1062 int
1063 gettimeofday (struct timeval *tp, void *tzp)
     /* [previous][next][first][last][top][bottom][index][help]  */
1064 {
1065     (void) tzp;
1066 
1067     return get_process_stats (tp, PS_SELF, 0, 0);
1068 }
1069 #endif /* HAVE_GET_PROCESS_STATS */
1070 
1071 /* --------------------------------------------------------------------------------------------- */
1072 
1073 char *
1074 mc_realpath (const char *path, char *resolved_path)
     /* [previous][next][first][last][top][bottom][index][help]  */
1075 {
1076 #ifdef HAVE_CHARSET
1077     const char *p = path;
1078     gboolean absolute_path = FALSE;
1079 
1080     if (IS_PATH_SEP (*p))
1081     {
1082         absolute_path = TRUE;
1083         p++;
1084     }
1085 
1086     /* ignore encoding: skip "#enc:" */
1087     if (g_str_has_prefix (p, VFS_ENCODING_PREFIX))
1088     {
1089         p += strlen (VFS_ENCODING_PREFIX);
1090         p = strchr (p, PATH_SEP);
1091         if (p != NULL)
1092         {
1093             if (!absolute_path && p[1] != '\0')
1094                 p++;
1095 
1096             path = p;
1097         }
1098     }
1099 #endif /* HAVE_CHARSET */
1100 
1101 #ifdef HAVE_REALPATH
1102     return realpath (path, resolved_path);
1103 #else
1104     {
1105         char copy_path[PATH_MAX];
1106         char got_path[PATH_MAX];
1107         char *new_path = got_path;
1108         char *max_path;
1109 #ifdef S_IFLNK
1110         char link_path[PATH_MAX];
1111         int readlinks = 0;
1112         int n;
1113 #endif /* S_IFLNK */
1114 
1115         /* Make a copy of the source path since we may need to modify it. */
1116         if (strlen (path) >= PATH_MAX - 2)
1117         {
1118             errno = ENAMETOOLONG;
1119             return NULL;
1120         }
1121 
1122         strcpy (copy_path, path);
1123         path = copy_path;
1124         max_path = copy_path + PATH_MAX - 2;
1125         /* If it's a relative pathname use getwd for starters. */
1126         if (!IS_PATH_SEP (*path))
1127         {
1128             new_path = g_get_current_dir ();
1129             if (new_path == NULL)
1130                 strcpy (got_path, "");
1131             else
1132             {
1133                 g_snprintf (got_path, sizeof (got_path), "%s", new_path);
1134                 g_free (new_path);
1135                 new_path = got_path;
1136             }
1137 
1138             new_path += strlen (got_path);
1139             if (!IS_PATH_SEP (new_path[-1]))
1140                 *new_path++ = PATH_SEP;
1141         }
1142         else
1143         {
1144             *new_path++ = PATH_SEP;
1145             path++;
1146         }
1147         /* Expand each slash-separated pathname component. */
1148         while (*path != '\0')
1149         {
1150             /* Ignore stray "/". */
1151             if (IS_PATH_SEP (*path))
1152             {
1153                 path++;
1154                 continue;
1155             }
1156             if (*path == '.')
1157             {
1158                 /* Ignore ".". */
1159                 if (path[1] == '\0' || IS_PATH_SEP (path[1]))
1160                 {
1161                     path++;
1162                     continue;
1163                 }
1164                 if (path[1] == '.')
1165                 {
1166                     if (path[2] == '\0' || IS_PATH_SEP (path[2]))
1167                     {
1168                         path += 2;
1169                         /* Ignore ".." at root. */
1170                         if (new_path == got_path + 1)
1171                             continue;
1172                         /* Handle ".." by backing up. */
1173                         while (!IS_PATH_SEP ((--new_path)[-1]))
1174                             ;
1175                         continue;
1176                     }
1177                 }
1178             }
1179             /* Safely copy the next pathname component. */
1180             while (*path != '\0' && !IS_PATH_SEP (*path))
1181             {
1182                 if (path > max_path)
1183                 {
1184                     errno = ENAMETOOLONG;
1185                     return NULL;
1186                 }
1187                 *new_path++ = *path++;
1188             }
1189 #ifdef S_IFLNK
1190             /* Protect against infinite loops. */
1191             if (readlinks++ > MAXSYMLINKS)
1192             {
1193                 errno = ELOOP;
1194                 return NULL;
1195             }
1196             /* See if latest pathname component is a symlink. */
1197             *new_path = '\0';
1198             n = readlink (got_path, link_path, PATH_MAX - 1);
1199             if (n < 0)
1200             {
1201                 /* EINVAL means the file exists but isn't a symlink. */
1202                 if (errno != EINVAL)
1203                 {
1204                     /* Make sure it's null terminated. */
1205                     *new_path = '\0';
1206                     strcpy (resolved_path, got_path);
1207                     return NULL;
1208                 }
1209             }
1210             else
1211             {
1212                 /* Note: readlink doesn't add the null byte. */
1213                 link_path[n] = '\0';
1214                 if (IS_PATH_SEP (*link_path))
1215                     /* Start over for an absolute symlink. */
1216                     new_path = got_path;
1217                 else
1218                     /* Otherwise back up over this component. */
1219                     while (!IS_PATH_SEP (*(--new_path)))
1220                         ;
1221                 /* Safe sex check. */
1222                 if (strlen (path) + n >= PATH_MAX - 2)
1223                 {
1224                     errno = ENAMETOOLONG;
1225                     return NULL;
1226                 }
1227                 /* Insert symlink contents into path. */
1228                 strcat (link_path, path);
1229                 strcpy (copy_path, link_path);
1230                 path = copy_path;
1231             }
1232 #endif /* S_IFLNK */
1233             *new_path++ = PATH_SEP;
1234         }
1235         /* Delete trailing slash but don't whomp a lone slash. */
1236         if (new_path != got_path + 1 && IS_PATH_SEP (new_path[-1]))
1237             new_path--;
1238         /* Make sure it's null terminated. */
1239         *new_path = '\0';
1240         strcpy (resolved_path, got_path);
1241         return resolved_path;
1242     }
1243 #endif /* HAVE_REALPATH */
1244 }
1245 
1246 /* --------------------------------------------------------------------------------------------- */
1247 /**
1248  * Return the index of the permissions triplet
1249  *
1250  */
1251 
1252 int
1253 get_user_permissions (struct stat *st)
     /* [previous][next][first][last][top][bottom][index][help]  */
1254 {
1255     static gboolean initialized = FALSE;
1256     static gid_t *groups;
1257     static int ngroups;
1258     static uid_t uid;
1259     int i;
1260 
1261     if (!initialized)
1262     {
1263         uid = geteuid ();
1264 
1265         ngroups = getgroups (0, NULL);
1266         if (ngroups == -1)
1267             ngroups = 0;        /* ignore errors */
1268 
1269         /* allocate space for one element in addition to what
1270          * will be filled by getgroups(). */
1271         groups = g_new (gid_t, ngroups + 1);
1272 
1273         if (ngroups != 0)
1274         {
1275             ngroups = getgroups (ngroups, groups);
1276             if (ngroups == -1)
1277                 ngroups = 0;    /* ignore errors */
1278         }
1279 
1280         /* getgroups() may or may not return the effective group ID,
1281          * so we always include it at the end of the list. */
1282         groups[ngroups++] = getegid ();
1283 
1284         initialized = TRUE;
1285     }
1286 
1287     if (st->st_uid == uid || uid == 0)
1288         return 0;
1289 
1290     for (i = 0; i < ngroups; i++)
1291         if (st->st_gid == groups[i])
1292             return 1;
1293 
1294     return 2;
1295 }
1296 
1297 /* --------------------------------------------------------------------------------------------- */
1298 /**
1299  * Build filename from arguments.
1300  * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
1301  */
1302 
1303 char *
1304 mc_build_filenamev (const char *first_element, va_list args)
     /* [previous][next][first][last][top][bottom][index][help]  */
1305 {
1306     gboolean absolute;
1307     const char *element = first_element;
1308     GString *path;
1309     char *ret;
1310 
1311     if (element == NULL)
1312         return NULL;
1313 
1314     path = g_string_new ("");
1315 
1316     absolute = IS_PATH_SEP (*first_element);
1317 
1318     do
1319     {
1320         if (*element == '\0')
1321             element = va_arg (args, char *);
1322         else
1323         {
1324             char *tmp_element;
1325             size_t len;
1326             const char *start;
1327 
1328             tmp_element = g_strdup (element);
1329 
1330             element = va_arg (args, char *);
1331 
1332             canonicalize_pathname (tmp_element);
1333             len = strlen (tmp_element);
1334             start = IS_PATH_SEP (tmp_element[0]) ? tmp_element + 1 : tmp_element;
1335 
1336             g_string_append (path, start);
1337             if (!IS_PATH_SEP (tmp_element[len - 1]) && element != NULL)
1338                 g_string_append_c (path, PATH_SEP);
1339 
1340             g_free (tmp_element);
1341         }
1342     }
1343     while (element != NULL);
1344 
1345     if (absolute)
1346         g_string_prepend_c (path, PATH_SEP);
1347 
1348     ret = g_string_free (path, FALSE);
1349     canonicalize_pathname (ret);
1350 
1351     return ret;
1352 }
1353 
1354 /* --------------------------------------------------------------------------------------------- */
1355 /**
1356  * Build filename from arguments.
1357  * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
1358  */
1359 
1360 char *
1361 mc_build_filename (const char *first_element, ...)
     /* [previous][next][first][last][top][bottom][index][help]  */
1362 {
1363     va_list args;
1364     char *ret;
1365 
1366     if (first_element == NULL)
1367         return NULL;
1368 
1369     va_start (args, first_element);
1370     ret = mc_build_filenamev (first_element, args);
1371     va_end (args);
1372     return ret;
1373 }
1374 
1375 /* --------------------------------------------------------------------------------------------- */

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