home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 2 / FFMCD02.bin / useful / dist / gnu / fileutils / fileutils-3.9-amiga / src / rm.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-12-13  |  13.9 KB  |  550 lines

  1. /* `rm' file deletion utility for GNU.
  2.    Copyright (C) 1988, 1990, 1991 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by Paul Rubin, David MacKenzie, and Richard Stallman. */
  19.  
  20. #ifdef HAVE_CONFIG_H
  21. #if defined (CONFIG_BROKETS)
  22. /* We use <config.h> instead of "config.h" so that a compilation
  23.    using -I. -I$srcdir will use ./config.h rather than $srcdir/config.h
  24.    (which it would do because it found this file in $srcdir).  */
  25. #include <config.h>
  26. #else
  27. #include "config.h"
  28. #endif
  29. #endif
  30.  
  31. #include <stdio.h>
  32. #include <getopt.h>
  33. #include <sys/types.h>
  34. #include "system.h"
  35. #include "version.h"
  36.  
  37. #ifdef _POSIX_SOURCE
  38. /* POSIX.1 doesn't have inodes, so fake them to avoid lots of ifdefs. */
  39. #define ino_t unsigned long
  40. #define D_INO(dp) 1
  41. #else
  42. #define D_INO(dp) ((dp)->d_ino)
  43. #endif
  44.  
  45. char *basename ();
  46. char *stpcpy ();
  47. char *xmalloc ();
  48. char *xrealloc ();
  49. int eaccess_stat ();
  50. int yesno ();
  51. void error ();
  52. void strip_trailing_slashes ();
  53.  
  54. static int clear_directory ();
  55. static int duplicate_entry ();
  56. static int remove_dir ();
  57. static int remove_file ();
  58. static int rm ();
  59. static void usage ();
  60.  
  61. /* Name this program was run with.  */
  62. char *program_name;
  63.  
  64. /* Path of file now being processed; extended as necessary. */
  65. static char *pathname;
  66.  
  67. /* Number of bytes currently allocated for `pathname';
  68.    made larger when necessary, but never smaller.  */
  69. static int pnsize;
  70.  
  71. /* If nonzero, display the name of each file removed. */
  72. static int verbose;
  73.  
  74. /* If nonzero, ignore nonexistant files. */
  75. static int ignore_missing_files;
  76.  
  77. /* If nonzero, recursively remove directories. */
  78. static int recursive;
  79.  
  80. /* If nonzero, query the user about whether to remove each file. */
  81. static int interactive;
  82.  
  83. /* If nonzero, remove directories with unlink instead of rmdir, and don't
  84.    require a directory to be empty before trying to unlink it.
  85.    Only works for the super-user. */
  86. static int unlink_dirs;
  87.  
  88. /* If nonzero, stdin is a tty. */
  89. static int stdin_tty;
  90.  
  91. /* If non-zero, display usage information and exit.  */
  92. static int show_help;
  93.  
  94. /* If non-zero, print the version on standard output and exit.  */
  95. static int show_version;
  96.  
  97. static struct option const long_opts[] =
  98. {
  99.   {"directory", no_argument, &unlink_dirs, 1},
  100.   {"force", no_argument, NULL, 'f'},
  101.   {"interactive", no_argument, NULL, 'i'},
  102.   {"recursive", no_argument, &recursive, 1},
  103.   {"verbose", no_argument, &verbose, 1},
  104.   {"help", no_argument, &show_help, 1},
  105.   {"version", no_argument, &show_version, 1},
  106.   {NULL, 0, NULL, 0}
  107. };
  108.  
  109. main (argc, argv)
  110.      int argc;
  111.      char **argv;
  112. {
  113.   int err = 0;
  114.   int c;
  115.  
  116.   verbose = ignore_missing_files = recursive = interactive
  117.     = unlink_dirs = 0;
  118.   pnsize = 256;
  119.   pathname = xmalloc (pnsize);
  120.   program_name = argv[0];
  121.  
  122.   while ((c = getopt_long (argc, argv, "dfirvR", long_opts, (int *) 0)) != EOF)
  123.     {
  124.       switch (c)
  125.     {
  126.     case 0:        /* Long option. */
  127.       break;
  128.     case 'd':
  129.       unlink_dirs = 1;
  130.       break;
  131.     case 'f':
  132.       interactive = 0;
  133.       ignore_missing_files = 1;
  134.       break;
  135.     case 'i':
  136.       interactive = 1;
  137.       ignore_missing_files = 0;
  138.       break;
  139.     case 'r':
  140.     case 'R':
  141.       recursive = 1;
  142.       break;
  143.     case 'v':
  144.       verbose = 1;
  145.       break;
  146.     default:
  147.       usage (1);
  148.     }
  149.     }
  150.  
  151.   if (show_version)
  152.     {
  153.       printf ("%s\n", version_string);
  154.       exit (0);
  155.     }
  156.  
  157.   if (show_help)
  158.     usage (0);
  159.  
  160.   if (optind == argc)
  161.     {
  162.       if (ignore_missing_files)
  163.     exit (0);
  164.       else
  165.     usage (1);
  166.     }
  167.  
  168.   stdin_tty = isatty (0);
  169.  
  170.   for (; optind < argc; optind++)
  171.     {
  172.       int len;
  173.  
  174.       /* Stripping slashes is harmless for rmdir;
  175.      if the arg is not a directory, it will fail with ENOTDIR.  */
  176.       strip_trailing_slashes (argv[optind]);
  177.       len = strlen (argv[optind]);
  178.       if (len + 1 > pnsize)
  179.     {
  180.       free (pathname);
  181.       pnsize = 2 * (len + 1);
  182.       pathname = xmalloc (pnsize);
  183.     }
  184.       strcpy (pathname, argv[optind]);
  185.       err += rm ();
  186.     }
  187.  
  188.   exit (err > 0);
  189. }
  190.  
  191. /* Remove file or directory `pathname' after checking appropriate things.
  192.    Return 0 if `pathname' is removed, 1 if not. */
  193.  
  194. static int
  195. rm ()
  196. {
  197.   struct stat path_stats;
  198.   char *base = basename (pathname);
  199.  
  200.   if (base[0] == '.' && (base[1] == '\0'
  201.                  || (base[1] == '.' && base[2] == '\0')))
  202.     {
  203.       error (0, 0, "cannot remove `.' or `..'");
  204.       return 1;
  205.     }
  206.  
  207.   if (lstat (pathname, &path_stats))
  208.     {
  209.       if (errno == ENOENT && ignore_missing_files)
  210.     return 0;
  211.       error (0, errno, "%s", pathname);
  212.       return 1;
  213.     }
  214.  
  215.   if (S_ISDIR (path_stats.st_mode) && !unlink_dirs)
  216.     return remove_dir (&path_stats);
  217.   else
  218.     return remove_file (&path_stats);
  219. }
  220.  
  221. /* Query the user if appropriate, and if ok try to remove the
  222.    non-directory `pathname', which STATP contains info about.
  223.    Return 0 if `pathname' is removed, 1 if not. */
  224.  
  225. static int
  226. remove_file (statp)
  227.      struct stat *statp;
  228. {
  229.   if (!ignore_missing_files && (interactive || stdin_tty)
  230.       && eaccess_stat (statp, W_OK)
  231. #ifdef S_ISLNK
  232.       && !S_ISLNK (statp->st_mode)
  233. #endif
  234.       )
  235.     {
  236.       fprintf (stderr, "%s: remove %s`%s', overriding mode %04o? ",
  237.            program_name,
  238.            S_ISDIR (statp->st_mode) ? "directory " : "",
  239.            pathname,
  240.            (unsigned int) (statp->st_mode & 07777));
  241.       if (!yesno ())
  242.     return 1;
  243.     }
  244.   else if (interactive)
  245.     {
  246.       fprintf (stderr, "%s: remove %s`%s'? ", program_name,
  247.            S_ISDIR (statp->st_mode) ? "directory " : "",
  248.            pathname);
  249.       if (!yesno ())
  250.     return 1;
  251.     }
  252.  
  253.   if (verbose)
  254.     printf ("%s\n", pathname);
  255.  
  256.   if (unlink (pathname) && (errno != ENOENT || !ignore_missing_files))
  257.     {
  258.       error (0, errno, "%s", pathname);
  259.       return 1;
  260.     }
  261.   return 0;
  262. }
  263.  
  264. /* If not in recursive mode, print an error message and return 1.
  265.    Otherwise, query the user if appropriate, then try to recursively
  266.    remove directory `pathname', which STATP contains info about.
  267.    Return 0 if `pathname' is removed, 1 if not. */
  268.  
  269. static int
  270. remove_dir (statp)
  271.      struct stat *statp;
  272. {
  273.   int err;
  274.  
  275.   if (!recursive)
  276.     {
  277.       error (0, 0, "%s: is a directory", pathname);
  278.       return 1;
  279.     }
  280.  
  281.   if (!ignore_missing_files && (interactive || stdin_tty)
  282.       && eaccess_stat (statp, W_OK))
  283.     {
  284.       fprintf (stderr,
  285.            "%s: descend directory `%s', overriding mode %04o? ",
  286.            program_name, pathname,
  287.            (unsigned int) (statp->st_mode & 07777));
  288.       if (!yesno ())
  289.     return 1;
  290.     }
  291.   else if (interactive)
  292.     {
  293.       fprintf (stderr, "%s: descend directory `%s'? ",
  294.            program_name, pathname);
  295.       if (!yesno ())
  296.     return 1;
  297.     }
  298.  
  299.   if (verbose)
  300.     printf ("%s\n", pathname);
  301.  
  302.   err = clear_directory (statp);
  303.  
  304.   if (interactive)
  305.     {
  306.       if (err)
  307.     fprintf (stderr, "%s: remove directory `%s' (might be nonempty)? ",
  308.          program_name, pathname);
  309.       else
  310.     fprintf (stderr, "%s: remove directory `%s'? ",
  311.          program_name, pathname);
  312.       if (!yesno ())
  313.     return 1;
  314.     }
  315.  
  316.   if (rmdir (pathname) && (errno != ENOENT || !ignore_missing_files))
  317.     {
  318.       error (0, errno, "%s", pathname);
  319.       return 1;
  320.     }
  321.   return 0;
  322. }
  323.  
  324. /* An element in a stack of pointers into `pathname'.
  325.    `pathp' points to where in `pathname' the terminating '\0' goes
  326.    for this level's directory name. */
  327. struct pathstack
  328. {
  329.   struct pathstack *next;
  330.   char *pathp;
  331.   ino_t inum;
  332. };
  333.  
  334. /* Linked list of pathnames of directories in progress in recursive rm.
  335.    The entries actually contain pointers into `pathname'.
  336.    `pathstack' is the current deepest level. */
  337. static struct pathstack *pathstack = NULL;
  338.  
  339. /* Read directory `pathname' and remove all of its entries,
  340.    avoiding use of chdir.
  341.    On entry, STATP points to the results of stat on `pathname'.
  342.    Return 0 for success, error count for failure.
  343.    Upon return, `pathname' will have the same contents as before,
  344.    but its address might be different; in that case, `pnsize' will
  345.    be larger, as well. */
  346.  
  347. static int
  348. clear_directory (statp)
  349.      struct stat *statp;
  350. {
  351.   DIR *dirp;
  352.   struct dirent *dp;
  353.   char *name_space;        /* Copy of directory's filenames. */
  354.   char *namep;            /* Current entry in `name_space'. */
  355.   unsigned name_size;        /* Bytes allocated for `name_space'. */
  356.   int name_length;        /* Length of filename in `namep' plus '\0'. */
  357.   int pathname_length;        /* Length of `pathname'. */
  358.   ino_t *inode_space;        /* Copy of directory's inodes. */
  359.   ino_t *inodep;        /* Current entry in `inode_space'. */
  360.   unsigned n_inodes_allocated;    /* There is space for this many inodes
  361.                       in `inode_space'. */
  362.   int err = 0;            /* Return status. */
  363.   struct pathstack pathframe;    /* New top of stack. */
  364.   struct pathstack *pp;        /* Temporary. */
  365.  
  366.   name_size = statp->st_size;
  367.   name_space = (char *) xmalloc (name_size);
  368.  
  369.   n_inodes_allocated = (statp->st_size + sizeof (ino_t) - 1) / sizeof (ino_t);
  370.   inode_space = (ino_t *) xmalloc (n_inodes_allocated * sizeof (ino_t));
  371.  
  372.   do
  373.     {
  374.       namep = name_space;
  375.       inodep = inode_space;
  376.  
  377.       errno = 0;
  378.       dirp = opendir (pathname);
  379.       if (dirp == NULL)
  380.     {
  381.       if (errno != ENOENT || !ignore_missing_files)
  382.         {
  383.           error (0, errno, "%s", pathname);
  384.           err = 1;
  385.         }
  386.       free (name_space);
  387.       free (inode_space);
  388.       return err;
  389.     }
  390.  
  391.       while ((dp = readdir (dirp)) != NULL)
  392.     {
  393.       /* Skip "." and ".." (some NFS filesystems' directories lack them). */
  394.       if (dp->d_name[0] != '.'
  395.           || (dp->d_name[1] != '\0'
  396.           && (dp->d_name[1] != '.' || dp->d_name[2] != '\0')))
  397.         {
  398.           unsigned size_needed = (namep - name_space) + NLENGTH (dp) + 2;
  399.  
  400.           if (size_needed > name_size)
  401.         {
  402.           char *new_name_space;
  403.  
  404.           while (size_needed > name_size)
  405.             name_size += 1024;
  406.  
  407.           new_name_space = xrealloc (name_space, name_size);
  408.           namep += new_name_space - name_space;
  409.           name_space = new_name_space;
  410.         }
  411.           namep = stpcpy (namep, dp->d_name) + 1;
  412.  
  413.           if (inodep == inode_space + n_inodes_allocated)
  414.         {
  415.           ino_t *new_inode_space;
  416.  
  417.           n_inodes_allocated += 1024;
  418.           new_inode_space = (ino_t *) xrealloc (inode_space,
  419.                     n_inodes_allocated * sizeof (ino_t));
  420.           inodep += new_inode_space - inode_space;
  421.           inode_space = new_inode_space;
  422.         }
  423.           *inodep++ = D_INO (dp);
  424.         }
  425.     }
  426.       *namep = '\0';
  427.       if (CLOSEDIR (dirp))
  428.     {
  429.       error (0, errno, "%s", pathname);
  430.       err = 1;
  431.     }
  432.  
  433.       pathname_length = strlen (pathname);
  434.  
  435.       for (namep = name_space, inodep = inode_space; *namep != '\0';
  436.        namep += name_length, inodep++)
  437.     {
  438.       name_length = strlen (namep) + 1;
  439.  
  440.       /* Satisfy GNU requirement that filenames can be arbitrarily long. */
  441.       if (pathname_length + 1 + name_length > pnsize)
  442.         {
  443.           char *new_pathname;
  444.  
  445.           pnsize = (pathname_length + 1 + name_length) * 2;
  446.           new_pathname = xrealloc (pathname, pnsize);
  447.           /* Update the all the pointers in the stack to use the new area. */
  448.           for (pp = pathstack; pp != NULL; pp = pp->next)
  449.         pp->pathp += new_pathname - pathname;
  450.           pathname = new_pathname;
  451.         }
  452.  
  453.       /* Add a new frame to the top of the path stack. */
  454.       pathframe.pathp = pathname + pathname_length;
  455.       pathframe.inum = *inodep;
  456.       pathframe.next = pathstack;
  457.       pathstack = &pathframe;
  458.  
  459.       /* Append '/' and the filename to current pathname, take care of the
  460.          file (which could result in recursive calls), and take the filename
  461.          back off. */
  462.  
  463.       *pathstack->pathp = '/';
  464.       strcpy (pathstack->pathp + 1, namep);
  465.  
  466.       /* If the i-number has already appeared, there's an error. */
  467.       if (duplicate_entry (pathstack->next, pathstack->inum))
  468.         err++;
  469.       else if (rm ())
  470.         err++;
  471.  
  472.       *pathstack->pathp = '\0';
  473.       pathstack = pathstack->next;    /* Pop the stack. */
  474.     }
  475.     }
  476.   /* Keep trying while there are still files to remove. */
  477.   while (namep > name_space && err == 0);
  478.  
  479.   free (name_space);
  480.   free (inode_space);
  481.   return err;
  482. }
  483.  
  484. /* If STACK does not already have an entry with the same i-number as INUM,
  485.    return 0. Otherwise, ask the user whether to continue;
  486.    if yes, return 1, and if no, exit.
  487.    This assumes that no one tries to remove filesystem mount points;
  488.    doing so could cause duplication of i-numbers that would not indicate
  489.    a corrupted file system. */
  490.  
  491. static int
  492. duplicate_entry (stack, inum)
  493.      struct pathstack *stack;
  494.      ino_t inum;
  495. {
  496. #ifndef _POSIX_SOURCE
  497.   struct pathstack *p;
  498.  
  499.   for (p = stack; p != NULL; p = p->next)
  500.     {
  501.       if (p->inum == inum)
  502.     {
  503.       fprintf (stderr, "\
  504. %s: WARNING: Circular directory structure.\n\
  505. This almost certainly means that you have a corrupted file system.\n\
  506. NOTIFY YOUR SYSTEM MANAGER.\n\
  507. Cycle detected:\n\
  508. %s\n\
  509. is the same file as\n", program_name, pathname);
  510.       *p->pathp = '\0';    /* Truncate pathname. */
  511.       fprintf (stderr, "%s\n", pathname);
  512.       *p->pathp = '/';    /* Put it back. */
  513.       if (interactive)
  514.         {
  515.           fprintf (stderr, "%s: continue? ", program_name);
  516.           if (!yesno ())
  517.         exit (1);
  518.           return 1;
  519.         }
  520.       else
  521.         exit (1);
  522.     }
  523.     }
  524. #endif
  525.   return 0;
  526. }
  527.  
  528. static void
  529. usage (status)
  530.      int status;
  531. {
  532.   if (status != 0)
  533.     fprintf (stderr, "Try `%s --help' for more information.\n",
  534.          program_name);
  535.   else
  536.     {
  537.       printf ("Usage: %s [OPTION]... PATH...\n", program_name);
  538.       printf ("\
  539. \n\
  540.   -d, --directory       unlink directory, even if non-empty (super-user only)\n\
  541.   -f, --force           ignore nonexistent files, never prompt\n\
  542.   -i, --interactive     prompt before any removal\n\
  543.   -v, --verbose         explain what is being done\n\
  544.   -r, -R, --recursive   remove the contents of directories recursively\n\
  545.       --help            display this help and exit\n\
  546.       --version         output version information and exit\n");
  547.     }
  548.   exit (status);
  549. }
  550.