xref: /f-stack/freebsd/netgraph/ng_socket.c (revision ebf5cedb)
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 <[email protected]>
39  *
40  * $FreeBSD$
41  * $Whistle: ng_socket.c,v 1.28 1999/11/01 09:24:52 julian Exp $
42  */
43 
44 /*
45  * Netgraph socket nodes
46  *
47  * There are two types of netgraph sockets, control and data.
48  * Control sockets have a netgraph node, but data sockets are
49  * parasitic on control sockets, and have no node of their own.
50  */
51 
52 #include <sys/param.h>
53 #include <sys/domain.h>
54 #include <sys/hash.h>
55 #include <sys/kernel.h>
56 #include <sys/linker.h>
57 #include <sys/lock.h>
58 #include <sys/malloc.h>
59 #include <sys/mbuf.h>
60 #include <sys/mutex.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 	/*
242 	 * Allocate an expendable buffer for the path, chop off
243 	 * the sockaddr header, and make sure it's NUL terminated.
244 	 */
245 	len = sap->sg_len - 2;
246 	path = malloc(len + 1, M_NETGRAPH_PATH, M_WAITOK);
247 	bcopy(sap->sg_data, path, len);
248 	path[len] = '\0';
249 
250 	/*
251 	 * Move the actual message out of mbufs into a linear buffer.
252 	 * Start by adding up the size of the data. (could use mh_len?)
253 	 */
254 	for (len = 0, m0 = m; m0 != NULL; m0 = m0->m_next)
255 		len += m0->m_len;
256 
257 	/*
258 	 * Move the data into a linear buffer as well.
259 	 * Messages are not delivered in mbufs.
260 	 */
261 	msg = malloc(len + 1, M_NETGRAPH_MSG, M_WAITOK);
262 	m_copydata(m, 0, len, (char *)msg);
263 
264 	if (msg->header.version != NG_VERSION) {
265 		free(msg, M_NETGRAPH_MSG);
266 		error = EINVAL;
267 		goto release;
268 	}
269 
270 	/*
271 	 * Hack alert!
272 	 * We look into the message and if it mkpeers a node of unknown type, we
273 	 * try to load it. We need to do this now, in syscall thread, because if
274 	 * message gets queued and applied later we will get panic.
275 	 */
276 	if (msg->header.typecookie == NGM_GENERIC_COOKIE &&
277 	    msg->header.cmd == NGM_MKPEER) {
278 		struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
279 
280 		if (ng_findtype(mkp->type) == NULL) {
281 #ifndef FSTACK
282 			char filename[NG_TYPESIZ + 3];
283 			int fileid;
284 
285 			/* Not found, try to load it as a loadable module. */
286 			snprintf(filename, sizeof(filename), "ng_%s",
287 			    mkp->type);
288 			error = kern_kldload(curthread, filename, &fileid);
289 			if (error != 0) {
290 				free(msg, M_NETGRAPH_MSG);
291 				goto release;
292 			}
293 
294 			/* See if type has been loaded successfully. */
295 			if (ng_findtype(mkp->type) == NULL) {
296 				free(msg, M_NETGRAPH_MSG);
297 				(void)kern_kldunload(curthread, fileid,
298 				    LINKER_UNLOAD_NORMAL);
299 				error =  ENXIO;
300 				goto release;
301 			}
302 #else
303 			error =  ENOENT;
304 			goto release;
305 #endif
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 ngpcb *const pcbp = sotongpcb(so);
412 	struct sockaddr_ng *const sap = (struct sockaddr_ng *) addr;
413 	int	len, error;
414 	hook_p  hook = NULL;
415 	char	hookname[NG_HOOKSIZ];
416 
417 	if ((pcbp == NULL) || (control != NULL)) {
418 		error = EINVAL;
419 		goto release;
420 	}
421 	if (pcbp->sockdata == NULL) {
422 		error = ENOTCONN;
423 		goto release;
424 	}
425 
426 	if (sap == NULL)
427 		len = 0;		/* Make compiler happy. */
428 	else
429 		len = sap->sg_len - 2;
430 
431 	/*
432 	 * If the user used any of these ways to not specify an address
433 	 * then handle specially.
434 	 */
435 	if ((sap == NULL) || (len <= 0) || (*sap->sg_data == '\0')) {
436 		if (NG_NODE_NUMHOOKS(pcbp->sockdata->node) != 1) {
437 			error = EDESTADDRREQ;
438 			goto release;
439 		}
440 		/*
441 		 * If exactly one hook exists, just use it.
442 		 * Special case to allow write(2) to work on an ng_socket.
443 		 */
444 		hook = LIST_FIRST(&pcbp->sockdata->node->nd_hooks);
445 	} else {
446 		if (len >= NG_HOOKSIZ) {
447 			error = EINVAL;
448 			goto release;
449 		}
450 
451 		/*
452 		 * chop off the sockaddr header, and make sure it's NUL
453 		 * terminated
454 		 */
455 		bcopy(sap->sg_data, hookname, len);
456 		hookname[len] = '\0';
457 
458 		/* Find the correct hook from 'hookname' */
459 		hook = ng_findhook(pcbp->sockdata->node, hookname);
460 		if (hook == NULL) {
461 			error = EHOSTUNREACH;
462 			goto release;
463 		}
464 	}
465 
466 	/* Send data. */
467 	NG_SEND_DATA_FLAGS(error, hook, m, NG_WAITOK);
468 
469 release:
470 	if (control != NULL)
471 		m_freem(control);
472 	if (m != NULL)
473 		m_freem(m);
474 	return (error);
475 }
476 
477 static int
478 ngd_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
479 {
480 	struct ngpcb *const pcbp = sotongpcb(so);
481 
482 	if (pcbp == NULL)
483 		return (EINVAL);
484 	return (ng_connect_data(nam, pcbp));
485 }
486 
487 /*
488  * Used for both data and control sockets
489  */
490 static int
491 ng_getsockaddr(struct socket *so, struct sockaddr **addr)
492 {
493 	struct ngpcb *pcbp;
494 	struct sockaddr_ng *sg;
495 	int sg_len;
496 	int error = 0;
497 
498 	pcbp = sotongpcb(so);
499 	if ((pcbp == NULL) || (pcbp->sockdata == NULL))
500 		/* XXXGL: can this still happen? */
501 		return (EINVAL);
502 
503 	sg_len = sizeof(struct sockaddr_ng) + NG_NODESIZ -
504 	    sizeof(sg->sg_data);
505 	sg = malloc(sg_len, M_SONAME, M_WAITOK | M_ZERO);
506 
507 	mtx_lock(&pcbp->sockdata->mtx);
508 	if (pcbp->sockdata->node != NULL) {
509 		node_p node = pcbp->sockdata->node;
510 
511 		if (NG_NODE_HAS_NAME(node))
512 			bcopy(NG_NODE_NAME(node), sg->sg_data,
513 			    strlen(NG_NODE_NAME(node)));
514 		mtx_unlock(&pcbp->sockdata->mtx);
515 
516 		sg->sg_len = sg_len;
517 		sg->sg_family = AF_NETGRAPH;
518 		*addr = (struct sockaddr *)sg;
519 	} else {
520 		mtx_unlock(&pcbp->sockdata->mtx);
521 		free(sg, M_SONAME);
522 		error = EINVAL;
523 	}
524 
525 	return (error);
526 }
527 
528 /*
529  * Attach a socket to it's protocol specific partner.
530  * For a control socket, actually create a netgraph node and attach
531  * to it as well.
532  */
533 
534 static int
535 ng_attach_cntl(struct socket *so)
536 {
537 	struct ngsock *priv;
538 	struct ngpcb *pcbp;
539 	node_p node;
540 	int error;
541 
542 	/* Setup protocol control block */
543 	if ((error = ng_attach_common(so, NG_CONTROL)) != 0)
544 		return (error);
545 	pcbp = sotongpcb(so);
546 
547 	/* Make the generic node components */
548 	if ((error = ng_make_node_common(&typestruct, &node)) != 0) {
549 		ng_detach_common(pcbp, NG_CONTROL);
550 		return (error);
551 	}
552 
553 	/*
554 	 * Allocate node private info and hash. We start
555 	 * with 16 hash entries, however we may grow later
556 	 * in ngs_newhook(). We can't predict how much hooks
557 	 * does this node plan to have.
558 	 */
559 	priv = malloc(sizeof(*priv), M_NETGRAPH_SOCK, M_WAITOK | M_ZERO);
560 	priv->hash = hashinit(16, M_NETGRAPH_SOCK, &priv->hmask);
561 
562 	/* Initialize mutex. */
563 	mtx_init(&priv->mtx, "ng_socket", NULL, MTX_DEF);
564 
565 	/* Link the pcb the private data. */
566 	priv->ctlsock = pcbp;
567 	pcbp->sockdata = priv;
568 	priv->refs++;
569 	priv->node = node;
570 	pcbp->node_id = node->nd_ID;	/* hint for netstat(1) */
571 
572 	/* Link the node and the private data. */
573 	NG_NODE_SET_PRIVATE(priv->node, priv);
574 	NG_NODE_REF(priv->node);
575 	priv->refs++;
576 
577 	return (0);
578 }
579 
580 static int
581 ng_attach_data(struct socket *so)
582 {
583 	return (ng_attach_common(so, NG_DATA));
584 }
585 
586 /*
587  * Set up a socket protocol control block.
588  * This code is shared between control and data sockets.
589  */
590 static int
591 ng_attach_common(struct socket *so, int type)
592 {
593 	struct ngpcb *pcbp;
594 	int error;
595 
596 	/* Standard socket setup stuff. */
597 	error = soreserve(so, ngpdg_sendspace, ngpdg_recvspace);
598 	if (error)
599 		return (error);
600 
601 	/* Allocate the pcb. */
602 	pcbp = malloc(sizeof(struct ngpcb), M_PCB, M_WAITOK | M_ZERO);
603 	pcbp->type = type;
604 
605 	/* Link the pcb and the socket. */
606 	so->so_pcb = (caddr_t)pcbp;
607 	pcbp->ng_socket = so;
608 
609 	/* Add the socket to linked list */
610 	mtx_lock(&ngsocketlist_mtx);
611 	LIST_INSERT_HEAD(&ngsocklist, pcbp, socks);
612 	mtx_unlock(&ngsocketlist_mtx);
613 	return (0);
614 }
615 
616 /*
617  * Disassociate the socket from it's protocol specific
618  * partner. If it's attached to a node's private data structure,
619  * then unlink from that too. If we were the last socket attached to it,
620  * then shut down the entire node. Shared code for control and data sockets.
621  */
622 static void
623 ng_detach_common(struct ngpcb *pcbp, int which)
624 {
625 	struct ngsock *priv = pcbp->sockdata;
626 
627 	if (priv != NULL) {
628 		mtx_lock(&priv->mtx);
629 
630 		switch (which) {
631 		case NG_CONTROL:
632 			priv->ctlsock = NULL;
633 			break;
634 		case NG_DATA:
635 			priv->datasock = NULL;
636 			break;
637 		default:
638 			panic("%s", __func__);
639 		}
640 		pcbp->sockdata = NULL;
641 		pcbp->node_id = 0;
642 
643 		ng_socket_free_priv(priv);
644 	}
645 
646 	pcbp->ng_socket->so_pcb = NULL;
647 	mtx_lock(&ngsocketlist_mtx);
648 	LIST_REMOVE(pcbp, socks);
649 	mtx_unlock(&ngsocketlist_mtx);
650 	free(pcbp, M_PCB);
651 }
652 
653 /*
654  * Remove a reference from node private data.
655  */
656 static void
657 ng_socket_free_priv(struct ngsock *priv)
658 {
659 	mtx_assert(&priv->mtx, MA_OWNED);
660 
661 	priv->refs--;
662 
663 	if (priv->refs == 0) {
664 		mtx_destroy(&priv->mtx);
665 		hashdestroy(priv->hash, M_NETGRAPH_SOCK, priv->hmask);
666 		free(priv, M_NETGRAPH_SOCK);
667 		return;
668 	}
669 
670 	if ((priv->refs == 1) && (priv->node != NULL)) {
671 		node_p node = priv->node;
672 
673 		priv->node = NULL;
674 		mtx_unlock(&priv->mtx);
675 		NG_NODE_UNREF(node);
676 		ng_rmnode_self(node);
677 	} else
678 		mtx_unlock(&priv->mtx);
679 }
680 
681 /*
682  * Connect the data socket to a named control socket node.
683  */
684 static int
685 ng_connect_data(struct sockaddr *nam, struct ngpcb *pcbp)
686 {
687 	struct sockaddr_ng *sap;
688 	node_p farnode;
689 	struct ngsock *priv;
690 	int error;
691 	item_p item;
692 
693 	/* If we are already connected, don't do it again. */
694 	if (pcbp->sockdata != NULL)
695 		return (EISCONN);
696 
697 	/*
698 	 * Find the target (victim) and check it doesn't already have
699 	 * a data socket. Also check it is a 'socket' type node.
700 	 * Use ng_package_data() and ng_address_path() to do this.
701 	 */
702 
703 	sap = (struct sockaddr_ng *) nam;
704 	/* The item will hold the node reference. */
705 	item = ng_package_data(NULL, NG_WAITOK);
706 
707 	if ((error = ng_address_path(NULL, item,  sap->sg_data, 0)))
708 		return (error); /* item is freed on failure */
709 
710 	/*
711 	 * Extract node from item and free item. Remember we now have
712 	 * a reference on the node. The item holds it for us.
713 	 * when we free the item we release the reference.
714 	 */
715 	farnode = item->el_dest; /* shortcut */
716 	if (strcmp(farnode->nd_type->name, NG_SOCKET_NODE_TYPE) != 0) {
717 		NG_FREE_ITEM(item); /* drop the reference to the node */
718 		return (EINVAL);
719 	}
720 	priv = NG_NODE_PRIVATE(farnode);
721 	if (priv->datasock != NULL) {
722 		NG_FREE_ITEM(item);	/* drop the reference to the node */
723 		return (EADDRINUSE);
724 	}
725 
726 	/*
727 	 * Link the PCB and the private data struct. and note the extra
728 	 * reference. Drop the extra reference on the node.
729 	 */
730 	mtx_lock(&priv->mtx);
731 	priv->datasock = pcbp;
732 	pcbp->sockdata = priv;
733 	pcbp->node_id = priv->node->nd_ID;	/* hint for netstat(1) */
734 	priv->refs++;
735 	mtx_unlock(&priv->mtx);
736 	NG_FREE_ITEM(item);	/* drop the reference to the node */
737 	return (0);
738 }
739 
740 /*
741  * Binding a socket means giving the corresponding node a name
742  */
743 static int
744 ng_bind(struct sockaddr *nam, struct ngpcb *pcbp)
745 {
746 	struct ngsock *const priv = pcbp->sockdata;
747 	struct sockaddr_ng *const sap = (struct sockaddr_ng *) nam;
748 
749 	if (priv == NULL) {
750 		TRAP_ERROR;
751 		return (EINVAL);
752 	}
753 	if ((sap->sg_len < 4) || (sap->sg_len > (NG_NODESIZ + 2)) ||
754 	    (sap->sg_data[0] == '\0') ||
755 	    (sap->sg_data[sap->sg_len - 3] != '\0')) {
756 		TRAP_ERROR;
757 		return (EINVAL);
758 	}
759 	return (ng_name_node(priv->node, sap->sg_data));
760 }
761 
762 /***************************************************************
763 	Netgraph node
764 ***************************************************************/
765 
766 /*
767  * You can only create new nodes from the socket end of things.
768  */
769 static int
770 ngs_constructor(node_p nodep)
771 {
772 	return (EINVAL);
773 }
774 
775 static void
776 ngs_rehash(node_p node)
777 {
778 	struct ngsock *priv = NG_NODE_PRIVATE(node);
779 	struct ngshash *new;
780 	struct hookpriv *hp;
781 	hook_p hook;
782 	uint32_t h;
783 	u_long hmask;
784 
785 	new = hashinit_flags((priv->hmask + 1) * 2, M_NETGRAPH_SOCK, &hmask,
786 	    HASH_NOWAIT);
787 	if (new == NULL)
788 		return;
789 
790 	LIST_FOREACH(hook, &node->nd_hooks, hk_hooks) {
791 		hp = NG_HOOK_PRIVATE(hook);
792 #ifdef INVARIANTS
793 		LIST_REMOVE(hp, next);
794 #endif
795 		h = hash32_str(NG_HOOK_NAME(hook), HASHINIT) & hmask;
796 		LIST_INSERT_HEAD(&new[h], hp, next);
797 	}
798 
799 	hashdestroy(priv->hash, M_NETGRAPH_SOCK, priv->hmask);
800 	priv->hash = new;
801 	priv->hmask = hmask;
802 }
803 
804 /*
805  * We allow any hook to be connected to the node.
806  * There is no per-hook private information though.
807  */
808 static int
809 ngs_newhook(node_p node, hook_p hook, const char *name)
810 {
811 	struct ngsock *const priv = NG_NODE_PRIVATE(node);
812 	struct hookpriv *hp;
813 	uint32_t h;
814 
815 	hp = malloc(sizeof(*hp), M_NETGRAPH_SOCK, M_NOWAIT);
816 	if (hp == NULL)
817 		return (ENOMEM);
818 	if (node->nd_numhooks * 2 > priv->hmask)
819 		ngs_rehash(node);
820 	hp->hook = hook;
821 	h = hash32_str(name, HASHINIT) & priv->hmask;
822 	LIST_INSERT_HEAD(&priv->hash[h], hp, next);
823 	NG_HOOK_SET_PRIVATE(hook, hp);
824 
825 	return (0);
826 }
827 
828 /*
829  * If only one hook, allow read(2) and write(2) to work.
830  */
831 static int
832 ngs_connect(hook_p hook)
833 {
834 	node_p node = NG_HOOK_NODE(hook);
835 	struct ngsock *priv = NG_NODE_PRIVATE(node);
836 
837 	if ((priv->datasock) && (priv->datasock->ng_socket)) {
838 		if (NG_NODE_NUMHOOKS(node) == 1)
839 			priv->datasock->ng_socket->so_state |= SS_ISCONNECTED;
840 		else
841 			priv->datasock->ng_socket->so_state &= ~SS_ISCONNECTED;
842 	}
843 	return (0);
844 }
845 
846 /* Look up hook by name */
847 static hook_p
848 ngs_findhook(node_p node, const char *name)
849 {
850 	struct ngsock *priv = NG_NODE_PRIVATE(node);
851 	struct hookpriv *hp;
852 	uint32_t h;
853 
854 	/*
855 	 * Microoptimisation for an ng_socket with
856 	 * a single hook, which is a common case.
857 	 */
858 	if (node->nd_numhooks == 1) {
859 		hook_p hook;
860 
861 		hook = LIST_FIRST(&node->nd_hooks);
862 
863 		if (strcmp(NG_HOOK_NAME(hook), name) == 0)
864 			return (hook);
865 		else
866 			return (NULL);
867 	}
868 
869 	h = hash32_str(name, HASHINIT) & priv->hmask;
870 
871 	LIST_FOREACH(hp, &priv->hash[h], next)
872 		if (strcmp(NG_HOOK_NAME(hp->hook), name) == 0)
873 			return (hp->hook);
874 
875 	return (NULL);
876 }
877 
878 /*
879  * Incoming messages get passed up to the control socket.
880  * Unless they are for us specifically (socket_type)
881  */
882 static int
883 ngs_rcvmsg(node_p node, item_p item, hook_p lasthook)
884 {
885 	struct ngsock *const priv = NG_NODE_PRIVATE(node);
886 	struct ngpcb *pcbp;
887 	struct socket *so;
888 	struct sockaddr_ng addr;
889 	struct ng_mesg *msg;
890 	struct mbuf *m;
891 	ng_ID_t	retaddr = NGI_RETADDR(item);
892 	int addrlen;
893 	int error = 0;
894 
895 	NGI_GET_MSG(item, msg);
896 	NG_FREE_ITEM(item);
897 
898 	/*
899 	 * Grab priv->mtx here to prevent destroying of control socket
900 	 * after checking that priv->ctlsock is not NULL.
901 	 */
902 	mtx_lock(&priv->mtx);
903 	pcbp = priv->ctlsock;
904 
905 	/*
906 	 * Only allow mesgs to be passed if we have the control socket.
907 	 * Data sockets can only support the generic messages.
908 	 */
909 	if (pcbp == NULL) {
910 		mtx_unlock(&priv->mtx);
911 		TRAP_ERROR;
912 		NG_FREE_MSG(msg);
913 		return (EINVAL);
914 	}
915 	so = pcbp->ng_socket;
916 	SOCKBUF_LOCK(&so->so_rcv);
917 
918 	/* As long as the race is handled, priv->mtx may be unlocked now. */
919 	mtx_unlock(&priv->mtx);
920 
921 #ifdef TRACE_MESSAGES
922 	printf("[%x]:---------->[socket]: c=<%d>cmd=%x(%s) f=%x #%d\n",
923 		retaddr,
924 		msg->header.typecookie,
925 		msg->header.cmd,
926 		msg->header.cmdstr,
927 		msg->header.flags,
928 		msg->header.token);
929 #endif
930 
931 	if (msg->header.typecookie == NGM_SOCKET_COOKIE) {
932 		switch (msg->header.cmd) {
933 		case NGM_SOCK_CMD_NOLINGER:
934 			priv->flags |= NGS_FLAG_NOLINGER;
935 			break;
936 		case NGM_SOCK_CMD_LINGER:
937 			priv->flags &= ~NGS_FLAG_NOLINGER;
938 			break;
939 		default:
940 			error = EINVAL;		/* unknown command */
941 		}
942 		SOCKBUF_UNLOCK(&so->so_rcv);
943 
944 		/* Free the message and return. */
945 		NG_FREE_MSG(msg);
946 		return (error);
947 	}
948 
949 	/* Get the return address into a sockaddr. */
950 	bzero(&addr, sizeof(addr));
951 	addr.sg_len = sizeof(addr);
952 	addr.sg_family = AF_NETGRAPH;
953 	addrlen = snprintf((char *)&addr.sg_data, sizeof(addr.sg_data),
954 	    "[%x]:", retaddr);
955 	if (addrlen < 0 || addrlen > sizeof(addr.sg_data)) {
956 		SOCKBUF_UNLOCK(&so->so_rcv);
957 		printf("%s: snprintf([%x]) failed - %d\n", __func__, retaddr,
958 		    addrlen);
959 		NG_FREE_MSG(msg);
960 		return (EINVAL);
961 	}
962 
963 	/* Copy the message itself into an mbuf chain. */
964 	m = m_devget((caddr_t)msg, sizeof(struct ng_mesg) + msg->header.arglen,
965 	    0, NULL, NULL);
966 
967 	/*
968 	 * Here we free the message. We need to do that
969 	 * regardless of whether we got mbufs.
970 	 */
971 	NG_FREE_MSG(msg);
972 
973 	if (m == NULL) {
974 		SOCKBUF_UNLOCK(&so->so_rcv);
975 		TRAP_ERROR;
976 		return (ENOBUFS);
977 	}
978 
979 	/* Send it up to the socket. */
980 	if (sbappendaddr_locked(&so->so_rcv, (struct sockaddr *)&addr, m,
981 	    NULL) == 0) {
982 		SOCKBUF_UNLOCK(&so->so_rcv);
983 		TRAP_ERROR;
984 		m_freem(m);
985 		return (ENOBUFS);
986 	}
987 	sorwakeup_locked(so);
988 
989 	return (error);
990 }
991 
992 /*
993  * Receive data on a hook
994  */
995 static int
996 ngs_rcvdata(hook_p hook, item_p item)
997 {
998 	struct ngsock *const priv = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
999 	struct ngpcb *const pcbp = priv->datasock;
1000 	struct socket *so;
1001 	struct sockaddr_ng *addr;
1002 	char *addrbuf[NG_HOOKSIZ + 4];
1003 	int addrlen;
1004 	struct mbuf *m;
1005 
1006 	NGI_GET_M(item, m);
1007 	NG_FREE_ITEM(item);
1008 
1009 	/* If there is no data socket, black-hole it. */
1010 	if (pcbp == NULL) {
1011 		NG_FREE_M(m);
1012 		return (0);
1013 	}
1014 	so = pcbp->ng_socket;
1015 
1016 	/* Get the return address into a sockaddr. */
1017 	addrlen = strlen(NG_HOOK_NAME(hook));	/* <= NG_HOOKSIZ - 1 */
1018 	addr = (struct sockaddr_ng *) addrbuf;
1019 	addr->sg_len = addrlen + 3;
1020 	addr->sg_family = AF_NETGRAPH;
1021 	bcopy(NG_HOOK_NAME(hook), addr->sg_data, addrlen);
1022 	addr->sg_data[addrlen] = '\0';
1023 
1024 	/* Try to tell the socket which hook it came in on. */
1025 	if (sbappendaddr(&so->so_rcv, (struct sockaddr *)addr, m, NULL) == 0) {
1026 		m_freem(m);
1027 		TRAP_ERROR;
1028 		return (ENOBUFS);
1029 	}
1030 	sorwakeup(so);
1031 	return (0);
1032 }
1033 
1034 /*
1035  * Hook disconnection
1036  *
1037  * For this type, removal of the last link destroys the node
1038  * if the NOLINGER flag is set.
1039  */
1040 static int
1041 ngs_disconnect(hook_p hook)
1042 {
1043 	node_p node = NG_HOOK_NODE(hook);
1044 	struct ngsock *const priv = NG_NODE_PRIVATE(node);
1045 	struct hookpriv *hp = NG_HOOK_PRIVATE(hook);
1046 
1047 	LIST_REMOVE(hp, next);
1048 	free(hp, M_NETGRAPH_SOCK);
1049 
1050 	if ((priv->datasock) && (priv->datasock->ng_socket)) {
1051 		if (NG_NODE_NUMHOOKS(node) == 1)
1052 			priv->datasock->ng_socket->so_state |= SS_ISCONNECTED;
1053 		else
1054 			priv->datasock->ng_socket->so_state &= ~SS_ISCONNECTED;
1055 	}
1056 
1057 	if ((priv->flags & NGS_FLAG_NOLINGER) &&
1058 	    (NG_NODE_NUMHOOKS(node) == 0) && (NG_NODE_IS_VALID(node)))
1059 		ng_rmnode_self(node);
1060 
1061 	return (0);
1062 }
1063 
1064 /*
1065  * Do local shutdown processing.
1066  * In this case, that involves making sure the socket
1067  * knows we should be shutting down.
1068  */
1069 static int
1070 ngs_shutdown(node_p node)
1071 {
1072 	struct ngsock *const priv = NG_NODE_PRIVATE(node);
1073 	struct ngpcb *dpcbp, *pcbp;
1074 
1075 	mtx_lock(&priv->mtx);
1076 	dpcbp = priv->datasock;
1077 	pcbp = priv->ctlsock;
1078 
1079 	if (dpcbp != NULL)
1080 		soisdisconnected(dpcbp->ng_socket);
1081 
1082 	if (pcbp != NULL)
1083 		soisdisconnected(pcbp->ng_socket);
1084 
1085 	priv->node = NULL;
1086 	NG_NODE_SET_PRIVATE(node, NULL);
1087 	ng_socket_free_priv(priv);
1088 
1089 	NG_NODE_UNREF(node);
1090 	return (0);
1091 }
1092 
1093 static void
1094 ng_socket_item_applied(void *context, int error)
1095 {
1096 	struct ngsock *const priv = (struct ngsock *)context;
1097 
1098 	mtx_lock(&priv->mtx);
1099 	priv->error = error;
1100 	wakeup(priv);
1101 	mtx_unlock(&priv->mtx);
1102 
1103 }
1104 
1105 static	int
1106 dummy_disconnect(struct socket *so)
1107 {
1108 	return (0);
1109 }
1110 /*
1111  * Control and data socket type descriptors
1112  *
1113  * XXXRW: Perhaps _close should do something?
1114  */
1115 
1116 static struct pr_usrreqs ngc_usrreqs = {
1117 	.pru_abort =		NULL,
1118 	.pru_attach =		ngc_attach,
1119 	.pru_bind =		ngc_bind,
1120 	.pru_connect =		ngc_connect,
1121 	.pru_detach =		ngc_detach,
1122 	.pru_disconnect =	dummy_disconnect,
1123 	.pru_peeraddr =		NULL,
1124 	.pru_send =		ngc_send,
1125 	.pru_shutdown =		NULL,
1126 	.pru_sockaddr =		ng_getsockaddr,
1127 	.pru_close =		NULL,
1128 };
1129 
1130 static struct pr_usrreqs ngd_usrreqs = {
1131 	.pru_abort =		NULL,
1132 	.pru_attach =		ngd_attach,
1133 	.pru_bind =		NULL,
1134 	.pru_connect =		ngd_connect,
1135 	.pru_detach =		ngd_detach,
1136 	.pru_disconnect =	dummy_disconnect,
1137 	.pru_peeraddr =		NULL,
1138 	.pru_send =		ngd_send,
1139 	.pru_shutdown =		NULL,
1140 	.pru_sockaddr =		ng_getsockaddr,
1141 	.pru_close =		NULL,
1142 };
1143 
1144 /*
1145  * Definitions of protocols supported in the NETGRAPH domain.
1146  */
1147 
1148 extern struct domain ngdomain;		/* stop compiler warnings */
1149 
1150 static struct protosw ngsw[] = {
1151 {
1152 	.pr_type =		SOCK_DGRAM,
1153 	.pr_domain =		&ngdomain,
1154 	.pr_protocol =		NG_CONTROL,
1155 	.pr_flags =		PR_ATOMIC | PR_ADDR /* | PR_RIGHTS */,
1156 	.pr_usrreqs =		&ngc_usrreqs
1157 },
1158 {
1159 	.pr_type =		SOCK_DGRAM,
1160 	.pr_domain =		&ngdomain,
1161 	.pr_protocol =		NG_DATA,
1162 	.pr_flags =		PR_ATOMIC | PR_ADDR,
1163 	.pr_usrreqs =		&ngd_usrreqs
1164 }
1165 };
1166 
1167 struct domain ngdomain = {
1168 	.dom_family =		AF_NETGRAPH,
1169 	.dom_name =		"netgraph",
1170 	.dom_protosw =		ngsw,
1171 	.dom_protoswNPROTOSW =	&ngsw[nitems(ngsw)]
1172 };
1173 
1174 /*
1175  * Handle loading and unloading for this node type.
1176  * This is to handle auxiliary linkages (e.g protocol domain addition).
1177  */
1178 static int
1179 ngs_mod_event(module_t mod, int event, void *data)
1180 {
1181 	int error = 0;
1182 
1183 	switch (event) {
1184 	case MOD_LOAD:
1185 		mtx_init(&ngsocketlist_mtx, "ng_socketlist", NULL, MTX_DEF);
1186 		break;
1187 	case MOD_UNLOAD:
1188 		/* Ensure there are no open netgraph sockets. */
1189 		if (!LIST_EMPTY(&ngsocklist)) {
1190 			error = EBUSY;
1191 			break;
1192 		}
1193 #ifdef NOTYET
1194 		/* Unregister protocol domain XXX can't do this yet.. */
1195 #endif
1196 		error = EBUSY;
1197 		break;
1198 	default:
1199 		error = EOPNOTSUPP;
1200 		break;
1201 	}
1202 	return (error);
1203 }
1204 
1205 VNET_DOMAIN_SET(ng);
1206 
1207 SYSCTL_INT(_net_graph, OID_AUTO, family, CTLFLAG_RD, SYSCTL_NULL_INT_PTR, AF_NETGRAPH, "");
1208 static SYSCTL_NODE(_net_graph, OID_AUTO, data, CTLFLAG_RW, 0, "DATA");
1209 SYSCTL_INT(_net_graph_data, OID_AUTO, proto, CTLFLAG_RD, SYSCTL_NULL_INT_PTR, NG_DATA, "");
1210 static SYSCTL_NODE(_net_graph, OID_AUTO, control, CTLFLAG_RW, 0, "CONTROL");
1211 SYSCTL_INT(_net_graph_control, OID_AUTO, proto, CTLFLAG_RD, SYSCTL_NULL_INT_PTR, NG_CONTROL, "");
1212 
1213