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