Initial import from FreeBSD RELENG_4:
[dragonfly.git] / bin / cp / cp.c
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  * 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.
23  *
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
34  * SUCH DAMAGE.
35  */
36
37 #ifndef lint
38 static char const copyright[] =
39 "@(#) Copyright (c) 1988, 1993, 1994\n\
40         The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42
43 #ifndef lint
44 #if 0
45 static char sccsid[] = "@(#)cp.c        8.2 (Berkeley) 4/1/94";
46 #endif
47 static const char rcsid[] =
48   "$FreeBSD: src/bin/cp/cp.c,v 1.24.2.7 2002/09/24 12:41:04 mckay Exp $";
49 #endif /* not lint */
50
51 /*
52  * Cp copies source files to target files.
53  *
54  * The global PATH_T structure "to" always contains the path to the
55  * current target file.  Since fts(3) does not change directories,
56  * this path can be either absolute or dot-relative.
57  *
58  * The basic algorithm is to initialize "to" and use fts(3) to traverse
59  * the file hierarchy rooted in the argument list.  A trivial case is the
60  * case of 'cp file1 file2'.  The more interesting case is the case of
61  * 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
62  * path (relative to the root of the traversal) is appended to dir (stored
63  * in "to") to form the final target path.
64  */
65
66 #include <sys/param.h>
67 #include <sys/stat.h>
68
69 #include <err.h>
70 #include <errno.h>
71 #include <fts.h>
72 #include <limits.h>
73 #include <stdio.h>
74 #include <stdlib.h>
75 #include <string.h>
76 #include <unistd.h>
77
78 #include "extern.h"
79
80 #define STRIP_TRAILING_SLASH(p) {                                       \
81         while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')      \
82                 *--(p).p_end = 0;                                       \
83 }
84
85 PATH_T to = { to.p_path, "", "" };
86
87 int Rflag, fflag, iflag, nflag, pflag, rflag, vflag;
88
89 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
90
91 int copy __P((char *[], enum op, int));
92 int mastercmp __P((const FTSENT **, const FTSENT **));
93
94 int
95 main(argc, argv)
96         int argc;
97         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         Hflag = Lflag = Pflag = 0;
105         while ((ch = getopt(argc, argv, "HLPRfinprv")) != -1)
106                 switch (ch) {
107                 case 'H':
108                         Hflag = 1;
109                         Lflag = Pflag = 0;
110                         break;
111                 case 'L':
112                         Lflag = 1;
113                         Hflag = Pflag = 0;
114                         break;
115                 case 'P':
116                         Pflag = 1;
117                         Hflag = Lflag = 0;
118                         break;
119                 case 'R':
120                         Rflag = 1;
121                         break;
122                 case 'f':
123                         fflag = 1;
124                         iflag = nflag = 0;
125                         break;
126                 case 'i':
127                         iflag = 1;
128                         fflag = nflag = 0;
129                         break;
130                 case 'n':
131                         nflag = 1;
132                         fflag = iflag = 0;
133                         break;
134                 case 'p':
135                         pflag = 1;
136                         break;
137                 case 'r':
138                         rflag = 1;
139                         break;
140                 case 'v':
141                         vflag = 1;
142                         break;
143                 default:
144                         usage();
145                         break;
146                 }
147         argc -= optind;
148         argv += optind;
149
150         if (argc < 2)
151                 usage();
152
153         fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
154         if (rflag) {
155                 if (Rflag)
156                         errx(1,
157                     "the -R and -r options may not be specified together.");
158                 if (Hflag || Lflag || Pflag)
159                         errx(1,
160         "the -H, -L, and -P options may not be specified with the -r option.");
161                 fts_options &= ~FTS_PHYSICAL;
162                 fts_options |= FTS_LOGICAL;
163         }
164         if (Rflag) {
165                 if (Hflag)
166                         fts_options |= FTS_COMFOLLOW;
167                 if (Lflag) {
168                         fts_options &= ~FTS_PHYSICAL;
169                         fts_options |= FTS_LOGICAL;
170                 }
171         } else {
172                 fts_options &= ~FTS_PHYSICAL;
173                 fts_options |= FTS_LOGICAL;
174         }
175
176         /* Save the target base in "to". */
177         target = argv[--argc];
178         if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
179                 errx(1, "%s: name too long", target);
180         to.p_end = to.p_path + strlen(to.p_path);
181         if (to.p_path == to.p_end) {
182                 *to.p_end++ = '.';
183                 *to.p_end = 0;
184         }
185         STRIP_TRAILING_SLASH(to);
186         to.target_end = to.p_end;
187
188         /* Set end of argument list for fts(3). */
189         argv[argc] = NULL;
190
191         /*
192          * Cp has two distinct cases:
193          *
194          * cp [-R] source target
195          * cp [-R] source1 ... sourceN directory
196          *
197          * In both cases, source can be either a file or a directory.
198          *
199          * In (1), the target becomes a copy of the source. That is, if the
200          * source is a file, the target will be a file, and likewise for
201          * directories.
202          *
203          * In (2), the real target is not directory, but "directory/source".
204          */
205         r = stat(to.p_path, &to_stat);
206         if (r == -1 && errno != ENOENT)
207                 err(1, "%s", to.p_path);
208         if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
209                 /*
210                  * Case (1).  Target is not a directory.
211                  */
212                 if (argc > 1) {
213                         usage();
214                         exit(1);
215                 }
216                 /*
217                  * Need to detect the case:
218                  *      cp -R dir foo
219                  * Where dir is a directory and foo does not exist, where
220                  * we want pathname concatenations turned on but not for
221                  * the initial mkdir().
222                  */
223                 if (r == -1) {
224                         if (rflag || (Rflag && (Lflag || Hflag)))
225                                 stat(*argv, &tmp_stat);
226                         else
227                                 lstat(*argv, &tmp_stat);
228
229                         if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
230                                 type = DIR_TO_DNE;
231                         else
232                                 type = FILE_TO_FILE;
233                 } else
234                         type = FILE_TO_FILE;
235         } else
236                 /*
237                  * Case (2).  Target is a directory.
238                  */
239                 type = FILE_TO_DIR;
240
241         exit (copy(argv, type, fts_options));
242 }
243
244 int
245 copy(argv, type, fts_options)
246         char *argv[];
247         enum op type;
248         int fts_options;
249 {
250         struct stat to_stat;
251         FTS *ftsp;
252         FTSENT *curr;
253         int base = 0, dne, badcp, nlen, rval;
254         char *p, *target_mid;
255         mode_t mask, mode;
256
257         /*
258          * Keep an inverted copy of the umask, for use in correcting
259          * permissions on created directories when not using -p.
260          */
261         mask = ~umask(0777);
262         umask(~mask);
263
264         if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
265                 err(1, NULL);
266         for (badcp = rval = 0; (curr = fts_read(ftsp)) != NULL; badcp = 0) {
267                 switch (curr->fts_info) {
268                 case FTS_NS:
269                 case FTS_DNR:
270                 case FTS_ERR:
271                         warnx("%s: %s",
272                             curr->fts_path, strerror(curr->fts_errno));
273                         badcp = rval = 1;
274                         continue;
275                 case FTS_DC:                    /* Warn, continue. */
276                         warnx("%s: directory causes a cycle", curr->fts_path);
277                         badcp = rval = 1;
278                         continue;
279                 }
280
281                 /*
282                  * If we are in case (2) or (3) above, we need to append the
283                  * source name to the target name.
284                  */
285                 if (type != FILE_TO_FILE) {
286                         /*
287                          * Need to remember the roots of traversals to create
288                          * correct pathnames.  If there's a directory being
289                          * copied to a non-existent directory, e.g.
290                          *      cp -R a/dir noexist
291                          * the resulting path name should be noexist/foo, not
292                          * noexist/dir/foo (where foo is a file in dir), which
293                          * is the case where the target exists.
294                          *
295                          * Also, check for "..".  This is for correct path
296                          * concatenation for paths ending in "..", e.g.
297                          *      cp -R .. /tmp
298                          * Paths ending in ".." are changed to ".".  This is
299                          * tricky, but seems the easiest way to fix the problem.
300                          *
301                          * XXX
302                          * Since the first level MUST be FTS_ROOTLEVEL, base
303                          * is always initialized.
304                          */
305                         if (curr->fts_level == FTS_ROOTLEVEL) {
306                                 if (type != DIR_TO_DNE) {
307                                         p = strrchr(curr->fts_path, '/');
308                                         base = (p == NULL) ? 0 :
309                                             (int)(p - curr->fts_path + 1);
310
311                                         if (!strcmp(&curr->fts_path[base],
312                                             ".."))
313                                                 base += 1;
314                                 } else
315                                         base = curr->fts_pathlen;
316                         }
317
318                         p = &curr->fts_path[base];
319                         nlen = curr->fts_pathlen - base;
320                         target_mid = to.target_end;
321                         if (*p != '/' && target_mid[-1] != '/')
322                                 *target_mid++ = '/';
323                         *target_mid = 0;
324                         if (target_mid - to.p_path + nlen >= PATH_MAX) {
325                                 warnx("%s%s: name too long (not copied)",
326                                     to.p_path, p);
327                                 badcp = rval = 1;
328                                 continue;
329                         }
330                         (void)strncat(target_mid, p, nlen);
331                         to.p_end = target_mid + nlen;
332                         *to.p_end = 0;
333                         STRIP_TRAILING_SLASH(to);
334                 }
335
336                 if (curr->fts_info == FTS_DP) {
337                         /*
338                          * We are nearly finished with this directory.  If we
339                          * didn't actually copy it, or otherwise don't need to
340                          * change its attributes, then we are done.
341                          */
342                         if (!curr->fts_number)
343                                 continue;
344                         /*
345                          * If -p is in effect, set all the attributes.
346                          * Otherwise, set the correct permissions, limited
347                          * by the umask.  Optimise by avoiding a chmod()
348                          * if possible (which is usually the case if we
349                          * made the directory).  Note that mkdir() does not
350                          * honour setuid, setgid and sticky bits, but we
351                          * normally want to preserve them on directories.
352                          */
353                         if (pflag) {
354                                 if (setfile(curr->fts_statp, 0))
355                                     rval = 1;
356                         } else {
357                                 mode = curr->fts_statp->st_mode;
358                                 if ((mode & (S_ISUID | S_ISGID | S_ISTXT)) ||
359                                     ((mode | S_IRWXU) & mask) != (mode & mask))
360                                         if (chmod(to.p_path, mode & mask) != 0){
361                                                 warn("chmod: %s", to.p_path);
362                                                 rval = 1;
363                                         }
364                         }
365                         continue;
366                 }
367
368                 /* Not an error but need to remember it happened */
369                 if (stat(to.p_path, &to_stat) == -1)
370                         dne = 1;
371                 else {
372                         if (to_stat.st_dev == curr->fts_statp->st_dev &&
373                             to_stat.st_ino == curr->fts_statp->st_ino) {
374                                 warnx("%s and %s are identical (not copied).",
375                                     to.p_path, curr->fts_path);
376                                 badcp = rval = 1;
377                                 if (S_ISDIR(curr->fts_statp->st_mode))
378                                         (void)fts_set(ftsp, curr, FTS_SKIP);
379                                 continue;
380                         }
381                         if (!S_ISDIR(curr->fts_statp->st_mode) &&
382                             S_ISDIR(to_stat.st_mode)) {
383                 warnx("cannot overwrite directory %s with non-directory %s",
384                                     to.p_path, curr->fts_path);
385                                 badcp = rval = 1;
386                                 continue;
387                         }
388                         dne = 0;
389                 }
390
391                 switch (curr->fts_statp->st_mode & S_IFMT) {
392                 case S_IFLNK:
393                         if (copy_link(curr, !dne))
394                                 badcp = rval = 1;
395                         break;
396                 case S_IFDIR:
397                         if (!Rflag && !rflag) {
398                                 warnx("%s is a directory (not copied).",
399                                     curr->fts_path);
400                                 (void)fts_set(ftsp, curr, FTS_SKIP);
401                                 badcp = rval = 1;
402                                 break;
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(1, "%s", to.p_path);
416                         } else if (!S_ISDIR(to_stat.st_mode)) {
417                                 errno = ENOTDIR;
418                                 err(1, "%s", to.p_path);
419                         }
420                         /*
421                          * Arrange to correct directory attributes later
422                          * (in the post-order phase) if this is a new
423                          * directory, or if the -p flag is in effect.
424                          */
425                         curr->fts_number = pflag || dne;
426                         break;
427                 case S_IFBLK:
428                 case S_IFCHR:
429                         if (Rflag) {
430                                 if (copy_special(curr->fts_statp, !dne))
431                                         badcp = rval = 1;
432                         } else {
433                                 if (copy_file(curr, dne))
434                                         badcp = rval = 1;
435                         }
436                         break;
437                 case S_IFIFO:
438                         if (Rflag) {
439                                 if (copy_fifo(curr->fts_statp, !dne))
440                                         badcp = rval = 1;
441                         } else {
442                                 if (copy_file(curr, dne))
443                                         badcp = rval = 1;
444                         }
445                         break;
446                 default:
447                         if (copy_file(curr, dne))
448                                 badcp = rval = 1;
449                         break;
450                 }
451                 if (vflag && !badcp)
452                         (void)printf("%s -> %s\n", curr->fts_path, to.p_path);
453         }
454         if (errno)
455                 err(1, "fts_read");
456         return (rval);
457 }
458
459 /*
460  * mastercmp --
461  *      The comparison function for the copy order.  The order is to copy
462  *      non-directory files before directory files.  The reason for this
463  *      is because files tend to be in the same cylinder group as their
464  *      parent directory, whereas directories tend not to be.  Copying the
465  *      files first reduces seeking.
466  */
467 int
468 mastercmp(a, b)
469         const FTSENT **a, **b;
470 {
471         int a_info, b_info;
472
473         a_info = (*a)->fts_info;
474         if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
475                 return (0);
476         b_info = (*b)->fts_info;
477         if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
478                 return (0);
479         if (a_info == FTS_D)
480                 return (-1);
481         if (b_info == FTS_D)
482                 return (1);
483         return (0);
484 }