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