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