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