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