Skip to content

Instantly share code, notes, and snippets.

@khenriks
Last active June 21, 2023 11:05
Show Gist options
  • Save khenriks/4f31e54a50830c65005b143418a93c98 to your computer and use it in GitHub Desktop.
Save khenriks/4f31e54a50830c65005b143418a93c98 to your computer and use it in GitHub Desktop.

Revisions

  1. khenriks revised this gist Feb 21, 2022. No changes.
  2. khenriks revised this gist Feb 21, 2022. 1 changed file with 6 additions and 0 deletions.
    6 changes: 6 additions & 0 deletions zfs_mount.c
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,9 @@
    // 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>
  3. khenriks created this gist Feb 21, 2022.
    50 changes: 50 additions & 0 deletions zfs_mount.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    #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;
    }