cp.c revision 1.35 1 /* $NetBSD: cp.c,v 1.35 2003/09/14 19:20:18 jschauma Exp $ */
2
3 /*
4 * Copyright (c) 1988, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * David Hitz of Auspex Systems Inc.
9 *
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.
21 *
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.
33 */
34
35 #include <sys/cdefs.h>
36 #ifndef lint
37 __COPYRIGHT(
38 "@(#) Copyright (c) 1988, 1993, 1994\n\
39 The Regents of the University of California. All rights reserved.\n");
40 #endif /* not lint */
41
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.35 2003/09/14 19:20:18 jschauma Exp $");
47 #endif
48 #endif /* not lint */
49
50 /*
51 * Cp copies source files to target files.
52 *
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.
56 *
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.
63 */
64
65 #include <sys/param.h>
66 #include <sys/stat.h>
67
68 #include <err.h>
69 #include <errno.h>
70 #include <fts.h>
71 #include <locale.h>
72 #include <stdlib.h>
73 #include <stdio.h>
74 #include <string.h>
75 #include <unistd.h>
76
77 #include "extern.h"
78
79 #define STRIP_TRAILING_SLASH(p) { \
80 while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/') \
81 *--(p).p_end = '\0'; \
82 }
83
84 PATH_T to = { to.p_path, "" };
85
86 uid_t myuid;
87 int Rflag, fflag, iflag, pflag, rflag, vflag;
88 mode_t myumask;
89
90 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
91
92 int main(int, char *[]);
93 int copy(char *[], enum op, int);
94 int mastercmp(const FTSENT **, const FTSENT **);
95
96 int
97 main(int argc, char *argv[])
98 {
99 struct stat to_stat, tmp_stat;
100 enum op type;
101 int Hflag, Lflag, Pflag, ch, fts_options, r;
102 char *target;
103
104 (void)setlocale(LC_ALL, "");
105
106 Hflag = Lflag = Pflag = Rflag = 0;
107 while ((ch = getopt(argc, argv, "HLPRfiprv")) != -1)
108 switch (ch) {
109 case 'H':
110 Hflag = 1;
111 Lflag = Pflag = 0;
112 break;
113 case 'L':
114 Lflag = 1;
115 Hflag = Pflag = 0;
116 break;
117 case 'P':
118 Pflag = 1;
119 Hflag = Lflag = 0;
120 break;
121 case 'R':
122 Rflag = 1;
123 break;
124 case 'f':
125 fflag = 1;
126 iflag = 0;
127 break;
128 case 'i':
129 iflag = isatty(fileno(stdin));
130 fflag = 0;
131 break;
132 case 'p':
133 pflag = 1;
134 break;
135 case 'r':
136 rflag = 1;
137 break;
138 case 'v':
139 vflag = 1;
140 break;
141 case '?':
142 default:
143 usage();
144 break;
145 }
146 argc -= optind;
147 argv += optind;
148
149 if (argc < 2)
150 usage();
151
152 fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
153 if (rflag) {
154 if (Rflag) {
155 errx(EXIT_FAILURE,
156 "the -R and -r options may not be specified together.");
157 /* NOTREACHED */
158 }
159 if (Hflag || Lflag || Pflag) {
160 errx(EXIT_FAILURE,
161 "the -H, -L, and -P options may not be specified with the -r option.");
162 /* NOTREACHED */
163 }
164 fts_options &= ~FTS_PHYSICAL;
165 fts_options |= FTS_LOGICAL;
166 }
167 if (Rflag) {
168 if (Hflag)
169 fts_options |= FTS_COMFOLLOW;
170 if (Lflag) {
171 fts_options &= ~FTS_PHYSICAL;
172 fts_options |= FTS_LOGICAL;
173 }
174 } else {
175 fts_options &= ~FTS_PHYSICAL;
176 fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
177 }
178
179 myuid = getuid();
180
181 /* Copy the umask for explicit mode setting. */
182 myumask = umask(0);
183 (void)umask(myumask);
184
185 /* Save the target base in "to". */
186 target = argv[--argc];
187 if (strlen(target) > MAXPATHLEN) {
188 errx(EXIT_FAILURE, "%s: name too long", target);
189 /* NOTREACHED */
190 }
191 (void)strcpy(to.p_path, target);
192 to.p_end = to.p_path + strlen(to.p_path);
193 if (to.p_path == to.p_end) {
194 *to.p_end++ = '.';
195 *to.p_end = 0;
196 }
197 STRIP_TRAILING_SLASH(to);
198 to.target_end = to.p_end;
199
200 /* Set end of argument list for fts(3). */
201 argv[argc] = NULL;
202
203 /*
204 * Cp has two distinct cases:
205 *
206 * cp [-R] source target
207 * cp [-R] source1 ... sourceN directory
208 *
209 * In both cases, source can be either a file or a directory.
210 *
211 * In (1), the target becomes a copy of the source. That is, if the
212 * source is a file, the target will be a file, and likewise for
213 * directories.
214 *
215 * In (2), the real target is not directory, but "directory/source".
216 */
217 r = stat(to.p_path, &to_stat);
218 if (r == -1 && errno != ENOENT) {
219 err(EXIT_FAILURE, "%s", to.p_path);
220 /* NOTREACHED */
221 }
222 if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
223 /*
224 * Case (1). Target is not a directory.
225 */
226 if (argc > 1) {
227 usage();
228 exit(1);
229 }
230 /*
231 * Need to detect the case:
232 * cp -R dir foo
233 * Where dir is a directory and foo does not exist, where
234 * we want pathname concatenations turned on but not for
235 * the initial mkdir().
236 */
237 if (r == -1) {
238 if (rflag || (Rflag && (Lflag || Hflag)))
239 r = stat(*argv, &tmp_stat);
240 else
241 r = lstat(*argv, &tmp_stat);
242 if (r == -1) {
243 err(EXIT_FAILURE, "%s", *argv);
244 /* NOTREACHED */
245 }
246
247 if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
248 type = DIR_TO_DNE;
249 else
250 type = FILE_TO_FILE;
251 } else
252 type = FILE_TO_FILE;
253 } else {
254 /*
255 * Case (2). Target is a directory.
256 */
257 type = FILE_TO_DIR;
258 }
259
260 exit(copy(argv, type, fts_options));
261 /* NOTREACHED */
262 }
263
264 int
265 copy(char *argv[], enum op type, int fts_options)
266 {
267 struct stat to_stat;
268 FTS *ftsp;
269 FTSENT *curr;
270 int base, dne, nlen, rval;
271 char *p, *tmp;
272
273 base = 0; /* XXX gcc -Wuninitialized (see comment below) */
274
275 if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
276 err(EXIT_FAILURE, "%s", argv[0]);
277 /* NOTREACHED */
278 for (rval = 0; (curr = fts_read(ftsp)) != NULL;) {
279 switch (curr->fts_info) {
280 case FTS_NS:
281 case FTS_DNR:
282 case FTS_ERR:
283 warnx("%s: %s", curr->fts_path,
284 strerror(curr->fts_errno));
285 rval = 1;
286 continue;
287 case FTS_DC: /* Warn, continue. */
288 warnx("%s: directory causes a cycle", curr->fts_path);
289 rval = 1;
290 continue;
291 }
292
293 /*
294 * If we are in case (2) or (3) above, we need to append the
295 * source name to the target name.
296 */
297 if (type != FILE_TO_FILE) {
298 if ((curr->fts_namelen +
299 to.target_end - to.p_path + 1) > MAXPATHLEN) {
300 warnx("%s/%s: name too long (not copied)",
301 to.p_path, curr->fts_name);
302 rval = 1;
303 continue;
304 }
305
306 /*
307 * Need to remember the roots of traversals to create
308 * correct pathnames. If there's a directory being
309 * copied to a non-existent directory, e.g.
310 * cp -R a/dir noexist
311 * the resulting path name should be noexist/foo, not
312 * noexist/dir/foo (where foo is a file in dir), which
313 * is the case where the target exists.
314 *
315 * Also, check for "..". This is for correct path
316 * concatentation for paths ending in "..", e.g.
317 * cp -R .. /tmp
318 * Paths ending in ".." are changed to ".". This is
319 * tricky, but seems the easiest way to fix the problem.
320 *
321 * XXX
322 * Since the first level MUST be FTS_ROOTLEVEL, base
323 * is always initialized.
324 */
325 if (curr->fts_level == FTS_ROOTLEVEL) {
326 if (type != DIR_TO_DNE) {
327 p = strrchr(curr->fts_path, '/');
328 base = (p == NULL) ? 0 :
329 (int)(p - curr->fts_path + 1);
330
331 if (!strcmp(&curr->fts_path[base],
332 ".."))
333 base += 1;
334 } else
335 base = curr->fts_pathlen;
336 }
337
338 p = &curr->fts_path[base];
339 nlen = curr->fts_pathlen - base;
340
341 tmp = to.target_end;
342 if (*p != '/' && *(tmp - 1) != '/')
343 *tmp++ = '/';
344 *tmp = 0;
345
346 (void)strncat(tmp, p, nlen);
347 to.p_end = tmp + nlen;
348 *to.p_end = 0;
349 STRIP_TRAILING_SLASH(to);
350 }
351
352 /* Not an error but need to remember it happened */
353 if (stat(to.p_path, &to_stat) == -1)
354 dne = 1;
355 else {
356 if (to_stat.st_dev == curr->fts_statp->st_dev &&
357 to_stat.st_ino == curr->fts_statp->st_ino) {
358 warnx("%s and %s are identical (not copied).",
359 to.p_path, curr->fts_path);
360 rval = 1;
361 if (S_ISDIR(curr->fts_statp->st_mode))
362 (void)fts_set(ftsp, curr, FTS_SKIP);
363 continue;
364 }
365 if (!S_ISDIR(curr->fts_statp->st_mode) &&
366 S_ISDIR(to_stat.st_mode)) {
367 warnx("cannot overwrite directory %s with non-directory %s",
368 to.p_path, curr->fts_path);
369 rval = 1;
370 continue;
371 }
372 dne = 0;
373 }
374
375 switch (curr->fts_statp->st_mode & S_IFMT) {
376 case S_IFLNK:
377 /* Catch special case of a non dangling symlink */
378 if((fts_options & FTS_LOGICAL) ||
379 ((fts_options & FTS_COMFOLLOW) && curr->fts_level == 0)) {
380 if (copy_file(curr, dne))
381 rval = 1;
382 } else {
383 if (copy_link(curr, !dne))
384 rval = 1;
385 }
386 break;
387 case S_IFDIR:
388 if (!Rflag && !rflag) {
389 if (curr->fts_info == FTS_D)
390 warnx("%s is a directory (not copied).",
391 curr->fts_path);
392 (void)fts_set(ftsp, curr, FTS_SKIP);
393 rval = 1;
394 break;
395 }
396
397 /*
398 * Directories get noticed twice:
399 * In the first pass, create it if needed.
400 * In the second pass, after the children have been copied, set the permissions.
401 */
402 if (curr->fts_info == FTS_D) /* First pass */
403 {
404 /*
405 * If the directory doesn't exist, create the new
406 * one with the from file mode plus owner RWX bits,
407 * modified by the umask. Trade-off between being
408 * able to write the directory (if from directory is
409 * 555) and not causing a permissions race. If the
410 * umask blocks owner writes, we fail..
411 */
412 if (dne) {
413 if (mkdir(to.p_path,
414 curr->fts_statp->st_mode | S_IRWXU) < 0)
415 err(EXIT_FAILURE, "%s",
416 to.p_path);
417 /* NOTREACHED */
418 } else if (!S_ISDIR(to_stat.st_mode)) {
419 errno = ENOTDIR;
420 err(EXIT_FAILURE, "%s",
421 to.p_path);
422 /* NOTREACHED */
423 }
424 }
425 else if (curr->fts_info == FTS_DP) /* Second pass */
426 {
427 /*
428 * If not -p and directory didn't exist, set it to be
429 * the same as the from directory, umodified by the
430 * umask; arguably wrong, but it's been that way
431 * forever.
432 */
433 if (pflag && setfile(curr->fts_statp, 0))
434 rval = 1;
435 else if (dne)
436 (void)chmod(to.p_path,
437 curr->fts_statp->st_mode);
438 }
439 else
440 {
441 warnx("directory %s encountered when not expected.",
442 curr->fts_path);
443 rval = 1;
444 break;
445 }
446
447 break;
448 case S_IFBLK:
449 case S_IFCHR:
450 if (Rflag) {
451 if (copy_special(curr->fts_statp, !dne))
452 rval = 1;
453 } else
454 if (copy_file(curr, dne))
455 rval = 1;
456 break;
457 case S_IFIFO:
458 if (Rflag) {
459 if (copy_fifo(curr->fts_statp, !dne))
460 rval = 1;
461 } else
462 if (copy_file(curr, dne))
463 rval = 1;
464 break;
465 default:
466 if (copy_file(curr, dne))
467 rval = 1;
468 break;
469 }
470 if (vflag)
471 (void)printf("%s -> %s\n", curr->fts_path, to.p_path);
472 }
473 if (errno) {
474 err(EXIT_FAILURE, "fts_read");
475 /* NOTREACHED */
476 }
477 return (rval);
478 }
479
480 /*
481 * mastercmp --
482 * The comparison function for the copy order. The order is to copy
483 * non-directory files before directory files. The reason for this
484 * is because files tend to be in the same cylinder group as their
485 * parent directory, whereas directories tend not to be. Copying the
486 * files first reduces seeking.
487 */
488 int
489 mastercmp(const FTSENT **a, const FTSENT **b)
490 {
491 int a_info, b_info;
492
493 a_info = (*a)->fts_info;
494 if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
495 return (0);
496 b_info = (*b)->fts_info;
497 if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
498 return (0);
499 if (a_info == FTS_D)
500 return (-1);
501 if (b_info == FTS_D)
502 return (1);
503 return (0);
504 }
505