summaryrefslogtreecommitdiff
path: root/usr.bin/rsync/copy.c
blob: 43967b2e3204dc5ec525044ade6e817a82469cd4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*	$OpenBSD: copy.c,v 1.4 2022/12/26 19:16:02 jmc Exp $ */
/*
 * Copyright (c) 2021 Claudio Jeker <claudio@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>

#include <err.h>
#include <fcntl.h>
#include <unistd.h>

#include "extern.h"

#define _MAXBSIZE (64 * 1024)

/*
 * Return true if all bytes in buffer are zero.
 * A buffer of zero length is also considered a zero buffer.
 */
static int
iszero(const void *b, size_t len)
{
	const unsigned char *c = b;

	for (; len > 0; len--) {
		if (*c++ != '\0')
			return 0;
	}
	return 1;
}

static int
copy_internal(int fromfd, int tofd)
{
	char buf[_MAXBSIZE];
	ssize_t r, w;

	while ((r = read(fromfd, buf, sizeof(buf))) > 0) {
		if (iszero(buf, sizeof(buf))) {
			if (lseek(tofd, r, SEEK_CUR) == -1)
				return -1;
		} else {
			w = write(tofd, buf, r);
			if (r != w || w == -1)
				return -1;
		}
	}
	if (r == -1)
		return -1;
	if (ftruncate(tofd, lseek(tofd, 0, SEEK_CUR)) == -1)
		return -1;
	return 0;
}

void
copy_file(int rootfd, const char *basedir, const struct flist *f)
{
	int fromfd, tofd, dfd;

	dfd = openat(rootfd, basedir, O_RDONLY | O_DIRECTORY);
	if (dfd == -1)
		err(ERR_FILE_IO, "%s: openat", basedir);

	fromfd = openat(dfd, f->path, O_RDONLY | O_NOFOLLOW);
	if (fromfd == -1)
		err(ERR_FILE_IO, "%s/%s: openat", basedir, f->path);
	close(dfd);

	tofd = openat(rootfd, f->path,
	    O_WRONLY | O_NOFOLLOW | O_TRUNC | O_CREAT | O_EXCL,
	    0600);
	if (tofd == -1)
		err(ERR_FILE_IO, "%s: openat", f->path);

	if (copy_internal(fromfd, tofd) == -1)
		err(ERR_FILE_IO, "%s: copy file", f->path);

	close(fromfd);
	close(tofd);
}