home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 8 / FreshFishVol8-CD2.bin / bbs / gnu / fileutils-3.12-src.lha / fileutils-3.12 / src / rm.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-12  |  13.7 KB  |  543 lines

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