2 * Copyright (c) 1988, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * David Hitz of Auspex Systems Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#) Copyright (c) 1988, 1993, 1994 The Regents of the University of California. All rights reserved.
37 * @(#)cp.c 8.2 (Berkeley) 4/1/94
38 * $FreeBSD: src/bin/cp/cp.c,v 1.24.2.7 2002/09/24 12:41:04 mckay Exp $
39 * $DragonFly: src/bin/cp/cp.c,v 1.8 2004/08/25 01:23:15 dillon Exp $
43 * Cp copies source files to target files.
45 * The global PATH_T structure "to" always contains the path to the
46 * current target file. Since fts(3) does not change directories,
47 * this path can be either absolute or dot-relative.
49 * The basic algorithm is to initialize "to" and use fts(3) to traverse
50 * the file hierarchy rooted in the argument list. A trivial case is the
51 * case of 'cp file1 file2'. The more interesting case is the case of
52 * 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
53 * path (relative to the root of the traversal) is appended to dir (stored
54 * in "to") to form the final target path.
57 #include <sys/param.h>
71 #define STRIP_TRAILING_SLASH(p) { \
72 while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/') \
76 PATH_T to = { to.p_path, to.p_path, "" };
78 int fflag, iflag, nflag, pflag, vflag;
79 static int Rflag, rflag;
81 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
83 static int copy (char **, enum op, int);
84 static int mastercmp (const FTSENT **, const FTSENT **);
87 main(int argc, char **argv)
89 struct stat to_stat, tmp_stat;
91 int Hflag, Lflag, Pflag, ch, fts_options, r;
94 Hflag = Lflag = Pflag = 0;
95 while ((ch = getopt(argc, argv, "HLPRfinprv")) != -1)
143 fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
147 "the -R and -r options may not be specified together.");
148 if (Hflag || Lflag || Pflag)
150 "the -H, -L, and -P options may not be specified with the -r option.");
151 fts_options &= ~FTS_PHYSICAL;
152 fts_options |= FTS_LOGICAL;
156 fts_options |= FTS_COMFOLLOW;
158 fts_options &= ~FTS_PHYSICAL;
159 fts_options |= FTS_LOGICAL;
162 fts_options &= ~FTS_PHYSICAL;
163 fts_options |= FTS_LOGICAL;
166 /* Save the target base in "to". */
167 target = argv[--argc];
168 if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
169 errx(1, "%s: name too long", target);
170 to.p_end = to.p_path + strlen(to.p_path);
171 if (to.p_path == to.p_end) {
175 STRIP_TRAILING_SLASH(to);
176 to.target_end = to.p_end;
178 /* Set end of argument list for fts(3). */
182 * Cp has two distinct cases:
184 * cp [-R] source target
185 * cp [-R] source1 ... sourceN directory
187 * In both cases, source can be either a file or a directory.
189 * In (1), the target becomes a copy of the source. That is, if the
190 * source is a file, the target will be a file, and likewise for
193 * In (2), the real target is not directory, but "directory/source".
195 r = stat(to.p_path, &to_stat);
196 if (r == -1 && errno != ENOENT)
197 err(1, "%s", to.p_path);
198 if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
200 * Case (1). Target is not a directory.
207 * Need to detect the case:
209 * Where dir is a directory and foo does not exist, where
210 * we want pathname concatenations turned on but not for
211 * the initial mkdir().
214 if (rflag || (Rflag && (Lflag || Hflag)))
215 stat(*argv, &tmp_stat);
217 lstat(*argv, &tmp_stat);
219 if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
227 * Case (2). Target is a directory.
231 exit (copy(argv, type, fts_options));
235 copy(char **argv, enum op type, int fts_options)
240 int base, dne, badcp, nlen, rval;
241 char *p, *target_mid;
245 * Keep an inverted copy of the umask, for use in correcting
246 * permissions on created directories when not using -p.
252 if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
254 for (badcp = rval = 0; (curr = fts_read(ftsp)) != NULL; badcp = 0) {
255 switch (curr->fts_info) {
260 curr->fts_path, strerror(curr->fts_errno));
263 case FTS_DC: /* Warn, continue. */
264 warnx("%s: directory causes a cycle", curr->fts_path);
270 * If we are in case (2) or (3) above, we need to append the
271 * source name to the target name.
273 if (type != FILE_TO_FILE) {
275 * Need to remember the roots of traversals to create
276 * correct pathnames. If there's a directory being
277 * copied to a non-existent directory, e.g.
278 * cp -R a/dir noexist
279 * the resulting path name should be noexist/foo, not
280 * noexist/dir/foo (where foo is a file in dir), which
281 * is the case where the target exists.
283 * Also, check for "..". This is for correct path
284 * concatenation for paths ending in "..", e.g.
286 * Paths ending in ".." are changed to ".". This is
287 * tricky, but seems the easiest way to fix the problem.
290 * Since the first level MUST be FTS_ROOTLEVEL, base
291 * is always initialized.
293 if (curr->fts_level == FTS_ROOTLEVEL) {
294 if (type != DIR_TO_DNE) {
295 p = strrchr(curr->fts_path, '/');
296 base = (p == NULL) ? 0 :
297 (int)(p - curr->fts_path + 1);
299 if (!strcmp(&curr->fts_path[base],
303 base = curr->fts_pathlen;
306 p = &curr->fts_path[base];
307 nlen = curr->fts_pathlen - base;
308 target_mid = to.target_end;
309 if (*p != '/' && target_mid[-1] != '/')
312 if (target_mid - to.p_path + nlen >= PATH_MAX) {
313 warnx("%s%s: name too long (not copied)",
318 (void)strncat(target_mid, p, nlen);
319 to.p_end = target_mid + nlen;
321 STRIP_TRAILING_SLASH(to);
324 if (curr->fts_info == FTS_DP) {
326 * We are nearly finished with this directory. If we
327 * didn't actually copy it, or otherwise don't need to
328 * change its attributes, then we are done.
330 if (!curr->fts_number)
333 * If -p is in effect, set all the attributes.
334 * Otherwise, set the correct permissions, limited
335 * by the umask. Optimise by avoiding a chmod()
336 * if possible (which is usually the case if we
337 * made the directory). Note that mkdir() does not
338 * honour setuid, setgid and sticky bits, but we
339 * normally want to preserve them on directories.
342 if (setfile(curr->fts_statp, 0))
345 mode = curr->fts_statp->st_mode;
346 if ((mode & (S_ISUID | S_ISGID | S_ISTXT)) ||
347 ((mode | S_IRWXU) & mask) != (mode & mask))
348 if (chmod(to.p_path, mode & mask) != 0){
349 warn("chmod: %s", to.p_path);
356 /* Not an error but need to remember it happened */
357 if (stat(to.p_path, &to_stat) == -1)
360 if (to_stat.st_dev == curr->fts_statp->st_dev &&
361 to_stat.st_ino == curr->fts_statp->st_ino) {
362 warnx("%s and %s are identical (not copied).",
363 to.p_path, curr->fts_path);
365 if (S_ISDIR(curr->fts_statp->st_mode))
366 (void)fts_set(ftsp, curr, FTS_SKIP);
369 if (!S_ISDIR(curr->fts_statp->st_mode) &&
370 S_ISDIR(to_stat.st_mode)) {
371 warnx("cannot overwrite directory %s with non-directory %s",
372 to.p_path, curr->fts_path);
379 switch (curr->fts_statp->st_mode & S_IFMT) {
381 if (copy_link(curr, !dne))
385 if (!Rflag && !rflag) {
386 warnx("%s is a directory (not copied).",
388 (void)fts_set(ftsp, curr, FTS_SKIP);
393 * If the directory doesn't exist, create the new
394 * one with the from file mode plus owner RWX bits,
395 * modified by the umask. Trade-off between being
396 * able to write the directory (if from directory is
397 * 555) and not causing a permissions race. If the
398 * umask blocks owner writes, we fail..
402 curr->fts_statp->st_mode | S_IRWXU) < 0)
403 err(1, "%s", to.p_path);
404 } else if (!S_ISDIR(to_stat.st_mode)) {
406 err(1, "%s", to.p_path);
409 * Arrange to correct directory attributes later
410 * (in the post-order phase) if this is a new
411 * directory, or if the -p flag is in effect.
413 curr->fts_number = pflag || dne;
418 if (copy_special(curr->fts_statp, !dne))
421 if (copy_file(curr, dne))
427 if (copy_fifo(curr->fts_statp, !dne))
430 if (copy_file(curr, dne))
435 if (copy_file(curr, dne))
440 (void)printf("%s -> %s\n", curr->fts_path, to.p_path);
449 * The comparison function for the copy order. The order is to copy
450 * non-directory files before directory files. The reason for this
451 * is because files tend to be in the same cylinder group as their
452 * parent directory, whereas directories tend not to be. Copying the
453 * files first reduces seeking.
456 mastercmp(const FTSENT **a, const FTSENT **b)
460 a_info = (*a)->fts_info;
461 if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
463 b_info = (*b)->fts_info;
464 if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)