1 /* $OpenBSD: imsg_util.c,v 1.21 2023/07/18 15:07:41 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 39 struct ibuf * 40 ibuf_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 66 struct ibuf * 67 ibuf_static(void) 68 { 69 return ibuf_open(IKED_MSGBUF_MAX); 70 } 71 72 size_t 73 ibuf_length(struct ibuf *buf) 74 { 75 if (buf == NULL) 76 return (0); 77 return (ibuf_size(buf)); 78 } 79 80 struct ibuf * 81 ibuf_getdata(struct ibuf *buf, size_t len) 82 { 83 void *data; 84 85 if ((data = ibuf_seek(buf, buf->rpos, len)) == NULL) 86 return (NULL); 87 buf->rpos += len; 88 89 return (ibuf_new(data, len)); 90 } 91 92 struct ibuf * 93 ibuf_dup(struct ibuf *buf) 94 { 95 if (buf == NULL) 96 return (NULL); 97 return (ibuf_new(ibuf_data(buf), ibuf_size(buf))); 98 } 99 100 struct ibuf * 101 ibuf_random(size_t len) 102 { 103 struct ibuf *buf; 104 void *ptr; 105 106 if ((buf = ibuf_open(len)) == NULL) 107 return (NULL); 108 if ((ptr = ibuf_reserve(buf, len)) == NULL) { 109 ibuf_free(buf); 110 return (NULL); 111 } 112 arc4random_buf(ptr, len); 113 return (buf); 114 } 115 116 int 117 ibuf_setsize(struct ibuf *buf, size_t len) 118 { 119 if (len > buf->size) 120 return (-1); 121 buf->wpos = len; 122 return (0); 123 } 124