xref: /openbsd-src/usr.bin/rsync/copy.c (revision d9a51c353c88dac7b4a389c112b4cfe97b8e3a46)
1 /*	$OpenBSD: copy.c,v 1.4 2022/12/26 19:16:02 jmc Exp $ */
2 /*
3  * Copyright (c) 2021 Claudio Jeker <claudio@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include <sys/types.h>
19 
20 #include <err.h>
21 #include <fcntl.h>
22 #include <unistd.h>
23 
24 #include "extern.h"
25 
26 #define _MAXBSIZE (64 * 1024)
27 
28 /*
29  * Return true if all bytes in buffer are zero.
30  * A buffer of zero length is also considered a zero buffer.
31  */
32 static int
iszero(const void * b,size_t len)33 iszero(const void *b, size_t len)
34 {
35 	const unsigned char *c = b;
36 
37 	for (; len > 0; len--) {
38 		if (*c++ != '\0')
39 			return 0;
40 	}
41 	return 1;
42 }
43 
44 static int
copy_internal(int fromfd,int tofd)45 copy_internal(int fromfd, int tofd)
46 {
47 	char buf[_MAXBSIZE];
48 	ssize_t r, w;
49 
50 	while ((r = read(fromfd, buf, sizeof(buf))) > 0) {
51 		if (iszero(buf, sizeof(buf))) {
52 			if (lseek(tofd, r, SEEK_CUR) == -1)
53 				return -1;
54 		} else {
55 			w = write(tofd, buf, r);
56 			if (r != w || w == -1)
57 				return -1;
58 		}
59 	}
60 	if (r == -1)
61 		return -1;
62 	if (ftruncate(tofd, lseek(tofd, 0, SEEK_CUR)) == -1)
63 		return -1;
64 	return 0;
65 }
66 
67 void
copy_file(int rootfd,const char * basedir,const struct flist * f)68 copy_file(int rootfd, const char *basedir, const struct flist *f)
69 {
70 	int fromfd, tofd, dfd;
71 
72 	dfd = openat(rootfd, basedir, O_RDONLY | O_DIRECTORY);
73 	if (dfd == -1)
74 		err(ERR_FILE_IO, "%s: openat", basedir);
75 
76 	fromfd = openat(dfd, f->path, O_RDONLY | O_NOFOLLOW);
77 	if (fromfd == -1)
78 		err(ERR_FILE_IO, "%s/%s: openat", basedir, f->path);
79 	close(dfd);
80 
81 	tofd = openat(rootfd, f->path,
82 	    O_WRONLY | O_NOFOLLOW | O_TRUNC | O_CREAT | O_EXCL,
83 	    0600);
84 	if (tofd == -1)
85 		err(ERR_FILE_IO, "%s: openat", f->path);
86 
87 	if (copy_internal(fromfd, tofd) == -1)
88 		err(ERR_FILE_IO, "%s: copy file", f->path);
89 
90 	close(fromfd);
91 	close(tofd);
92 }
93