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