#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <dev/fssvar.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "snapshot.h"
int
snap_open(char *file, char *backup, time_t *snap_date, char **snap_dev)
{
int i, n, fd, israw, fsinternal, dounlink;
char path[MAXPATHLEN], fss_dev[20], *cp;
dev_t mountdev;
struct fss_set fss;
struct fss_get fsg;
struct stat sb;
struct statvfs *mntbuf, *fs, fsb;
dounlink = 0;
fd = -1;
mntbuf = NULL;
if (lstat(file, &sb) < 0)
goto fail;
fss.fss_mount = NULL;
if (S_ISCHR(sb.st_mode)) {
if ((cp = strrchr(file, '/')) == NULL || cp[1] != 'r') {
errno = EINVAL;
goto fail;
}
snprintf(path, sizeof(path), "%.*s/%s",
(int)(cp - file), file, cp + 2);
n = getmntinfo(&mntbuf, MNT_NOWAIT);
for (fs = mntbuf, i = 0; i < n; i++, fs++) {
if (strcmp(fs->f_mntfromname, path) == 0) {
fss.fss_mount = fs->f_mntonname;
if (stat(fss.fss_mount, &sb) < 0)
goto fail;
break;
}
}
} else if (S_ISDIR(sb.st_mode))
fss.fss_mount = file;
if (fss.fss_mount == NULL) {
errno = EINVAL;
goto fail;
}
fss.fss_bstore = backup ? backup : fss.fss_mount;
fss.fss_csize = 0;
mountdev = sb.st_dev;
israw = 0;
if (stat(fss.fss_bstore, &sb) == 0) {
if (S_ISDIR(sb.st_mode)) {
snprintf(path, sizeof(path),
"%s/XXXXXXXXXX", fss.fss_bstore);
fd = mkstemp(path);
fss.fss_bstore = path;
dounlink = 1;
} else if (S_ISCHR(sb.st_mode)) {
fd = open(fss.fss_bstore, O_RDWR);
israw = 1;
} else
goto fail;
} else {
fd = open(fss.fss_bstore, O_CREAT|O_EXCL|O_WRONLY, 0600);
dounlink = 1;
}
if (fd < 0)
goto fail;
if (fstat(fd, &sb) < 0)
goto fail;
fsinternal = (!israw && sb.st_dev == mountdev);
if (!israw && !fsinternal) {
if (statvfs(fss.fss_bstore, &fsb) < 0)
goto fail;
if (ftruncate(fd, (off_t)fsb.f_frsize*fsb.f_bavail) < 0)
goto fail;
}
if (close(fd) < 0)
goto fail;
fss.fss_flags = FSS_UNCONFIG_ON_CLOSE;
if (dounlink)
fss.fss_flags |= FSS_UNLINK_ON_CREATE;
for (i = 0; ; i++) {
snprintf(fss_dev, sizeof(fss_dev), "/dev/rfss%d", i);
if ((fd = open(fss_dev, O_RDWR, 0)) < 0)
goto fail;
if (ioctl(fd, FSSIOCSET, &fss) < 0) {
if (errno != EBUSY)
goto fail;
close(fd);
fd = -1;
continue;
}
dounlink = 0;
if (snap_dev != NULL) {
*snap_dev = strdup(fss_dev);
if (*snap_dev == NULL) {
ioctl(fd, FSSIOCCLR);
goto fail;
}
}
if (ioctl(fd, FSSIOCGET, &fsg) < 0) {
ioctl(fd, FSSIOCCLR);
goto fail;
}
if (mntbuf)
free(mntbuf);
if (snap_date != NULL)
*snap_date = fsg.fsg_time.tv_sec;
return fd;
}
fail:
if (mntbuf)
free(mntbuf);
if (dounlink)
unlink(fss.fss_bstore);
if (fd >= 0)
close(fd);
return -1;
}