msg.c revision 154265
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: head/lib/libnetgraph/msg.c 154265 2006-01-12 19:14:40Z glebius $");
43
44#include <sys/types.h>
45#include <stdarg.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 */
53static int	gMsgId;
54
55/* For delivering both messages and replies */
56static 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 */
64int
65NgSendMsg(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	if (++gMsgId < 0)
75		gMsgId = 1;
76	msg.header.token = gMsgId;
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 */
91int
92NgSendAsciiMsg(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	if (++gMsgId < 0)
146		gMsgId = 1;
147	binary->header.token = gMsgId;
148	binary->header.version = NG_VERSION;
149	if (NgDeliverMsg(cs,
150	    path, binary, binary->data, binary->header.arglen) < 0) {
151		free(reply);
152		return (-1);
153	}
154	token = binary->header.token;
155	free(reply);
156	return (token);
157}
158
159/*
160 * Send a message that is a reply to a previously received message.
161 * Returns -1 and sets errno on error, otherwise returns zero.
162 */
163int
164NgSendReplyMsg(int cs, const char *path,
165	const struct ng_mesg *msg, const void *args, size_t arglen)
166{
167	struct ng_mesg rep;
168
169	/* Prepare message header */
170	rep = *msg;
171	rep.header.flags = NGF_RESP;
172
173	/* Deliver message */
174	return (NgDeliverMsg(cs, path, &rep, args, arglen));
175}
176
177/*
178 * Send a message to a node using control socket node "cs".
179 * Returns -1 if error and sets errno appropriately, otherwise zero.
180 */
181static int
182NgDeliverMsg(int cs, const char *path,
183	const struct ng_mesg *hdr, const void *args, size_t arglen)
184{
185	u_char sgbuf[NG_PATHSIZ + NGSA_OVERHEAD];
186	struct sockaddr_ng *const sg = (struct sockaddr_ng *) sgbuf;
187	u_char *buf = NULL;
188	struct ng_mesg *msg;
189	int errnosv = 0;
190	int rtn = 0;
191
192	/* Sanity check */
193	if (args == NULL)
194		arglen = 0;
195
196	/* Get buffer */
197	if ((buf = malloc(sizeof(*msg) + arglen)) == NULL) {
198		errnosv = errno;
199		if (_gNgDebugLevel >= 1)
200			NGLOG("malloc");
201		rtn = -1;
202		goto done;
203	}
204	msg = (struct ng_mesg *) buf;
205
206	/* Finalize message */
207	*msg = *hdr;
208	msg->header.arglen = arglen;
209	memcpy(msg->data, args, arglen);
210
211	/* Prepare socket address */
212	sg->sg_family = AF_NETGRAPH;
213	/* XXX handle overflow */
214	strlcpy(sg->sg_data, path, NG_PATHSIZ);
215	sg->sg_len = strlen(sg->sg_data) + 1 + NGSA_OVERHEAD;
216
217	/* Debugging */
218	if (_gNgDebugLevel >= 2) {
219		NGLOGX("SENDING %s:",
220		    (msg->header.flags & NGF_RESP) ? "RESPONSE" : "MESSAGE");
221		_NgDebugSockaddr(sg);
222		_NgDebugMsg(msg, sg->sg_data);
223	}
224
225	/* Send it */
226	if (sendto(cs, msg, sizeof(*msg) + arglen,
227		   0, (struct sockaddr *) sg, sg->sg_len) < 0) {
228		errnosv = errno;
229		if (_gNgDebugLevel >= 1)
230			NGLOG("sendto(%s)", sg->sg_data);
231		rtn = -1;
232		goto done;
233	}
234
235	/* Wait for reply if there should be one. */
236	if (msg->header.cmd & NGM_HASREPLY) {
237		fd_set rfds;
238		int n;
239
240		FD_ZERO(&rfds);
241		FD_SET(cs, &rfds);
242		n = select(cs + 1, &rfds, NULL, NULL, NULL);
243		if (n == -1) {
244			errnosv = errno;
245			if (_gNgDebugLevel >= 1)
246				NGLOG("select");
247			rtn = -1;
248		}
249	}
250
251done:
252	/* Done */
253	free(buf);		/* OK if buf is NULL */
254	errno = errnosv;
255	return (rtn);
256}
257
258/*
259 * Receive a control message.
260 *
261 * On error, this returns -1 and sets errno.
262 * Otherwise, it returns the length of the received reply.
263 */
264int
265NgRecvMsg(int cs, struct ng_mesg *rep, size_t replen, char *path)
266{
267	u_char sgbuf[NG_PATHSIZ + NGSA_OVERHEAD];
268	struct sockaddr_ng *const sg = (struct sockaddr_ng *) sgbuf;
269	socklen_t sglen = sizeof(sgbuf);
270	int len, errnosv;
271
272	/* Read reply */
273	len = recvfrom(cs, rep, replen, 0, (struct sockaddr *) sg, &sglen);
274	if (len < 0) {
275		errnosv = errno;
276		if (_gNgDebugLevel >= 1)
277			NGLOG("recvfrom");
278		goto errout;
279	}
280	if (path != NULL)
281		strlcpy(path, sg->sg_data, NG_PATHSIZ);
282
283	/* Debugging */
284	if (_gNgDebugLevel >= 2) {
285		NGLOGX("RECEIVED %s:",
286		    (rep->header.flags & NGF_RESP) ? "RESPONSE" : "MESSAGE");
287		_NgDebugSockaddr(sg);
288		_NgDebugMsg(rep, sg->sg_data);
289	}
290
291	/* Done */
292	return (len);
293
294errout:
295	errno = errnosv;
296	return (-1);
297}
298
299/*
300 * Identical to NgRecvMsg() except buffer is dynamically allocated.
301 */
302int
303NgAllocRecvMsg(int cs, struct ng_mesg **rep, char *path)
304{
305	int len;
306	socklen_t optlen;
307
308	optlen = sizeof(len);
309	if (getsockopt(cs, SOL_SOCKET, SO_RCVBUF, &len, &optlen) == -1 ||
310	    (*rep = malloc(len)) == NULL)
311		return (-1);
312	if ((len = NgRecvMsg(cs, *rep, len, path)) < 0)
313		free(*rep);
314	return (len);
315}
316
317/*
318 * Receive a control message and convert the arguments to ASCII
319 */
320int
321NgRecvAsciiMsg(int cs, struct ng_mesg *reply, size_t replen, char *path)
322{
323	struct ng_mesg *msg, *ascii;
324	int bufSize, errnosv;
325	u_char *buf;
326
327	/* Allocate buffer */
328	bufSize = 2 * sizeof(*reply) + replen;
329	if ((buf = malloc(bufSize)) == NULL)
330		return (-1);
331	msg = (struct ng_mesg *)buf;
332	ascii = (struct ng_mesg *)msg->data;
333
334	/* Get binary message */
335	if (NgRecvMsg(cs, msg, bufSize, path) < 0)
336		goto fail;
337	memcpy(reply, msg, sizeof(*msg));
338
339	/* Ask originating node to convert the arguments to ASCII */
340	if (NgSendMsg(cs, path, NGM_GENERIC_COOKIE,
341	    NGM_BINARY2ASCII, msg, sizeof(*msg) + msg->header.arglen) < 0)
342		goto fail;
343	if (NgRecvMsg(cs, msg, bufSize, NULL) < 0)
344		goto fail;
345
346	/* Copy result to client buffer */
347	if (sizeof(*ascii) + ascii->header.arglen > replen) {
348		errno = ERANGE;
349fail:
350		errnosv = errno;
351		free(buf);
352		errno = errnosv;
353		return (-1);
354	}
355	strncpy(reply->data, ascii->data, ascii->header.arglen);
356
357	/* Done */
358	free(buf);
359	return (0);
360}
361
362/*
363 * Identical to NgRecvAsciiMsg() except buffer is dynamically allocated.
364 */
365int
366NgAllocRecvAsciiMsg(int cs, struct ng_mesg **reply, char *path)
367{
368	int len;
369	socklen_t optlen;
370
371	optlen = sizeof(len);
372	if (getsockopt(cs, SOL_SOCKET, SO_RCVBUF, &len, &optlen) == -1 ||
373	    (*reply = malloc(len)) == NULL)
374		return (-1);
375	if ((len = NgRecvAsciiMsg(cs, *reply, len, path)) < 0)
376		free(*reply);
377	return (len);
378}
379