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