#include <sys/types.h>
#include <err.h>
#include <fcntl.h>
#include <unistd.h>
#include "extern.h"
#define _MAXBSIZE (64 * 1024)
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_abs, const struct flist *f)
{
int fromfd, tofd, dfd;
dfd = open(basedir_abs, O_RDONLY | O_DIRECTORY);
if (dfd == -1)
err(ERR_FILE_IO, "%s: open", basedir_abs);
fromfd = openat(dfd, f->path, O_RDONLY | O_NOFOLLOW);
if (fromfd == -1)
err(ERR_FILE_IO, "%s/%s: openat", basedir_abs, 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);
}