toolbox: add OpenADK toolbox for very small systems, thx Thorsten Glaser
[openadk.git] / package / toolbox / src / cp / cp.c
blobd04702f2a4141b814d9cdd551be6d661f0b61c13
1 /* $NetBSD: cp.c,v 1.58 2012/01/04 15:58:37 christos Exp $ */
3 /*
4 * Copyright (c) 1988, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * David Hitz of Auspex Systems Inc.
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.
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.
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 */
42 #ifndef lint
43 #if 0
44 static 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 */
51 * Cp copies source files to target files.
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.
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.
65 #include <sys/param.h>
66 #include <sys/stat.h>
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>
79 #include "extern.h"
81 #define STRIP_TRAILING_SLASH(p) { \
82 while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/') \
83 *--(p).p_end = '\0'; \
86 static char empty[] = "";
87 PATH_T to = { .p_end = to.p_path, .target_end = empty };
89 uid_t myuid;
90 int Hflag, Lflag, Rflag, Pflag, fflag, iflag, lflag, pflag, rflag, vflag, Nflag;
91 mode_t myumask;
92 sig_atomic_t pinfo;
94 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
96 static int copy(char *[], enum op, int);
98 #ifdef SIGINFO
99 static void
100 progress(int sig __unused)
103 pinfo++;
105 #endif
108 main(int argc, char *argv[])
110 struct stat to_stat, tmp_stat;
111 enum op type;
112 int ch, fts_options, r, have_trailing_slash;
113 char *target, **src;
115 Hflag = Lflag = Pflag = Rflag = 0;
116 while ((ch = getopt(argc, argv, "HLNPRfailprv")) != -1)
117 switch (ch) {
118 case 'H':
119 Hflag = 1;
120 Lflag = Pflag = 0;
121 break;
122 case 'L':
123 Lflag = 1;
124 Hflag = Pflag = 0;
125 break;
126 case 'N':
127 Nflag = 1;
128 break;
129 case 'P':
130 Pflag = 1;
131 Hflag = Lflag = 0;
132 break;
133 case 'R':
134 Rflag = 1;
135 break;
136 case 'a':
137 Pflag = 1;
138 pflag = 1;
139 Rflag = 1;
140 Hflag = Lflag = 0;
141 break;
142 case 'f':
143 fflag = 1;
144 iflag = 0;
145 break;
146 case 'i':
147 iflag = isatty(fileno(stdin));
148 fflag = 0;
149 break;
150 case 'l':
151 lflag = 1;
152 break;
153 case 'p':
154 pflag = 1;
155 break;
156 case 'r':
157 rflag = 1;
158 break;
159 case 'v':
160 vflag = 1;
161 break;
162 case '?':
163 default:
164 cp_usage();
165 /* NOTREACHED */
167 argc -= optind;
168 argv += optind;
170 if (argc < 2)
171 cp_usage();
173 fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
174 if (rflag) {
175 if (Rflag) {
176 errx(EXIT_FAILURE,
177 "the -R and -r options may not be specified together.");
178 /* NOTREACHED */
180 if (Hflag || Lflag || Pflag) {
181 errx(EXIT_FAILURE,
182 "the -H, -L, and -P options may not be specified with the -r option.");
183 /* NOTREACHED */
185 fts_options &= ~FTS_PHYSICAL;
186 fts_options |= FTS_LOGICAL;
189 if (Rflag) {
190 if (Hflag)
191 fts_options |= FTS_COMFOLLOW;
192 if (Lflag) {
193 fts_options &= ~FTS_PHYSICAL;
194 fts_options |= FTS_LOGICAL;
196 } else if (!Pflag) {
197 fts_options &= ~FTS_PHYSICAL;
198 fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
201 myuid = getuid();
203 /* Copy the umask for explicit mode setting. */
204 myumask = umask(0);
205 (void)umask(myumask);
207 /* Save the target base in "to". */
208 target = argv[--argc];
209 if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
210 errx(EXIT_FAILURE, "%s: name too long", target);
211 to.p_end = to.p_path + strlen(to.p_path);
212 have_trailing_slash = (to.p_end[-1] == '/');
213 if (have_trailing_slash)
214 STRIP_TRAILING_SLASH(to);
215 to.target_end = to.p_end;
217 /* Set end of argument list for fts(3). */
218 argv[argc] = NULL;
220 #ifdef SIGINFO
221 (void)signal(SIGINFO, progress);
222 #endif
225 * Cp has two distinct cases:
227 * cp [-R] source target
228 * cp [-R] source1 ... sourceN directory
230 * In both cases, source can be either a file or a directory.
232 * In (1), the target becomes a copy of the source. That is, if the
233 * source is a file, the target will be a file, and likewise for
234 * directories.
236 * In (2), the real target is not directory, but "directory/source".
238 if (Pflag)
239 r = lstat(to.p_path, &to_stat);
240 else
241 r = stat(to.p_path, &to_stat);
242 if (r == -1 && errno != ENOENT) {
243 err(EXIT_FAILURE, "%s", to.p_path);
244 /* NOTREACHED */
246 if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
248 * Case (1). Target is not a directory.
250 if (argc > 1)
251 cp_usage();
253 * Need to detect the case:
254 * cp -R dir foo
255 * Where dir is a directory and foo does not exist, where
256 * we want pathname concatenations turned on but not for
257 * the initial mkdir().
259 if (r == -1) {
260 if (rflag || (Rflag && (Lflag || Hflag)))
261 r = stat(*argv, &tmp_stat);
262 else
263 r = lstat(*argv, &tmp_stat);
264 if (r == -1) {
265 err(EXIT_FAILURE, "%s", *argv);
266 /* NOTREACHED */
269 if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
270 type = DIR_TO_DNE;
271 else
272 type = FILE_TO_FILE;
273 } else
274 type = FILE_TO_FILE;
276 if (have_trailing_slash && type == FILE_TO_FILE) {
277 if (r == -1)
278 errx(1, "directory %s does not exist",
279 to.p_path);
280 else
281 errx(1, "%s is not a directory", to.p_path);
283 } else {
285 * Case (2). Target is a directory.
287 type = FILE_TO_DIR;
291 * make "cp -rp src/ dst" behave like "cp -rp src dst" not
292 * like "cp -rp src/. dst"
294 for (src = argv; *src; src++) {
295 size_t len = strlen(*src);
296 while (len-- > 1 && (*src)[len] == '/')
297 (*src)[len] = '\0';
300 exit(copy(argv, type, fts_options));
301 /* NOTREACHED */
304 static int dnestack[MAXPATHLEN]; /* unlikely we'll have more nested dirs */
305 static ssize_t dnesp;
306 static void
307 pushdne(int dne)
310 dnestack[dnesp++] = dne;
311 assert(dnesp < MAXPATHLEN);
314 static int
315 popdne(void)
317 int rv;
319 rv = dnestack[--dnesp];
320 assert(dnesp >= 0);
321 return rv;
324 static int
325 copy(char *argv[], enum op type, int fts_options)
327 struct stat to_stat;
328 FTS *ftsp;
329 FTSENT *curr;
330 int base, dne, sval;
331 int this_failed, any_failed;
332 size_t nlen;
333 char *p, *target_mid;
335 base = 0; /* XXX gcc -Wuninitialized (see comment below) */
337 if ((ftsp = fts_open(argv, fts_options, NULL)) == NULL)
338 err(EXIT_FAILURE, "%s", argv[0]);
339 /* NOTREACHED */
340 for (any_failed = 0; (curr = fts_read(ftsp)) != NULL;) {
341 this_failed = 0;
342 switch (curr->fts_info) {
343 case FTS_NS:
344 case FTS_DNR:
345 case FTS_ERR:
346 warnx("%s: %s", curr->fts_path,
347 strerror(curr->fts_errno));
348 this_failed = any_failed = 1;
349 continue;
350 case FTS_DC: /* Warn, continue. */
351 warnx("%s: directory causes a cycle", curr->fts_path);
352 this_failed = any_failed = 1;
353 continue;
357 * If we are in case (2) or (3) above, we need to append the
358 * source name to the target name.
360 if (type != FILE_TO_FILE) {
361 if ((curr->fts_namelen +
362 to.target_end - to.p_path + 1) > MAXPATHLEN) {
363 warnx("%s/%s: name too long (not copied)",
364 to.p_path, curr->fts_name);
365 this_failed = any_failed = 1;
366 continue;
370 * Need to remember the roots of traversals to create
371 * correct pathnames. If there's a directory being
372 * copied to a non-existent directory, e.g.
373 * cp -R a/dir noexist
374 * the resulting path name should be noexist/foo, not
375 * noexist/dir/foo (where foo is a file in dir), which
376 * is the case where the target exists.
378 * Also, check for "..". This is for correct path
379 * concatentation for paths ending in "..", e.g.
380 * cp -R .. /tmp
381 * Paths ending in ".." are changed to ".". This is
382 * tricky, but seems the easiest way to fix the problem.
384 * XXX
385 * Since the first level MUST be FTS_ROOTLEVEL, base
386 * is always initialized.
388 if (curr->fts_level == FTS_ROOTLEVEL) {
389 if (type != DIR_TO_DNE) {
390 p = strrchr(curr->fts_path, '/');
391 base = (p == NULL) ? 0 :
392 (int)(p - curr->fts_path + 1);
394 if (!strcmp(&curr->fts_path[base],
395 ".."))
396 base += 1;
397 } else
398 base = curr->fts_pathlen;
401 p = &curr->fts_path[base];
402 nlen = curr->fts_pathlen - base;
403 target_mid = to.target_end;
404 if (*p != '/' && target_mid[-1] != '/')
405 *target_mid++ = '/';
406 *target_mid = 0;
408 if (target_mid - to.p_path + nlen >= PATH_MAX) {
409 warnx("%s%s: name too long (not copied)",
410 to.p_path, p);
411 this_failed = any_failed = 1;
412 continue;
414 (void)strncat(target_mid, p, nlen);
415 to.p_end = target_mid + nlen;
416 *to.p_end = 0;
417 STRIP_TRAILING_SLASH(to);
420 sval = Pflag ? lstat(to.p_path, &to_stat) : stat(to.p_path, &to_stat);
421 /* Not an error but need to remember it happened */
422 if (sval == -1)
423 dne = 1;
424 else {
425 if (to_stat.st_dev == curr->fts_statp->st_dev &&
426 to_stat.st_ino == curr->fts_statp->st_ino) {
427 warnx("%s and %s are identical (not copied).",
428 to.p_path, curr->fts_path);
429 this_failed = any_failed = 1;
430 if (S_ISDIR(curr->fts_statp->st_mode))
431 (void)fts_set(ftsp, curr, FTS_SKIP);
432 continue;
434 if (!S_ISDIR(curr->fts_statp->st_mode) &&
435 S_ISDIR(to_stat.st_mode)) {
436 warnx("cannot overwrite directory %s with non-directory %s",
437 to.p_path, curr->fts_path);
438 this_failed = any_failed = 1;
439 continue;
441 dne = 0;
444 switch (curr->fts_statp->st_mode & S_IFMT) {
445 case S_IFLNK:
446 /* Catch special case of a non dangling symlink */
447 if((fts_options & FTS_LOGICAL) ||
448 ((fts_options & FTS_COMFOLLOW) && curr->fts_level == 0)) {
449 if (copy_file(curr, dne))
450 this_failed = any_failed = 1;
451 } else {
452 if (copy_link(curr, !dne))
453 this_failed = any_failed = 1;
455 break;
456 case S_IFDIR:
457 if (!Rflag && !rflag) {
458 if (curr->fts_info == FTS_D)
459 warnx("%s is a directory (not copied).",
460 curr->fts_path);
461 (void)fts_set(ftsp, curr, FTS_SKIP);
462 this_failed = any_failed = 1;
463 break;
467 * Directories get noticed twice:
468 * In the first pass, create it if needed.
469 * In the second pass, after the children have been copied, set the permissions.
471 if (curr->fts_info == FTS_D) /* First pass */
474 * If the directory doesn't exist, create the new
475 * one with the from file mode plus owner RWX bits,
476 * modified by the umask. Trade-off between being
477 * able to write the directory (if from directory is
478 * 555) and not causing a permissions race. If the
479 * umask blocks owner writes, we fail..
481 pushdne(dne);
482 if (dne) {
483 if (mkdir(to.p_path,
484 curr->fts_statp->st_mode | S_IRWXU) < 0)
485 err(EXIT_FAILURE, "%s",
486 to.p_path);
487 /* NOTREACHED */
488 } else if (!S_ISDIR(to_stat.st_mode)) {
489 errno = ENOTDIR;
490 err(EXIT_FAILURE, "%s",
491 to.p_path);
492 /* NOTREACHED */
495 else if (curr->fts_info == FTS_DP) /* Second pass */
498 * If not -p and directory didn't exist, set it to be
499 * the same as the from directory, umodified by the
500 * umask; arguably wrong, but it's been that way
501 * forever.
503 if (pflag && setfile(curr->fts_statp, 0))
504 this_failed = any_failed = 1;
505 else if ((dne = popdne()))
506 (void)chmod(to.p_path,
507 curr->fts_statp->st_mode);
509 else
511 warnx("directory %s encountered when not expected.",
512 curr->fts_path);
513 this_failed = any_failed = 1;
514 break;
517 break;
518 case S_IFBLK:
519 case S_IFCHR:
520 if (Rflag) {
521 if (copy_special(curr->fts_statp, !dne))
522 this_failed = any_failed = 1;
523 } else
524 if (copy_file(curr, dne))
525 this_failed = any_failed = 1;
526 break;
527 case S_IFIFO:
528 if (Rflag) {
529 if (copy_fifo(curr->fts_statp, !dne))
530 this_failed = any_failed = 1;
531 } else
532 if (copy_file(curr, dne))
533 this_failed = any_failed = 1;
534 break;
535 default:
536 if (copy_file(curr, dne))
537 this_failed = any_failed = 1;
538 break;
540 if (vflag && !this_failed)
541 (void)printf("%s -> %s\n", curr->fts_path, to.p_path);
543 if (errno) {
544 err(EXIT_FAILURE, "fts_read");
545 /* NOTREACHED */
547 (void)fts_close(ftsp);
548 return (any_failed);