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

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

Added --version and --help to all builtins.

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