rm(1): Add -x option to prevent recursive rm crossing mount points.
[dragonfly.git] / bin / rm / rm.c
1 /*-
2  * Copyright (c) 1990, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#) Copyright (c) 1990, 1993, 1994 The Regents of the University of California.  All rights reserved.
34  * @(#)rm.c     8.5 (Berkeley) 4/18/94
35  * $FreeBSD: src/bin/rm/rm.c,v 1.29.2.5 2002/07/12 07:25:48 tjr Exp $
36  */
37
38 #include <sys/stat.h>
39 #include <sys/param.h>
40 #include <sys/mount.h>
41 #include <sys/ioctl.h>
42
43 #include <err.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <fts.h>
47 #include <grp.h>
48 #include <pwd.h>
49 #include <signal.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <sysexits.h>
54 #include <unistd.h>
55
56 static int dflag, eval, fflag, iflag, Pflag, vflag, Wflag, stdin_ok;
57 static int rflag, Iflag, xflag;
58 static uid_t uid;
59 volatile sig_atomic_t info;
60
61 static int      check(const char *, const char *, struct stat *);
62 static int      check2(char **);
63 static void     checkdot(char **);
64 static void     rm_file(char **);
65 static int      rm_overwrite(const char *, struct stat *);
66 static void     rm_tree(char **);
67 static void     siginfo(int);
68 static void     usage(void);
69
70 /*
71  * rm --
72  *      This rm is different from historic rm's, but is expected to match
73  *      POSIX 1003.2 behavior.  The most visible difference is that -f
74  *      has two specific effects now, ignore non-existent files and force
75  *      file removal.
76  */
77 int
78 main(int argc, char *argv[])
79 {
80         int ch;
81         const char *p;
82         pid_t tty_pgrp;
83
84         /*
85          * Test for the special case where the utility is called as
86          * "unlink", for which the functionality provided is greatly
87          * simplified.
88          */
89         if ((p = strrchr(argv[0], '/')) == NULL)
90                 p = argv[0];
91         else
92                 ++p;
93         if (strcmp(p, "unlink") == 0) {
94                 while (getopt(argc, argv, "") != -1)
95                         usage();
96                 argc -= optind;
97                 argv += optind;
98                 if (argc != 1)
99                         usage();
100                 rm_file(&argv[0]);
101                 exit(eval);
102         }
103
104         Pflag = rflag = xflag = 0;
105         while ((ch = getopt(argc, argv, "dfiIPRrvWx")) != -1) {
106                 switch(ch) {
107                 case 'd':
108                         dflag = 1;
109                         break;
110                 case 'f':
111                         fflag = 1;
112                         iflag = 0;
113                         break;
114                 case 'i':
115                         fflag = 0;
116                         iflag = 1;
117                         break;
118                 case 'I':
119                         /*
120                          * The -I flag is intended to be generally aliasable
121                          * in /etc/csh.cshrc.  We apply it only to foreground
122                          * processes.
123                          */
124                         if (ioctl(0, TIOCGPGRP, &tty_pgrp) == 0) {
125                                 if (tty_pgrp == getpgrp())
126                                         Iflag = 1;
127                         }
128                         break;
129                 case 'P':
130                         Pflag = 1;
131                         break;
132                 case 'R':
133                 case 'r':                       /* Compatibility. */
134                         rflag = 1;
135                         break;
136                 case 'v':
137                         vflag = 1;
138                         break;
139                 case 'W':
140                         Wflag = 1;
141                         break;
142                 case 'x':
143                         xflag = 1;
144                         break;
145                 default:
146                         usage();
147                 }
148         }
149         argc -= optind;
150         argv += optind;
151
152         if (argc < 1) {
153                 if (fflag)
154                         return 0;
155                 usage();
156         }
157
158         checkdot(argv);
159         uid = geteuid();
160         
161         signal(SIGINFO, siginfo);
162
163         if (*argv) {
164                 stdin_ok = isatty(STDIN_FILENO);
165
166                 if (Iflag && !iflag) {
167                         if (check2(argv) == 0)
168                                 exit (1);
169                 }
170                 if (rflag)
171                         rm_tree(argv);
172                 else
173                         rm_file(argv);
174         }
175
176         exit (eval);
177 }
178
179 static void
180 rm_tree(char **argv)
181 {
182         FTS *fts;
183         FTSENT *p;
184         int needstat;
185         int flags;
186         int rval;
187
188         /*
189          * Remove a file hierarchy.  If forcing removal (-f), or interactive
190          * (-i) or can't ask anyway (stdin_ok), don't stat the file.
191          */
192         needstat = !uid || (!fflag && !iflag && stdin_ok);
193
194         /*
195          * If the -i option is specified, the user can skip on the pre-order
196          * visit.  The fts_number field flags skipped directories.
197          */
198 #define SKIPPED 1
199
200         flags = FTS_PHYSICAL;
201         if (!needstat)
202                 flags |= FTS_NOSTAT;
203         if (Wflag)
204                 flags |= FTS_WHITEOUT;
205         if (xflag)
206                 flags |= FTS_XDEV;
207         if ((fts = fts_open(argv, flags, NULL)) == NULL) {
208                 if (fflag && errno == ENOENT)
209                         return;
210                 err(1, NULL);
211         }
212         while ((p = fts_read(fts)) != NULL) {
213                 switch (p->fts_info) {
214                 case FTS_DNR:
215                         if (!fflag || p->fts_errno != ENOENT) {
216                                 warnx("%s: %s",
217                                     p->fts_path, strerror(p->fts_errno));
218                                 eval = 1;
219                         }
220                         continue;
221                 case FTS_ERR:
222                         errx(1, "%s: %s", p->fts_path, strerror(p->fts_errno));
223                 case FTS_NS:
224                        /*
225                         * Assume that since fts_read() couldn't stat
226                         * the file, it can't be unlinked.
227                         */
228                         if (!needstat)
229                                 break;
230                         if (!fflag || p->fts_errno != ENOENT) {
231                                 warnx("%s: %s",
232                                     p->fts_path, strerror(p->fts_errno));
233                                 eval = 1;
234                         }
235                         continue;
236                 case FTS_D:
237                         /* Pre-order: give user chance to skip. */
238                         if (!fflag && !check(p->fts_path, p->fts_accpath,
239                             p->fts_statp)) {
240                                 fts_set(fts, p, FTS_SKIP);
241                                 p->fts_number = SKIPPED;
242                         }
243                         else if (!uid &&
244                                  (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
245                                  !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
246                                  lchflags(p->fts_accpath,
247                                          p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE)) < 0)
248                                 goto err;
249                         continue;
250                 case FTS_DP:
251                         /* Post-order: see if user skipped. */
252                         if (p->fts_number == SKIPPED)
253                                 continue;
254                         break;
255                 default:
256                         if (!fflag &&
257                             !check(p->fts_path, p->fts_accpath, p->fts_statp))
258                                 continue;
259                 }
260
261                 if (info) {
262                         info = 0;
263                         fprintf(stderr, "Currently removing: %s\n", p->fts_path);
264                 }
265
266                 rval = 0;
267                 if (!uid &&
268                     (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
269                     !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)))
270                         rval = lchflags(p->fts_accpath,
271                                        p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
272
273                 if (rval == 0) {
274                         /*
275                          * If we can't read or search the directory, may still be
276                          * able to remove it.  Don't print out the un{read,search}able
277                          * message unless the remove fails.
278                          */
279                         switch (p->fts_info) {
280                         case FTS_DP:
281                         case FTS_DNR:
282                                 rval = rmdir(p->fts_accpath);
283                                 if (rval == 0 || (fflag && errno == ENOENT)) {
284                                         if (rval == 0 && vflag)
285                                                 printf("%s\n",
286                                                     p->fts_path);
287                                         continue;
288                                 }
289                                 break;
290
291                         case FTS_W:
292                                 rval = undelete(p->fts_accpath);
293                                 if (rval == 0 && (fflag && errno == ENOENT)) {
294                                         if (vflag)
295                                                 printf("%s\n",
296                                                     p->fts_path);
297                                         continue;
298                                 }
299                                 break;
300
301                         case FTS_NS:
302                         /*
303                          * Assume that since fts_read() couldn't stat
304                          * the file, it can't be unlinked.
305                          */
306                                 if (fflag)
307                                         continue;
308                                 /* FALLTHROUGH */
309                         default:
310                                 if (Pflag)
311                                         if (!rm_overwrite(p->fts_accpath, NULL))
312                                                 continue;
313                                 rval = unlink(p->fts_accpath);
314                                 if (rval == 0 || (fflag && errno == ENOENT)) {
315                                         if (rval == 0 && vflag)
316                                                 printf("%s\n",
317                                                     p->fts_path);
318                                         continue;
319                                 }
320                         }
321                 }
322 err:
323                 warn("%s", p->fts_path);
324                 eval = 1;
325         }
326         if (errno)
327                 err(1, "fts_read");
328         fts_close(fts);
329 }
330
331 static void
332 rm_file(char **argv)
333 {
334         struct stat sb;
335         int rval;
336         const char *f;
337
338         /*
339          * Remove a file.  POSIX 1003.2 states that, by default, attempting
340          * to remove a directory is an error, so must always stat the file.
341          */
342         while ((f = *argv++) != NULL) {
343                 if (info) {
344                         info = 0;
345                         fprintf(stderr, "Currently removing: %s\n", f);
346                 }
347
348                 /* Assume if can't stat the file, can't unlink it. */
349                 if (lstat(f, &sb)) {
350                         if (Wflag) {
351                                 sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR;
352                         } else {
353                                 if (!fflag || errno != ENOENT) {
354                                         warn("%s", f);
355                                         eval = 1;
356                                 }
357                                 continue;
358                         }
359                 } else if (Wflag) {
360                         warnx("%s: %s", f, strerror(EEXIST));
361                         eval = 1;
362                         continue;
363                 }
364
365                 if (S_ISDIR(sb.st_mode) && !dflag) {
366                         warnx("%s: is a directory", f);
367                         eval = 1;
368                         continue;
369                 }
370                 if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb))
371                         continue;
372                 rval = 0;
373                 if (!uid &&
374                     (sb.st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
375                     !(sb.st_flags & (SF_APPEND|SF_IMMUTABLE)))
376                         rval = lchflags(f, sb.st_flags & ~(UF_APPEND|UF_IMMUTABLE));
377                 if (rval == 0) {
378                         if (S_ISWHT(sb.st_mode))
379                                 rval = undelete(f);
380                         else if (S_ISDIR(sb.st_mode))
381                                 rval = rmdir(f);
382                         else {
383                                 if (Pflag)
384                                         if (!rm_overwrite(f, &sb))
385                                                 continue;
386                                 rval = unlink(f);
387                         }
388                 }
389                 if (rval && (!fflag || errno != ENOENT)) {
390                         warn("%s", f);
391                         eval = 1;
392                 }
393                 if (vflag && rval == 0)
394                         printf("%s\n", f);
395         }
396 }
397
398 /*
399  * rm_overwrite --
400  *      Overwrite the file 3 times with varying bit patterns.
401  *
402  * XXX
403  * This is a cheap way to *really* delete files.  Note that only regular
404  * files are deleted, directories (and therefore names) will remain.
405  * Also, this assumes a fixed-block filesystem (like FFS, or a V7 or a
406  * System V filesystem).  In a logging filesystem, you'll have to have
407  * kernel support.
408  */
409 static int 
410 rm_overwrite(const char *file, struct stat *sbp)
411 {
412         struct stat sb;
413         struct statfs fsb;
414         off_t len;
415         int bsize, fd, wlen;
416         char *buf = NULL;
417
418         fd = -1;
419         if (sbp == NULL) {
420                 if (lstat(file, &sb))
421                         goto err;
422                 sbp = &sb;
423         }
424         if (!S_ISREG(sbp->st_mode)) {
425                 warnx("%s: cannot overwrite a non-regular file", file);
426                 return (1);
427         }
428         if (sbp->st_nlink > 1) {
429                 warnx("%s (inode %ju): not overwritten due to multiple links",
430                       file, (uintmax_t)sbp->st_ino);
431                 return (0);
432         }
433         if ((fd = open(file, O_WRONLY, 0)) == -1)
434                 goto err;
435         if (fstatfs(fd, &fsb) == -1)
436                 goto err;
437         bsize = MAX(fsb.f_iosize, 1024);
438         if ((buf = malloc(bsize)) == NULL)
439                 err(1, "%s malloc failed", file);
440
441 #define PASS(byte) {                                                    \
442         memset(buf, byte, bsize);                                       \
443         for (len = sbp->st_size; len > 0; len -= wlen) {                \
444                 wlen = len < bsize ? len : bsize;                       \
445                 if (write(fd, buf, wlen) != wlen)                       \
446                         goto err;                                       \
447         }                                                               \
448 }
449         PASS(0xff);
450         if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
451                 goto err;
452         PASS(0x00);
453         if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
454                 goto err;
455         PASS(0xff);
456         if (!fsync(fd) && !close(fd)) {
457                 free(buf);
458                 return (1);
459         }
460
461 err:    eval = 1;
462         if (buf)
463                 free(buf);
464         if (fd != -1)
465                 close(fd);
466         warn("%s", file);
467         return (0);
468 }
469
470
471 static int
472 check(const char *path, const char *name, struct stat *sp)
473 {
474         static int perm_answer = -1;
475         struct choice {
476                 int ch;
477                 const char *str;
478                 int res;
479                 int perm;
480         } *choice, choices[] = {
481                 { 'y', "yes"   , 1, 0 },
482                 { 'n', "no"    , 0, 0 },
483                 { 'a', "always", 1, 1 },
484                 { 'v', "never" , 0, 1 },
485                 { 0, NULL, 0, 0 }
486         };
487         char modep[15], *flagsp;
488
489         if (perm_answer != -1)
490                 return (perm_answer);
491
492         /* Check -i first. */
493         if (iflag)
494                 fprintf(stderr, "remove %s? ", path);
495         else {
496                 /*
497                  * If it's not a symbolic link and it's unwritable and we're
498                  * talking to a terminal, ask.  Symbolic links are excluded
499                  * because their permissions are meaningless.  Check stdin_ok
500                  * first because we may not have stat'ed the file.
501                  * Also skip this check if the -P option was specified because
502                  * we will not be able to overwrite file contents and will
503                  * barf later.
504                  */
505                 if (!stdin_ok || S_ISLNK(sp->st_mode) || Pflag ||
506                     (!access(name, W_OK) &&
507                     !(sp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
508                     (!(sp->st_flags & (UF_APPEND|UF_IMMUTABLE)) || !uid)))
509                         return (1);
510                 strmode(sp->st_mode, modep);
511                 if ((flagsp = fflagstostr(sp->st_flags)) == NULL)
512                         err(1, NULL);
513                 fprintf(stderr, "override %s%s%s/%s %s%sfor %s? ",
514                     modep + 1, modep[9] == ' ' ? "" : " ",
515                     user_from_uid(sp->st_uid, 0),
516                     group_from_gid(sp->st_gid, 0),
517                     *flagsp ? flagsp : "", *flagsp ? " " : "",
518                     path);
519                 free(flagsp);
520         }
521         fflush(stderr);
522
523         for (;;) {
524                 size_t len;
525                 char *answer;
526
527                 answer = fgetln(stdin, &len);
528                 /* clearerr(stdin); */
529                 if (answer == NULL)
530                         return (0);
531                 if (answer[len - 1] == '\n')
532                         len--;
533                 if (len == 0)
534                         continue;
535
536                 for (choice = choices; choice->str != NULL; choice++) {
537                         if (len == 1 && choice->ch == answer[0])
538                                 goto valid_choice;
539                         if (strncasecmp(answer, choice->str, len) == 0)
540                                 goto valid_choice;
541                 }
542
543                 fprintf(stderr, "invalid answer, try again (y/n/a/v): ");
544         }
545
546 valid_choice:
547         if (choice->perm)
548                 perm_answer = choice->res;
549         return (choice->res);
550 }
551
552 static int
553 check2(char **argv)
554 {
555         struct stat st;
556         int first;
557         int ch;
558         int fcount = 0;
559         int dcount = 0;
560         int i;
561         const char *dname = NULL;
562
563         for (i = 0; argv[i]; ++i) {
564                 if (lstat(argv[i], &st) == 0) {
565                         if (S_ISDIR(st.st_mode)) {
566                                 ++dcount;
567                                 dname = argv[i];    /* only used if 1 dir */
568                         } else {
569                                 ++fcount;
570                         }
571                 }
572         }
573         first = 0;
574         while (first != 'n' && first != 'N' && first != 'y' && first != 'Y') {
575                 if (dcount && rflag) {
576                         fprintf(stderr, "recursively remove");
577                         if (dcount == 1)
578                                 fprintf(stderr, " %s", dname);
579                         else
580                                 fprintf(stderr, " %d dirs", dcount);
581                         if (fcount == 1)
582                                 fprintf(stderr, " and 1 file");
583                         else if (fcount > 1)
584                                 fprintf(stderr, " and %d files", fcount);
585                 } else if (dcount + fcount > 3) {
586                         fprintf(stderr, "remove %d files", dcount + fcount);
587                 } else {
588                         return(1);
589                 }
590                 fprintf(stderr, "? ");
591                 fflush(stderr);
592
593                 first = ch = getchar();
594                 while (ch != '\n' && ch != EOF)
595                         ch = getchar();
596                 if (ch == EOF)
597                         break;
598         }
599         return (first == 'y' || first == 'Y');
600 }
601
602 #define ISDOT(a)        ((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
603 static void
604 checkdot(char **argv)
605 {
606         char *p, **save, **t;
607         int complained;
608
609         complained = 0;
610         for (t = argv; *t;) {
611                 if ((p = strrchr(*t, '/')) != NULL)
612                         ++p;
613                 else
614                         p = *t;
615                 if (ISDOT(p)) {
616                         if (!complained++)
617                                 warnx("\".\" and \"..\" may not be removed");
618                         eval = 1;
619                         for (save = t; (t[0] = t[1]) != NULL; ++t)
620                                 continue;
621                         t = save;
622                 } else
623                         ++t;
624         }
625 }
626
627 static void
628 usage(void)
629 {
630
631         fprintf(stderr, "%s\n%s\n",
632             "usage: rm [-f | -i] [-dIPRrvWx] file ...",
633             "       unlink file");
634         exit(EX_USAGE);
635 }
636
637 static void
638 siginfo(int notused __unused)
639 {
640         info = 1;
641 }