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

Last change on this file since 1309 was 1309, checked in by bird, 18 years ago

combined the bulk of the cmp stuff into cmp_util.c. implemented cp --changed.

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