Skip to content

Instantly share code, notes, and snippets.

@jackwasey
Forked from khenriks/zfs_mount.c
Created July 3, 2022 17:20
Show Gist options
  • Save jackwasey/49afa04cea7dee58ad5a5f9f4405c623 to your computer and use it in GitHub Desktop.
Save jackwasey/49afa04cea7dee58ad5a5f9f4405c623 to your computer and use it in GitHub Desktop.
Auxiliary mount helper for non-root ZFS mounts
// Compile with:
// cc -DUID=$UID -DUSER=$USER -D_LARGEFILE64_SOURCE -o zfs_mount zfs_mount.c `pkg-config --cflags --libs libzfs`
// then install with:
// sudo cp zfs_mount /usr/local/bin
// sudo setcap cap_sys_admin+ep /usr/local/bin/zfs_mount
#include <libzfs.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#define STR_AUX(x) #x
#define STR(x) STR_AUX(x)
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <fs_name>\n", argv[0]);
return 2;
}
char* fs_path = argv[1];
char* user = getlogin();
uid_t uid = getuid();
if (strcmp(user, STR(USER)) != 0 || uid != UID) {
fprintf(stderr, "Bad user: %s (%d)\n", user, uid);
return 1;
}
libzfs_handle_t *g_zfs;
if ((g_zfs = libzfs_init()) == NULL) {
fprintf(stderr, "%s\n", libzfs_error_init(errno));
return 1;
}
zfs_handle_t *zhp;
if ((zhp = zfs_open(g_zfs, fs_path, ZFS_TYPE_FILESYSTEM)) == NULL) {
fprintf(stderr, "filesystem '%s' cannot be "
"mounted, does it exist?\n", fs_path);
libzfs_fini(g_zfs);
return 1;
}
if (zfs_mount(zhp, "", 0)) {
fprintf(stderr, "zfs_mount() failed: %s\n",
libzfs_error_description(g_zfs));
zfs_close(zhp);
libzfs_fini(g_zfs);
return 1;
}
zfs_close(zhp);
libzfs_fini(g_zfs);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment