source: trunk/src/kmk/kmkbuiltin/cp.c@ 1597

Last change on this file since 1597 was 1597, checked in by bird, 17 years ago

protection work in progress.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 17.8 KB
Line 
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
35static 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
41static char sccsid[] = "@(#)cp.c 8.2 (Berkeley) 4/1/94";
42#endif /* not lint */
43#include <sys/cdefs.h>
44__FBSDID("$FreeBSD: src/bin/cp/cp.c,v 1.50 2004/04/06 20:06:44 markm Exp $");
45#endif
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#include "getopt.h"
75#include "k/kDefs.h"
76#ifdef _MSC_VER
77# include "mscfakes.h"
78#endif
79#include "cp_extern.h"
80#include "kmkbuiltin.h"
81
82
83#ifndef S_IFWHT
84#define S_IFWHT 0
85#define S_ISWHT(s) 0
86#define undelete(s) (-1)
87#endif
88
89#ifndef S_ISTXT
90#ifdef S_ISVTX
91#define S_ISTXT S_ISVTX
92#else
93#define S_ISTXT 0
94#endif
95#endif /* !S_ISTXT */
96
97#ifndef __unused
98# define __unused
99#endif
100
101#if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
102# define IS_SLASH(ch) ((ch) == '/' || (ch) == '\\')
103#else
104# define IS_SLASH(ch) ((ch) == '/')
105#endif
106
107#define STRIP_TRAILING_SLASH(p) { \
108 while ((p).p_end > (p).p_path + 1 && IS_SLASH((p).p_end[-1])) \
109 *--(p).p_end = 0; \
110}
111
112/* have wrappers for globals in cp_extern! */
113
114const char *cp_argv0;
115static char emptystring[] = "";
116
117PATH_T to = { to.p_path, emptystring, "" };
118
119int fflag, iflag, nflag, pflag, vflag;
120static int Rflag, rflag;
121volatile sig_atomic_t info;
122static int cp_ignore_non_existing, cp_changed_only;
123
124enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
125
126enum cp_arg {
127 CP_OPT_HELP = 261,
128 CP_OPT_VERSION,
129 CP_OPT_IGNORE_NON_EXISTING,
130 CP_OPT_CHANGED,
131 CP_OPT_DISABLE_PROTECTION,
132 CP_OPT_ENABLE_PROTECTION,
133 CP_OPT_ENABLE_FULL_PROTECTION,
134 CP_OPT_DISABLE_FULL_PROTECTION,
135 CP_OPT_PROTECTION_DEPTH
136};
137static struct option long_options[] =
138{
139 { "help", no_argument, 0, CP_OPT_HELP },
140 { "version", no_argument, 0, CP_OPT_VERSION },
141 { "ignore-non-existing", no_argument, 0, CP_OPT_IGNORE_NON_EXISTING },
142 { "changed", no_argument, 0, CP_OPT_CHANGED },
143/*
144 { "disable-protection", no_argument, 0, CP_OPT_DISABLE_PROTECTION },
145 { "enable-protection", no_argument, 0, CP_OPT_ENABLE_PROTECTION },
146 { "enable-full-protection", no_argument, 0, CP_OPT_ENABLE_FULL_PROTECTION },
147 { "disable-full-protection", no_argument, 0, CP_OPT_DISABLE_FULL_PROTECTION },
148 { "protection-depth", required_argument, 0, CP_OPT_PROTECTION_DEPTH },
149*/
150 { 0, 0, 0, 0 },
151};
152
153
154static int copy(char *[], enum op, int);
155static int mastercmp(const FTSENT * const *, const FTSENT * const *);
156#ifdef SIGINFO
157static void siginfo(int __unused);
158#endif
159static int usage(FILE *);
160
161int
162kmk_builtin_cp(int argc, char *argv[], char **envp)
163{
164 struct stat to_stat, tmp_stat;
165 enum op type;
166 int Hflag, Lflag, Pflag, ch, fts_options, r, have_trailing_slash;
167 char *target;
168
169 /* init globals */
170 cp_argv0 = argv[0];
171 to.p_end = to.p_path;
172 to.target_end = emptystring;
173 memset(to.p_path, 0, sizeof(to.p_path));
174 fflag = iflag = nflag = pflag = vflag = Rflag = rflag = 0;
175 info = 0;
176 cp_ignore_non_existing = cp_changed_only = 0;
177
178 /* reset getopt and set progname. */
179 g_progname = argv[0];
180 opterr = 1;
181 optarg = NULL;
182 optopt = 0;
183 optind = 0; /* init */
184
185 Hflag = Lflag = Pflag = 0;
186 while ((ch = getopt_long(argc, argv, "HLPRfinprv", long_options, NULL)) != -1)
187 switch (ch) {
188 case 'H':
189 Hflag = 1;
190 Lflag = Pflag = 0;
191 break;
192 case 'L':
193 Lflag = 1;
194 Hflag = Pflag = 0;
195 break;
196 case 'P':
197 Pflag = 1;
198 Hflag = Lflag = 0;
199 break;
200 case 'R':
201#ifdef DO_CP_TREE
202 Rflag = 1;
203 break;
204#else
205 return errx(1, "recursive copy is not implemented!");
206#endif
207 case 'f':
208 fflag = 1;
209 iflag = nflag = 0;
210 break;
211 case 'i':
212 iflag = 1;
213 fflag = nflag = 0;
214 break;
215 case 'n':
216 nflag = 1;
217 fflag = iflag = 0;
218 break;
219 case 'p':
220 pflag = 1;
221 break;
222 case 'r':
223#ifdef DO_CP_TREE
224 rflag = 1;
225 break;
226#else
227 return errx(1, "recursive copy is not implemented!");
228#endif
229 case 'v':
230 vflag = 1;
231 break;
232 case CP_OPT_HELP:
233 usage(stdout);
234 return 0;
235 case CP_OPT_VERSION:
236 return kbuild_version(argv[0]);
237 case CP_OPT_IGNORE_NON_EXISTING:
238 cp_ignore_non_existing = 1;
239 break;
240 case CP_OPT_CHANGED:
241 cp_changed_only = 1;
242 break;
243 default:
244 return usage(stderr);
245 }
246 argc -= optind;
247 argv += optind;
248
249 if (argc < 2)
250 return usage(stderr);
251
252 fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
253 if (rflag) {
254 if (Rflag)
255 return errx(1,
256 "the -R and -r options may not be specified together.");
257 if (Hflag || Lflag || Pflag)
258 errx(1,
259 "the -H, -L, and -P options may not be specified with the -r option.");
260#ifdef DO_CP_TREE
261 fts_options &= ~FTS_PHYSICAL;
262 fts_options |= FTS_LOGICAL;
263#endif
264 }
265#ifdef DO_CP_TREE
266 if (Rflag) {
267 if (Hflag)
268 fts_options |= FTS_COMFOLLOW;
269 if (Lflag) {
270 fts_options &= ~FTS_PHYSICAL;
271 fts_options |= FTS_LOGICAL;
272 }
273 } else
274#endif
275 {
276 fts_options &= ~FTS_PHYSICAL;
277 fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
278 }
279#ifdef SIGINFO
280 (void)signal(SIGINFO, siginfo);
281#endif
282
283 /* Save the target base in "to". */
284 target = argv[--argc];
285 if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
286 return errx(1, "%s: name too long", target);
287 to.p_end = to.p_path + strlen(to.p_path);
288 if (to.p_path == to.p_end) {
289 *to.p_end++ = '.';
290 *to.p_end = 0;
291 }
292 have_trailing_slash = IS_SLASH(to.p_end[-1]);
293 if (have_trailing_slash)
294 STRIP_TRAILING_SLASH(to);
295 to.target_end = to.p_end;
296
297 /* Set end of argument list for fts(3). */
298 argv[argc] = NULL;
299
300 /*
301 * Cp has two distinct cases:
302 *
303 * cp [-R] source target
304 * cp [-R] source1 ... sourceN directory
305 *
306 * In both cases, source can be either a file or a directory.
307 *
308 * In (1), the target becomes a copy of the source. That is, if the
309 * source is a file, the target will be a file, and likewise for
310 * directories.
311 *
312 * In (2), the real target is not directory, but "directory/source".
313 */
314 r = stat(to.p_path, &to_stat);
315 if (r == -1 && errno != ENOENT)
316 return err(1, "%s", to.p_path);
317 if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
318 /*
319 * Case (1). Target is not a directory.
320 */
321 if (argc > 1)
322 return usage(stderr);
323 /*
324 * Need to detect the case:
325 * cp -R dir foo
326 * Where dir is a directory and foo does not exist, where
327 * we want pathname concatenations turned on but not for
328 * the initial mkdir().
329 */
330 if (r == -1) {
331 if (rflag || (Rflag && (Lflag || Hflag)))
332 stat(*argv, &tmp_stat);
333 else
334 lstat(*argv, &tmp_stat);
335
336 if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
337 type = DIR_TO_DNE;
338 else
339 type = FILE_TO_FILE;
340 } else
341 type = FILE_TO_FILE;
342
343 if (have_trailing_slash && type == FILE_TO_FILE) {
344 if (r == -1)
345 return errx(1, "directory %s does not exist",
346 to.p_path);
347 else
348 return errx(1, "%s is not a directory", to.p_path);
349 }
350 } else
351 /*
352 * Case (2). Target is a directory.
353 */
354 type = FILE_TO_DIR;
355
356 return copy(argv, type, fts_options);
357}
358
359static int
360copy(char *argv[], enum op type, int fts_options)
361{
362 struct stat to_stat;
363 FTS *ftsp;
364 FTSENT *curr;
365 int base = 0, dne, badcp, rval;
366 size_t nlen;
367 char *p, *target_mid;
368 mode_t mask, mode;
369
370 /*
371 * Keep an inverted copy of the umask, for use in correcting
372 * permissions on created directories when not using -p.
373 */
374 mask = ~umask(0777);
375 umask(~mask);
376
377 if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
378 return err(1, "fts_open");
379 for (badcp = rval = 0; (curr = fts_read(ftsp)) != NULL; badcp = 0) {
380 int copied = 0;
381
382 switch (curr->fts_info) {
383 case FTS_NS:
384 if ( cp_ignore_non_existing
385 && curr->fts_errno == ENOENT) {
386 if (vflag) {
387 warnx("%s: %s", curr->fts_path,
388 strerror(curr->fts_errno));
389 }
390 continue;
391 }
392 case FTS_DNR:
393 case FTS_ERR:
394 warnx("%s: %s",
395 curr->fts_path, strerror(curr->fts_errno));
396 badcp = rval = 1;
397 continue;
398 case FTS_DC: /* Warn, continue. */
399 warnx("%s: directory causes a cycle", curr->fts_path);
400 badcp = rval = 1;
401 continue;
402 default:
403 ;
404 }
405
406 /*
407 * If we are in case (2) or (3) above, we need to append the
408 * source name to the target name.
409 */
410 if (type != FILE_TO_FILE) {
411 /*
412 * Need to remember the roots of traversals to create
413 * correct pathnames. If there's a directory being
414 * copied to a non-existent directory, e.g.
415 * cp -R a/dir noexist
416 * the resulting path name should be noexist/foo, not
417 * noexist/dir/foo (where foo is a file in dir), which
418 * is the case where the target exists.
419 *
420 * Also, check for "..". This is for correct path
421 * concatenation for paths ending in "..", e.g.
422 * cp -R .. /tmp
423 * Paths ending in ".." are changed to ".". This is
424 * tricky, but seems the easiest way to fix the problem.
425 *
426 * XXX
427 * Since the first level MUST be FTS_ROOTLEVEL, base
428 * is always initialized.
429 */
430 if (curr->fts_level == FTS_ROOTLEVEL) {
431 if (type != DIR_TO_DNE) {
432 p = strrchr(curr->fts_path, '/');
433#if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
434 if (strrchr(curr->fts_path, '\\') > p)
435 p = strrchr(curr->fts_path, '\\');
436#endif
437 base = (p == NULL) ? 0 :
438 (int)(p - curr->fts_path + 1);
439
440 if (!strcmp(&curr->fts_path[base],
441 ".."))
442 base += 1;
443 } else
444 base = curr->fts_pathlen;
445 }
446
447 p = &curr->fts_path[base];
448 nlen = curr->fts_pathlen - base;
449 target_mid = to.target_end;
450 if (!IS_SLASH(*p) && !IS_SLASH(target_mid[-1]))
451 *target_mid++ = '/';
452 *target_mid = 0;
453 if (target_mid - to.p_path + nlen >= PATH_MAX) {
454 warnx("%s%s: name too long (not copied)",
455 to.p_path, p);
456 badcp = rval = 1;
457 continue;
458 }
459 (void)strncat(target_mid, p, nlen);
460 to.p_end = target_mid + nlen;
461 *to.p_end = 0;
462 STRIP_TRAILING_SLASH(to);
463 }
464
465 if (curr->fts_info == FTS_DP) {
466 /*
467 * We are nearly finished with this directory. If we
468 * didn't actually copy it, or otherwise don't need to
469 * change its attributes, then we are done.
470 */
471 if (!curr->fts_number)
472 continue;
473 /*
474 * If -p is in effect, set all the attributes.
475 * Otherwise, set the correct permissions, limited
476 * by the umask. Optimise by avoiding a chmod()
477 * if possible (which is usually the case if we
478 * made the directory). Note that mkdir() does not
479 * honour setuid, setgid and sticky bits, but we
480 * normally want to preserve them on directories.
481 */
482 if (pflag) {
483 if (setfile(curr->fts_statp, -1))
484 rval = 1;
485 } else {
486 mode = curr->fts_statp->st_mode;
487 if ((mode & (S_ISUID | S_ISGID | S_ISTXT)) ||
488 ((mode | S_IRWXU) & mask) != (mode & mask))
489 if (chmod(to.p_path, mode & mask) != 0){
490 warn("chmod: %s", to.p_path);
491 rval = 1;
492 }
493 }
494 continue;
495 }
496
497 /* Not an error but need to remember it happened */
498 if (stat(to.p_path, &to_stat) == -1)
499 dne = 1;
500 else {
501 if (to_stat.st_dev == curr->fts_statp->st_dev &&
502 to_stat.st_dev != 0 &&
503 to_stat.st_ino == curr->fts_statp->st_ino &&
504 to_stat.st_ino != 0) {
505 warnx("%s and %s are identical (not copied).",
506 to.p_path, curr->fts_path);
507 badcp = rval = 1;
508 if (S_ISDIR(curr->fts_statp->st_mode))
509 (void)fts_set(ftsp, curr, FTS_SKIP);
510 continue;
511 }
512 if (!S_ISDIR(curr->fts_statp->st_mode) &&
513 S_ISDIR(to_stat.st_mode)) {
514 warnx("cannot overwrite directory %s with "
515 "non-directory %s",
516 to.p_path, curr->fts_path);
517 badcp = rval = 1;
518 continue;
519 }
520 dne = 0;
521 }
522
523 switch (curr->fts_statp->st_mode & S_IFMT) {
524#ifdef S_IFLNK
525 case S_IFLNK:
526 /* Catch special case of a non-dangling symlink */
527 if ((fts_options & FTS_LOGICAL) ||
528 ((fts_options & FTS_COMFOLLOW) &&
529 curr->fts_level == 0)) {
530 if (copy_file(curr, dne, cp_changed_only, &copied))
531 badcp = rval = 1;
532 } else {
533 if (copy_link(curr, !dne))
534 badcp = rval = 1;
535 }
536 break;
537#endif
538 case S_IFDIR:
539 if (!Rflag && !rflag) {
540 warnx("%s is a directory (not copied).",
541 curr->fts_path);
542 (void)fts_set(ftsp, curr, FTS_SKIP);
543 badcp = rval = 1;
544 break;
545 }
546 /*
547 * If the directory doesn't exist, create the new
548 * one with the from file mode plus owner RWX bits,
549 * modified by the umask. Trade-off between being
550 * able to write the directory (if from directory is
551 * 555) and not causing a permissions race. If the
552 * umask blocks owner writes, we fail..
553 */
554 if (dne) {
555 if (mkdir(to.p_path,
556 curr->fts_statp->st_mode | S_IRWXU) < 0)
557 return err(1, "%s", to.p_path);
558 } else if (!S_ISDIR(to_stat.st_mode)) {
559 errno = ENOTDIR;
560 return err(1, "%s", to.p_path);
561 }
562 /*
563 * Arrange to correct directory attributes later
564 * (in the post-order phase) if this is a new
565 * directory, or if the -p flag is in effect.
566 */
567 curr->fts_number = pflag || dne;
568 break;
569#ifdef S_IFBLK
570 case S_IFBLK:
571#endif
572 case S_IFCHR:
573 if (Rflag) {
574 if (copy_special(curr->fts_statp, !dne))
575 badcp = rval = 1;
576 } else {
577 if (copy_file(curr, dne, cp_changed_only, &copied))
578 badcp = rval = 1;
579 }
580 break;
581#ifdef S_IFIFO
582 case S_IFIFO:
583#endif
584 if (Rflag) {
585 if (copy_fifo(curr->fts_statp, !dne))
586 badcp = rval = 1;
587 } else {
588 if (copy_file(curr, dne, cp_changed_only, &copied))
589 badcp = rval = 1;
590 }
591 break;
592 default:
593 if (copy_file(curr, dne, cp_changed_only, &copied))
594 badcp = rval = 1;
595 break;
596 }
597 if (vflag && !badcp)
598 (void)printf(copied ? "%s -> %s\n" : "%s matches %s - not copied\n",
599 curr->fts_path, to.p_path);
600 }
601 if (errno)
602 return err(1, "fts_read");
603 return (rval);
604}
605
606/*
607 * mastercmp --
608 * The comparison function for the copy order. The order is to copy
609 * non-directory files before directory files. The reason for this
610 * is because files tend to be in the same cylinder group as their
611 * parent directory, whereas directories tend not to be. Copying the
612 * files first reduces seeking.
613 */
614static int
615mastercmp(const FTSENT * const *a, const FTSENT * const *b)
616{
617 int a_info, b_info;
618
619 a_info = (*a)->fts_info;
620 if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
621 return (0);
622 b_info = (*b)->fts_info;
623 if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
624 return (0);
625 if (a_info == FTS_D)
626 return (-1);
627 if (b_info == FTS_D)
628 return (1);
629 return (0);
630}
631
632#ifdef SIGINFO
633static void
634siginfo(int sig __unused)
635{
636
637 info = 1;
638}
639#endif
640
641
642static int
643usage(FILE *fp)
644{
645 fprintf(fp, "usage: %s [options] src target\n"
646 " or: %s [options] src1 ... srcN directory\n"
647 " or: %s --help\n"
648 " or: %s --version\n"
649 "\n"
650 "Options:\n"
651 " -R Recursive copy.\n"
652 " -H Follow symbolic links on the commandline. Only valid with -R.\n"
653 " -L Follow all symbolic links. Only valid with -R.\n"
654 " -P Do not follow symbolic links. Default. Only valid with -R\n"
655 " -f Force. Overrides -i and -n.\n"
656 " -i Iteractive. Overrides -n and -f.\n"
657 " -n Don't overwrite any files. Overrides -i and -f.\n"
658 " --ignore-non-existing\n"
659 " Don't fail if the specified source file doesn't exist.\n"
660 " --changed\n"
661 " Only copy if changed (i.e. compare first). TODO.\n"
662 ,
663 g_progname, g_progname, g_progname, g_progname);
664 return 1;
665}
Note: See TracBrowser for help on using the repository browser.