1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1991, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 #include <sys/param.h>
33 #include <sys/acl.h>
34 #include <sys/stat.h>
35
36 #include <err.h>
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <fts.h>
40 #include <limits.h>
41 #include <stdbool.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <sysexits.h>
45 #include <unistd.h>
46
47 #include "extern.h"
48
49 #define cp_pct(x, y) ((y == 0) ? 0 : (int)(100.0 * (x) / (y)))
50
51 /*
52 * Memory strategy threshold, in pages: if physmem is larger then this, use a
53 * large buffer.
54 */
55 #define PHYSPAGES_THRESHOLD (32*1024)
56
57 /* Maximum buffer size in bytes - do not allow it to grow larger than this. */
58 #define BUFSIZE_MAX (2*1024*1024)
59
60 /*
61 * Small (default) buffer size in bytes. It's inefficient for this to be
62 * smaller than MAXPHYS.
63 */
64 #define BUFSIZE_SMALL (MAXPHYS)
65
66 /*
67 * Prompt used in -i case.
68 */
69 #define YESNO "(y/n [n]) "
70
71 static ssize_t
copy_fallback(int from_fd,int to_fd)72 copy_fallback(int from_fd, int to_fd)
73 {
74 static char *buf = NULL;
75 static size_t bufsize;
76 ssize_t rcount, wresid, wcount = 0;
77 char *bufp;
78
79 if (buf == NULL) {
80 if (sysconf(_SC_PHYS_PAGES) > PHYSPAGES_THRESHOLD)
81 bufsize = MIN(BUFSIZE_MAX, MAXPHYS * 8);
82 else
83 bufsize = BUFSIZE_SMALL;
84 buf = malloc(bufsize);
85 if (buf == NULL)
86 err(1, "Not enough memory");
87 }
88 rcount = read(from_fd, buf, bufsize);
89 if (rcount <= 0)
90 return (rcount);
91 for (bufp = buf, wresid = rcount; ; bufp += wcount, wresid -= wcount) {
92 wcount = write(to_fd, bufp, wresid);
93 if (wcount <= 0)
94 break;
95 if (wcount >= wresid)
96 break;
97 }
98 return (wcount < 0 ? wcount : rcount);
99 }
100
101 int
copy_file(const FTSENT * entp,bool dne,bool beneath)102 copy_file(const FTSENT *entp, bool dne, bool beneath)
103 {
104 struct stat sb, *fs;
105 ssize_t wcount;
106 off_t wtotal;
107 int ch, checkch, from_fd, rval, to_fd;
108 bool use_copy_file_range = true;
109
110 fs = entp->fts_statp;
111 from_fd = to_fd = -1;
112 if (!lflag && !sflag) {
113 if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) < 0 ||
114 fstat(from_fd, &sb) != 0) {
115 warn("%s", entp->fts_path);
116 if (from_fd >= 0)
117 (void)close(from_fd);
118 return (1);
119 }
120 /*
121 * Check that the file hasn't been replaced with one of a
122 * different type. This can happen if we've been asked to
123 * copy something which is actively being modified and
124 * lost the race, or if we've been asked to copy something
125 * like /proc/X/fd/Y which stat(2) reports as S_IFREG but
126 * is actually something else once you open it.
127 */
128 if ((sb.st_mode & S_IFMT) != (fs->st_mode & S_IFMT)) {
129 warnx("%s: File changed", entp->fts_path);
130 (void)close(from_fd);
131 return (1);
132 }
133 }
134
135 /*
136 * If the file exists and we're interactive, verify with the user.
137 * If the file DNE, set the mode to be the from file, minus setuid
138 * bits, modified by the umask; arguably wrong, but it makes copying
139 * executables work right and it's been that way forever. (The
140 * other choice is 666 or'ed with the execute bits on the from file
141 * modified by the umask.)
142 */
143 if (!dne) {
144 if (nflag) {
145 if (vflag)
146 printf("%s%s not overwritten\n",
147 to.base, to.path);
148 rval = 1;
149 goto done;
150 } else if (iflag) {
151 (void)fprintf(stderr, "overwrite %s%s? %s",
152 to.base, to.path, YESNO);
153 checkch = ch = getchar();
154 while (ch != '\n' && ch != EOF)
155 ch = getchar();
156 if (checkch != 'y' && checkch != 'Y') {
157 (void)fprintf(stderr, "not overwritten\n");
158 rval = 1;
159 goto done;
160 }
161 }
162
163 if (fflag) {
164 /* remove existing destination file */
165 (void)unlinkat(to.dir, to.path,
166 beneath ? AT_RESOLVE_BENEATH : 0);
167 dne = 1;
168 }
169 }
170
171 rval = 0;
172
173 if (lflag) {
174 if (linkat(AT_FDCWD, entp->fts_path, to.dir, to.path, 0) != 0) {
175 warn("%s%s", to.base, to.path);
176 rval = 1;
177 }
178 goto done;
179 }
180
181 if (sflag) {
182 if (symlinkat(entp->fts_path, to.dir, to.path) != 0) {
183 warn("%s%s", to.base, to.path);
184 rval = 1;
185 }
186 goto done;
187 }
188
189 if (!dne) {
190 /* overwrite existing destination file */
191 to_fd = openat(to.dir, to.path,
192 O_WRONLY | O_TRUNC | (beneath ? O_RESOLVE_BENEATH : 0), 0);
193 } else {
194 /* create new destination file */
195 to_fd = openat(to.dir, to.path,
196 O_WRONLY | O_TRUNC | O_CREAT |
197 (beneath ? O_RESOLVE_BENEATH : 0),
198 fs->st_mode & ~(S_ISUID | S_ISGID));
199 }
200 if (to_fd == -1) {
201 warn("%s%s", to.base, to.path);
202 rval = 1;
203 goto done;
204 }
205
206 wtotal = 0;
207 do {
208 if (use_copy_file_range) {
209 wcount = copy_file_range(from_fd, NULL,
210 to_fd, NULL, SSIZE_MAX, 0);
211 if (wcount < 0 && errno == EINVAL) {
212 /* probably a non-seekable descriptor */
213 use_copy_file_range = false;
214 }
215 }
216 if (!use_copy_file_range) {
217 wcount = copy_fallback(from_fd, to_fd);
218 }
219 if (wcount >= 0)
220 wtotal += wcount;
221 else if (errno != EINTR)
222 break;
223 if (info) {
224 info = 0;
225 (void)fprintf(stderr,
226 "%s -> %s%s %3d%%\n",
227 entp->fts_path, to.base, to.path,
228 cp_pct(wtotal, fs->st_size));
229 }
230 } while (wcount != 0);
231 if (wcount < 0) {
232 warn("%s", entp->fts_path);
233 rval = 1;
234 }
235
236 /*
237 * Don't remove the target even after an error. The target might
238 * not be a regular file, or its attributes might be important,
239 * or its contents might be irreplaceable. It would only be safe
240 * to remove it if we created it and its length is 0.
241 */
242 if (pflag && setfile(fs, to_fd, beneath))
243 rval = 1;
244 if (pflag && preserve_fd_acls(from_fd, to_fd) != 0)
245 rval = 1;
246 if (close(to_fd)) {
247 warn("%s%s", to.base, to.path);
248 rval = 1;
249 }
250
251 done:
252 if (from_fd != -1)
253 (void)close(from_fd);
254 return (rval);
255 }
256
257 int
copy_link(const FTSENT * p,bool dne,bool beneath)258 copy_link(const FTSENT *p, bool dne, bool beneath)
259 {
260 ssize_t len;
261 int atflags = beneath ? AT_RESOLVE_BENEATH : 0;
262 char llink[PATH_MAX];
263
264 if (!dne && nflag) {
265 if (vflag)
266 printf("%s%s not overwritten\n", to.base, to.path);
267 return (1);
268 }
269 if ((len = readlink(p->fts_path, llink, sizeof(llink) - 1)) == -1) {
270 warn("readlink: %s", p->fts_path);
271 return (1);
272 }
273 llink[len] = '\0';
274 if (!dne && unlinkat(to.dir, to.path, atflags) != 0) {
275 warn("unlink: %s%s", to.base, to.path);
276 return (1);
277 }
278 if (symlinkat(llink, to.dir, to.path) != 0) {
279 warn("symlink: %s", llink);
280 return (1);
281 }
282 return (pflag ? setfile(p->fts_statp, -1, beneath) : 0);
283 }
284
285 int
copy_fifo(struct stat * from_stat,bool dne,bool beneath)286 copy_fifo(struct stat *from_stat, bool dne, bool beneath)
287 {
288 int atflags = beneath ? AT_RESOLVE_BENEATH : 0;
289
290 if (!dne && nflag) {
291 if (vflag)
292 printf("%s%s not overwritten\n", to.base, to.path);
293 return (1);
294 }
295 if (!dne && unlinkat(to.dir, to.path, atflags) != 0) {
296 warn("unlink: %s%s", to.base, to.path);
297 return (1);
298 }
299 if (mkfifoat(to.dir, to.path, from_stat->st_mode) != 0) {
300 warn("mkfifo: %s%s", to.base, to.path);
301 return (1);
302 }
303 return (pflag ? setfile(from_stat, -1, beneath) : 0);
304 }
305
306 int
copy_special(struct stat * from_stat,bool dne,bool beneath)307 copy_special(struct stat *from_stat, bool dne, bool beneath)
308 {
309 int atflags = beneath ? AT_RESOLVE_BENEATH : 0;
310
311 if (!dne && nflag) {
312 if (vflag)
313 printf("%s%s not overwritten\n", to.base, to.path);
314 return (1);
315 }
316 if (!dne && unlinkat(to.dir, to.path, atflags) != 0) {
317 warn("unlink: %s%s", to.base, to.path);
318 return (1);
319 }
320 if (mknodat(to.dir, to.path, from_stat->st_mode, from_stat->st_rdev) != 0) {
321 warn("mknod: %s%s", to.base, to.path);
322 return (1);
323 }
324 return (pflag ? setfile(from_stat, -1, beneath) : 0);
325 }
326
327 int
setfile(struct stat * fs,int fd,bool beneath)328 setfile(struct stat *fs, int fd, bool beneath)
329 {
330 static struct timespec tspec[2];
331 struct stat ts;
332 int atflags = beneath ? AT_RESOLVE_BENEATH : 0;
333 int rval, gotstat, islink, fdval;
334
335 rval = 0;
336 fdval = fd != -1;
337 islink = !fdval && S_ISLNK(fs->st_mode);
338 if (islink)
339 atflags |= AT_SYMLINK_NOFOLLOW;
340 fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX |
341 S_IRWXU | S_IRWXG | S_IRWXO;
342
343 tspec[0] = fs->st_atim;
344 tspec[1] = fs->st_mtim;
345 if (fdval ? futimens(fd, tspec) :
346 utimensat(to.dir, to.path, tspec, atflags)) {
347 warn("utimensat: %s%s", to.base, to.path);
348 rval = 1;
349 }
350 if (fdval ? fstat(fd, &ts) :
351 fstatat(to.dir, to.path, &ts, atflags)) {
352 gotstat = 0;
353 } else {
354 gotstat = 1;
355 ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
356 S_IRWXU | S_IRWXG | S_IRWXO;
357 }
358 /*
359 * Changing the ownership probably won't succeed, unless we're root
360 * or POSIX_CHOWN_RESTRICTED is not set. Set uid/gid before setting
361 * the mode; current BSD behavior is to remove all setuid bits on
362 * chown. If chown fails, lose setuid/setgid bits.
363 */
364 if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid) {
365 if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) :
366 fchownat(to.dir, to.path, fs->st_uid, fs->st_gid, atflags)) {
367 if (errno != EPERM) {
368 warn("chown: %s%s", to.base, to.path);
369 rval = 1;
370 }
371 fs->st_mode &= ~(S_ISUID | S_ISGID);
372 }
373 }
374
375 if (!gotstat || fs->st_mode != ts.st_mode) {
376 if (fdval ? fchmod(fd, fs->st_mode) :
377 fchmodat(to.dir, to.path, fs->st_mode, atflags)) {
378 warn("chmod: %s%s", to.base, to.path);
379 rval = 1;
380 }
381 }
382
383 if (!Nflag && (!gotstat || fs->st_flags != ts.st_flags)) {
384 if (fdval ? fchflags(fd, fs->st_flags) :
385 chflagsat(to.dir, to.path, fs->st_flags, atflags)) {
386 /*
387 * NFS doesn't support chflags; ignore errors unless
388 * there's reason to believe we're losing bits. (Note,
389 * this still won't be right if the server supports
390 * flags and we were trying to *remove* flags on a file
391 * that we copied, i.e., that we didn't create.)
392 */
393 if (errno != EOPNOTSUPP || fs->st_flags != 0) {
394 warn("chflags: %s%s", to.base, to.path);
395 rval = 1;
396 }
397 }
398 }
399
400 return (rval);
401 }
402
403 int
preserve_fd_acls(int source_fd,int dest_fd)404 preserve_fd_acls(int source_fd, int dest_fd)
405 {
406 acl_t acl;
407 acl_type_t acl_type;
408 int acl_supported = 0, ret, trivial;
409
410 ret = fpathconf(source_fd, _PC_ACL_NFS4);
411 if (ret > 0 ) {
412 acl_supported = 1;
413 acl_type = ACL_TYPE_NFS4;
414 } else if (ret < 0 && errno != EINVAL) {
415 warn("fpathconf(..., _PC_ACL_NFS4) failed for %s%s",
416 to.base, to.path);
417 return (-1);
418 }
419 if (acl_supported == 0) {
420 ret = fpathconf(source_fd, _PC_ACL_EXTENDED);
421 if (ret > 0 ) {
422 acl_supported = 1;
423 acl_type = ACL_TYPE_ACCESS;
424 } else if (ret < 0 && errno != EINVAL) {
425 warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s%s",
426 to.base, to.path);
427 return (-1);
428 }
429 }
430 if (acl_supported == 0)
431 return (0);
432
433 acl = acl_get_fd_np(source_fd, acl_type);
434 if (acl == NULL) {
435 warn("failed to get acl entries while setting %s%s",
436 to.base, to.path);
437 return (-1);
438 }
439 if (acl_is_trivial_np(acl, &trivial)) {
440 warn("acl_is_trivial() failed for %s%s",
441 to.base, to.path);
442 acl_free(acl);
443 return (-1);
444 }
445 if (trivial) {
446 acl_free(acl);
447 return (0);
448 }
449 if (acl_set_fd_np(dest_fd, acl, acl_type) < 0) {
450 warn("failed to set acl entries for %s%s",
451 to.base, to.path);
452 acl_free(acl);
453 return (-1);
454 }
455 acl_free(acl);
456 return (0);
457 }
458
459 int
preserve_dir_acls(const char * source_dir,const char * dest_dir)460 preserve_dir_acls(const char *source_dir, const char *dest_dir)
461 {
462 int source_fd = -1, dest_fd = -1, ret;
463
464 if ((source_fd = open(source_dir, O_DIRECTORY | O_RDONLY)) < 0) {
465 warn("%s: failed to copy ACLs", source_dir);
466 return (-1);
467 }
468 dest_fd = (*dest_dir == '\0') ? to.dir :
469 openat(to.dir, dest_dir, O_DIRECTORY, AT_RESOLVE_BENEATH);
470 if (dest_fd < 0) {
471 warn("%s: failed to copy ACLs to %s%s", source_dir,
472 to.base, dest_dir);
473 close(source_fd);
474 return (-1);
475 }
476 if ((ret = preserve_fd_acls(source_fd, dest_fd)) != 0) {
477 /* preserve_fd_acls() already printed a message */
478 }
479 if (dest_fd != to.dir)
480 close(dest_fd);
481 close(source_fd);
482 return (ret);
483 }
484
485 void
usage(void)486 usage(void)
487 {
488
489 (void)fprintf(stderr, "%s\n%s\n",
490 "usage: cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpsvx] "
491 "source_file target_file",
492 " cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpsvx] "
493 "source_file ... "
494 "target_directory");
495 exit(EX_USAGE);
496 }
497