Due to the deletion of the gcc support from libc we need again the
[unix-history] / bin / cp / cp.c
CommitLineData
15637ed4
RG
1/*
2 * Copyright (c) 1988 The Regents of the University of California.
3 * 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
38char copyright[] =
39"@(#) Copyright (c) 1988 The Regents of the University of California.\n\
40 All rights reserved.\n";
41#endif /* not lint */
42
43#ifndef lint
fc9e4a1c 44static char sccsid[] = "@(#)cp.c 5.26 (Berkeley) 10/27/91";
15637ed4
RG
45#endif /* not lint */
46
47/*
48 * cp copies source files to target files.
49 *
50 * The global PATH_T structures "to" and "from" always contain paths to the
51 * current source and target files, respectively. Since cp does not change
52 * directories, these paths can be either absolute or dot-realative.
53 *
54 * The basic algorithm is to initialize "to" and "from", and then call the
55 * recursive copy() function to do the actual work. If "from" is a file,
56 * copy copies the data. If "from" is a directory, copy creates the
57 * corresponding "to" directory, and calls itself recursively on all of
58 * the entries in the "from" directory.
59 */
60
61#include <sys/param.h>
62#include <sys/stat.h>
fc9e4a1c 63#include <sys/mman.h>
15637ed4
RG
64#include <sys/time.h>
65#include <dirent.h>
66#include <fcntl.h>
67#include <errno.h>
68#include <unistd.h>
69#include <stdio.h>
70#include <stdlib.h>
71#include <string.h>
fc9e4a1c
AM
72#include "extern.h"
73
74static void copy __P((void));
75static void copy_dir __P((void));
76static void copy_fifo __P((struct stat *, int));
77static void copy_file __P((struct stat *, int));
78static void copy_link __P((int));
79static void copy_special __P((struct stat *, int));
80static void setfile __P((struct stat *, int));
81static void usage __P((void));
15637ed4
RG
82
83PATH_T from = { from.p_path, "" };
84PATH_T to = { to.p_path, "" };
85
86uid_t myuid;
87int exit_val, myumask;
88int iflag, pflag, orflag, rflag;
89int (*statfcn)();
fc9e4a1c 90char *progname;
15637ed4
RG
91
92main(argc, argv)
93 int argc;
94 char **argv;
95{
96 extern int optind;
97 struct stat to_stat;
98 register int c, r;
99 int symfollow, lstat(), stat();
100 char *old_to, *p;
101
102 /*
103 * The utility cp(1) is used by mv(1) -- except for usage statements,
104 * print the "called as" program name.
105 */
106 progname = (p = rindex(*argv,'/')) ? ++p : *argv;
107
108 symfollow = 0;
109 while ((c = getopt(argc, argv, "Rfhipr")) != EOF) {
110 switch ((char)c) {
111 case 'f':
112 iflag = 0;
113 break;
114 case 'h':
115 symfollow = 1;
116 break;
117 case 'i':
118 iflag = isatty(fileno(stdin));
119 break;
120 case 'p':
121 pflag = 1;
122 break;
123 case 'R':
124 rflag = 1;
125 break;
126 case 'r':
127 orflag = 1;
128 break;
129 case '?':
130 default:
131 usage();
132 break;
133 }
134 }
135 argc -= optind;
136 argv += optind;
137
138 if (argc < 2)
139 usage();
140
141 if (rflag && orflag) {
142 (void)fprintf(stderr,
143 "cp: the -R and -r options are mutually exclusive.\n");
144 exit(1);
145 }
146
15637ed4
RG
147 myuid = getuid();
148
149 /* copy the umask for explicit mode setting */
150 myumask = umask(0);
151 (void)umask(myumask);
152
153 /* consume last argument first. */
154 if (!path_set(&to, argv[--argc]))
155 exit(1);
156
157 statfcn = symfollow || !rflag ? stat : lstat;
158
159 /*
160 * Cp has two distinct cases:
161 *
162 * % cp [-rip] source target
163 * % cp [-rip] source1 ... directory
164 *
165 * In both cases, source can be either a file or a directory.
166 *
167 * In (1), the target becomes a copy of the source. That is, if the
168 * source is a file, the target will be a file, and likewise for
169 * directories.
170 *
171 * In (2), the real target is not directory, but "directory/source".
172 */
173
174 r = stat(to.p_path, &to_stat);
175 if (r == -1 && errno != ENOENT) {
fc9e4a1c 176 err("%s: %s", to.p_path, strerror(errno));
15637ed4
RG
177 exit(1);
178 }
179 if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
180 /*
181 * Case (1). Target is not a directory.
182 */
183 if (argc > 1) {
184 usage();
185 exit(1);
186 }
187 if (!path_set(&from, *argv))
188 exit(1);
189 copy();
190 }
191 else {
192 /*
193 * Case (2). Target is a directory.
194 */
195 for (;; ++argv) {
fc9e4a1c 196 if (!path_set(&from, *argv))
15637ed4 197 continue;
fc9e4a1c
AM
198 if (!(old_to =
199 path_append(&to, path_basename(&from), -1)))
15637ed4 200 continue;
15637ed4
RG
201 copy();
202 if (!--argc)
203 break;
204 path_restore(&to, old_to);
205 }
206 }
207 exit(exit_val);
208}
209
210/* copy file or directory at "from" to "to". */
fc9e4a1c 211static void
15637ed4
RG
212copy()
213{
214 struct stat from_stat, to_stat;
215 int dne, statval;
216
217 statval = statfcn(from.p_path, &from_stat);
218 if (statval == -1) {
fc9e4a1c 219 err("%s: %s", from.p_path, strerror(errno));
15637ed4
RG
220 return;
221 }
222
223 /* not an error, but need to remember it happened */
224 if (stat(to.p_path, &to_stat) == -1)
225 dne = 1;
226 else {
227 if (to_stat.st_dev == from_stat.st_dev &&
228 to_stat.st_ino == from_stat.st_ino) {
229 (void)fprintf(stderr,
230 "%s: %s and %s are identical (not copied).\n",
231 progname, to.p_path, from.p_path);
232 exit_val = 1;
233 return;
234 }
235 dne = 0;
236 }
237
238 switch(from_stat.st_mode & S_IFMT) {
239 case S_IFLNK:
240 copy_link(!dne);
241 return;
242 case S_IFDIR:
243 if (!rflag && !orflag) {
244 (void)fprintf(stderr,
245 "%s: %s is a directory (not copied).\n",
246 progname, from.p_path);
247 exit_val = 1;
248 return;
249 }
250 if (dne) {
251 /*
252 * If the directory doesn't exist, create the new
253 * one with the from file mode plus owner RWX bits,
254 * modified by the umask. Trade-off between being
255 * able to write the directory (if from directory is
256 * 555) and not causing a permissions race. If the
257 * umask blocks owner writes cp fails.
258 */
259 if (mkdir(to.p_path, from_stat.st_mode|S_IRWXU) < 0) {
fc9e4a1c 260 err("%s: %s", to.p_path, strerror(errno));
15637ed4
RG
261 return;
262 }
263 }
fc9e4a1c 264 else if (!S_ISDIR(to_stat.st_mode)) {
15637ed4
RG
265 (void)fprintf(stderr, "%s: %s: not a directory.\n",
266 progname, to.p_path);
267 return;
268 }
269 copy_dir();
270 /*
271 * If not -p and directory didn't exist, set it to be the
272 * same as the from directory, umodified by the umask;
273 * arguably wrong, but it's been that way forever.
274 */
275 if (pflag)
276 setfile(&from_stat, 0);
277 else if (dne)
278 (void)chmod(to.p_path, from_stat.st_mode);
279 return;
280 case S_IFCHR:
281 case S_IFBLK:
282 if (rflag) {
283 copy_special(&from_stat, !dne);
284 return;
285 }
286 break;
287 case S_IFIFO:
288 if (rflag) {
289 copy_fifo(&from_stat, !dne);
290 return;
291 }
292 break;
293 }
294 copy_file(&from_stat, dne);
295}
296
fc9e4a1c 297static void
15637ed4
RG
298copy_file(fs, dne)
299 struct stat *fs;
300 int dne;
301{
fc9e4a1c 302 static char buf[MAXBSIZE];
15637ed4
RG
303 register int from_fd, to_fd, rcount, wcount;
304 struct stat to_stat;
fc9e4a1c 305 char *p;
15637ed4
RG
306
307 if ((from_fd = open(from.p_path, O_RDONLY, 0)) == -1) {
fc9e4a1c 308 err("%s: %s", from.p_path, strerror(errno));
15637ed4
RG
309 return;
310 }
311
312 /*
313 * If the file exists and we're interactive, verify with the user.
314 * If the file DNE, set the mode to be the from file, minus setuid
315 * bits, modified by the umask; arguably wrong, but it makes copying
316 * executables work right and it's been that way forever. (The
317 * other choice is 666 or'ed with the execute bits on the from file
318 * modified by the umask.)
319 */
320 if (!dne) {
321 if (iflag) {
322 int checkch, ch;
323
324 (void)fprintf(stderr, "overwrite %s? ", to.p_path);
325 checkch = ch = getchar();
326 while (ch != '\n' && ch != EOF)
327 ch = getchar();
f87f93ac 328 if (checkch != 'y' && checkch != 'Y') {
15637ed4
RG
329 (void)close(from_fd);
330 return;
331 }
332 }
333 to_fd = open(to.p_path, O_WRONLY|O_TRUNC, 0);
334 } else
335 to_fd = open(to.p_path, O_WRONLY|O_CREAT|O_TRUNC,
336 fs->st_mode & ~(S_ISUID|S_ISGID));
337
338 if (to_fd == -1) {
fc9e4a1c 339 err("%s: %s", to.p_path, strerror(errno));
15637ed4
RG
340 (void)close(from_fd);
341 return;
342 }
343
fc9e4a1c
AM
344 /*
345 * Mmap and write if less than 8M (the limit is so we don't totally
346 * trash memory on big files. This is really a minor hack, but it
347 * wins some CPU back.
348 */
349 if (fs->st_size <= 8 * 1048576) {
350 if ((p = mmap(NULL, fs->st_size, PROT_READ,
351 MAP_FILE, from_fd, (off_t)0)) == (char *)-1)
352 err("%s: %s", from.p_path, strerror(errno));
c804fd49
AM
353 /* Not implemented yet...
354 madvise((caddr_t) p, fs->st_size, MADV_SEQUENTIAL);
355 */
fc9e4a1c
AM
356 if (write(to_fd, p, fs->st_size) != fs->st_size)
357 err("%s: %s", to.p_path, strerror(errno));
c804fd49
AM
358 if (munmap((caddr_t) p, fs->st_size) < 0)
359 err("%s: %s", from.p_path, strerror(errno));
fc9e4a1c
AM
360 } else {
361 while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
362 wcount = write(to_fd, buf, rcount);
363 if (rcount != wcount || wcount == -1) {
364 err("%s: %s", to.p_path, strerror(errno));
365 break;
366 }
15637ed4 367 }
fc9e4a1c
AM
368 if (rcount < 0)
369 err("%s: %s", from.p_path, strerror(errno));
15637ed4 370 }
15637ed4
RG
371 if (pflag)
372 setfile(fs, to_fd);
373 /*
374 * If the source was setuid or setgid, lose the bits unless the
375 * copy is owned by the same user and group.
376 */
377 else if (fs->st_mode & (S_ISUID|S_ISGID) && fs->st_uid == myuid)
378 if (fstat(to_fd, &to_stat))
fc9e4a1c 379 err("%s: %s", to.p_path, strerror(errno));
15637ed4
RG
380#define RETAINBITS (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)
381 else if (fs->st_gid == to_stat.st_gid && fchmod(to_fd,
382 fs->st_mode & RETAINBITS & ~myumask))
fc9e4a1c 383 err("%s: %s", to.p_path, strerror(errno));
15637ed4
RG
384 (void)close(from_fd);
385 if (close(to_fd))
fc9e4a1c 386 err("%s: %s", to.p_path, strerror(errno));
15637ed4
RG
387}
388
fc9e4a1c 389static void
15637ed4
RG
390copy_dir()
391{
392 struct stat from_stat;
393 struct dirent *dp, **dir_list;
394 register int dir_cnt, i;
395 char *old_from, *old_to;
396
397 dir_cnt = scandir(from.p_path, &dir_list, NULL, NULL);
398 if (dir_cnt == -1) {
399 (void)fprintf(stderr, "%s: can't read directory %s.\n",
400 progname, from.p_path);
401 exit_val = 1;
402 }
403
404 /*
405 * Instead of handling directory entries in the order they appear
406 * on disk, do non-directory files before directory files.
407 * There are two reasons to do directories last. The first is
408 * efficiency. Files tend to be in the same cylinder group as
409 * their parent, whereas directories tend not to be. Copying files
410 * all at once reduces seeking. Second, deeply nested tree's
411 * could use up all the file descriptors if we didn't close one
412 * directory before recursivly starting on the next.
413 */
414 /* copy files */
415 for (i = 0; i < dir_cnt; ++i) {
416 dp = dir_list[i];
417 if (dp->d_namlen <= 2 && dp->d_name[0] == '.'
418 && (dp->d_name[1] == NULL || dp->d_name[1] == '.'))
419 goto done;
fc9e4a1c
AM
420 if (!(old_from =
421 path_append(&from, dp->d_name, (int)dp->d_namlen)))
15637ed4 422 goto done;
15637ed4
RG
423
424 if (statfcn(from.p_path, &from_stat) < 0) {
fc9e4a1c 425 err("%s: %s", dp->d_name, strerror(errno));
15637ed4
RG
426 path_restore(&from, old_from);
427 goto done;
428 }
429 if (S_ISDIR(from_stat.st_mode)) {
430 path_restore(&from, old_from);
431 continue;
432 }
fc9e4a1c 433 if (old_to = path_append(&to, dp->d_name, (int)dp->d_namlen)) {
15637ed4
RG
434 copy();
435 path_restore(&to, old_to);
fc9e4a1c 436 }
15637ed4
RG
437 path_restore(&from, old_from);
438done: dir_list[i] = NULL;
fc9e4a1c 439 free(dp);
15637ed4
RG
440 }
441
442 /* copy directories */
443 for (i = 0; i < dir_cnt; ++i) {
444 dp = dir_list[i];
445 if (!dp)
446 continue;
fc9e4a1c
AM
447 if (!(old_from =
448 path_append(&from, dp->d_name, (int)dp->d_namlen))) {
449 free(dp);
15637ed4
RG
450 continue;
451 }
fc9e4a1c
AM
452 if (!(old_to =
453 path_append(&to, dp->d_name, (int)dp->d_namlen))) {
454 free(dp);
15637ed4
RG
455 path_restore(&from, old_from);
456 continue;
457 }
458 copy();
fc9e4a1c 459 free(dp);
15637ed4
RG
460 path_restore(&from, old_from);
461 path_restore(&to, old_to);
462 }
fc9e4a1c 463 free(dir_list);
15637ed4
RG
464}
465
fc9e4a1c 466static void
15637ed4
RG
467copy_link(exists)
468 int exists;
469{
470 int len;
471 char link[MAXPATHLEN];
472
473 if ((len = readlink(from.p_path, link, sizeof(link))) == -1) {
fc9e4a1c 474 err("readlink: %s: %s", from.p_path, strerror(errno));
15637ed4
RG
475 return;
476 }
477 link[len] = '\0';
478 if (exists && unlink(to.p_path)) {
fc9e4a1c 479 err("unlink: %s: %s", to.p_path, strerror(errno));
15637ed4
RG
480 return;
481 }
482 if (symlink(link, to.p_path)) {
fc9e4a1c 483 err("symlink: %s: %s", link, strerror(errno));
15637ed4
RG
484 return;
485 }
486}
487
fc9e4a1c 488static void
15637ed4
RG
489copy_fifo(from_stat, exists)
490 struct stat *from_stat;
491 int exists;
492{
493 if (exists && unlink(to.p_path)) {
fc9e4a1c 494 err("unlink: %s: %s", to.p_path, strerror(errno));
15637ed4
RG
495 return;
496 }
497 if (mkfifo(to.p_path, from_stat->st_mode)) {
fc9e4a1c 498 err("mkfifo: %s: %s", to.p_path, strerror(errno));
15637ed4
RG
499 return;
500 }
501 if (pflag)
502 setfile(from_stat, 0);
503}
504
fc9e4a1c 505static void
15637ed4
RG
506copy_special(from_stat, exists)
507 struct stat *from_stat;
508 int exists;
509{
510 if (exists && unlink(to.p_path)) {
fc9e4a1c 511 err("unlink: %s: %s", to.p_path, strerror(errno));
15637ed4
RG
512 return;
513 }
514 if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
fc9e4a1c 515 err("mknod: %s: %s", to.p_path, strerror(errno));
15637ed4
RG
516 return;
517 }
518 if (pflag)
519 setfile(from_stat, 0);
520}
521
fc9e4a1c 522static void
15637ed4
RG
523setfile(fs, fd)
524 register struct stat *fs;
525 int fd;
526{
527 static struct timeval tv[2];
15637ed4
RG
528
529 fs->st_mode &= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
530
531 tv[0].tv_sec = fs->st_atime;
532 tv[1].tv_sec = fs->st_mtime;
fc9e4a1c
AM
533 if (utimes(to.p_path, tv))
534 err("utimes: %s: %s", to.p_path, strerror(errno));
15637ed4
RG
535 /*
536 * Changing the ownership probably won't succeed, unless we're root
537 * or POSIX_CHOWN_RESTRICTED is not set. Set uid/gid before setting
538 * the mode; current BSD behavior is to remove all setuid bits on
539 * chown. If chown fails, lose setuid/setgid bits.
540 */
541 if (fd ? fchown(fd, fs->st_uid, fs->st_gid) :
542 chown(to.p_path, fs->st_uid, fs->st_gid)) {
fc9e4a1c
AM
543 if (errno != EPERM)
544 err("chown: %s: %s", to.p_path, strerror(errno));
15637ed4
RG
545 fs->st_mode &= ~(S_ISUID|S_ISGID);
546 }
fc9e4a1c
AM
547 if (fd ? fchmod(fd, fs->st_mode) : chmod(to.p_path, fs->st_mode))
548 err("chown: %s: %s", to.p_path, strerror(errno));
15637ed4
RG
549}
550
fc9e4a1c 551static void
15637ed4
RG
552usage()
553{
554 (void)fprintf(stderr,
fc9e4a1c 555"usage: cp [-Rfhip] src target;\n cp [-Rfhip] src1 ... srcN directory\n");
15637ed4
RG
556 exit(1);
557}
fc9e4a1c
AM
558
559#if __STDC__
560#include <stdarg.h>
561#else
562#include <varargs.h>
563#endif
564
565void
566#if __STDC__
567err(const char *fmt, ...)
568#else
569err(fmt, va_alist)
570 char *fmt;
571 va_dcl
572#endif
573{
574 va_list ap;
575#if __STDC__
576 va_start(ap, fmt);
577#else
578 va_start(ap);
579#endif
580 (void)fprintf(stderr, "%s: ", progname);
581 (void)vfprintf(stderr, fmt, ap);
582 va_end(ap);
583 (void)fprintf(stderr, "\n");
584 exit_val = 1;
585}