xref: /freebsd/lib/libnetgraph/msg.c (revision 2008043f386721d58158e37e0d7e50df8095942d)
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 #include <sys/types.h>
43 #include <sys/socket.h>
44 #include <stdarg.h>
45 #include <stdatomic.h>
46 #include <netgraph/ng_message.h>
47 #include <netgraph/ng_socket.h>
48 
49 #include "netgraph.h"
50 #include "internal.h"
51 
52 /* Next message token value */
53 static _Atomic(unsigned int) gMsgId;
54 
55 /* For delivering both messages and replies */
56 static int	NgDeliverMsg(int cs, const char *path,
57 		  const struct ng_mesg *hdr, const void *args, size_t arglen);
58 
59 /*
60  * Send a message to a node using control socket node "cs".
61  * Returns -1 if error and sets errno appropriately.
62  * If successful, returns the message ID (token) used.
63  */
64 int
65 NgSendMsg(int cs, const char *path,
66 	  int cookie, int cmd, const void *args, size_t arglen)
67 {
68 	struct ng_mesg msg;
69 
70 	/* Prepare message header */
71 	memset(&msg, 0, sizeof(msg));
72 	msg.header.version = NG_VERSION;
73 	msg.header.typecookie = cookie;
74 	msg.header.token = atomic_fetch_add(&gMsgId, 1) & INT_MAX;
75 	msg.header.flags = NGF_ORIG;
76 	msg.header.cmd = cmd;
77 	snprintf((char *)msg.header.cmdstr, NG_CMDSTRSIZ, "cmd%d", cmd);
78 
79 	/* Deliver message */
80 	if (NgDeliverMsg(cs, path, &msg, args, arglen) < 0)
81 		return (-1);
82 	return (msg.header.token);
83 }
84 
85 /*
86  * Send a message given in ASCII format. We first ask the node to translate
87  * the command into binary, and then we send the binary.
88  */
89 int
90 NgSendAsciiMsg(int cs, const char *path, const char *fmt, ...)
91 {
92 	struct ng_mesg *reply, *binary, *ascii;
93 	char *buf, *cmd, *args;
94 	va_list fmtargs;
95 	int token;
96 
97 	/* Parse out command and arguments */
98 	va_start(fmtargs, fmt);
99 	vasprintf(&buf, fmt, fmtargs);
100 	va_end(fmtargs);
101 	if (buf == NULL)
102 		return (-1);
103 
104 	/* Parse out command, arguments */
105 	for (cmd = buf; isspace(*cmd); cmd++)
106 		;
107 	for (args = cmd; *args != '\0' && !isspace(*args); args++)
108 		;
109 	if (*args != '\0') {
110 		while (isspace(*args))
111 			*args++ = '\0';
112 	}
113 
114 	/* Get a bigger buffer to hold inner message header plus arg string */
115 	if ((ascii = malloc(sizeof(struct ng_mesg)
116 	    + strlen(args) + 1)) == NULL) {
117 		free(buf);
118 		return (-1);
119 	}
120 	memset(ascii, 0, sizeof(*ascii));
121 
122 	/* Build inner header (only need cmdstr, arglen, and data fields) */
123 	strncpy((char *)ascii->header.cmdstr, cmd,
124 	    sizeof(ascii->header.cmdstr) - 1);
125 	strcpy(ascii->data, args);
126 	ascii->header.arglen = strlen(ascii->data) + 1;
127 	free(buf);
128 
129 	/* Send node a request to convert ASCII to binary */
130 	if (NgSendMsg(cs, path, NGM_GENERIC_COOKIE, NGM_ASCII2BINARY,
131 	    (u_char *)ascii, sizeof(*ascii) + ascii->header.arglen) < 0) {
132 		free(ascii);
133 		return (-1);
134 	}
135 	free(ascii);
136 
137 	/* Get reply */
138 	if (NgAllocRecvMsg(cs, &reply, NULL) < 0)
139 		return (-1);
140 
141 	/* Now send binary version */
142 	binary = (struct ng_mesg *)reply->data;
143 	binary->header.token = atomic_fetch_add(&gMsgId, 1) & INT_MAX;
144 	binary->header.version = NG_VERSION;
145 	if (NgDeliverMsg(cs,
146 	    path, binary, binary->data, binary->header.arglen) < 0) {
147 		free(reply);
148 		return (-1);
149 	}
150 	token = binary->header.token;
151 	free(reply);
152 	return (token);
153 }
154 
155 /*
156  * Send a message that is a reply to a previously received message.
157  * Returns -1 and sets errno on error, otherwise returns zero.
158  */
159 int
160 NgSendReplyMsg(int cs, const char *path,
161 	const struct ng_mesg *msg, const void *args, size_t arglen)
162 {
163 	struct ng_mesg rep;
164 
165 	/* Prepare message header */
166 	rep = *msg;
167 	rep.header.flags = NGF_RESP;
168 
169 	/* Deliver message */
170 	return (NgDeliverMsg(cs, path, &rep, args, arglen));
171 }
172 
173 /*
174  * Send a message to a node using control socket node "cs".
175  * Returns -1 if error and sets errno appropriately, otherwise zero.
176  */
177 static int
178 NgDeliverMsg(int cs, const char *path,
179 	const struct ng_mesg *hdr, const void *args, size_t arglen)
180 {
181 	u_char sgbuf[NG_PATHSIZ + NGSA_OVERHEAD];
182 	struct sockaddr_ng *const sg = (struct sockaddr_ng *) sgbuf;
183 	u_char *buf = NULL;
184 	struct ng_mesg *msg;
185 	int errnosv = 0;
186 	int rtn = 0;
187 
188 	/* Sanity check */
189 	if (args == NULL)
190 		arglen = 0;
191 
192 	/* Get buffer */
193 	if ((buf = malloc(sizeof(*msg) + arglen)) == NULL) {
194 		errnosv = errno;
195 		if (_gNgDebugLevel >= 1)
196 			NGLOG("malloc");
197 		rtn = -1;
198 		goto done;
199 	}
200 	msg = (struct ng_mesg *) buf;
201 
202 	/* Finalize message */
203 	*msg = *hdr;
204 	msg->header.arglen = arglen;
205 	memcpy(msg->data, args, arglen);
206 
207 	/* Prepare socket address */
208 	sg->sg_family = AF_NETGRAPH;
209 	/* XXX handle overflow */
210 	strlcpy(sg->sg_data, path, NG_PATHSIZ);
211 	sg->sg_len = strlen(sg->sg_data) + 1 + NGSA_OVERHEAD;
212 
213 	/* Debugging */
214 	if (_gNgDebugLevel >= 2) {
215 		NGLOGX("SENDING %s:",
216 		    (msg->header.flags & NGF_RESP) ? "RESPONSE" : "MESSAGE");
217 		_NgDebugSockaddr(sg);
218 		_NgDebugMsg(msg, sg->sg_data);
219 	}
220 
221 	/* Send it */
222 	if (sendto(cs, msg, sizeof(*msg) + arglen,
223 		   0, (struct sockaddr *) sg, sg->sg_len) < 0) {
224 		errnosv = errno;
225 		if (_gNgDebugLevel >= 1)
226 			NGLOG("sendto(%s)", sg->sg_data);
227 		rtn = -1;
228 		goto done;
229 	}
230 
231 	/* Wait for reply if there should be one. */
232 	if (msg->header.cmd & NGM_HASREPLY && !(msg->header.flags & NGF_RESP)) {
233 		struct pollfd rfds;
234 		int n;
235 
236 		rfds.fd = cs;
237 		rfds.events = POLLIN;
238 		rfds.revents = 0;
239 		n = poll(&rfds, 1, INFTIM);
240 		if (n == -1) {
241 			errnosv = errno;
242 			if (_gNgDebugLevel >= 1)
243 				NGLOG("poll");
244 			rtn = -1;
245 		}
246 	}
247 
248 done:
249 	/* Done */
250 	free(buf);		/* OK if buf is NULL */
251 	errno = errnosv;
252 	return (rtn);
253 }
254 
255 /*
256  * Receive a control message.
257  *
258  * On error, this returns -1 and sets errno.
259  * Otherwise, it returns the length of the received reply.
260  */
261 int
262 NgRecvMsg(int cs, struct ng_mesg *rep, size_t replen, char *path)
263 {
264 	u_char sgbuf[NG_PATHSIZ + NGSA_OVERHEAD];
265 	struct sockaddr_ng *const sg = (struct sockaddr_ng *) sgbuf;
266 	socklen_t sglen = sizeof(sgbuf);
267 	int len, errnosv;
268 
269 	/* Read reply */
270 	len = recvfrom(cs, rep, replen, 0, (struct sockaddr *) sg, &sglen);
271 	if (len < 0) {
272 		errnosv = errno;
273 		if (_gNgDebugLevel >= 1)
274 			NGLOG("recvfrom");
275 		goto errout;
276 	}
277 	if (path != NULL)
278 		strlcpy(path, sg->sg_data, NG_PATHSIZ);
279 
280 	/* Debugging */
281 	if (_gNgDebugLevel >= 2) {
282 		NGLOGX("RECEIVED %s:",
283 		    (rep->header.flags & NGF_RESP) ? "RESPONSE" : "MESSAGE");
284 		_NgDebugSockaddr(sg);
285 		_NgDebugMsg(rep, sg->sg_data);
286 	}
287 
288 	/* Done */
289 	return (len);
290 
291 errout:
292 	errno = errnosv;
293 	return (-1);
294 }
295 
296 /*
297  * Identical to NgRecvMsg() except buffer is dynamically allocated.
298  */
299 int
300 NgAllocRecvMsg(int cs, struct ng_mesg **rep, char *path)
301 {
302 	int len;
303 	socklen_t optlen;
304 
305 	optlen = sizeof(len);
306 	if (getsockopt(cs, SOL_SOCKET, SO_RCVBUF, &len, &optlen) == -1 ||
307 	    (*rep = malloc(len)) == NULL)
308 		return (-1);
309 	if ((len = NgRecvMsg(cs, *rep, len, path)) < 0)
310 		free(*rep);
311 	return (len);
312 }
313 
314 /*
315  * Receive a control message and convert the arguments to ASCII
316  */
317 int
318 NgRecvAsciiMsg(int cs, struct ng_mesg *reply, size_t replen, char *path)
319 {
320 	struct ng_mesg *msg, *ascii;
321 	int bufSize, errnosv;
322 	u_char *buf;
323 
324 	/* Allocate buffer */
325 	bufSize = 2 * sizeof(*reply) + replen;
326 	if ((buf = malloc(bufSize)) == NULL)
327 		return (-1);
328 	msg = (struct ng_mesg *)buf;
329 	ascii = (struct ng_mesg *)msg->data;
330 
331 	/* Get binary message */
332 	if (NgRecvMsg(cs, msg, bufSize, path) < 0)
333 		goto fail;
334 	memcpy(reply, msg, sizeof(*msg));
335 
336 	/* Ask originating node to convert the arguments to ASCII */
337 	if (NgSendMsg(cs, path, NGM_GENERIC_COOKIE,
338 	    NGM_BINARY2ASCII, msg, sizeof(*msg) + msg->header.arglen) < 0)
339 		goto fail;
340 	if (NgRecvMsg(cs, msg, bufSize, NULL) < 0)
341 		goto fail;
342 
343 	/* Copy result to client buffer */
344 	if (sizeof(*ascii) + ascii->header.arglen > replen) {
345 		errno = ERANGE;
346 fail:
347 		errnosv = errno;
348 		free(buf);
349 		errno = errnosv;
350 		return (-1);
351 	}
352 	strncpy(reply->data, ascii->data, ascii->header.arglen);
353 
354 	/* Done */
355 	free(buf);
356 	return (0);
357 }
358 
359 /*
360  * Identical to NgRecvAsciiMsg() except buffer is dynamically allocated.
361  */
362 int
363 NgAllocRecvAsciiMsg(int cs, struct ng_mesg **reply, char *path)
364 {
365 	int len;
366 	socklen_t optlen;
367 
368 	optlen = sizeof(len);
369 	if (getsockopt(cs, SOL_SOCKET, SO_RCVBUF, &len, &optlen) == -1 ||
370 	    (*reply = malloc(len)) == NULL)
371 		return (-1);
372 	if ((len = NgRecvAsciiMsg(cs, *reply, len, path)) < 0)
373 		free(*reply);
374 	return (len);
375 }
376