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