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