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