1/*
2 * sock.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: sock.c,v 1.12 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/* The socket node type KLD */
54#define NG_SOCKET_KLD	"ng_socket.ko"
55
56/*
57 * Create a socket type node and give it the supplied name.
58 * Return data and control sockets corresponding to the node.
59 * Returns -1 if error and sets errno.
60 */
61int
62NgMkSockNode(const char *name, int *csp, int *dsp)
63{
64	char namebuf[NG_NODESIZ];
65	int cs = -1;		/* control socket */
66	int ds = -1;		/* data socket */
67	int errnosv;
68
69	/* Empty name means no name */
70	if (name && *name == 0)
71		name = NULL;
72
73	/* Create control socket; this also creates the netgraph node.
74	   If we get an EAFNOSUPPORT then the socket node type is
75	   not loaded, so load it and try again. */
76	if ((cs = socket(AF_NETGRAPH, SOCK_DGRAM, NG_CONTROL)) < 0) {
77		if (errno == EAFNOSUPPORT) {
78			if (kldload(NG_SOCKET_KLD) < 0) {
79				errnosv = errno;
80				if (_gNgDebugLevel >= 1)
81					NGLOG("can't load %s", NG_SOCKET_KLD);
82				goto errout;
83			}
84			cs = socket(AF_NETGRAPH, SOCK_DGRAM, NG_CONTROL);
85			if (cs >= 0)
86				goto gotNode;
87		}
88		errnosv = errno;
89		if (_gNgDebugLevel >= 1)
90			NGLOG("socket");
91		goto errout;
92	}
93
94gotNode:
95	/* Assign the node the desired name, if any */
96	if (name != NULL) {
97		u_char sbuf[NG_NODESIZ + NGSA_OVERHEAD];
98		struct sockaddr_ng *const sg = (struct sockaddr_ng *) sbuf;
99
100		/* Assign name */
101		strlcpy(sg->sg_data, name, NG_NODESIZ);
102		sg->sg_family = AF_NETGRAPH;
103		sg->sg_len = strlen(sg->sg_data) + 1 + NGSA_OVERHEAD;
104		if (bind(cs, (struct sockaddr *) sg, sg->sg_len) < 0) {
105			errnosv = errno;
106			if (_gNgDebugLevel >= 1)
107				NGLOG("bind(%s)", sg->sg_data);
108			goto errout;
109		}
110
111		/* Save node name */
112		strlcpy(namebuf, name, sizeof(namebuf));
113	} else if (dsp != NULL) {
114		u_char rbuf[sizeof(struct ng_mesg) + sizeof(struct nodeinfo)];
115		struct ng_mesg *const resp = (struct ng_mesg *) rbuf;
116		struct nodeinfo *const ni = (struct nodeinfo *) resp->data;
117
118		/* Find out the node ID */
119		if (NgSendMsg(cs, ".", NGM_GENERIC_COOKIE,
120		    NGM_NODEINFO, NULL, 0) < 0) {
121			errnosv = errno;
122			if (_gNgDebugLevel >= 1)
123				NGLOG("send nodeinfo");
124			goto errout;
125		}
126		if (NgRecvMsg(cs, resp, sizeof(rbuf), NULL) < 0) {
127			errnosv = errno;
128			if (_gNgDebugLevel >= 1)
129				NGLOG("recv nodeinfo");
130			goto errout;
131		}
132
133		/* Save node "name" */
134		snprintf(namebuf, sizeof(namebuf), "[%lx]", (u_long) ni->id);
135	}
136
137	/* Create data socket if desired */
138	if (dsp != NULL) {
139		u_char sbuf[NG_NODESIZ + 1 + NGSA_OVERHEAD];
140		struct sockaddr_ng *const sg = (struct sockaddr_ng *) sbuf;
141
142		/* Create data socket, initially just "floating" */
143		if ((ds = socket(AF_NETGRAPH, SOCK_DGRAM, NG_DATA)) < 0) {
144			errnosv = errno;
145			if (_gNgDebugLevel >= 1)
146				NGLOG("socket");
147			goto errout;
148		}
149
150		/* Associate the data socket with the node */
151		snprintf(sg->sg_data, NG_NODESIZ + 1, "%s:", namebuf);
152		sg->sg_family = AF_NETGRAPH;
153		sg->sg_len = strlen(sg->sg_data) + 1 + NGSA_OVERHEAD;
154		if (connect(ds, (struct sockaddr *) sg, sg->sg_len) < 0) {
155			errnosv = errno;
156			if (_gNgDebugLevel >= 1)
157				NGLOG("connect(%s)", sg->sg_data);
158			goto errout;
159		}
160	}
161
162	/* Return the socket(s) */
163	if (csp)
164		*csp = cs;
165	else
166		close(cs);
167	if (dsp)
168		*dsp = ds;
169	return (0);
170
171errout:
172	/* Failed */
173	if (cs >= 0)
174		close(cs);
175	if (ds >= 0)
176		close(ds);
177	errno = errnosv;
178	return (-1);
179}
180
181/*
182 * Assign a globally unique name to a node
183 * Returns -1 if error and sets errno.
184 */
185int
186NgNameNode(int cs, const char *path, const char *fmt, ...)
187{
188	struct ngm_name ngn;
189	va_list args;
190
191	/* Build message arg */
192	va_start(args, fmt);
193	vsnprintf(ngn.name, sizeof(ngn.name), fmt, args);
194	va_end(args);
195
196	/* Send message */
197	if (NgSendMsg(cs, path,
198	    NGM_GENERIC_COOKIE, NGM_NAME, &ngn, sizeof(ngn)) < 0) {
199		if (_gNgDebugLevel >= 1)
200			NGLOGX("%s: failed", __func__);
201		return (-1);
202	}
203
204	/* Done */
205	return (0);
206}
207
208/*
209 * Read a packet from a data socket
210 * Returns -1 if error and sets errno.
211 */
212int
213NgRecvData(int ds, u_char * buf, size_t len, char *hook)
214{
215	u_char frombuf[NG_HOOKSIZ + NGSA_OVERHEAD];
216	struct sockaddr_ng *const from = (struct sockaddr_ng *) frombuf;
217	socklen_t fromlen = sizeof(frombuf);
218	int rtn, errnosv;
219
220	/* Read packet */
221	rtn = recvfrom(ds, buf, len, 0, (struct sockaddr *) from, &fromlen);
222	if (rtn < 0) {
223		errnosv = errno;
224		if (_gNgDebugLevel >= 1)
225			NGLOG("recvfrom");
226		errno = errnosv;
227		return (-1);
228	}
229
230	/* Copy hook name */
231	if (hook != NULL)
232		strlcpy(hook, from->sg_data, NG_HOOKSIZ);
233
234	/* Debugging */
235	if (_gNgDebugLevel >= 2) {
236		NGLOGX("READ %s from hook \"%s\" (%d bytes)",
237		       rtn ? "PACKET" : "EOF", from->sg_data, rtn);
238		if (_gNgDebugLevel >= 3)
239			_NgDebugBytes(buf, rtn);
240	}
241
242	/* Done */
243	return (rtn);
244}
245
246/*
247 * Identical to NgRecvData() except buffer is dynamically allocated.
248 */
249int
250NgAllocRecvData(int ds, u_char **buf, char *hook)
251{
252	int len;
253	socklen_t optlen;
254
255	optlen = sizeof(len);
256	if (getsockopt(ds, SOL_SOCKET, SO_RCVBUF, &len, &optlen) == -1 ||
257	    (*buf = malloc(len)) == NULL)
258		return (-1);
259	if ((len = NgRecvData(ds, *buf, len, hook)) < 0)
260		free(*buf);
261	return (len);
262}
263
264/*
265 * Write a packet to a data socket. The packet will be sent
266 * out the corresponding node on the specified hook.
267 * Returns -1 if error and sets errno.
268 */
269int
270NgSendData(int ds, const char *hook, const u_char * buf, size_t len)
271{
272	u_char sgbuf[NG_HOOKSIZ + NGSA_OVERHEAD];
273	struct sockaddr_ng *const sg = (struct sockaddr_ng *) sgbuf;
274	int errnosv;
275
276	/* Set up destination hook */
277	sg->sg_family = AF_NETGRAPH;
278	strlcpy(sg->sg_data, hook, NG_HOOKSIZ);
279	sg->sg_len = strlen(sg->sg_data) + 1 + NGSA_OVERHEAD;
280
281	/* Debugging */
282	if (_gNgDebugLevel >= 2) {
283		NGLOGX("WRITE PACKET to hook \"%s\" (%d bytes)", hook, len);
284		_NgDebugSockaddr(sg);
285		if (_gNgDebugLevel >= 3)
286			_NgDebugBytes(buf, len);
287	}
288
289	/* Send packet */
290	if (sendto(ds, buf, len, 0, (struct sockaddr *) sg, sg->sg_len) < 0) {
291		errnosv = errno;
292		if (_gNgDebugLevel >= 1)
293			NGLOG("sendto(%s)", sg->sg_data);
294		errno = errnosv;
295		return (-1);
296	}
297
298	/* Done */
299	return (0);
300}
301
302