xref: /freebsd/lib/libnetgraph/msg.c (revision 924226fba12cc9a228c73b956e1b7fa24c60b055)
1 /*
2  * msg.c
3  *
4  * Copyright (c) 1996-1999 Whistle Communications, Inc.
5  * All rights reserved.
6  *
7  * Subject to the following obligations and disclaimer of warranty, use and
8  * redistribution of this software, in source or object code forms, with or
9  * without modifications are expressly permitted by Whistle Communications;
10  * provided, however, that:
11  * 1. Any and all reproductions of the source or object code must include the
12  *    copyright notice above and the following disclaimer of warranties; and
13  * 2. No rights are granted, in any manner or form, to use Whistle
14  *    Communications, Inc. trademarks, including the mark "WHISTLE
15  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
16  *    such appears in the above copyright notice or in the software.
17  *
18  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
19  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
20  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
21  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
23  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
24  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
25  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
26  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
27  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
28  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
29  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
30  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
31  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
34  * OF SUCH DAMAGE.
35  *
36  * Author: Archie Cobbs <archie@whistle.com>
37  *
38  * $Whistle: msg.c,v 1.9 1999/01/20 00:57:23 archie Exp $
39  */
40 
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include <sys/types.h>
45 #include <sys/socket.h>
46 #include <stdarg.h>
47 #include <stdatomic.h>
48 #include <netgraph/ng_message.h>
49 #include <netgraph/ng_socket.h>
50 
51 #include "netgraph.h"
52 #include "internal.h"
53 
54 /* Next message token value */
55 static _Atomic(unsigned int) gMsgId;
56 
57 /* For delivering both messages and replies */
58 static int	NgDeliverMsg(int cs, const char *path,
59 		  const struct ng_mesg *hdr, const void *args, size_t arglen);
60 
61 /*
62  * Send a message to a node using control socket node "cs".
63  * Returns -1 if error and sets errno appropriately.
64  * If successful, returns the message ID (token) used.
65  */
66 int
67 NgSendMsg(int cs, const char *path,
68 	  int cookie, int cmd, const void *args, size_t arglen)
69 {
70 	struct ng_mesg msg;
71 
72 	/* Prepare message header */
73 	memset(&msg, 0, sizeof(msg));
74 	msg.header.version = NG_VERSION;
75 	msg.header.typecookie = cookie;
76 	msg.header.token = atomic_fetch_add(&gMsgId, 1) & INT_MAX;
77 	msg.header.flags = NGF_ORIG;
78 	msg.header.cmd = cmd;
79 	snprintf((char *)msg.header.cmdstr, NG_CMDSTRSIZ, "cmd%d", cmd);
80 
81 	/* Deliver message */
82 	if (NgDeliverMsg(cs, path, &msg, args, arglen) < 0)
83 		return (-1);
84 	return (msg.header.token);
85 }
86 
87 /*
88  * Send a message given in ASCII format. We first ask the node to translate
89  * the command into binary, and then we send the binary.
90  */
91 int
92 NgSendAsciiMsg(int cs, const char *path, const char *fmt, ...)
93 {
94 	struct ng_mesg *reply, *binary, *ascii;
95 	char *buf, *cmd, *args;
96 	va_list fmtargs;
97 	int token;
98 
99 	/* Parse out command and arguments */
100 	va_start(fmtargs, fmt);
101 	vasprintf(&buf, fmt, fmtargs);
102 	va_end(fmtargs);
103 	if (buf == NULL)
104 		return (-1);
105 
106 	/* Parse out command, arguments */
107 	for (cmd = buf; isspace(*cmd); cmd++)
108 		;
109 	for (args = cmd; *args != '\0' && !isspace(*args); args++)
110 		;
111 	if (*args != '\0') {
112 		while (isspace(*args))
113 			*args++ = '\0';
114 	}
115 
116 	/* Get a bigger buffer to hold inner message header plus arg string */
117 	if ((ascii = malloc(sizeof(struct ng_mesg)
118 	    + strlen(args) + 1)) == NULL) {
119 		free(buf);
120 		return (-1);
121 	}
122 	memset(ascii, 0, sizeof(*ascii));
123 
124 	/* Build inner header (only need cmdstr, arglen, and data fields) */
125 	strncpy((char *)ascii->header.cmdstr, cmd,
126 	    sizeof(ascii->header.cmdstr) - 1);
127 	strcpy(ascii->data, args);
128 	ascii->header.arglen = strlen(ascii->data) + 1;
129 	free(buf);
130 
131 	/* Send node a request to convert ASCII to binary */
132 	if (NgSendMsg(cs, path, NGM_GENERIC_COOKIE, NGM_ASCII2BINARY,
133 	    (u_char *)ascii, sizeof(*ascii) + ascii->header.arglen) < 0) {
134 		free(ascii);
135 		return (-1);
136 	}
137 	free(ascii);
138 
139 	/* Get reply */
140 	if (NgAllocRecvMsg(cs, &reply, NULL) < 0)
141 		return (-1);
142 
143 	/* Now send binary version */
144 	binary = (struct ng_mesg *)reply->data;
145 	binary->header.token = atomic_fetch_add(&gMsgId, 1) & INT_MAX;
146 	binary->header.version = NG_VERSION;
147 	if (NgDeliverMsg(cs,
148 	    path, binary, binary->data, binary->header.arglen) < 0) {
149 		free(reply);
150 		return (-1);
151 	}
152 	token = binary->header.token;
153 	free(reply);
154 	return (token);
155 }
156 
157 /*
158  * Send a message that is a reply to a previously received message.
159  * Returns -1 and sets errno on error, otherwise returns zero.
160  */
161 int
162 NgSendReplyMsg(int cs, const char *path,
163 	const struct ng_mesg *msg, const void *args, size_t arglen)
164 {
165 	struct ng_mesg rep;
166 
167 	/* Prepare message header */
168 	rep = *msg;
169 	rep.header.flags = NGF_RESP;
170 
171 	/* Deliver message */
172 	return (NgDeliverMsg(cs, path, &rep, args, arglen));
173 }
174 
175 /*
176  * Send a message to a node using control socket node "cs".
177  * Returns -1 if error and sets errno appropriately, otherwise zero.
178  */
179 static int
180 NgDeliverMsg(int cs, const char *path,
181 	const struct ng_mesg *hdr, const void *args, size_t arglen)
182 {
183 	u_char sgbuf[NG_PATHSIZ + NGSA_OVERHEAD];
184 	struct sockaddr_ng *const sg = (struct sockaddr_ng *) sgbuf;
185 	u_char *buf = NULL;
186 	struct ng_mesg *msg;
187 	int errnosv = 0;
188 	int rtn = 0;
189 
190 	/* Sanity check */
191 	if (args == NULL)
192 		arglen = 0;
193 
194 	/* Get buffer */
195 	if ((buf = malloc(sizeof(*msg) + arglen)) == NULL) {
196 		errnosv = errno;
197 		if (_gNgDebugLevel >= 1)
198 			NGLOG("malloc");
199 		rtn = -1;
200 		goto done;
201 	}
202 	msg = (struct ng_mesg *) buf;
203 
204 	/* Finalize message */
205 	*msg = *hdr;
206 	msg->header.arglen = arglen;
207 	memcpy(msg->data, args, arglen);
208 
209 	/* Prepare socket address */
210 	sg->sg_family = AF_NETGRAPH;
211 	/* XXX handle overflow */
212 	strlcpy(sg->sg_data, path, NG_PATHSIZ);
213 	sg->sg_len = strlen(sg->sg_data) + 1 + NGSA_OVERHEAD;
214 
215 	/* Debugging */
216 	if (_gNgDebugLevel >= 2) {
217 		NGLOGX("SENDING %s:",
218 		    (msg->header.flags & NGF_RESP) ? "RESPONSE" : "MESSAGE");
219 		_NgDebugSockaddr(sg);
220 		_NgDebugMsg(msg, sg->sg_data);
221 	}
222 
223 	/* Send it */
224 	if (sendto(cs, msg, sizeof(*msg) + arglen,
225 		   0, (struct sockaddr *) sg, sg->sg_len) < 0) {
226 		errnosv = errno;
227 		if (_gNgDebugLevel >= 1)
228 			NGLOG("sendto(%s)", sg->sg_data);
229 		rtn = -1;
230 		goto done;
231 	}
232 
233 	/* Wait for reply if there should be one. */
234 	if (msg->header.cmd & NGM_HASREPLY && !(msg->header.flags & NGF_RESP)) {
235 		struct pollfd rfds;
236 		int n;
237 
238 		rfds.fd = cs;
239 		rfds.events = POLLIN;
240 		rfds.revents = 0;
241 		n = poll(&rfds, 1, INFTIM);
242 		if (n == -1) {
243 			errnosv = errno;
244 			if (_gNgDebugLevel >= 1)
245 				NGLOG("poll");
246 			rtn = -1;
247 		}
248 	}
249 
250 done:
251 	/* Done */
252 	free(buf);		/* OK if buf is NULL */
253 	errno = errnosv;
254 	return (rtn);
255 }
256 
257 /*
258  * Receive a control message.
259  *
260  * On error, this returns -1 and sets errno.
261  * Otherwise, it returns the length of the received reply.
262  */
263 int
264 NgRecvMsg(int cs, struct ng_mesg *rep, size_t replen, char *path)
265 {
266 	u_char sgbuf[NG_PATHSIZ + NGSA_OVERHEAD];
267 	struct sockaddr_ng *const sg = (struct sockaddr_ng *) sgbuf;
268 	socklen_t sglen = sizeof(sgbuf);
269 	int len, errnosv;
270 
271 	/* Read reply */
272 	len = recvfrom(cs, rep, replen, 0, (struct sockaddr *) sg, &sglen);
273 	if (len < 0) {
274 		errnosv = errno;
275 		if (_gNgDebugLevel >= 1)
276 			NGLOG("recvfrom");
277 		goto errout;
278 	}
279 	if (path != NULL)
280 		strlcpy(path, sg->sg_data, NG_PATHSIZ);
281 
282 	/* Debugging */
283 	if (_gNgDebugLevel >= 2) {
284 		NGLOGX("RECEIVED %s:",
285 		    (rep->header.flags & NGF_RESP) ? "RESPONSE" : "MESSAGE");
286 		_NgDebugSockaddr(sg);
287 		_NgDebugMsg(rep, sg->sg_data);
288 	}
289 
290 	/* Done */
291 	return (len);
292 
293 errout:
294 	errno = errnosv;
295 	return (-1);
296 }
297 
298 /*
299  * Identical to NgRecvMsg() except buffer is dynamically allocated.
300  */
301 int
302 NgAllocRecvMsg(int cs, struct ng_mesg **rep, char *path)
303 {
304 	int len;
305 	socklen_t optlen;
306 
307 	optlen = sizeof(len);
308 	if (getsockopt(cs, SOL_SOCKET, SO_RCVBUF, &len, &optlen) == -1 ||
309 	    (*rep = malloc(len)) == NULL)
310 		return (-1);
311 	if ((len = NgRecvMsg(cs, *rep, len, path)) < 0)
312 		free(*rep);
313 	return (len);
314 }
315 
316 /*
317  * Receive a control message and convert the arguments to ASCII
318  */
319 int
320 NgRecvAsciiMsg(int cs, struct ng_mesg *reply, size_t replen, char *path)
321 {
322 	struct ng_mesg *msg, *ascii;
323 	int bufSize, errnosv;
324 	u_char *buf;
325 
326 	/* Allocate buffer */
327 	bufSize = 2 * sizeof(*reply) + replen;
328 	if ((buf = malloc(bufSize)) == NULL)
329 		return (-1);
330 	msg = (struct ng_mesg *)buf;
331 	ascii = (struct ng_mesg *)msg->data;
332 
333 	/* Get binary message */
334 	if (NgRecvMsg(cs, msg, bufSize, path) < 0)
335 		goto fail;
336 	memcpy(reply, msg, sizeof(*msg));
337 
338 	/* Ask originating node to convert the arguments to ASCII */
339 	if (NgSendMsg(cs, path, NGM_GENERIC_COOKIE,
340 	    NGM_BINARY2ASCII, msg, sizeof(*msg) + msg->header.arglen) < 0)
341 		goto fail;
342 	if (NgRecvMsg(cs, msg, bufSize, NULL) < 0)
343 		goto fail;
344 
345 	/* Copy result to client buffer */
346 	if (sizeof(*ascii) + ascii->header.arglen > replen) {
347 		errno = ERANGE;
348 fail:
349 		errnosv = errno;
350 		free(buf);
351 		errno = errnosv;
352 		return (-1);
353 	}
354 	strncpy(reply->data, ascii->data, ascii->header.arglen);
355 
356 	/* Done */
357 	free(buf);
358 	return (0);
359 }
360 
361 /*
362  * Identical to NgRecvAsciiMsg() except buffer is dynamically allocated.
363  */
364 int
365 NgAllocRecvAsciiMsg(int cs, struct ng_mesg **reply, char *path)
366 {
367 	int len;
368 	socklen_t optlen;
369 
370 	optlen = sizeof(len);
371 	if (getsockopt(cs, SOL_SOCKET, SO_RCVBUF, &len, &optlen) == -1 ||
372 	    (*reply = malloc(len)) == NULL)
373 		return (-1);
374 	if ((len = NgRecvAsciiMsg(cs, *reply, len, path)) < 0)
375 		free(*reply);
376 	return (len);
377 }
378