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