Skip to content

Instantly share code, notes, and snippets.

@jclulow
Created Jul 8, 2020
Embed
What would you like to do?
#include <stdlib.h>
#include <stdio.h>
#include <libnvpair.h>
#include <fcntl.h>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <err.h>
#include <errno.h>
int
main(int argc, char *argv[])
{
int fd;
struct stat st;
char *buf;
size_t pos = 0;
size_t rem;
int e;
if (argc != 2) {
errx(1, "which file?");
}
if ((fd = open(argv[1], O_RDONLY)) < 0) {
err(1, "open %s", argv[1]);
}
if (fstat(fd, &st) != 0) {
err(1, "fstat %s", argv[1]);
}
rem = st.st_size;
if ((buf = malloc(rem)) == NULL) {
err(1, "malloc");
}
for (;;) {
ssize_t rsz;
if ((rsz = read(fd, buf + pos, rem)) < 0) {
if (errno == EINTR) {
continue;
}
err(1, "read %s", argv[1]);
} else if (rsz == 0) {
if (rem != 0) {
errx(1, "file length changed?");
}
break;
}
rem -= rsz;
pos += rsz;
}
/*
* Look for the appropriate header:
*/
if (st.st_size < 128) {
errx(1, "file too short");
}
uint32_t magic;
bcopy(buf, &magic, sizeof (magic));
if (magic != 0xdeb1dcac) {
errx(1, "magic %x was not %x", magic, 0xdeb1dcac);
}
int32_t version;
bcopy(buf + 4, &version, sizeof (version));
if (version != 1) {
errx(1, "version %d was not %d", version, 1);
}
nvlist_t *nvl;
if ((e = nvlist_unpack(buf + 128, st.st_size - 128, &nvl, 0)) != 0) {
errno = e;
err(1, "nvlist_unpack");
}
nvlist_print(stdout, nvl);
free(buf);
nvlist_free(nvl);
(void) close(fd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment