ng_socket.c revision 125116
1
2/*
3 * ng_socket.c
4 *
5 * Copyright (c) 1996-1999 Whistle Communications, Inc.
6 * All rights reserved.
7 *
8 * Subject to the following obligations and disclaimer of warranty, use and
9 * redistribution of this software, in source or object code forms, with or
10 * without modifications are expressly permitted by Whistle Communications;
11 * provided, however, that:
12 * 1. Any and all reproductions of the source or object code must include the
13 *    copyright notice above and the following disclaimer of warranties; and
14 * 2. No rights are granted, in any manner or form, to use Whistle
15 *    Communications, Inc. trademarks, including the mark "WHISTLE
16 *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
17 *    such appears in the above copyright notice or in the software.
18 *
19 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
20 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
21 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
22 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
23 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
24 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
25 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
26 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
27 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
28 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
29 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34 * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
35 * OF SUCH DAMAGE.
36 *
37 * Author: Julian Elischer <julian@freebsd.org>
38 *
39 * $FreeBSD: head/sys/netgraph/ng_socket.c 125116 2004-01-27 22:02:01Z ru $
40 * $Whistle: ng_socket.c,v 1.28 1999/11/01 09:24:52 julian Exp $
41 */
42
43/*
44 * Netgraph socket nodes
45 *
46 * There are two types of netgraph sockets, control and data.
47 * Control sockets have a netgraph node, but data sockets are
48 * parasitic on control sockets, and have no node of their own.
49 */
50
51#include <sys/param.h>
52#include <sys/domain.h>
53#include <sys/errno.h>
54#include <sys/kernel.h>
55#include <sys/lock.h>
56#include <sys/malloc.h>
57#include <sys/mbuf.h>
58#include <sys/protosw.h>
59#include <sys/queue.h>
60#include <sys/signalvar.h>
61#include <sys/socket.h>
62#include <sys/socketvar.h>
63#include <sys/sx.h>
64#include <sys/sysctl.h>
65#include <sys/systm.h>
66#ifdef NOTYET
67#include <sys/vnode.h>
68#endif
69#include <netgraph/ng_message.h>
70#include <netgraph/netgraph.h>
71#include <netgraph/ng_socketvar.h>
72#include <netgraph/ng_socket.h>
73
74#ifdef NG_SEPARATE_MALLOC
75MALLOC_DEFINE(M_NETGRAPH_PATH, "netgraph_path", "netgraph path info ");
76MALLOC_DEFINE(M_NETGRAPH_SOCK, "netgraph_sock", "netgraph socket info ");
77#else
78#define M_NETGRAPH_PATH M_NETGRAPH
79#define M_NETGRAPH_SOCK M_NETGRAPH
80#endif
81
82/*
83 * It's Ascii-art time!
84 *   +-------------+   +-------------+
85 *   |socket  (ctl)|   |socket (data)|
86 *   +-------------+   +-------------+
87 *          ^                 ^
88 *          |                 |
89 *          v                 v
90 *    +-----------+     +-----------+
91 *    |pcb   (ctl)|     |pcb  (data)|
92 *    +-----------+     +-----------+
93 *          ^                 ^
94 *          |                 |
95 *          v                 v
96 *      +--------------------------+
97 *      |   Socket type private    |
98 *      |       data               |
99 *      +--------------------------+
100 *                   ^
101 *                   |
102 *                   v
103 *           +----------------+
104 *           | struct ng_node |
105 *           +----------------+
106 */
107
108/* Netgraph node methods */
109static ng_constructor_t	ngs_constructor;
110static ng_rcvmsg_t	ngs_rcvmsg;
111static ng_shutdown_t	ngs_shutdown;
112static ng_newhook_t	ngs_newhook;
113static ng_connect_t	ngs_connect;
114static ng_rcvdata_t	ngs_rcvdata;
115static ng_disconnect_t	ngs_disconnect;
116
117/* Internal methods */
118static int	ng_attach_data(struct socket *so);
119static int	ng_attach_cntl(struct socket *so);
120static int	ng_attach_common(struct socket *so, int type);
121static void	ng_detach_common(struct ngpcb *pcbp, int type);
122/*static int	ng_internalize(struct mbuf *m, struct thread *p); */
123
124static int	ng_connect_data(struct sockaddr *nam, struct ngpcb *pcbp);
125static int	ng_bind(struct sockaddr *nam, struct ngpcb *pcbp);
126
127static int	ngs_mod_event(module_t mod, int event, void *data);
128static int	ship_msg(struct ngpcb *pcbp, struct ng_mesg *msg,
129			struct sockaddr_ng *addr);
130
131/* Netgraph type descriptor */
132static struct ng_type typestruct = {
133	NG_ABI_VERSION,
134	NG_SOCKET_NODE_TYPE,
135	ngs_mod_event,
136	ngs_constructor,
137	ngs_rcvmsg,
138	ngs_shutdown,
139	ngs_newhook,
140	NULL,
141	ngs_connect,
142	ngs_rcvdata,
143	ngs_disconnect,
144	NULL
145};
146NETGRAPH_INIT(socket, &typestruct);
147
148/* Buffer space */
149static u_long ngpdg_sendspace = 20 * 1024;	/* really max datagram size */
150SYSCTL_INT(_net_graph, OID_AUTO, maxdgram, CTLFLAG_RW,
151    &ngpdg_sendspace , 0, "Maximum outgoing Netgraph datagram size");
152static u_long ngpdg_recvspace = 20 * 1024;
153SYSCTL_INT(_net_graph, OID_AUTO, recvspace, CTLFLAG_RW,
154    &ngpdg_recvspace , 0, "Maximum space for incoming Netgraph datagrams");
155
156/* List of all sockets */
157static LIST_HEAD(, ngpcb) ngsocklist;
158
159#define sotongpcb(so) ((struct ngpcb *)(so)->so_pcb)
160
161/* If getting unexplained errors returned, set this to "Debugger("X"); */
162#ifndef TRAP_ERROR
163#define TRAP_ERROR
164#endif
165
166/***************************************************************
167	Control sockets
168***************************************************************/
169
170static int
171ngc_attach(struct socket *so, int proto, struct thread *td)
172{
173	struct ngpcb *const pcbp = sotongpcb(so);
174
175	if (suser(td))
176		return (EPERM);
177	if (pcbp != NULL)
178		return (EISCONN);
179	return (ng_attach_cntl(so));
180}
181
182static int
183ngc_detach(struct socket *so)
184{
185	struct ngpcb *const pcbp = sotongpcb(so);
186
187	if (pcbp == NULL)
188		return (EINVAL);
189	ng_detach_common(pcbp, NG_CONTROL);
190	return (0);
191}
192
193static int
194ngc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
195	 struct mbuf *control, struct thread *td)
196{
197	struct ngpcb *const pcbp = sotongpcb(so);
198	struct sockaddr_ng *const sap = (struct sockaddr_ng *) addr;
199	struct ng_mesg *msg;
200	struct mbuf *m0;
201	char *path = NULL;
202	int len, error = 0;
203
204	if (pcbp == NULL) {
205		error = EINVAL;
206		goto release;
207	}
208#ifdef	NOTYET
209	if (control && (error = ng_internalize(control, td))) {
210		if (pcbp->sockdata == NULL) {
211			error = ENOTCONN;
212			goto release;
213		}
214	}
215#else	/* NOTYET */
216	if (control) {
217		error = EINVAL;
218		goto release;
219	}
220#endif	/* NOTYET */
221
222	/* Require destination as there may be >= 1 hooks on this node */
223	if (addr == NULL) {
224		error = EDESTADDRREQ;
225		goto release;
226	}
227
228	/* Allocate an expendable buffer for the path, chop off
229	 * the sockaddr header, and make sure it's NUL terminated */
230	len = sap->sg_len - 2;
231	MALLOC(path, char *, len + 1, M_NETGRAPH_PATH, M_WAITOK);
232	if (path == NULL) {
233		error = ENOMEM;
234		goto release;
235	}
236	bcopy(sap->sg_data, path, len);
237	path[len] = '\0';
238
239	/* Move the actual message out of mbufs into a linear buffer.
240	 * Start by adding up the size of the data. (could use mh_len?) */
241	for (len = 0, m0 = m; m0 != NULL; m0 = m0->m_next)
242		len += m0->m_len;
243
244	/* Move the data into a linear buffer as well. Messages are not
245	 * delivered in mbufs. */
246	MALLOC(msg, struct ng_mesg *, len + 1, M_NETGRAPH_MSG, M_WAITOK);
247	if (msg == NULL) {
248		error = ENOMEM;
249		goto release;
250	}
251	m_copydata(m, 0, len, (char *)msg);
252
253#ifdef TRACE_MESSAGES
254	do {
255		item_p item;
256		if ((item = ng_package_msg(msg)) == NULL) {
257			(msg) = NULL;
258			(error) = ENOMEM;
259printf("err=%d\n",error);
260			break;
261		}
262		if (((error) = ng_address_path((pcbp->sockdata->node), (item),
263					(path), (NULL))) == 0) {
264printf("[%x]:<---------[socket]: c=<%d>cmd=%x(%s) f=%x #%d (%s)\n",
265item->el_dest->nd_ID,
266msg->header.typecookie,
267msg->header.cmd,
268msg->header.cmdstr,
269msg->header.flags,
270msg->header.token,
271item->el_dest->nd_type->name);
272			SAVE_LINE(item);
273			(error) = ng_snd_item((item), 0);
274		}
275else {
276printf("errx=%d\n",error);
277}
278		(msg) = NULL;
279	} while (0);
280
281#else
282	/* The callee will free the msg when done. The path is our business. */
283	NG_SEND_MSG_PATH(error, pcbp->sockdata->node, msg, path, 0);
284#endif
285release:
286	if (path != NULL)
287		FREE(path, M_NETGRAPH_PATH);
288	if (control != NULL)
289		m_freem(control);
290	if (m != NULL)
291		m_freem(m);
292	return (error);
293}
294
295static int
296ngc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
297{
298	struct ngpcb *const pcbp = sotongpcb(so);
299
300	if (pcbp == 0)
301		return (EINVAL);
302	return (ng_bind(nam, pcbp));
303}
304
305static int
306ngc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
307{
308printf(" program tried to connect control socket to remote node\n ");
309	/*
310	 * At this time refuse to do this.. it used to
311	 * do something but it was undocumented and not used.
312	 */
313	return (EINVAL);
314}
315
316/***************************************************************
317	Data sockets
318***************************************************************/
319
320static int
321ngd_attach(struct socket *so, int proto, struct thread *td)
322{
323	struct ngpcb *const pcbp = sotongpcb(so);
324
325	if (pcbp != NULL)
326		return (EISCONN);
327	return (ng_attach_data(so));
328}
329
330static int
331ngd_detach(struct socket *so)
332{
333	struct ngpcb *const pcbp = sotongpcb(so);
334
335	if (pcbp == NULL)
336		return (EINVAL);
337	ng_detach_common(pcbp, NG_DATA);
338	return (0);
339}
340
341static int
342ngd_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
343	 struct mbuf *control, struct thread *td)
344{
345	struct ngpcb *const pcbp = sotongpcb(so);
346	struct sockaddr_ng *const sap = (struct sockaddr_ng *) addr;
347	int     len, error;
348	hook_p  hook = NULL;
349	char	hookname[NG_HOOKSIZ];
350
351	if ((pcbp == NULL) || (control != NULL)) {
352		error = EINVAL;
353		goto release;
354	}
355	if (pcbp->sockdata == NULL) {
356		error = ENOTCONN;
357		goto release;
358	}
359	/*
360	 * If the user used any of these ways to not specify an address
361	 * then handle specially.
362	 */
363	if ((sap == NULL)
364	    || ((len = sap->sg_len - 2) <= 0)
365	    || (*sap->sg_data == '\0')) {
366		if (NG_NODE_NUMHOOKS(pcbp->sockdata->node) != 1) {
367			error = EDESTADDRREQ;
368			goto release;
369		}
370		/*
371		 * if exactly one hook exists, just use it.
372		 * Special case to allow write(2) to work on an ng_socket.
373		 */
374		hook = LIST_FIRST(&pcbp->sockdata->node->nd_hooks);
375	} else {
376		if (len >= NG_HOOKSIZ) {
377			error = EINVAL;
378			goto release;
379		}
380
381		/*
382		 * chop off the sockaddr header, and make sure it's NUL
383		 * terminated
384		 */
385		bcopy(sap->sg_data, hookname, len);
386		hookname[len] = '\0';
387
388		/* Find the correct hook from 'hookname' */
389		LIST_FOREACH(hook, &pcbp->sockdata->node->nd_hooks, hk_hooks) {
390			if (strcmp(hookname, NG_HOOK_NAME(hook)) == 0) {
391				break;
392			}
393		}
394		if (hook == NULL) {
395			error = EHOSTUNREACH;
396		}
397	}
398
399	/* Send data (OK if hook is NULL) */
400	NG_SEND_DATA_ONLY(error, hook, m);	/* makes m NULL */
401
402release:
403	if (control != NULL)
404		m_freem(control);
405	if (m != NULL)
406		m_freem(m);
407	return (error);
408}
409
410static int
411ngd_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
412{
413	struct ngpcb *const pcbp = sotongpcb(so);
414
415	if (pcbp == 0)
416		return (EINVAL);
417	return (ng_connect_data(nam, pcbp));
418}
419
420/*
421 * Used for both data and control sockets
422 */
423static int
424ng_setsockaddr(struct socket *so, struct sockaddr **addr)
425{
426	struct ngpcb *pcbp;
427	struct sockaddr_ng *sg;
428	int sg_len, namelen, s;
429
430	/* Why isn't sg_data a `char[1]' ? :-( */
431	sg_len = sizeof(struct sockaddr_ng) - sizeof(sg->sg_data) + 1;
432
433	s = splnet();
434	pcbp = sotongpcb(so);
435	if ((pcbp == NULL) || (pcbp->sockdata == NULL)) {
436		splx(s);
437		return (EINVAL);
438	}
439
440	namelen = 0;		/* silence compiler ! */
441	if ( NG_NODE_HAS_NAME(pcbp->sockdata->node))
442		sg_len += namelen = strlen(NG_NODE_NAME(pcbp->sockdata->node));
443
444	MALLOC(sg, struct sockaddr_ng *, sg_len, M_SONAME, M_WAITOK | M_ZERO);
445
446	if (NG_NODE_HAS_NAME(pcbp->sockdata->node))
447		bcopy(NG_NODE_NAME(pcbp->sockdata->node), sg->sg_data, namelen);
448	splx(s);
449
450	sg->sg_len = sg_len;
451	sg->sg_family = AF_NETGRAPH;
452	*addr = (struct sockaddr *)sg;
453
454	return (0);
455}
456
457/*
458 * Attach a socket to it's protocol specific partner.
459 * For a control socket, actually create a netgraph node and attach
460 * to it as well.
461 */
462
463static int
464ng_attach_cntl(struct socket *so)
465{
466	struct ngsock *privdata;
467	struct ngpcb *pcbp;
468	int error;
469
470	/* Setup protocol control block */
471	if ((error = ng_attach_common(so, NG_CONTROL)) != 0)
472		return (error);
473	pcbp = sotongpcb(so);
474
475	/* Allocate node private info */
476	MALLOC(privdata, struct ngsock *,
477	    sizeof(*privdata), M_NETGRAPH_SOCK, M_WAITOK | M_ZERO);
478	if (privdata == NULL) {
479		ng_detach_common(pcbp, NG_CONTROL);
480		return (ENOMEM);
481	}
482
483	/* Make the generic node components */
484	if ((error = ng_make_node_common(&typestruct, &privdata->node)) != 0) {
485		FREE(privdata, M_NETGRAPH_SOCK);
486		ng_detach_common(pcbp, NG_CONTROL);
487		return (error);
488	}
489	NG_NODE_SET_PRIVATE(privdata->node, privdata);
490
491	/* Link the pcb and the node private data */
492	privdata->ctlsock = pcbp;
493	pcbp->sockdata = privdata;
494	privdata->refs++;
495	return (0);
496}
497
498static int
499ng_attach_data(struct socket *so)
500{
501	return(ng_attach_common(so, NG_DATA));
502}
503
504/*
505 * Set up a socket protocol control block.
506 * This code is shared between control and data sockets.
507 */
508static int
509ng_attach_common(struct socket *so, int type)
510{
511	struct ngpcb *pcbp;
512	int error;
513
514	/* Standard socket setup stuff */
515	error = soreserve(so, ngpdg_sendspace, ngpdg_recvspace);
516	if (error)
517		return (error);
518
519	/* Allocate the pcb */
520	MALLOC(pcbp, struct ngpcb *, sizeof(*pcbp), M_PCB, M_WAITOK | M_ZERO);
521	if (pcbp == NULL)
522		return (ENOMEM);
523	pcbp->type = type;
524
525	/* Link the pcb and the socket */
526	so->so_pcb = (caddr_t) pcbp;
527	pcbp->ng_socket = so;
528
529	/* Add the socket to linked list */
530	LIST_INSERT_HEAD(&ngsocklist, pcbp, socks);
531	return (0);
532}
533
534/*
535 * Disassociate the socket from it's protocol specific
536 * partner. If it's attached to a node's private data structure,
537 * then unlink from that too. If we were the last socket attached to it,
538 * then shut down the entire node. Shared code for control and data sockets.
539 */
540static void
541ng_detach_common(struct ngpcb *pcbp, int which)
542{
543	struct ngsock *priv;
544
545	if (pcbp->sockdata) {
546		priv = pcbp->sockdata;
547		pcbp->sockdata = NULL;
548		switch (which) {
549		case NG_CONTROL:
550			priv->ctlsock = NULL;
551			break;
552		case NG_DATA:
553			priv->datasock = NULL;
554			break;
555		default:
556			panic(__func__);
557		}
558		if ((--priv->refs == 0) && (priv->node != NULL))
559			ng_rmnode_self(priv->node);
560	}
561	pcbp->ng_socket->so_pcb = NULL;
562	pcbp->ng_socket = NULL;
563	LIST_REMOVE(pcbp, socks);
564	FREE(pcbp, M_PCB);
565}
566
567#ifdef NOTYET
568/*
569 * File descriptors can be passed into an AF_NETGRAPH socket.
570 * Note, that file descriptors cannot be passed OUT.
571 * Only character device descriptors are accepted.
572 * Character devices are useful to connect a graph to a device,
573 * which after all is the purpose of this whole system.
574 */
575static int
576ng_internalize(struct mbuf *control, struct thread *td)
577{
578	const struct cmsghdr *cm = mtod(control, const struct cmsghdr *);
579	struct file *fp;
580	struct vnode *vn;
581	int oldfds;
582	int fd;
583
584	if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
585	    cm->cmsg_len != control->m_len) {
586		TRAP_ERROR;
587		return (EINVAL);
588	}
589
590	/* Check there is only one FD. XXX what would more than one signify? */
591	oldfds = ((caddr_t)cm + cm->cmsg_len - (caddr_t)data) / sizeof (int);
592	if (oldfds != 1) {
593		TRAP_ERROR;
594		return (EINVAL);
595	}
596
597	/* Check that the FD given is legit. and change it to a pointer to a
598	 * struct file. */
599	fd = CMSG_DATA(cm);
600	if ((error = fget(td, fd, &fp)) != 0)
601		return (error);
602
603	/* Depending on what kind of resource it is, act differently. For
604	 * devices, we treat it as a file. For an AF_NETGRAPH socket,
605	 * shortcut straight to the node. */
606	switch (fp->f_type) {
607	case DTYPE_VNODE:
608		vn = fp->f_data;
609		if (vn && (vn->v_type == VCHR)) {
610			/* for a VCHR, actually reference the FILE */
611			fp->f_count++;
612			/* XXX then what :) */
613			/* how to pass on to other modules? */
614		} else {
615			fdrop(fp, td);
616			TRAP_ERROR;
617			return (EINVAL);
618		}
619		break;
620	default:
621		fdrop(fp, td);
622		TRAP_ERROR;
623		return (EINVAL);
624	}
625	fdrop(fp, td);
626	return (0);
627}
628#endif	/* NOTYET */
629
630/*
631 * Connect the data socket to a named control socket node.
632 */
633static int
634ng_connect_data(struct sockaddr *nam, struct ngpcb *pcbp)
635{
636	struct sockaddr_ng *sap;
637	node_p farnode;
638	struct ngsock *priv;
639	int error;
640	item_p item;
641
642	/* If we are already connected, don't do it again */
643	if (pcbp->sockdata != NULL)
644		return (EISCONN);
645
646	/* Find the target (victim) and check it doesn't already have a data
647	 * socket. Also check it is a 'socket' type node.
648	 * Use ng_package_data() and address_path() to do this.
649	 */
650
651	sap = (struct sockaddr_ng *) nam;
652	/* The item will hold the node reference */
653	item = ng_package_data(NULL, NULL);
654	if (item == NULL) {
655		return (ENOMEM);
656	}
657	if ((error = ng_address_path(NULL, item,  sap->sg_data, 0)))
658		return (error); /* item is freed on failure */
659
660	/*
661	 * Extract node from item and free item. Remember we now have
662	 * a reference on the node. The item holds it for us.
663	 * when we free the item we release the reference.
664	 */
665	farnode = item->el_dest; /* shortcut */
666	if (strcmp(farnode->nd_type->name, NG_SOCKET_NODE_TYPE) != 0) {
667		NG_FREE_ITEM(item); /* drop the reference to the node */
668		return (EINVAL);
669	}
670	priv = NG_NODE_PRIVATE(farnode);
671	if (priv->datasock != NULL) {
672		NG_FREE_ITEM(item);	/* drop the reference to the node */
673		return (EADDRINUSE);
674	}
675
676	/*
677	 * Link the PCB and the private data struct. and note the extra
678	 * reference. Drop the extra reference on the node.
679	 */
680	priv->datasock = pcbp;
681	pcbp->sockdata = priv;
682	priv->refs++; /* XXX possible race if it's being freed */
683	NG_FREE_ITEM(item);	/* drop the reference to the node */
684	return (0);
685}
686
687/*
688 * Binding a socket means giving the corresponding node a name
689 */
690static int
691ng_bind(struct sockaddr *nam, struct ngpcb *pcbp)
692{
693	struct ngsock *const priv = pcbp->sockdata;
694	struct sockaddr_ng *const sap = (struct sockaddr_ng *) nam;
695
696	if (priv == NULL) {
697		TRAP_ERROR;
698		return (EINVAL);
699	}
700	if ((sap->sg_len < 4)
701	||  (sap->sg_len > (NG_NODESIZ + 2))
702	||  (sap->sg_data[0] == '\0')
703	||  (sap->sg_data[sap->sg_len - 3] != '\0')) {
704		TRAP_ERROR;
705		return (EINVAL);
706	}
707	return (ng_name_node(priv->node, sap->sg_data));
708}
709
710/*
711 * Take a message and pass it up to the control socket associated
712 * with the node.
713 */
714static int
715ship_msg(struct ngpcb *pcbp, struct ng_mesg *msg, struct sockaddr_ng *addr)
716{
717	struct socket *const so = pcbp->ng_socket;
718	struct mbuf *mdata;
719	int msglen;
720
721	/* Copy the message itself into an mbuf chain */
722	msglen = sizeof(struct ng_mesg) + msg->header.arglen;
723	mdata = m_devget((caddr_t) msg, msglen, 0, NULL, NULL);
724
725	/* Here we free the message, as we are the end of the line.
726	 * We need to do that regardless of whether we got mbufs. */
727	NG_FREE_MSG(msg);
728
729	if (mdata == NULL) {
730		TRAP_ERROR;
731		return (ENOBUFS);
732	}
733
734	/* Send it up to the socket */
735	if (sbappendaddr(&so->so_rcv,
736	    (struct sockaddr *) addr, mdata, NULL) == 0) {
737		TRAP_ERROR;
738		m_freem(mdata);
739		return (ENOBUFS);
740	}
741	sorwakeup(so);
742	return (0);
743}
744
745/*
746 * You can only create new nodes from the socket end of things.
747 */
748static int
749ngs_constructor(node_p nodep)
750{
751	return (EINVAL);
752}
753
754/*
755 * We allow any hook to be connected to the node.
756 * There is no per-hook private information though.
757 */
758static int
759ngs_newhook(node_p node, hook_p hook, const char *name)
760{
761	NG_HOOK_SET_PRIVATE(hook, NG_NODE_PRIVATE(node));
762	return (0);
763}
764
765/*
766 * if only one hook, allow read(2) and write(2) to work.
767 */
768static int
769ngs_connect(hook_p hook)
770{
771	node_p node = NG_HOOK_NODE(hook);
772	struct ngsock *priv = NG_NODE_PRIVATE(node);
773
774	if ((priv->datasock)
775	&&  (priv->datasock->ng_socket)) {
776		if (NG_NODE_NUMHOOKS(node) == 1) {
777			priv->datasock->ng_socket->so_state |= SS_ISCONNECTED;
778		} else {
779			priv->datasock->ng_socket->so_state &= ~SS_ISCONNECTED;
780		}
781	}
782	return (0);
783}
784
785/*
786 * Incoming messages get passed up to the control socket.
787 * Unless they are for us specifically (socket_type)
788 */
789static int
790ngs_rcvmsg(node_p node, item_p item, hook_p lasthook)
791{
792	struct ngsock *const priv = NG_NODE_PRIVATE(node);
793	struct ngpcb *const pcbp = priv->ctlsock;
794	struct sockaddr_ng *addr;
795	int addrlen;
796	int error = 0;
797	struct	ng_mesg *msg;
798	ng_ID_t	retaddr = NGI_RETADDR(item);
799	char	retabuf[32];
800
801	NGI_GET_MSG(item, msg);
802	NG_FREE_ITEM(item); /* we have all we need */
803
804	/* Only allow mesgs to be passed if we have the control socket.
805	 * Data sockets can only support the generic messages. */
806	if (pcbp == NULL) {
807		TRAP_ERROR;
808		return (EINVAL);
809	}
810#ifdef TRACE_MESSAGES
811printf("[%x]:---------->[socket]: c=<%d>cmd=%x(%s) f=%x #%d\n",
812retaddr,
813msg->header.typecookie,
814msg->header.cmd,
815msg->header.cmdstr,
816msg->header.flags,
817msg->header.token);
818
819#endif
820
821	if (msg->header.typecookie == NGM_SOCKET_COOKIE) {
822		switch (msg->header.cmd) {
823		case NGM_SOCK_CMD_NOLINGER:
824			priv->flags |= NGS_FLAG_NOLINGER;
825			break;
826		case NGM_SOCK_CMD_LINGER:
827			priv->flags &= ~NGS_FLAG_NOLINGER;
828			break;
829		default:
830			error = EINVAL;		/* unknown command */
831		}
832		/* Free the message and return */
833		NG_FREE_MSG(msg);
834		return(error);
835
836	}
837	/* Get the return address into a sockaddr */
838	sprintf(retabuf,"[%x]:", retaddr);
839	addrlen = strlen(retabuf);
840	MALLOC(addr, struct sockaddr_ng *, addrlen + 4, M_NETGRAPH_PATH, M_NOWAIT);
841	if (addr == NULL) {
842		TRAP_ERROR;
843		return (ENOMEM);
844	}
845	addr->sg_len = addrlen + 3;
846	addr->sg_family = AF_NETGRAPH;
847	bcopy(retabuf, addr->sg_data, addrlen);
848	addr->sg_data[addrlen] = '\0';
849
850	/* Send it up */
851	error = ship_msg(pcbp, msg, addr);
852	FREE(addr, M_NETGRAPH_PATH);
853	return (error);
854}
855
856/*
857 * Receive data on a hook
858 */
859static int
860ngs_rcvdata(hook_p hook, item_p item)
861{
862	struct ngsock *const priv = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
863	struct ngpcb *const pcbp = priv->datasock;
864	struct socket *so;
865	struct sockaddr_ng *addr;
866	char *addrbuf[NG_HOOKSIZ + 4];
867	int addrlen;
868	struct mbuf *m;
869
870	NGI_GET_M(item, m);
871	NG_FREE_ITEM(item);
872	/* If there is no data socket, black-hole it */
873	if (pcbp == NULL) {
874		NG_FREE_M(m);
875		return (0);
876	}
877	so = pcbp->ng_socket;
878
879	/* Get the return address into a sockaddr. */
880	addrlen = strlen(NG_HOOK_NAME(hook));	/* <= NG_HOOKSIZ - 1 */
881	addr = (struct sockaddr_ng *) addrbuf;
882	addr->sg_len = addrlen + 3;
883	addr->sg_family = AF_NETGRAPH;
884	bcopy(NG_HOOK_NAME(hook), addr->sg_data, addrlen);
885	addr->sg_data[addrlen] = '\0';
886
887	/* Try to tell the socket which hook it came in on */
888	if (sbappendaddr(&so->so_rcv, (struct sockaddr *) addr, m, NULL) == 0) {
889		m_freem(m);
890		TRAP_ERROR;
891		return (ENOBUFS);
892	}
893	sorwakeup(so);
894	return (0);
895}
896
897/*
898 * Hook disconnection
899 *
900 * For this type, removal of the last link destroys the node
901 * if the NOLINGER flag is set.
902 */
903static int
904ngs_disconnect(hook_p hook)
905{
906	node_p node = NG_HOOK_NODE(hook);
907	struct ngsock *const priv = NG_NODE_PRIVATE(node);
908
909	if ((priv->datasock)
910	&&  (priv->datasock->ng_socket)) {
911		if (NG_NODE_NUMHOOKS(node) == 1) {
912			priv->datasock->ng_socket->so_state |= SS_ISCONNECTED;
913		} else {
914			priv->datasock->ng_socket->so_state &= ~SS_ISCONNECTED;
915		}
916	}
917
918	if ((priv->flags & NGS_FLAG_NOLINGER )
919	&& (NG_NODE_NUMHOOKS(node) == 0)
920	&& (NG_NODE_IS_VALID(node))) {
921		ng_rmnode_self(node);
922	}
923	return (0);
924}
925
926/*
927 * Do local shutdown processing.
928 * In this case, that involves making sure the socket
929 * knows we should be shutting down.
930 */
931static int
932ngs_shutdown(node_p node)
933{
934	struct ngsock *const priv = NG_NODE_PRIVATE(node);
935	struct ngpcb *const dpcbp = priv->datasock;
936	struct ngpcb *const pcbp = priv->ctlsock;
937
938	if (dpcbp != NULL) {
939		soisdisconnected(dpcbp->ng_socket);
940		dpcbp->sockdata = NULL;
941		priv->datasock = NULL;
942		priv->refs--;
943	}
944	if (pcbp != NULL) {
945		soisdisconnected(pcbp->ng_socket);
946		pcbp->sockdata = NULL;
947		priv->ctlsock = NULL;
948		priv->refs--;
949	}
950	NG_NODE_SET_PRIVATE(node, NULL);
951	NG_NODE_UNREF(node);
952	FREE(priv, M_NETGRAPH_SOCK);
953	return (0);
954}
955
956static	int
957dummy_disconnect(struct socket *so)
958{
959	return (0);
960}
961/*
962 * Control and data socket type descriptors
963 */
964
965static struct pr_usrreqs ngc_usrreqs = {
966	NULL,			/* abort */
967	pru_accept_notsupp,
968	ngc_attach,
969	ngc_bind,
970	ngc_connect,
971	pru_connect2_notsupp,
972	pru_control_notsupp,
973	ngc_detach,
974	dummy_disconnect,	/* disconnect */
975	pru_listen_notsupp,
976	NULL,			/* setpeeraddr */
977	pru_rcvd_notsupp,
978	pru_rcvoob_notsupp,
979	ngc_send,
980	pru_sense_null,
981	NULL,			/* shutdown */
982	ng_setsockaddr,
983	sosend,
984	soreceive,
985	sopoll,
986	pru_sosetlabel_null
987};
988
989static struct pr_usrreqs ngd_usrreqs = {
990	NULL,			/* abort */
991	pru_accept_notsupp,
992	ngd_attach,
993	NULL,			/* bind */
994	ngd_connect,
995	pru_connect2_notsupp,
996	pru_control_notsupp,
997	ngd_detach,
998	dummy_disconnect,	/* disconnect */
999	pru_listen_notsupp,
1000	NULL,			/* setpeeraddr */
1001	pru_rcvd_notsupp,
1002	pru_rcvoob_notsupp,
1003	ngd_send,
1004	pru_sense_null,
1005	NULL,			/* shutdown */
1006	ng_setsockaddr,
1007	sosend,
1008	soreceive,
1009	sopoll,
1010	pru_sosetlabel_null
1011};
1012
1013/*
1014 * Definitions of protocols supported in the NETGRAPH domain.
1015 */
1016
1017extern struct domain ngdomain;		/* stop compiler warnings */
1018
1019static struct protosw ngsw[] = {
1020	{
1021		SOCK_DGRAM,		/* protocol type */
1022		&ngdomain,		/* backpointer to domain */
1023		NG_CONTROL,
1024		PR_ATOMIC | PR_ADDR /* | PR_RIGHTS */,	/* flags */
1025		0, 0, 0, 0,		/* input, output, ctlinput, ctloutput */
1026		NULL,			/* ousrreq */
1027		0, 0, 0, 0,		/* init, fasttimeo, slowtimo, drain */
1028		&ngc_usrreqs,		/* usrreq table (above) */
1029		/*{NULL}*/		/* pffh (protocol filter head?) */
1030	},
1031	{
1032		SOCK_DGRAM,		/* protocol type */
1033		&ngdomain,		/* backpointer to domain */
1034		NG_DATA,
1035		PR_ATOMIC | PR_ADDR,	/* flags */
1036		0, 0, 0, 0,		/* input, output, ctlinput, ctloutput */
1037		NULL,			/* ousrreq() */
1038		0, 0, 0, 0,		/* init, fasttimeo, slowtimo, drain */
1039		&ngd_usrreqs,		/* usrreq table (above) */
1040		/*{NULL}*/		/* pffh (protocol filter head?) */
1041	}
1042};
1043
1044struct domain ngdomain = {
1045	AF_NETGRAPH,
1046	"netgraph",
1047	NULL,					/* init() */
1048	NULL,					/* externalise() */
1049	NULL,					/* dispose() */
1050	ngsw,					/* protosw entry */
1051	&ngsw[sizeof(ngsw) / sizeof(ngsw[0])], 	/* Number of protosw entries */
1052	NULL,					/* next domain in list */
1053	NULL,					/* rtattach() */
1054	0,					/* arg to rtattach in bits */
1055	0					/* maxrtkey */
1056};
1057
1058/*
1059 * Handle loading and unloading for this node type
1060 * This is to handle auxiliary linkages (e.g protocol domain addition).
1061 */
1062static int
1063ngs_mod_event(module_t mod, int event, void *data)
1064{
1065	int error = 0;
1066
1067	switch (event) {
1068	case MOD_LOAD:
1069		/* Register protocol domain */
1070		net_add_domain(&ngdomain);
1071		break;
1072	case MOD_UNLOAD:
1073		/* Insure there are no open netgraph sockets */
1074		if (!LIST_EMPTY(&ngsocklist)) {
1075			error = EBUSY;
1076			break;
1077		}
1078
1079#ifdef NOTYET
1080		if ((LIST_EMPTY(&ngsocklist)) && (typestruct.refs == 0)) {
1081		/* Unregister protocol domain XXX can't do this yet.. */
1082			if ((error = net_rm_domain(&ngdomain)) != 0)
1083				break;
1084		} else
1085#endif
1086			error = EBUSY;
1087		break;
1088	default:
1089		error = EOPNOTSUPP;
1090		break;
1091	}
1092	return (error);
1093}
1094
1095SYSCTL_INT(_net_graph, OID_AUTO, family, CTLFLAG_RD, 0, AF_NETGRAPH, "");
1096SYSCTL_NODE(_net_graph, OID_AUTO, data, CTLFLAG_RW, 0, "DATA");
1097SYSCTL_INT(_net_graph_data, OID_AUTO, proto, CTLFLAG_RD, 0, NG_DATA, "");
1098SYSCTL_NODE(_net_graph, OID_AUTO, control, CTLFLAG_RW, 0, "CONTROL");
1099SYSCTL_INT(_net_graph_control, OID_AUTO, proto, CTLFLAG_RD, 0, NG_CONTROL, "");
1100
1101