file_cmds-184.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 volatile sig_atomic_t info;
99
100 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
101
102 static int copy(char *[], enum op, int);
103 static int mastercmp(const FTSENT * const *, const FTSENT * const *);
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, "HLPRXfinprv")) != -1)
116 switch (ch) {
117 case 'H':
118 Hflag = 1;
119 Lflag = Pflag = 0;
120 break;
121 case 'L':
122 Lflag = 1;
123 Hflag = Pflag = 0;
124 break;
125 case 'P':
126 Pflag = 1;
127 Hflag = Lflag = 0;
128 break;
129 case 'R':
130 Rflag = 1;
131 break;
132 case 'X':
133 Xflag = 1;
134 break;
135 case 'f':
136 fflag = 1;
137 /* Determine if the STD is SUSv3 or Legacy */
138 if (COMPAT_MODE("bin/cp", "unix2003"))
139 nflag = 0; /* reset nflag, but not iflag */
140 else
141 iflag = nflag = 0; /* reset both */
142 break;
143 case 'i':
144 iflag = 1;
145 if (COMPAT_MODE("bin/cp", "unix2003"))
146 nflag = 0; /* reset nflag, but not fflag */
147 else
148 fflag = nflag = 0;
149 break;
150 case 'n':
151 nflag = 1;
152 fflag = iflag = 0;
153 break;
154 case 'p':
155 pflag = 1;
156 break;
157 case 'r':
158 rflag = 1;
159 break;
160 case 'v':
161 vflag = 1;
162 break;
163 default:
164 usage();
165 break;
166 }
167 argc -= optind;
168 argv += optind;
169
170 if (argc < 2)
171 usage();
172
173 fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
174 if (rflag) {
175 if (Rflag)
176 errx(1,
177 "the -R and -r options may not be specified together.");
178 if (Hflag || Lflag || Pflag)
179 errx(1,
180 "the -H, -L, and -P options may not be specified with the -r option.");
181 fts_options &= ~FTS_PHYSICAL;
182 fts_options |= FTS_LOGICAL;
183 }
184 if (Rflag) {
185 if (Hflag)
186 fts_options |= FTS_COMFOLLOW;
187 if (Lflag) {
188 fts_options &= ~FTS_PHYSICAL;
189 fts_options |= FTS_LOGICAL;
190 }
191 } else {
192 fts_options &= ~FTS_PHYSICAL;
193 fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
194 }
195 (void)signal(SIGINFO, siginfo);
196
197 /* Save the target base in "to". */
198 target = argv[--argc];
199 if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
200 errx(1, "%s: name too long", target);
201 to.p_end = to.p_path + strlen(to.p_path);
202 if (to.p_path == to.p_end) {
203 *to.p_end++ = '.';
204 *to.p_end = 0;
205 }
206 have_trailing_slash = (to.p_end[-1] == '/');
207 if (have_trailing_slash)
208 STRIP_TRAILING_SLASH(to);
209 to.target_end = to.p_end;
210
211 /* Set end of argument list for fts(3). */
212 argv[argc] = NULL;
213
214 /*
215 * Cp has two distinct cases:
216 *
217 * cp [-R] source target
218 * cp [-R] source1 ... sourceN directory
219 *
220 * In both cases, source can be either a file or a directory.
221 *
222 * In (1), the target becomes a copy of the source. That is, if the
223 * source is a file, the target will be a file, and likewise for
224 * directories.
225 *
226 * In (2), the real target is not directory, but "directory/source".
227 */
228 r = stat(to.p_path, &to_stat);
229 if (r == -1 && errno != ENOENT)
230 err(1, "%s", to.p_path);
231 if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
232 /*
233 * Case (1). Target is not a directory.
234 */
235 if (argc > 1) {
236 usage();
237 exit(1);
238 }
239 /*
240 * Need to detect the case:
241 * cp -R dir foo
242 * Where dir is a directory and foo does not exist, where
243 * we want pathname concatenations turned on but not for
244 * the initial mkdir().
245 */
246 if (r == -1) {
247 if (rflag || (Rflag && (Lflag || Hflag)))
248 stat(*argv, &tmp_stat);
249 else
250 lstat(*argv, &tmp_stat);
251
252 if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
253 type = DIR_TO_DNE;
254 else
255 type = FILE_TO_FILE;
256 } else
257 type = FILE_TO_FILE;
258
259 if (have_trailing_slash && type == FILE_TO_FILE) {
260 if (r == -1)
261 errx(1, "directory %s does not exist",
262 to.p_path);
263 else
264 errx(1, "%s is not a directory", to.p_path);
265 }
266 } else
267 /*
268 * Case (2). Target is a directory.
269 */
270 type = FILE_TO_DIR;
271
272 exit (copy(argv, type, fts_options));
273 }
274
275 static int
276 copy(char *argv[], enum op type, int fts_options)
277 {
278 struct stat to_stat;
279 FTS *ftsp;
280 FTSENT *curr;
281 int base = 0, dne, badcp, rval;
282 size_t nlen;
283 char *p, *target_mid;
284 mode_t mask, mode;
285
286 /*
287 * Keep an inverted copy of the umask, for use in correcting
288 * permissions on created directories when not using -p.
289 */
290 mask = ~umask(0777);
291 umask(~mask);
292
293 if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
294 err(1, "fts_open");
295 for (badcp = rval = 0; (curr = fts_read(ftsp)) != NULL; badcp = 0) {
296 switch (curr->fts_info) {
297 case FTS_NS:
298 case FTS_DNR:
299 case FTS_ERR:
300 warnx("%s: %s",
301 curr->fts_path, strerror(curr->fts_errno));
302 badcp = rval = 1;
303 continue;
304 case FTS_DC: /* Warn, continue. */
305 warnx("%s: directory causes a cycle", curr->fts_path);
306 badcp = rval = 1;
307 continue;
308 default:
309 ;
310 }
311
312 /*
313 * If we are in case (2) or (3) above, we need to append the
314 * source name to the target name.
315 */
316 if (type != FILE_TO_FILE) {
317 /*
318 * Need to remember the roots of traversals to create
319 * correct pathnames. If there's a directory being
320 * copied to a non-existent directory, e.g.
321 * cp -R a/dir noexist
322 * the resulting path name should be noexist/foo, not
323 * noexist/dir/foo (where foo is a file in dir), which
324 * is the case where the target exists.
325 *
326 * Also, check for "..". This is for correct path
327 * concatenation for paths ending in "..", e.g.
328 * cp -R .. /tmp
329 * Paths ending in ".." are changed to ".". This is
330 * tricky, but seems the easiest way to fix the problem.
331 *
332 * XXX
333 * Since the first level MUST be FTS_ROOTLEVEL, base
334 * is always initialized.
335 */
336 if (curr->fts_level == FTS_ROOTLEVEL) {
337 if (type != DIR_TO_DNE) {
338 p = strrchr(curr->fts_path, '/');
339 base = (p == NULL) ? 0 :
340 (int)(p - curr->fts_path + 1);
341
342 if (!strcmp(&curr->fts_path[base],
343 ".."))
344 base += 1;
345 } else
346 base = curr->fts_pathlen;
347 }
348
349 p = &curr->fts_path[base];
350 nlen = curr->fts_pathlen - base;
351 target_mid = to.target_end;
352 if (*p != '/' && target_mid[-1] != '/')
353 *target_mid++ = '/';
354 *target_mid = 0;
355 if (target_mid - to.p_path + nlen >= PATH_MAX) {
356 warnx("%s%s: name too long (not copied)",
357 to.p_path, p);
358 badcp = rval = 1;
359 continue;
360 }
361 (void)strncat(target_mid, p, nlen);
362 to.p_end = target_mid + nlen;
363 *to.p_end = 0;
364 STRIP_TRAILING_SLASH(to);
365 }
366
367 if (curr->fts_info == FTS_DP) {
368 /*
369 * We are nearly finished with this directory. If we
370 * didn't actually copy it, or otherwise don't need to
371 * change its attributes, then we are done.
372 */
373 if (!curr->fts_number)
374 continue;
375 /*
376 * If -p is in effect, set all the attributes.
377 * Otherwise, set the correct permissions, limited
378 * by the umask. Optimise by avoiding a chmod()
379 * if possible (which is usually the case if we
380 * made the directory). Note that mkdir() does not
381 * honour setuid, setgid and sticky bits, but we
382 * normally want to preserve them on directories.
383 */
384 if (pflag) {
385 if (setfile(curr->fts_statp, -1))
386 rval = 1;
387 #ifdef __APPLE__
388 /* setfile will fail if writeattr is denied */
389 if (copyfile(curr->fts_path, to.p_path, NULL, COPYFILE_ACL)<0)
390 warn("%s: unable to copy ACL to %s", curr->fts_path, to.p_path);
391 #else /* !__APPLE__ */
392 if (preserve_dir_acls(curr->fts_statp,
393 curr->fts_accpath, to.p_path) != 0)
394 rval = 1;
395 #endif /* __APPLE__ */
396 } else {
397 mode = curr->fts_statp->st_mode;
398 if ((mode & (S_ISUID | S_ISGID | S_ISTXT)) ||
399 ((mode | S_IRWXU) & mask) != (mode & mask))
400 if (chmod(to.p_path, mode & mask) != 0){
401 warn("chmod: %s", to.p_path);
402 rval = 1;
403 }
404 }
405 continue;
406 }
407
408 /* Not an error but need to remember it happened */
409 if (stat(to.p_path, &to_stat) == -1)
410 dne = 1;
411 else {
412 if (to_stat.st_dev == curr->fts_statp->st_dev &&
413 to_stat.st_ino == curr->fts_statp->st_ino) {
414 warnx("%s and %s are identical (not copied).",
415 to.p_path, curr->fts_path);
416 badcp = rval = 1;
417 if (S_ISDIR(curr->fts_statp->st_mode))
418 (void)fts_set(ftsp, curr, FTS_SKIP);
419 continue;
420 }
421 if (!S_ISDIR(curr->fts_statp->st_mode) &&
422 S_ISDIR(to_stat.st_mode)) {
423 warnx("cannot overwrite directory %s with "
424 "non-directory %s",
425 to.p_path, curr->fts_path);
426 badcp = rval = 1;
427 continue;
428 }
429 dne = 0;
430 }
431
432 switch (curr->fts_statp->st_mode & S_IFMT) {
433 case S_IFLNK:
434 /* Catch special case of a non-dangling symlink */
435 if ((fts_options & FTS_LOGICAL) ||
436 ((fts_options & FTS_COMFOLLOW) &&
437 curr->fts_level == 0)) {
438 if (copy_file(curr, dne))
439 badcp = rval = 1;
440 } else {
441 if (copy_link(curr, !dne))
442 badcp = rval = 1;
443 }
444 break;
445 case S_IFDIR:
446 if (!Rflag && !rflag) {
447 warnx("%s is a directory (not copied).",
448 curr->fts_path);
449 (void)fts_set(ftsp, curr, FTS_SKIP);
450 badcp = rval = 1;
451 break;
452 }
453 /*
454 * If the directory doesn't exist, create the new
455 * one with the from file mode plus owner RWX bits,
456 * modified by the umask. Trade-off between being
457 * able to write the directory (if from directory is
458 * 555) and not causing a permissions race. If the
459 * umask blocks owner writes, we fail..
460 */
461 if (dne) {
462 if (mkdir(to.p_path,
463 curr->fts_statp->st_mode | S_IRWXU) < 0)
464 if (COMPAT_MODE("bin/cp", "unix2003")) {
465 warn("%s", to.p_path);
466 } else {
467 err(1, "%s", to.p_path);
468 }
469 } else if (!S_ISDIR(to_stat.st_mode)) {
470 errno = ENOTDIR;
471 if (COMPAT_MODE("bin/cp", "unix2003")) {
472 warn("%s", to.p_path);
473 } else {
474 err(1, "%s", to.p_path);
475 }
476 }
477 /*
478 * Arrange to correct directory attributes later
479 * (in the post-order phase) if this is a new
480 * directory, or if the -p flag is in effect.
481 */
482 curr->fts_number = pflag || dne;
483 #ifdef __APPLE__
484 if (!Xflag) {
485 if (copyfile(curr->fts_path, to.p_path, NULL, COPYFILE_XATTR) < 0)
486 warn("%s: unable to copy extended attributes to %s", curr->fts_path, to.p_path);
487 /* ACL and mtime set in postorder traversal */
488 }
489 #endif /* __APPLE__ */
490 break;
491 case S_IFBLK:
492 case S_IFCHR:
493 if (Rflag) {
494 if (copy_special(curr->fts_statp, !dne))
495 badcp = rval = 1;
496 } else {
497 if (copy_file(curr, dne))
498 badcp = rval = 1;
499 }
500 break;
501 case S_IFIFO:
502 if (Rflag) {
503 if (copy_fifo(curr->fts_statp, !dne))
504 badcp = rval = 1;
505 } else {
506 if (copy_file(curr, dne))
507 badcp = rval = 1;
508 }
509 break;
510 default:
511 if (copy_file(curr, dne))
512 badcp = rval = 1;
513 break;
514 }
515 if (vflag && !badcp)
516 (void)printf("%s -> %s\n", curr->fts_path, to.p_path);
517 }
518 if (errno)
519 err(1, "fts_read");
520 fts_close(ftsp);
521 return (rval);
522 }
523
524 /*
525 * mastercmp --
526 * The comparison function for the copy order. The order is to copy
527 * non-directory files before directory files. The reason for this
528 * is because files tend to be in the same cylinder group as their
529 * parent directory, whereas directories tend not to be. Copying the
530 * files first reduces seeking.
531 */
532 static int
533 mastercmp(const FTSENT * const *a, const FTSENT * const *b)
534 {
535 int a_info, b_info;
536
537 a_info = (*a)->fts_info;
538 if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
539 return (0);
540 b_info = (*b)->fts_info;
541 if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
542 return (0);
543 if (a_info == FTS_D)
544 return (-1);
545 if (b_info == FTS_D)
546 return (1);
547 return (0);
548 }
549
550 static void
551 siginfo(int sig __unused)
552 {
553
554 info = 1;
555 }