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