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