/* $NetBSD$ */ /*- * Copyright (c) 2015 Taylor R. Campbell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __RCSID("$NetBSD$"); #include "namespace.h" #include #include #include int ioctl_pb_init(int fd, unsigned long cmd, struct pb_msg req, struct pb_msg res) { pb_init(res); if (ioctl_pb(fd, cmd, req, res) == -1) { pb_destroy(res); return -1; } return 0; } int ioctl_pb(int fd, unsigned long cmd, struct pb_msg req, struct pb_msg res) { const size_t nmagic = sizeof(PB_IOCTL_MAGIC); struct plistref pref; unsigned char *reqbuf = NULL, *resbuf = NULL; size_t reqlen, reslen; int error; error = pb_encoding_size(req, &reqlen); if (error) goto out; if (reqlen > SIZE_MAX - nmagic) { error = ENOMEM; goto out; } reqbuf = malloc(nmagic + reqlen); if (reqbuf == NULL) { error = ENOMEM; goto out; } (void)memcpy(reqbuf, PB_IOCTL_MAGIC, nmagic); error = pb_encode_to_memory(req, reqbuf + nmagic, reqlen); if (error) goto out; pref.pref_plist = reqbuf; pref.pref_len = nmagic + reqlen; if (ioctl(fd, cmd, &pref) == -1) { error = errno; goto out; } free(reqbuf); reqbuf = NULL; resbuf = pref.pref_plist; reslen = pref.pref_len; error = pb_decode_from_memory(res, resbuf, reslen); if (error) goto out; (void)munmap(resbuf, reslen); resbuf = NULL; out: if (resbuf) (void)munmap(resbuf, reslen); if (reqbuf) free(reqbuf); if (error) { errno = error; return -1; } else { return 0; } }