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