]> git.saurik.com Git - apple/file_cmds.git/blob - cp/cp.c
file_cmds-321.100.10.0.1.tar.gz
[apple/file_cmds.git] / cp / cp.c
1 /*-
2 * Copyright (c) 1988, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * David Hitz of Auspex Systems Inc.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33 #if 0
34 #ifndef lint
35 static char const copyright[] =
36 "@(#) Copyright (c) 1988, 1993, 1994\n\
37 The Regents of the University of California. All rights reserved.\n";
38 #endif /* not lint */
39
40 #ifndef lint
41 static char sccsid[] = "@(#)cp.c 8.2 (Berkeley) 4/1/94";
42 #endif /* not lint */
43 #endif
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD: src/bin/cp/cp.c,v 1.52 2005/09/05 04:36:08 csjp Exp $");
46
47 /*
48 * Cp copies source files to target files.
49 *
50 * The global PATH_T structure "to" always contains the path to the
51 * current target file. Since fts(3) does not change directories,
52 * this path can be either absolute or dot-relative.
53 *
54 * The basic algorithm is to initialize "to" and use fts(3) to traverse
55 * the file hierarchy rooted in the argument list. A trivial case is the
56 * case of 'cp file1 file2'. The more interesting case is the case of
57 * 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
58 * path (relative to the root of the traversal) is appended to dir (stored
59 * in "to") to form the final target path.
60 */
61
62 #include <sys/types.h>
63 #include <sys/stat.h>
64
65 #include <err.h>
66 #include <errno.h>
67 #include <fts.h>
68 #include <limits.h>
69 #include <signal.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <unistd.h>
74
75 #ifdef __APPLE__
76 #include <copyfile.h>
77 #include <get_compat.h>
78 #else /* !__APPLE__ */
79 #define COMPAT_MODE(a,b) (1)
80 #endif /* __APPLE__ */
81
82 #include "extern.h"
83
84 #define STRIP_TRAILING_SLASH(p) { \
85 while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/') \
86 *--(p).p_end = 0; \
87 }
88
89 static char emptystring[] = "";
90
91 PATH_T to = { to.p_path, emptystring, "" };
92
93 int fflag, iflag, nflag, pflag, vflag;
94 #ifdef __APPLE__
95 int Xflag;
96 #endif /* __APPLE__ */
97 static int Rflag, rflag;
98 int cflag = 0;
99 volatile sig_atomic_t info;
100
101 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
102
103 static int copy(char *[], enum op, int);
104 static void siginfo(int __unused);
105
106 int
107 main(int argc, char *argv[])
108 {
109 struct stat to_stat, tmp_stat;
110 enum op type;
111 int Hflag, Lflag, Pflag, ch, fts_options, r, have_trailing_slash;
112 char *target;
113
114 Hflag = Lflag = Pflag = 0;
115 while ((ch = getopt(argc, argv, "cHLPRXafinprv")) != -1)
116 switch (ch) {
117 case 'c':
118 cflag = 1;
119 break;
120 case 'H':
121 Hflag = 1;
122 Lflag = Pflag = 0;
123 break;
124 case 'L':
125 Lflag = 1;
126 Hflag = Pflag = 0;
127 break;
128 case 'P':
129 Pflag = 1;
130 Hflag = Lflag = 0;
131 break;
132 case 'R':
133 Rflag = 1;
134 break;
135 case 'X':
136 Xflag = 1;
137 break;
138 case 'f':
139 fflag = 1;
140 /* Determine if the STD is SUSv3 or Legacy */
141 if (COMPAT_MODE("bin/cp", "unix2003"))
142 nflag = 0; /* reset nflag, but not iflag */
143 else
144 iflag = nflag = 0; /* reset both */
145 break;
146 case 'i':
147 iflag = 1;
148 if (COMPAT_MODE("bin/cp", "unix2003"))
149 nflag = 0; /* reset nflag, but not fflag */
150 else
151 fflag = nflag = 0;
152 break;
153 case 'n':
154 nflag = 1;
155 fflag = iflag = 0;
156 break;
157 case 'p':
158 pflag = 1;
159 break;
160 case 'r':
161 rflag = 1;
162 break;
163 case 'v':
164 vflag = 1;
165 break;
166 case 'a':
167 pflag = 1;
168 Pflag = 1;
169 Rflag = 1;
170 break;
171 default:
172 usage();
173 break;
174 }
175 argc -= optind;
176 argv += optind;
177
178 if (argc < 2)
179 usage();
180
181 if (cflag && Xflag) {
182 errx(1, "the -c and -X options may not be specified together");
183 }
184
185 fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
186 if (rflag) {
187 if (Rflag)
188 errx(1,
189 "the -R and -r options may not be specified together.");
190 if (Hflag || Lflag || Pflag)
191 errx(1,
192 "the -H, -L, and -P options may not be specified with the -r option.");
193 fts_options &= ~FTS_PHYSICAL;
194 fts_options |= FTS_LOGICAL;
195 }
196 if (Rflag) {
197 if (Hflag)
198 fts_options |= FTS_COMFOLLOW;
199 if (Lflag) {
200 fts_options &= ~FTS_PHYSICAL;
201 fts_options |= FTS_LOGICAL;
202 }
203 } else {
204 fts_options &= ~FTS_PHYSICAL;
205 fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
206 }
207 (void)signal(SIGINFO, siginfo);
208
209 /* Save the target base in "to". */
210 target = argv[--argc];
211 if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
212 errx(1, "%s: name too long", target);
213 to.p_end = to.p_path + strlen(to.p_path);
214 if (to.p_path == to.p_end) {
215 *to.p_end++ = '.';
216 *to.p_end = 0;
217 }
218 have_trailing_slash = (to.p_end[-1] == '/');
219 if (have_trailing_slash)
220 STRIP_TRAILING_SLASH(to);
221 to.target_end = to.p_end;
222
223 /* Set end of argument list for fts(3). */
224 argv[argc] = NULL;
225
226 /*
227 * Cp has two distinct cases:
228 *
229 * cp [-R] source target
230 * cp [-R] source1 ... sourceN directory
231 *
232 * In both cases, source can be either a file or a directory.
233 *
234 * In (1), the target becomes a copy of the source. That is, if the
235 * source is a file, the target will be a file, and likewise for
236 * directories.
237 *
238 * In (2), the real target is not directory, but "directory/source".
239 */
240 r = stat(to.p_path, &to_stat);
241 if (r == -1 && errno != ENOENT)
242 err(1, "%s", to.p_path);
243 if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
244 /*
245 * Case (1). Target is not a directory.
246 */
247 if (argc > 1) {
248 usage();
249 exit(1);
250 }
251 /*
252 * Need to detect the case:
253 * cp -R dir foo
254 * Where dir is a directory and foo does not exist, where
255 * we want pathname concatenations turned on but not for
256 * the initial mkdir().
257 */
258 if (r == -1) {
259 if (rflag || (Rflag && (Lflag || Hflag)))
260 stat(*argv, &tmp_stat);
261 else
262 lstat(*argv, &tmp_stat);
263
264 if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
265 type = DIR_TO_DNE;
266 else
267 type = FILE_TO_FILE;
268 } else
269 type = FILE_TO_FILE;
270
271 if (have_trailing_slash && type == FILE_TO_FILE) {
272 if (r == -1)
273 errx(1, "directory %s does not exist",
274 to.p_path);
275 else
276 errx(1, "%s is not a directory", to.p_path);
277 }
278 } else
279 /*
280 * Case (2). Target is a directory.
281 */
282 type = FILE_TO_DIR;
283
284 exit (copy(argv, type, fts_options));
285 }
286
287 static int
288 copy(char *argv[], enum op type, int fts_options)
289 {
290 struct stat to_stat;
291 FTS *ftsp;
292 FTSENT *curr;
293 int base = 0, dne, badcp, rval;
294 size_t nlen;
295 char *p, *target_mid;
296 mode_t mask, mode;
297
298 /*
299 * Keep an inverted copy of the umask, for use in correcting
300 * permissions on created directories when not using -p.
301 */
302 mask = ~umask(0777);
303 umask(~mask);
304
305 if ((ftsp = fts_open(argv, fts_options, NULL)) == NULL)
306 err(1, "fts_open");
307 for (badcp = rval = 0; (curr = fts_read(ftsp)) != NULL; badcp = 0) {
308 switch (curr->fts_info) {
309 case FTS_NS:
310 case FTS_DNR:
311 case FTS_ERR:
312 warnx("%s: %s",
313 curr->fts_path, strerror(curr->fts_errno));
314 rval = 1;
315 continue;
316 case FTS_DC: /* Warn, continue. */
317 warnx("%s: directory causes a cycle", curr->fts_path);
318 rval = 1;
319 continue;
320 default:
321 ;
322 }
323 #ifdef __APPLE__
324
325 #ifdef __clang__
326 #pragma clang diagnostic push
327 /* clang doesn't like fts_name[1], but we know better... */
328 #pragma clang diagnostic ignored "-Warray-bounds"
329 #endif
330 /* Skip ._<file> when using copyfile and <file> exists */
331 if ((pflag || !Xflag) && (curr->fts_level != FTS_ROOTLEVEL) &&
332 (curr->fts_namelen > 2) && /* ._\0 is not AppleDouble */
333 (curr->fts_name[0] == '.') && (curr->fts_name[1] == '_')) {
334 #ifdef __clang__
335 #pragma clang diagnostic pop
336 #endif
337 struct stat statbuf;
338 char path[PATH_MAX];
339 char *p = strrchr(curr->fts_path, '/');
340 if (p) {
341 size_t s = p + 2 - curr->fts_path;
342 if (s > sizeof(path)) s = sizeof(path);
343 strlcpy(path, curr->fts_path, s);
344 strlcat(path, curr->fts_name+2, sizeof(path));
345 } else {
346 strlcpy(path, curr->fts_name+2, sizeof(path));
347 }
348 if (!lstat(path, &statbuf)) {
349 continue;
350 }
351 }
352 #endif /* __APPLE__ */
353 /*
354 * If we are in case (2) or (3) above, we need to append the
355 * source name to the target name.
356 */
357 if (type != FILE_TO_FILE) {
358 /*
359 * Need to remember the roots of traversals to create
360 * correct pathnames. If there's a directory being
361 * copied to a non-existent directory, e.g.
362 * cp -R a/dir noexist
363 * the resulting path name should be noexist/foo, not
364 * noexist/dir/foo (where foo is a file in dir), which
365 * is the case where the target exists.
366 *
367 * Also, check for "..". This is for correct path
368 * concatenation for paths ending in "..", e.g.
369 * cp -R .. /tmp
370 * Paths ending in ".." are changed to ".". This is
371 * tricky, but seems the easiest way to fix the problem.
372 *
373 * XXX
374 * Since the first level MUST be FTS_ROOTLEVEL, base
375 * is always initialized.
376 */
377 if (curr->fts_level == FTS_ROOTLEVEL) {
378 if (type != DIR_TO_DNE) {
379 p = strrchr(curr->fts_path, '/');
380 base = (p == NULL) ? 0 :
381 (int)(p - curr->fts_path + 1);
382
383 if (!strcmp(&curr->fts_path[base],
384 ".."))
385 base += 1;
386 } else
387 base = curr->fts_pathlen;
388 }
389
390 p = &curr->fts_path[base];
391 nlen = curr->fts_pathlen - base;
392 target_mid = to.target_end;
393 if (*p != '/' && target_mid[-1] != '/')
394 *target_mid++ = '/';
395 *target_mid = 0;
396 if (target_mid - to.p_path + nlen >= PATH_MAX) {
397 warnx("%s%s: name too long (not copied)",
398 to.p_path, p);
399 rval = 1;
400 continue;
401 }
402 (void)strncat(target_mid, p, nlen);
403 to.p_end = target_mid + nlen;
404 *to.p_end = 0;
405 STRIP_TRAILING_SLASH(to);
406 }
407
408 if (curr->fts_info == FTS_DP) {
409 /*
410 * We are nearly finished with this directory. If we
411 * didn't actually copy it, or otherwise don't need to
412 * change its attributes, then we are done.
413 */
414 if (!curr->fts_number)
415 continue;
416 /*
417 * If -p is in effect, set all the attributes.
418 * Otherwise, set the correct permissions, limited
419 * by the umask. Optimise by avoiding a chmod()
420 * if possible (which is usually the case if we
421 * made the directory). Note that mkdir() does not
422 * honour setuid, setgid and sticky bits, but we
423 * normally want to preserve them on directories.
424 */
425 if (pflag) {
426 if (setfile(curr->fts_statp, -1))
427 rval = 1;
428 #ifdef __APPLE__
429 /* setfile will fail if writeattr is denied */
430 if (copyfile(curr->fts_path, to.p_path, NULL, COPYFILE_ACL)<0)
431 warn("%s: unable to copy ACL to %s", curr->fts_path, to.p_path);
432 #else /* !__APPLE__ */
433 if (preserve_dir_acls(curr->fts_statp,
434 curr->fts_accpath, to.p_path) != 0)
435 rval = 1;
436 #endif /* __APPLE__ */
437 } else {
438 mode = curr->fts_statp->st_mode;
439 if ((mode & (S_ISUID | S_ISGID | S_ISTXT)) ||
440 ((mode | S_IRWXU) & mask) != (mode & mask))
441 if (chmod(to.p_path, mode & mask) != 0){
442 warn("chmod: %s", to.p_path);
443 rval = 1;
444 }
445 }
446 continue;
447 }
448
449 /* Not an error but need to remember it happened */
450 if (stat(to.p_path, &to_stat) == -1)
451 dne = 1;
452 else {
453 if (to_stat.st_dev == curr->fts_statp->st_dev &&
454 to_stat.st_ino == curr->fts_statp->st_ino) {
455 warnx("%s and %s are identical (not copied).",
456 to.p_path, curr->fts_path);
457 rval = 1;
458 if (S_ISDIR(curr->fts_statp->st_mode))
459 (void)fts_set(ftsp, curr, FTS_SKIP);
460 continue;
461 }
462 if (!S_ISDIR(curr->fts_statp->st_mode) &&
463 S_ISDIR(to_stat.st_mode)) {
464 warnx("cannot overwrite directory %s with "
465 "non-directory %s",
466 to.p_path, curr->fts_path);
467 rval = 1;
468 continue;
469 }
470 dne = 0;
471 }
472
473 switch (curr->fts_statp->st_mode & S_IFMT) {
474 case S_IFLNK:
475 /* Catch special case of a non-dangling symlink */
476 if ((fts_options & FTS_LOGICAL) ||
477 ((fts_options & FTS_COMFOLLOW) &&
478 curr->fts_level == 0)) {
479 if (copy_file(curr, dne))
480 badcp = rval = 1;
481 } else {
482 if (copy_link(curr, !dne))
483 badcp = rval = 1;
484 }
485 break;
486 case S_IFDIR:
487 if (!Rflag && !rflag) {
488 warnx("%s is a directory (not copied).",
489 curr->fts_path);
490 (void)fts_set(ftsp, curr, FTS_SKIP);
491 badcp = rval = 1;
492 break;
493 }
494 /*
495 * If the directory doesn't exist, create the new
496 * one with the from file mode plus owner RWX bits,
497 * modified by the umask. Trade-off between being
498 * able to write the directory (if from directory is
499 * 555) and not causing a permissions race. If the
500 * umask blocks owner writes, we fail..
501 */
502 if (dne) {
503 if (mkdir(to.p_path,
504 curr->fts_statp->st_mode | S_IRWXU) < 0) {
505 if (COMPAT_MODE("bin/cp", "unix2003")) {
506 warn("%s", to.p_path);
507 } else {
508 err(1, "%s", to.p_path);
509 }
510 }
511 } else if (!S_ISDIR(to_stat.st_mode)) {
512 errno = ENOTDIR;
513 if (COMPAT_MODE("bin/cp", "unix2003")) {
514 warn("%s", to.p_path);
515 } else {
516 err(1, "%s", to.p_path);
517 }
518 }
519 /*
520 * Arrange to correct directory attributes later
521 * (in the post-order phase) if this is a new
522 * directory, or if the -p flag is in effect.
523 */
524 curr->fts_number = pflag || dne;
525 #ifdef __APPLE__
526 if (!Xflag) {
527 if (copyfile(curr->fts_path, to.p_path, NULL, COPYFILE_XATTR) < 0)
528 warn("%s: unable to copy extended attributes to %s", curr->fts_path, to.p_path);
529 /* ACL and mtime set in postorder traversal */
530 }
531 #endif /* __APPLE__ */
532 break;
533 case S_IFBLK:
534 case S_IFCHR:
535 if (Rflag) {
536 if (copy_special(curr->fts_statp, !dne))
537 badcp = rval = 1;
538 } else {
539 if (copy_file(curr, dne))
540 badcp = rval = 1;
541 }
542 break;
543 case S_IFIFO:
544 if (Rflag) {
545 if (copy_fifo(curr->fts_statp, !dne))
546 badcp = rval = 1;
547 } else {
548 if (copy_file(curr, dne))
549 badcp = rval = 1;
550 }
551 break;
552 default:
553 if (copy_file(curr, dne))
554 badcp = rval = 1;
555 break;
556 }
557 if (vflag && !badcp)
558 (void)printf("%s -> %s\n", curr->fts_path, to.p_path);
559 }
560 if (errno)
561 err(1, "fts_read");
562 fts_close(ftsp);
563 return (rval);
564 }
565
566 static void
567 siginfo(int sig __unused)
568 {
569
570 info = 1;
571 }