1/* $OpenBSD: imsg_util.c,v 1.22 2023/12/12 15:52:58 claudio Exp $ */ 2 3/* 4 * Copyright (c) 2010-2013 Reyk Floeter <reyk@openbsd.org> 5 * 6 * Permission to use, copy, modify, and distribute this software for any 7 * purpose with or without fee is hereby granted, provided that the above 8 * copyright notice and this permission notice appear in all copies. 9 * 10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 */ 18 19#include <sys/queue.h> 20#include <sys/socket.h> 21#include <sys/uio.h> 22 23#include <netdb.h> 24#include <stdio.h> 25#include <stdlib.h> 26#include <unistd.h> 27#include <string.h> 28#include <errno.h> 29#include <fcntl.h> 30#include <ctype.h> 31#include <event.h> 32 33#include "iked.h" 34 35/* 36 * Extending the imsg buffer API for internal use 37 */ 38 39struct ibuf * 40ibuf_new(const void *data, size_t len) 41{ 42 struct ibuf *buf; 43 44 if ((buf = ibuf_dynamic(len, 45 IKED_MSGBUF_MAX)) == NULL) 46 return (NULL); 47 48 if (len == 0) 49 return (buf); 50 51 if (data == NULL) { 52 if (ibuf_add_zero(buf, len) != 0) { 53 ibuf_free(buf); 54 return (NULL); 55 } 56 } else { 57 if (ibuf_add(buf, data, len) != 0) { 58 ibuf_free(buf); 59 return (NULL); 60 } 61 } 62 63 return (buf); 64} 65 66struct ibuf * 67ibuf_static(void) 68{ 69 return ibuf_open(IKED_MSGBUF_MAX); 70} 71 72size_t 73ibuf_length(struct ibuf *buf) 74{ 75 if (buf == NULL) 76 return (0); 77 return (ibuf_size(buf)); 78} 79 80struct ibuf * 81ibuf_getdata(struct ibuf *buf, size_t len) 82{ 83 struct ibuf tmp; 84 85 if (ibuf_get_ibuf(buf, len, &tmp) == -1) 86 return (NULL); 87 88 return (ibuf_new(ibuf_data(&tmp), ibuf_size(&tmp))); 89} 90 91struct ibuf * 92ibuf_dup(struct ibuf *buf) 93{ 94 if (buf == NULL) 95 return (NULL); 96 return (ibuf_new(ibuf_data(buf), ibuf_size(buf))); 97} 98 99struct ibuf * 100ibuf_random(size_t len) 101{ 102 struct ibuf *buf; 103 void *ptr; 104 105 if ((buf = ibuf_open(len)) == NULL) 106 return (NULL); 107 if ((ptr = ibuf_reserve(buf, len)) == NULL) { 108 ibuf_free(buf); 109 return (NULL); 110 } 111 arc4random_buf(ptr, len); 112 return (buf); 113} 114 115int 116ibuf_setsize(struct ibuf *buf, size_t len) 117{ 118 if (len > buf->size) 119 return (-1); 120 buf->wpos = len; 121 return (0); 122} 123