]> git.cameronkatri.com Git - apple_cmds.git/blob - file_cmds/rm/rm.c
file_cmds: Fix compilation for lower targets
[apple_cmds.git] / file_cmds / 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
34 #include <sys/cdefs.h>
35 #ifndef lint
36 __used static const char copyright[] =
37 "@(#) Copyright (c) 1990, 1993, 1994\n\
38 The Regents of the University of California. All rights reserved.\n";
39 #endif /* not lint */
40
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)rm.c 8.5 (Berkeley) 4/18/94";
44 #else
45 __used static const char rcsid[] =
46 "$FreeBSD: src/bin/rm/rm.c,v 1.33 2001/06/13 15:01:25 ru Exp $";
47 #endif
48 #endif /* not lint */
49
50 #include <sys/stat.h>
51 #include <sys/param.h>
52 #include <sys/mount.h>
53
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 <sysexits.h>
62 #include <unistd.h>
63 #include <locale.h>
64
65 #ifdef __APPLE__
66 #include <removefile.h>
67 #include <pwd.h>
68 #include <grp.h>
69 #include "get_compat.h"
70
71 #ifndef AT_REMOVEDIR_DATALESS
72 #define AT_REMOVEDIR_DATALESS 0x0100 /* Remove a dataless directory without materializing first */
73 #endif
74 #else
75 #define COMPAT_MODE(func, mode) 1
76 #endif
77
78 #if __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ < 140000
79 #include "rpmatch.c"
80 #endif
81
82 int dflag, eval, fflag, iflag, Pflag, vflag, Wflag, stdin_ok;
83 uid_t uid;
84
85 int check __P((char *, char *, struct stat *));
86 int checkdir __P((char *));
87 int yes_or_no __P((void));
88 void checkdot __P((char **));
89 void rm_file __P((char **));
90 void rm_overwrite __P((char *, struct stat *));
91 void rm_tree __P((char **));
92 void usage __P((void));
93
94 /*
95 * rm --
96 * This rm is different from historic rm's, but is expected to match
97 * POSIX 1003.2 behavior. The most visible difference is that -f
98 * has two specific effects now, ignore non-existent files and force
99 * file removal.
100 */
101 int
102 main(argc, argv)
103 int argc;
104 char *argv[];
105 {
106 int ch, rflag;
107 char *p;
108
109 if (argc < 1)
110 usage();
111
112 /*
113 * Test for the special case where the utility is called as
114 * "unlink", for which the functionality provided is greatly
115 * simplified.
116 */
117 if ((p = rindex(argv[0], '/')) == NULL)
118 p = argv[0];
119 else
120 ++p;
121 uid = geteuid();
122 if (strcmp(p, "unlink") == 0) {
123 if (argc == 2) {
124 rm_file(&argv[1]);
125 exit(eval);
126 } else
127 usage();
128 }
129
130 Pflag = rflag = 0;
131 while ((ch = getopt(argc, argv, "dfiPRrvW")) != -1)
132 switch(ch) {
133 case 'd':
134 dflag = 1;
135 break;
136 case 'f':
137 fflag = 1;
138 iflag = 0;
139 break;
140 case 'i':
141 fflag = 0;
142 iflag = 1;
143 break;
144 case 'P':
145 Pflag = 1;
146 break;
147 case 'R':
148 case 'r': /* Compatibility. */
149 rflag = 1;
150 break;
151 case 'v':
152 vflag = 1;
153 break;
154 case 'W':
155 Wflag = 1;
156 break;
157 default:
158 usage();
159 }
160 argc -= optind;
161 argv += optind;
162
163 if (argc < 1) {
164 if (fflag)
165 return 0;
166 usage();
167 }
168
169 checkdot(argv);
170
171 if (*argv) {
172 stdin_ok = isatty(STDIN_FILENO);
173
174 if (rflag)
175 rm_tree(argv);
176 else
177 rm_file(argv);
178 }
179
180 exit (eval);
181 }
182
183 void
184 rm_tree(argv)
185 char **argv;
186 {
187 FTS *fts;
188 FTSENT *p;
189 int needstat;
190 int flags;
191 int rval;
192 int wantConformance = COMPAT_MODE("bin/rm", "unix2003");
193 /*
194 * Remove a file hierarchy. If forcing removal (-f), or interactive
195 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
196 */
197 needstat = !uid || (!fflag && !iflag && stdin_ok);
198
199 /*
200 * If the -i option is specified, the user can skip on the pre-order
201 * visit. The fts_number field flags skipped directories.
202 */
203 #define SKIPPED 1
204
205 flags = FTS_PHYSICAL;
206 if (!needstat)
207 flags |= FTS_NOSTAT;
208 if (Wflag)
209 flags |= FTS_WHITEOUT;
210 if (!(fts = fts_open(argv, flags, NULL))) {
211 if (fflag && errno == ENOENT)
212 return;
213 err(1, NULL);
214 }
215 while ((p = fts_read(fts)) != NULL) {
216 switch (p->fts_info) {
217 case FTS_DNR:
218 if (!fflag || p->fts_errno != ENOENT) {
219 warnx("%s: %s",
220 p->fts_path, strerror(p->fts_errno));
221 eval = 1;
222 }
223 continue;
224 case FTS_ERR:
225 errx(1, "%s: %s", p->fts_path, strerror(p->fts_errno));
226 case FTS_NS:
227 /*
228 * FTS_NS: assume that if can't stat the file, it
229 * can't be unlinked.
230 */
231 if (!needstat)
232 break;
233 if (!fflag || p->fts_errno != ENOENT) {
234 warnx("%s: %s",
235 p->fts_path, strerror(p->fts_errno));
236 eval = 1;
237 }
238 continue;
239 case FTS_D:
240 /* Pre-order: give user chance to skip. */
241 /* In conformance mode the user is prompted to skip processing the contents.
242 * Then the option to delete the dir is presented post-order */
243 if (!fflag &&
244 ( (wantConformance && !checkdir(p->fts_path)) ||
245 (!wantConformance && !check(p->fts_path, p->fts_accpath, p->fts_statp))
246 )
247 ){
248 (void)fts_set(fts, p, FTS_SKIP);
249 p->fts_number = SKIPPED;
250 }
251 else if (!uid &&
252 (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
253 !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
254 chflags(p->fts_accpath,
255 p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE)) < 0)
256 goto err;
257 continue;
258 case FTS_DP:
259 /* Post-order: see if user skipped. */
260 if(p->fts_number == SKIPPED)/*in legacy mode, the user was prompted pre-order */
261 continue;
262 else if(wantConformance)
263 {
264 /* delete directory if force is on, or if user answers Y to prompt */
265 if(fflag || check(p->fts_path, p->fts_accpath, p->fts_statp))
266 break;
267 else
268 continue;
269 }
270 break;
271 default:
272 if (!fflag &&
273 !check(p->fts_path, p->fts_accpath, p->fts_statp))
274 continue;
275 }
276
277 rval = 0;
278 if (!uid &&
279 (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
280 !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)))
281 rval = chflags(p->fts_accpath,
282 p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
283 if (rval == 0) {
284 /*
285 * If we can't read or search the directory, may still be
286 * able to remove it. Don't print out the un{read,search}able
287 * message unless the remove fails.
288 */
289 switch (p->fts_info) {
290 case FTS_DP:
291 case FTS_DNR:
292 #if __APPLE__
293 rval = unlinkat(AT_FDCWD, p->fts_accpath, AT_REMOVEDIR_DATALESS);
294 if (rval == -1 && errno == EINVAL) {
295 /*
296 * Kernel rejected AT_REMOVEDIR_DATALESS?
297 * I guess we fall back on the painful
298 * route (but it's better than failing).
299 */
300 rval = rmdir(p->fts_accpath);
301 }
302 #else
303 rval = rmdir(p->fts_accpath);
304 #endif
305 if (rval == 0 || (fflag && errno == ENOENT)) {
306 if (rval == 0 && vflag)
307 (void)printf("%s\n",
308 p->fts_path);
309 continue;
310 }
311 break;
312
313 case FTS_W:
314 rval = undelete(p->fts_accpath);
315 if (rval == 0 && (fflag && errno == ENOENT)) {
316 if (vflag)
317 (void)printf("%s\n",
318 p->fts_path);
319 continue;
320 }
321 break;
322
323 default:
324 #ifdef __APPLE__
325 if (Pflag) {
326 if (removefile(p->fts_accpath, NULL, REMOVEFILE_SECURE_7_PASS)) /* overwrites and unlinks */
327 eval = rval = 1;
328 } else
329 rval = unlink(p->fts_accpath);
330 #else /* !__APPLE_ */
331 if (Pflag)
332 rm_overwrite(p->fts_accpath, NULL);
333 rval = unlink(p->fts_accpath);
334 #endif /* __APPLE__ */
335 if (rval == 0 || (fflag && errno == ENOENT)) {
336 if (rval == 0 && vflag)
337 (void)printf("%s\n",
338 p->fts_path);
339 continue;
340 }
341 }
342 }
343 err:
344 warn("%s", p->fts_path);
345 eval = 1;
346 }
347 if (errno)
348 err(1, "fts_read");
349 fts_close(fts);
350 }
351
352 void
353 rm_file(argv)
354 char **argv;
355 {
356 struct stat sb;
357 int rval;
358 char *f;
359
360 /*
361 * Remove a file. POSIX 1003.2 states that, by default, attempting
362 * to remove a directory is an error, so must always stat the file.
363 */
364 while ((f = *argv++) != NULL) {
365 /* Assume if can't stat the file, can't unlink it. */
366 if (lstat(f, &sb)) {
367 if (Wflag) {
368 sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR;
369 } else {
370 if (!fflag || errno != ENOENT) {
371 warn("%s", f);
372 eval = 1;
373 }
374 continue;
375 }
376 } else if (Wflag) {
377 warnx("%s: %s", f, strerror(EEXIST));
378 eval = 1;
379 continue;
380 }
381
382 if (S_ISDIR(sb.st_mode) && !dflag) {
383 warnx("%s: is a directory", f);
384 eval = 1;
385 continue;
386 }
387 if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb))
388 continue;
389 rval = 0;
390 if (!uid &&
391 (sb.st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
392 !(sb.st_flags & (SF_APPEND|SF_IMMUTABLE)))
393 rval = chflags(f, sb.st_flags & ~(UF_APPEND|UF_IMMUTABLE));
394 if (rval == 0) {
395 if (S_ISWHT(sb.st_mode))
396 rval = undelete(f);
397 else if (S_ISDIR(sb.st_mode))
398 rval = rmdir(f);
399 else {
400 #ifdef __APPLE__
401 if (Pflag) {
402 if (removefile(f, NULL, REMOVEFILE_SECURE_7_PASS)) /* overwrites and unlinks */
403 eval = rval = 1;
404 } else
405 rval = unlink(f);
406 #else /* !__APPLE__ */
407 if (Pflag)
408 rm_overwrite(f, &sb);
409 rval = unlink(f);
410 #endif /* __APPLE__ */
411 }
412 }
413 if (rval && (!fflag || errno != ENOENT)) {
414 warn("%s", f);
415 eval = 1;
416 }
417 if (vflag && rval == 0)
418 (void)printf("%s\n", f);
419 }
420 }
421
422 /*
423 * rm_overwrite --
424 * Overwrite the file 3 times with varying bit patterns.
425 *
426 * XXX
427 * This is a cheap way to *really* delete files. Note that only regular
428 * files are deleted, directories (and therefore names) will remain.
429 * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
430 * System V file system). In a logging file system, you'll have to have
431 * kernel support.
432 */
433 void
434 rm_overwrite(file, sbp)
435 char *file;
436 struct stat *sbp;
437 {
438 struct stat sb;
439 struct statfs fsb;
440 off_t len;
441 int bsize, fd, wlen;
442 char *buf = NULL;
443
444 if (sbp == NULL) {
445 if (lstat(file, &sb))
446 goto err;
447 sbp = &sb;
448 }
449 if (!S_ISREG(sbp->st_mode))
450 return;
451 if ((fd = open(file, O_WRONLY, 0)) == -1)
452 goto err;
453 if (fstatfs(fd, &fsb) == -1)
454 goto err;
455 bsize = MAX(fsb.f_iosize, 1024);
456 if ((buf = malloc(bsize)) == NULL)
457 err(1, "malloc");
458
459 #define PASS(byte) { \
460 memset(buf, byte, bsize); \
461 for (len = sbp->st_size; len > 0; len -= wlen) { \
462 wlen = len < bsize ? (int)len : bsize; \
463 if (write(fd, buf, wlen) != wlen) \
464 goto err; \
465 } \
466 }
467 PASS(0xff);
468 if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
469 goto err;
470 PASS(0x00);
471 if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
472 goto err;
473 PASS(0xff);
474 if (!fsync(fd) && !close(fd)) {
475 free(buf);
476 return;
477 }
478
479 err: eval = 1;
480 if (buf)
481 free(buf);
482 warn("%s", file);
483 }
484
485 int
486 yes_or_no()
487 {
488 int ch, first;
489 char resp[] = {'\0', '\0'};
490
491 (void)fflush(stderr);
492
493 /* Load user specified locale */
494 setlocale(LC_MESSAGES, "");
495
496 first = ch = getchar();
497 while (ch != '\n' && ch != EOF)
498 ch = getchar();
499
500 /* only care about the first character */
501 resp[0] = first;
502
503 return (rpmatch(resp) == 1);
504 }
505
506 int
507 checkdir(path)
508 char *path;
509 {
510 if(!iflag)
511 return 1; //if not interactive, process directory's contents
512 (void)fprintf(stderr, "examine files in directory %s? ", path);
513 return yes_or_no();
514 }
515
516 int
517 check(path, name, sp)
518 char *path, *name;
519 struct stat *sp;
520 {
521 char modep[15], *flagsp;
522
523 /* Check -i first. */
524 if (iflag)
525 (void)fprintf(stderr, "remove %s? ", path);
526 else {
527 /*
528 * If it's not a symbolic link and it's unwritable and we're
529 * talking to a terminal, ask. Symbolic links are excluded
530 * because their permissions are meaningless. Check stdin_ok
531 * first because we may not have stat'ed the file.
532 */
533 if (!stdin_ok || S_ISLNK(sp->st_mode) ||
534 (!access(name, W_OK) &&
535 !(sp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
536 (!(sp->st_flags & (UF_APPEND|UF_IMMUTABLE)) || !uid)))
537 return (1);
538 strmode(sp->st_mode, modep);
539 if ((flagsp = fflagstostr(sp->st_flags)) == NULL)
540 err(1, NULL);
541 (void)fprintf(stderr, "override %s%s%s/%s %s%sfor %s? ",
542 modep + 1, modep[9] == ' ' ? "" : " ",
543 user_from_uid(sp->st_uid, 0),
544 group_from_gid(sp->st_gid, 0),
545 *flagsp ? flagsp : "", *flagsp ? " " : "",
546 path);
547 free(flagsp);
548 }
549 return yes_or_no();
550 }
551
552
553 #define ISDOT(a) ((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
554 void
555 checkdot(argv)
556 char **argv;
557 {
558 char *p, **save, **t;
559 int complained;
560
561 complained = 0;
562 for (t = argv; *t;) {
563 size_t len = strlen(*t);
564 char truncated[len];
565
566 if ((p = strrchr(*t, '/')) != NULL) {
567 if (p[1] == '\0') { // one or more trailing / -- treat as if not present
568 for (; (p > *t) && (p[-1] == '/');) {
569 len--;
570 p--;
571 }
572 strlcpy(truncated, *t, len);
573 p = strrchr(truncated, '/');
574 if (p) {
575 ++p;
576 } else {
577 p = truncated;
578 }
579 } else {
580 ++p;
581 }
582 } else {
583 p = *t;
584 }
585 if (ISDOT(p)) {
586 if (!complained++)
587 warnx("\".\" and \"..\" may not be removed");
588 eval = 1;
589 for (save = t; (t[0] = t[1]) != NULL; ++t)
590 continue;
591 t = save;
592 } else
593 ++t;
594 }
595 }
596
597 void
598 usage()
599 {
600
601 (void)fprintf(stderr, "%s\n%s\n",
602 "usage: rm [-f | -i] [-dPRrvW] file ...",
603 " unlink file");
604 exit(EX_USAGE);
605 }