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