rm.c revision 1.27 1 /* $NetBSD: rm.c,v 1.27 2001/09/16 21:24:54 wiz Exp $ */
2
3 /*-
4 * Copyright (c) 1990, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36 #include <sys/cdefs.h>
37 #ifndef lint
38 __COPYRIGHT("@(#) Copyright (c) 1990, 1993, 1994\n\
39 The Regents of the University of California. All rights reserved.\n");
40 #endif /* not lint */
41
42 #ifndef lint
43 #if 0
44 static char sccsid[] = "@(#)rm.c 8.8 (Berkeley) 4/27/95";
45 #else
46 __RCSID("$NetBSD: rm.c,v 1.27 2001/09/16 21:24:54 wiz Exp $");
47 #endif
48 #endif /* not lint */
49
50 #include <sys/types.h>
51 #include <sys/stat.h>
52
53 #include <locale.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <fts.h>
58 #include <grp.h>
59 #include <pwd.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64
65 int dflag, eval, fflag, iflag, Pflag ,stdin_ok, Wflag;
66
67 int check(char *, char *, struct stat *);
68 void checkdot(char **);
69 void rm_file(char **);
70 void rm_overwrite(char *, struct stat *);
71 void rm_tree(char **);
72 void usage(void);
73 int main(int, char *[]);
74
75 /*
76 * For the sake of the `-f' flag, check whether an error number indicates the
77 * failure of an operation due to an non-existent file, either per se (ENOENT)
78 * or because its filename argument was illegal (ENAMETOOLONG, ENOTDIR).
79 */
80 #define NONEXISTENT(x) \
81 ((x) == ENOENT || (x) == ENAMETOOLONG || (x) == ENOTDIR)
82
83 /*
84 * rm --
85 * This rm is different from historic rm's, but is expected to match
86 * POSIX 1003.2 behavior. The most visible difference is that -f
87 * has two specific effects now, ignore non-existent files and force
88 * file removal.
89 */
90 int
91 main(int argc, char *argv[])
92 {
93 int ch, rflag;
94
95 setprogname(argv[0]);
96 (void)setlocale(LC_ALL, "");
97
98 Pflag = rflag = 0;
99 while ((ch = getopt(argc, argv, "dfiPRrW")) != -1)
100 switch(ch) {
101 case 'd':
102 dflag = 1;
103 break;
104 case 'f':
105 fflag = 1;
106 iflag = 0;
107 break;
108 case 'i':
109 fflag = 0;
110 iflag = 1;
111 break;
112 case 'P':
113 Pflag = 1;
114 break;
115 case 'R':
116 case 'r': /* Compatibility. */
117 rflag = 1;
118 break;
119 case 'W':
120 Wflag = 1;
121 break;
122 case '?':
123 default:
124 usage();
125 }
126 argc -= optind;
127 argv += optind;
128
129 if (argc < 1)
130 usage();
131
132 checkdot(argv);
133
134 if (*argv) {
135 stdin_ok = isatty(STDIN_FILENO);
136
137 if (rflag)
138 rm_tree(argv);
139 else
140 rm_file(argv);
141 }
142
143 exit(eval);
144 /* NOTREACHED */
145 }
146
147 void
148 rm_tree(char **argv)
149 {
150 FTS *fts;
151 FTSENT *p;
152 int flags, needstat;
153
154 /*
155 * Remove a file hierarchy. If forcing removal (-f), or interactive
156 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
157 */
158 needstat = !fflag && !iflag && stdin_ok;
159
160 /*
161 * If the -i option is specified, the user can skip on the pre-order
162 * visit. The fts_number field flags skipped directories.
163 */
164 #define SKIPPED 1
165
166 flags = FTS_PHYSICAL;
167 if (!needstat)
168 flags |= FTS_NOSTAT;
169 if (Wflag)
170 flags |= FTS_WHITEOUT;
171 if (!(fts = fts_open(argv, flags,
172 (int (*) __P((const FTSENT **, const FTSENT **)))NULL)))
173 err(1, NULL);
174 while ((p = fts_read(fts)) != NULL) {
175 switch (p->fts_info) {
176 case FTS_DNR:
177 if (!fflag || p->fts_errno != ENOENT) {
178 warnx("%s: %s",
179 p->fts_path, strerror(p->fts_errno));
180 eval = 1;
181 }
182 continue;
183 case FTS_ERR:
184 errx(1, "%s: %s", p->fts_path, strerror(p->fts_errno));
185 /* NOTREACHED */
186 case FTS_NS:
187 /*
188 * FTS_NS: assume that if can't stat the file, it
189 * can't be unlinked.
190 */
191 if (!needstat)
192 break;
193 if (!fflag || !NONEXISTENT(p->fts_errno)) {
194 warnx("%s: %s",
195 p->fts_path, strerror(p->fts_errno));
196 eval = 1;
197 }
198 continue;
199 case FTS_D:
200 /* Pre-order: give user chance to skip. */
201 if (!fflag && !check(p->fts_path, p->fts_accpath,
202 p->fts_statp)) {
203 (void)fts_set(fts, p, FTS_SKIP);
204 p->fts_number = SKIPPED;
205 }
206 continue;
207 case FTS_DP:
208 /* Post-order: see if user skipped. */
209 if (p->fts_number == SKIPPED)
210 continue;
211 break;
212 default:
213 if (!fflag &&
214 !check(p->fts_path, p->fts_accpath, p->fts_statp))
215 continue;
216 }
217
218 /*
219 * If we can't read or search the directory, may still be
220 * able to remove it. Don't print out the un{read,search}able
221 * message unless the remove fails.
222 */
223 switch (p->fts_info) {
224 case FTS_DP:
225 case FTS_DNR:
226 if (!rmdir(p->fts_accpath) ||
227 (fflag && errno == ENOENT))
228 continue;
229 break;
230
231 case FTS_W:
232 if (!undelete(p->fts_accpath) ||
233 (fflag && errno == ENOENT))
234 continue;
235 break;
236
237 default:
238 if (Pflag)
239 rm_overwrite(p->fts_accpath, NULL);
240 if (!unlink(p->fts_accpath) ||
241 (fflag && NONEXISTENT(errno)))
242 continue;
243 }
244 warn("%s", p->fts_path);
245 eval = 1;
246 }
247 if (errno)
248 err(1, "fts_read");
249 }
250
251 void
252 rm_file(char **argv)
253 {
254 struct stat sb;
255 int rval;
256 char *f;
257
258 /*
259 * Remove a file. POSIX 1003.2 states that, by default, attempting
260 * to remove a directory is an error, so must always stat the file.
261 */
262 while ((f = *argv++) != NULL) {
263 /* Assume if can't stat the file, can't unlink it. */
264 if (lstat(f, &sb)) {
265 if (Wflag) {
266 sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR;
267 } else {
268 if (!fflag || !NONEXISTENT(errno)) {
269 warn("%s", f);
270 eval = 1;
271 }
272 continue;
273 }
274 } else if (Wflag) {
275 warnx("%s: %s", f, strerror(EEXIST));
276 eval = 1;
277 continue;
278 }
279
280 if (S_ISDIR(sb.st_mode) && !dflag) {
281 warnx("%s: is a directory", f);
282 eval = 1;
283 continue;
284 }
285 if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb))
286 continue;
287 if (S_ISWHT(sb.st_mode))
288 rval = undelete(f);
289 else if (S_ISDIR(sb.st_mode))
290 rval = rmdir(f);
291 else {
292 if (Pflag)
293 rm_overwrite(f, &sb);
294 rval = unlink(f);
295 }
296 if (rval && (!fflag || !NONEXISTENT(errno))) {
297 warn("%s", f);
298 eval = 1;
299 }
300 }
301 }
302
303 /*
304 * rm_overwrite --
305 * Overwrite the file 3 times with varying bit patterns.
306 *
307 * XXX
308 * This is a cheap way to *really* delete files. Note that only regular
309 * files are deleted, directories (and therefore names) will remain.
310 * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
311 * System V file system). In a logging file system, you'll have to have
312 * kernel support.
313 */
314 void
315 rm_overwrite(char *file, struct stat *sbp)
316 {
317 struct stat sb;
318 off_t len;
319 int fd, wlen;
320 char buf[8 * 1024];
321
322 fd = -1;
323 if (sbp == NULL) {
324 if (lstat(file, &sb))
325 goto err;
326 sbp = &sb;
327 }
328 if (!S_ISREG(sbp->st_mode))
329 return;
330 if ((fd = open(file, O_WRONLY, 0)) == -1)
331 goto err;
332
333 #define PASS(byte) { \
334 memset(buf, byte, sizeof(buf)); \
335 for (len = sbp->st_size; len > 0; len -= wlen) { \
336 wlen = len < sizeof(buf) ? len : sizeof(buf); \
337 if (write(fd, buf, wlen) != wlen) \
338 goto err; \
339 } \
340 }
341 PASS(0xff);
342 if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
343 goto err;
344 PASS(0x00);
345 if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
346 goto err;
347 PASS(0xff);
348 if (!fsync(fd) && !close(fd))
349 return;
350
351 err: eval = 1;
352 warn("%s", file);
353 }
354
355
356 int
357 check(char *path, char *name, struct stat *sp)
358 {
359 int ch, first;
360 char modep[15];
361
362 /* Check -i first. */
363 if (iflag)
364 (void)fprintf(stderr, "remove %s? ", path);
365 else {
366 /*
367 * If it's not a symbolic link and it's unwritable and we're
368 * talking to a terminal, ask. Symbolic links are excluded
369 * because their permissions are meaningless. Check stdin_ok
370 * first because we may not have stat'ed the file.
371 */
372 if (!stdin_ok || S_ISLNK(sp->st_mode) ||
373 !(access(name, W_OK) && (errno != ETXTBSY)))
374 return (1);
375 strmode(sp->st_mode, modep);
376 (void)fprintf(stderr, "override %s%s%s/%s for %s? ",
377 modep + 1, modep[9] == ' ' ? "" : " ",
378 user_from_uid(sp->st_uid, 0),
379 group_from_gid(sp->st_gid, 0), path);
380 }
381 (void)fflush(stderr);
382
383 first = ch = getchar();
384 while (ch != '\n' && ch != EOF)
385 ch = getchar();
386 return (first == 'y' || first == 'Y');
387 }
388
389 /*
390 * POSIX.2 requires that if "." or ".." are specified as the basename
391 * portion of an operand, a diagnostic message be written to standard
392 * error and nothing more be done with such operands.
393 *
394 * Since POSIX.2 defines basename as the final portion of a path after
395 * trailing slashes have been removed, we'll remove them here.
396 */
397 #define ISDOT(a) ((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
398 void
399 checkdot(char **argv)
400 {
401 char *p, **save, **t;
402 int complained;
403
404 complained = 0;
405 for (t = argv; *t;) {
406 /* strip trailing slashes */
407 p = strrchr (*t, '\0');
408 while (--p > *t && *p == '/')
409 *p = '\0';
410
411 /* extract basename */
412 if ((p = strrchr(*t, '/')) != NULL)
413 ++p;
414 else
415 p = *t;
416
417 if (ISDOT(p)) {
418 if (!complained++)
419 warnx("\".\" and \"..\" may not be removed");
420 eval = 1;
421 for (save = t; (t[0] = t[1]) != NULL; ++t)
422 continue;
423 t = save;
424 } else
425 ++t;
426 }
427 }
428
429 void
430 usage(void)
431 {
432 (void)fprintf(stderr, "usage: %s [-dfiPRrW] file ...\n", getprogname());
433 exit(1);
434 /* NOTREACHED */
435 }
436