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