]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netgraph/ng_socket.c
This commit was generated by cvs2svn to compensate for changes in r146532,
[FreeBSD/FreeBSD.git] / sys / netgraph / ng_socket.c
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         item_p item;
215         char *path = NULL;
216         int len, error = 0;
217
218         if (pcbp == NULL) {
219                 error = EINVAL;
220                 goto release;
221         }
222 #ifdef  NOTYET
223         if (control && (error = ng_internalize(control, td))) {
224                 if (pcbp->sockdata == NULL) {
225                         error = ENOTCONN;
226                         goto release;
227                 }
228         }
229 #else   /* NOTYET */
230         if (control) {
231                 error = EINVAL;
232                 goto release;
233         }
234 #endif  /* NOTYET */
235
236         /* Require destination as there may be >= 1 hooks on this node */
237         if (addr == NULL) {
238                 error = EDESTADDRREQ;
239                 goto release;
240         }
241
242         /* Allocate an expendable buffer for the path, chop off
243          * the sockaddr header, and make sure it's NUL terminated */
244         len = sap->sg_len - 2;
245         MALLOC(path, char *, len + 1, M_NETGRAPH_PATH, M_WAITOK);
246         if (path == NULL) {
247                 error = ENOMEM;
248                 goto release;
249         }
250         bcopy(sap->sg_data, path, len);
251         path[len] = '\0';
252
253         /* Move the actual message out of mbufs into a linear buffer.
254          * Start by adding up the size of the data. (could use mh_len?) */
255         for (len = 0, m0 = m; m0 != NULL; m0 = m0->m_next)
256                 len += m0->m_len;
257
258         /* Move the data into a linear buffer as well. Messages are not
259          * delivered in mbufs. */
260         MALLOC(msg, struct ng_mesg *, len + 1, M_NETGRAPH_MSG, M_WAITOK);
261         if (msg == NULL) {
262                 error = ENOMEM;
263                 goto release;
264         }
265         m_copydata(m, 0, len, (char *)msg);
266
267         if (msg->header.version != NG_VERSION) {
268                 error = EINVAL;
269                 goto release;
270         }
271
272         /*
273          * Hack alert!
274          * We look into the message and if it mkpeers a node of unknown type, we
275          * try to load it. We need to do this now, in syscall thread, because if
276          * message gets queued and applied later we will get panic.
277          */
278         if (msg->header.typecookie == NGM_GENERIC_COOKIE &&
279             msg->header.cmd == NGM_MKPEER) {
280                 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
281                 struct ng_type *type;
282
283                 if ((type = ng_findtype(mkp->type)) == NULL) {
284                         char filename[NG_TYPESIZ + 3];
285                         linker_file_t lf;
286                         int error;
287
288                         /* Not found, try to load it as a loadable module. */
289                         snprintf(filename, sizeof(filename), "ng_%s",
290                             mkp->type);
291                         mtx_lock(&Giant);
292                         error = linker_load_module(NULL, filename, NULL, NULL,
293                             &lf);
294                         mtx_unlock(&Giant);
295                         if (error != 0) {
296                                 FREE(msg, M_NETGRAPH_MSG);
297                                 goto release;
298                         }
299                         lf->userrefs++;
300
301                         /* See if type has been loaded successfully. */
302                         if ((type = ng_findtype(mkp->type)) == NULL) {
303                                 FREE(msg, M_NETGRAPH_MSG);
304                                 error =  ENXIO;
305                                 goto release;
306                         }
307                 }
308         }
309
310         if ((item = ng_package_msg(msg, M_WAITOK)) == NULL) {
311                 error = ENOMEM;
312 #ifdef TRACE_MESSAGES
313                 printf("ng_package_msg: err=%d\n", error);
314 #endif
315                 goto release;
316         }
317         if ((error = ng_address_path((pcbp->sockdata->node), item,
318             path, 0)) != 0) {
319 #ifdef TRACE_MESSAGES
320                 printf("ng_address_path: errx=%d\n", error);
321 #endif
322                 goto release;
323         }
324
325 #ifdef TRACE_MESSAGES
326         printf("[%x]:<---------[socket]: c=<%d>cmd=%x(%s) f=%x #%d (%s)\n",
327                 item->el_dest->nd_ID,
328                 msg->header.typecookie,
329                 msg->header.cmd,
330                 msg->header.cmdstr,
331                 msg->header.flags,
332                 msg->header.token,
333                 item->el_dest->nd_type->name);
334 #endif
335         SAVE_LINE(item);
336         error = ng_snd_item(item, NG_NOFLAGS);
337
338 release:
339         if (path != NULL)
340                 FREE(path, M_NETGRAPH_PATH);
341         if (control != NULL)
342                 m_freem(control);
343         if (m != NULL)
344                 m_freem(m);
345         return (error);
346 }
347
348 static int
349 ngc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
350 {
351         struct ngpcb *const pcbp = sotongpcb(so);
352
353         if (pcbp == 0)
354                 return (EINVAL);
355         return (ng_bind(nam, pcbp));
356 }
357
358 static int
359 ngc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
360 {
361 printf(" program tried to connect control socket to remote node\n ");
362         /*
363          * At this time refuse to do this.. it used to
364          * do something but it was undocumented and not used.
365          */
366         return (EINVAL);
367 }
368
369 /***************************************************************
370         Data sockets
371 ***************************************************************/
372
373 static int
374 ngd_attach(struct socket *so, int proto, struct thread *td)
375 {
376         struct ngpcb *const pcbp = sotongpcb(so);
377
378         if (pcbp != NULL)
379                 return (EISCONN);
380         return (ng_attach_data(so));
381 }
382
383 static int
384 ngd_detach(struct socket *so)
385 {
386         struct ngpcb *const pcbp = sotongpcb(so);
387
388         if (pcbp == NULL)
389                 return (EINVAL);
390
391         /*
392          * If there is a node, then obtain netgraph locking first.
393          */
394         if (pcbp->sockdata != NULL)
395                 ng_send_fn1(pcbp->sockdata->node, NULL, &ng_detach_common,
396                     pcbp, NG_DATA, NG_WAITOK);
397         else
398                 ng_detach_common(NULL, NULL, pcbp, NG_DATA);
399
400         return (0);
401 }
402
403 static int
404 ngd_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
405          struct mbuf *control, struct thread *td)
406 {
407         struct ngpcb *const pcbp = sotongpcb(so);
408         struct sockaddr_ng *const sap = (struct sockaddr_ng *) addr;
409         int     len, error;
410         hook_p  hook = NULL;
411         char    hookname[NG_HOOKSIZ];
412
413         if ((pcbp == NULL) || (control != NULL)) {
414                 error = EINVAL;
415                 goto release;
416         }
417         if (pcbp->sockdata == NULL) {
418                 error = ENOTCONN;
419                 goto release;
420         }
421         /*
422          * If the user used any of these ways to not specify an address
423          * then handle specially.
424          */
425         if ((sap == NULL)
426             || ((len = sap->sg_len - 2) <= 0)
427             || (*sap->sg_data == '\0')) {
428                 if (NG_NODE_NUMHOOKS(pcbp->sockdata->node) != 1) {
429                         error = EDESTADDRREQ;
430                         goto release;
431                 }
432                 /*
433                  * if exactly one hook exists, just use it.
434                  * Special case to allow write(2) to work on an ng_socket.
435                  */
436                 hook = LIST_FIRST(&pcbp->sockdata->node->nd_hooks);
437         } else {
438                 if (len >= NG_HOOKSIZ) {
439                         error = EINVAL;
440                         goto release;
441                 }
442
443                 /*
444                  * chop off the sockaddr header, and make sure it's NUL
445                  * terminated
446                  */
447                 bcopy(sap->sg_data, hookname, len);
448                 hookname[len] = '\0';
449
450                 /* Find the correct hook from 'hookname' */
451                 LIST_FOREACH(hook, &pcbp->sockdata->node->nd_hooks, hk_hooks) {
452                         if (strcmp(hookname, NG_HOOK_NAME(hook)) == 0) {
453                                 break;
454                         }
455                 }
456                 if (hook == NULL) {
457                         error = EHOSTUNREACH;
458                 }
459         }
460
461         /* Send data (OK if hook is NULL) */
462         NG_SEND_DATA_ONLY(error, hook, m);      /* makes m NULL */
463
464 release:
465         if (control != NULL)
466                 m_freem(control);
467         if (m != NULL)
468                 m_freem(m);
469         return (error);
470 }
471
472 static int
473 ngd_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
474 {
475         struct ngpcb *const pcbp = sotongpcb(so);
476
477         if (pcbp == 0)
478                 return (EINVAL);
479         return (ng_connect_data(nam, pcbp));
480 }
481
482 /*
483  * Used for both data and control sockets
484  */
485 static int
486 ng_setsockaddr(struct socket *so, struct sockaddr **addr)
487 {
488         struct ngpcb *pcbp;
489         struct sockaddr_ng *sg;
490         int sg_len, namelen, s;
491
492         /* Why isn't sg_data a `char[1]' ? :-( */
493         sg_len = sizeof(struct sockaddr_ng) - sizeof(sg->sg_data) + 1;
494
495         s = splnet();
496         pcbp = sotongpcb(so);
497         if ((pcbp == NULL) || (pcbp->sockdata == NULL)) {
498                 splx(s);
499                 return (EINVAL);
500         }
501
502         namelen = 0;            /* silence compiler ! */
503         if ( NG_NODE_HAS_NAME(pcbp->sockdata->node))
504                 sg_len += namelen = strlen(NG_NODE_NAME(pcbp->sockdata->node));
505
506         MALLOC(sg, struct sockaddr_ng *, sg_len, M_SONAME, M_WAITOK | M_ZERO);
507
508         if (NG_NODE_HAS_NAME(pcbp->sockdata->node))
509                 bcopy(NG_NODE_NAME(pcbp->sockdata->node), sg->sg_data, namelen);
510         splx(s);
511
512         sg->sg_len = sg_len;
513         sg->sg_family = AF_NETGRAPH;
514         *addr = (struct sockaddr *)sg;
515
516         return (0);
517 }
518
519 /*
520  * Attach a socket to it's protocol specific partner.
521  * For a control socket, actually create a netgraph node and attach
522  * to it as well.
523  */
524
525 static int
526 ng_attach_cntl(struct socket *so)
527 {
528         struct ngsock *privdata;
529         struct ngpcb *pcbp;
530         int error;
531
532         /* Setup protocol control block */
533         if ((error = ng_attach_common(so, NG_CONTROL)) != 0)
534                 return (error);
535         pcbp = sotongpcb(so);
536
537         /* Allocate node private info */
538         MALLOC(privdata, struct ngsock *,
539             sizeof(*privdata), M_NETGRAPH_SOCK, M_WAITOK | M_ZERO);
540         if (privdata == NULL) {
541                 ng_detach_common(NULL, NULL, pcbp, NG_CONTROL);
542                 return (ENOMEM);
543         }
544
545         /* Make the generic node components */
546         if ((error = ng_make_node_common(&typestruct, &privdata->node)) != 0) {
547                 FREE(privdata, M_NETGRAPH_SOCK);
548                 ng_detach_common(NULL, NULL, pcbp, NG_CONTROL);
549                 return (error);
550         }
551         NG_NODE_SET_PRIVATE(privdata->node, privdata);
552
553         /* Link the pcb and the node private data */
554         privdata->ctlsock = pcbp;
555         pcbp->sockdata = privdata;
556         privdata->refs++;
557         return (0);
558 }
559
560 static int
561 ng_attach_data(struct socket *so)
562 {
563         return(ng_attach_common(so, NG_DATA));
564 }
565
566 /*
567  * Set up a socket protocol control block.
568  * This code is shared between control and data sockets.
569  */
570 static int
571 ng_attach_common(struct socket *so, int type)
572 {
573         struct ngpcb *pcbp;
574         int error;
575
576         /* Standard socket setup stuff */
577         error = soreserve(so, ngpdg_sendspace, ngpdg_recvspace);
578         if (error)
579                 return (error);
580
581         /* Allocate the pcb */
582         MALLOC(pcbp, struct ngpcb *, sizeof(*pcbp), M_PCB, M_WAITOK | M_ZERO);
583         if (pcbp == NULL)
584                 return (ENOMEM);
585         pcbp->type = type;
586
587         /* Link the pcb and the socket */
588         so->so_pcb = (caddr_t) pcbp;
589         pcbp->ng_socket = so;
590
591         /* Add the socket to linked list */
592         mtx_lock(&ngsocketlist_mtx);
593         LIST_INSERT_HEAD(&ngsocklist, pcbp, socks);
594         mtx_unlock(&ngsocketlist_mtx);
595         return (0);
596 }
597
598 /*
599  * Disassociate the socket from it's protocol specific
600  * partner. If it's attached to a node's private data structure,
601  * then unlink from that too. If we were the last socket attached to it,
602  * then shut down the entire node. Shared code for control and data sockets.
603  */
604 static void
605 ng_detach_common(node_p node, hook_p hook, void *arg1, int which)
606 {
607         struct ngpcb *pcbp = arg1;
608
609         if (pcbp->sockdata) {
610                 struct ngsock *priv;
611
612                 priv = pcbp->sockdata;
613                 pcbp->sockdata = NULL;
614                 switch (which) {
615                 case NG_CONTROL:
616                         priv->ctlsock = NULL;
617                         break;
618                 case NG_DATA:
619                         priv->datasock = NULL;
620                         break;
621                 default:
622                         panic(__func__);
623                 }
624                 if ((--priv->refs == 0) && (priv->node != NULL))
625                         ng_rmnode_self(priv->node);
626         }
627         pcbp->ng_socket->so_pcb = NULL;
628         pcbp->ng_socket = NULL;
629         mtx_lock(&ngsocketlist_mtx);
630         LIST_REMOVE(pcbp, socks);
631         mtx_unlock(&ngsocketlist_mtx);
632         FREE(pcbp, M_PCB);
633 }
634
635 #ifdef NOTYET
636 /*
637  * File descriptors can be passed into an AF_NETGRAPH socket.
638  * Note, that file descriptors cannot be passed OUT.
639  * Only character device descriptors are accepted.
640  * Character devices are useful to connect a graph to a device,
641  * which after all is the purpose of this whole system.
642  */
643 static int
644 ng_internalize(struct mbuf *control, struct thread *td)
645 {
646         const struct cmsghdr *cm = mtod(control, const struct cmsghdr *);
647         struct file *fp;
648         struct vnode *vn;
649         int oldfds;
650         int fd;
651
652         if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
653             cm->cmsg_len != control->m_len) {
654                 TRAP_ERROR;
655                 return (EINVAL);
656         }
657
658         /* Check there is only one FD. XXX what would more than one signify? */
659         oldfds = ((caddr_t)cm + cm->cmsg_len - (caddr_t)data) / sizeof (int);
660         if (oldfds != 1) {
661                 TRAP_ERROR;
662                 return (EINVAL);
663         }
664
665         /* Check that the FD given is legit. and change it to a pointer to a
666          * struct file. */
667         fd = CMSG_DATA(cm);
668         if ((error = fget(td, fd, &fp)) != 0)
669                 return (error);
670
671         /* Depending on what kind of resource it is, act differently. For
672          * devices, we treat it as a file. For an AF_NETGRAPH socket,
673          * shortcut straight to the node. */
674         switch (fp->f_type) {
675         case DTYPE_VNODE:
676                 vn = fp->f_data;
677                 if (vn && (vn->v_type == VCHR)) {
678                         /* for a VCHR, actually reference the FILE */
679                         fp->f_count++;
680                         /* XXX then what :) */
681                         /* how to pass on to other modules? */
682                 } else {
683                         fdrop(fp, td);
684                         TRAP_ERROR;
685                         return (EINVAL);
686                 }
687                 break;
688         default:
689                 fdrop(fp, td);
690                 TRAP_ERROR;
691                 return (EINVAL);
692         }
693         fdrop(fp, td);
694         return (0);
695 }
696 #endif  /* NOTYET */
697
698 /*
699  * Connect the data socket to a named control socket node.
700  */
701 static int
702 ng_connect_data(struct sockaddr *nam, struct ngpcb *pcbp)
703 {
704         struct sockaddr_ng *sap;
705         node_p farnode;
706         struct ngsock *priv;
707         int error;
708         item_p item;
709
710         /* If we are already connected, don't do it again */
711         if (pcbp->sockdata != NULL)
712                 return (EISCONN);
713
714         /* Find the target (victim) and check it doesn't already have a data
715          * socket. Also check it is a 'socket' type node.
716          * Use ng_package_data() and address_path() to do this.
717          */
718
719         sap = (struct sockaddr_ng *) nam;
720         /* The item will hold the node reference */
721         item = ng_package_data(NULL, NG_WAITOK);
722         if (item == NULL) {
723                 return (ENOMEM);
724         }
725         if ((error = ng_address_path(NULL, item,  sap->sg_data, 0)))
726                 return (error); /* item is freed on failure */
727
728         /*
729          * Extract node from item and free item. Remember we now have
730          * a reference on the node. The item holds it for us.
731          * when we free the item we release the reference.
732          */
733         farnode = item->el_dest; /* shortcut */
734         if (strcmp(farnode->nd_type->name, NG_SOCKET_NODE_TYPE) != 0) {
735                 NG_FREE_ITEM(item); /* drop the reference to the node */
736                 return (EINVAL);
737         }
738         priv = NG_NODE_PRIVATE(farnode);
739         if (priv->datasock != NULL) {
740                 NG_FREE_ITEM(item);     /* drop the reference to the node */
741                 return (EADDRINUSE);
742         }
743
744         /*
745          * Link the PCB and the private data struct. and note the extra
746          * reference. Drop the extra reference on the node.
747          */
748         priv->datasock = pcbp;
749         pcbp->sockdata = priv;
750         priv->refs++; /* XXX possible race if it's being freed */
751         NG_FREE_ITEM(item);     /* drop the reference to the node */
752         return (0);
753 }
754
755 /*
756  * Binding a socket means giving the corresponding node a name
757  */
758 static int
759 ng_bind(struct sockaddr *nam, struct ngpcb *pcbp)
760 {
761         struct ngsock *const priv = pcbp->sockdata;
762         struct sockaddr_ng *const sap = (struct sockaddr_ng *) nam;
763
764         if (priv == NULL) {
765                 TRAP_ERROR;
766                 return (EINVAL);
767         }
768         if ((sap->sg_len < 4)
769         ||  (sap->sg_len > (NG_NODESIZ + 2))
770         ||  (sap->sg_data[0] == '\0')
771         ||  (sap->sg_data[sap->sg_len - 3] != '\0')) {
772                 TRAP_ERROR;
773                 return (EINVAL);
774         }
775         return (ng_name_node(priv->node, sap->sg_data));
776 }
777
778 /*
779  * Take a message and pass it up to the control socket associated
780  * with the node.
781  */
782 static int
783 ship_msg(struct ngpcb *pcbp, struct ng_mesg *msg, struct sockaddr_ng *addr)
784 {
785         struct socket *const so = pcbp->ng_socket;
786         struct mbuf *mdata;
787         int msglen;
788
789         /* Copy the message itself into an mbuf chain */
790         msglen = sizeof(struct ng_mesg) + msg->header.arglen;
791         mdata = m_devget((caddr_t) msg, msglen, 0, NULL, NULL);
792
793         /* Here we free the message, as we are the end of the line.
794          * We need to do that regardless of whether we got mbufs. */
795         NG_FREE_MSG(msg);
796
797         if (mdata == NULL) {
798                 TRAP_ERROR;
799                 return (ENOBUFS);
800         }
801
802         /* Send it up to the socket */
803         if (sbappendaddr(&so->so_rcv,
804             (struct sockaddr *) addr, mdata, NULL) == 0) {
805                 TRAP_ERROR;
806                 m_freem(mdata);
807                 return (ENOBUFS);
808         }
809         sorwakeup(so);
810         return (0);
811 }
812
813 /*
814  * You can only create new nodes from the socket end of things.
815  */
816 static int
817 ngs_constructor(node_p nodep)
818 {
819         return (EINVAL);
820 }
821
822 /*
823  * We allow any hook to be connected to the node.
824  * There is no per-hook private information though.
825  */
826 static int
827 ngs_newhook(node_p node, hook_p hook, const char *name)
828 {
829         NG_HOOK_SET_PRIVATE(hook, NG_NODE_PRIVATE(node));
830         return (0);
831 }
832
833 /* 
834  * if only one hook, allow read(2) and write(2) to work.
835  */
836 static int
837 ngs_connect(hook_p hook)
838 {
839         node_p node = NG_HOOK_NODE(hook);
840         struct ngsock *priv = NG_NODE_PRIVATE(node);
841
842         if ((priv->datasock)
843         &&  (priv->datasock->ng_socket)) {
844                 if (NG_NODE_NUMHOOKS(node) == 1) {
845                         priv->datasock->ng_socket->so_state |= SS_ISCONNECTED;
846                 } else {
847                         priv->datasock->ng_socket->so_state &= ~SS_ISCONNECTED;
848                 }
849         }
850         return (0);
851 }
852
853 /*
854  * Incoming messages get passed up to the control socket.
855  * Unless they are for us specifically (socket_type)
856  */
857 static int
858 ngs_rcvmsg(node_p node, item_p item, hook_p lasthook)
859 {
860         struct ngsock *const priv = NG_NODE_PRIVATE(node);
861         struct ngpcb *const pcbp = priv->ctlsock;
862         struct sockaddr_ng *addr;
863         int addrlen;
864         int error = 0;
865         struct  ng_mesg *msg;
866         ng_ID_t retaddr = NGI_RETADDR(item);
867         char    retabuf[32];
868
869         NGI_GET_MSG(item, msg);
870         NG_FREE_ITEM(item); /* we have all we need */
871
872         /* Only allow mesgs to be passed if we have the control socket.
873          * Data sockets can only support the generic messages. */
874         if (pcbp == NULL) {
875                 TRAP_ERROR;
876                 return (EINVAL);
877         }
878
879 #ifdef TRACE_MESSAGES
880         printf("[%x]:---------->[socket]: c=<%d>cmd=%x(%s) f=%x #%d\n",
881                 retaddr,
882                 msg->header.typecookie,
883                 msg->header.cmd,
884                 msg->header.cmdstr,
885                 msg->header.flags,
886                 msg->header.token);
887 #endif
888
889         if (msg->header.typecookie == NGM_SOCKET_COOKIE) {
890                 switch (msg->header.cmd) {
891                 case NGM_SOCK_CMD_NOLINGER:
892                         priv->flags |= NGS_FLAG_NOLINGER;
893                         break;
894                 case NGM_SOCK_CMD_LINGER:
895                         priv->flags &= ~NGS_FLAG_NOLINGER;
896                         break;
897                 default:
898                         error = EINVAL;         /* unknown command */
899                 }
900                 /* Free the message and return */
901                 NG_FREE_MSG(msg);
902                 return(error);
903
904         }
905         /* Get the return address into a sockaddr */
906         sprintf(retabuf,"[%x]:", retaddr);
907         addrlen = strlen(retabuf);
908         MALLOC(addr, struct sockaddr_ng *, addrlen + 4, M_NETGRAPH_PATH, M_NOWAIT);
909         if (addr == NULL) {
910                 TRAP_ERROR;
911                 return (ENOMEM);
912         }
913         addr->sg_len = addrlen + 3;
914         addr->sg_family = AF_NETGRAPH;
915         bcopy(retabuf, addr->sg_data, addrlen);
916         addr->sg_data[addrlen] = '\0';
917
918         /* Send it up */
919         error = ship_msg(pcbp, msg, addr);
920         FREE(addr, M_NETGRAPH_PATH);
921         return (error);
922 }
923
924 /*
925  * Receive data on a hook
926  */
927 static int
928 ngs_rcvdata(hook_p hook, item_p item)
929 {
930         struct ngsock *const priv = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
931         struct ngpcb *const pcbp = priv->datasock;
932         struct socket *so;
933         struct sockaddr_ng *addr;
934         char *addrbuf[NG_HOOKSIZ + 4];
935         int addrlen;
936         struct mbuf *m;
937
938         NGI_GET_M(item, m);
939         NG_FREE_ITEM(item);
940         /* If there is no data socket, black-hole it */
941         if (pcbp == NULL) {
942                 NG_FREE_M(m);
943                 return (0);
944         }
945         so = pcbp->ng_socket;
946
947         /* Get the return address into a sockaddr. */
948         addrlen = strlen(NG_HOOK_NAME(hook));   /* <= NG_HOOKSIZ - 1 */
949         addr = (struct sockaddr_ng *) addrbuf;
950         addr->sg_len = addrlen + 3;
951         addr->sg_family = AF_NETGRAPH;
952         bcopy(NG_HOOK_NAME(hook), addr->sg_data, addrlen);
953         addr->sg_data[addrlen] = '\0';
954
955         /* Try to tell the socket which hook it came in on */
956         if (sbappendaddr(&so->so_rcv, (struct sockaddr *) addr, m, NULL) == 0) {
957                 m_freem(m);
958                 TRAP_ERROR;
959                 return (ENOBUFS);
960         }
961         sorwakeup(so);
962         return (0);
963 }
964
965 /*
966  * Hook disconnection
967  *
968  * For this type, removal of the last link destroys the node
969  * if the NOLINGER flag is set.
970  */
971 static int
972 ngs_disconnect(hook_p hook)
973 {
974         node_p node = NG_HOOK_NODE(hook);
975         struct ngsock *const priv = NG_NODE_PRIVATE(node);
976
977         if ((priv->datasock)
978         &&  (priv->datasock->ng_socket)) {
979                 if (NG_NODE_NUMHOOKS(node) == 1) {
980                         priv->datasock->ng_socket->so_state |= SS_ISCONNECTED;
981                 } else {
982                         priv->datasock->ng_socket->so_state &= ~SS_ISCONNECTED;
983                 }
984         }
985
986         if ((priv->flags & NGS_FLAG_NOLINGER )
987         && (NG_NODE_NUMHOOKS(node) == 0)
988         && (NG_NODE_IS_VALID(node))) {
989                 ng_rmnode_self(node);
990         }
991         return (0);
992 }
993
994 /*
995  * Do local shutdown processing.
996  * In this case, that involves making sure the socket
997  * knows we should be shutting down.
998  */
999 static int
1000 ngs_shutdown(node_p node)
1001 {
1002         struct ngsock *const priv = NG_NODE_PRIVATE(node);
1003         struct ngpcb *const dpcbp = priv->datasock;
1004         struct ngpcb *const pcbp = priv->ctlsock;
1005
1006         if (dpcbp != NULL) {
1007                 soisdisconnected(dpcbp->ng_socket);
1008                 dpcbp->sockdata = NULL;
1009                 priv->datasock = NULL;
1010                 priv->refs--;
1011         }
1012         if (pcbp != NULL) {
1013                 soisdisconnected(pcbp->ng_socket);
1014                 pcbp->sockdata = NULL;
1015                 priv->ctlsock = NULL;
1016                 priv->refs--;
1017         }
1018         NG_NODE_SET_PRIVATE(node, NULL);
1019         NG_NODE_UNREF(node);
1020         FREE(priv, M_NETGRAPH_SOCK);
1021         return (0);
1022 }
1023
1024 static  int
1025 dummy_disconnect(struct socket *so)
1026 {
1027         return (0);
1028 }
1029 /*
1030  * Control and data socket type descriptors
1031  */
1032
1033 static struct pr_usrreqs ngc_usrreqs = {
1034         .pru_abort =            NULL,
1035         .pru_attach =           ngc_attach,
1036         .pru_bind =             ngc_bind,
1037         .pru_connect =          ngc_connect,
1038         .pru_detach =           ngc_detach,
1039         .pru_disconnect =       dummy_disconnect,
1040         .pru_peeraddr =         NULL,
1041         .pru_send =             ngc_send,
1042         .pru_shutdown =         NULL,
1043         .pru_sockaddr =         ng_setsockaddr,
1044 };
1045
1046 static struct pr_usrreqs ngd_usrreqs = {
1047         .pru_abort =            NULL,
1048         .pru_attach =           ngd_attach,
1049         .pru_bind =             NULL,
1050         .pru_connect =          ngd_connect,
1051         .pru_detach =           ngd_detach,
1052         .pru_disconnect =       dummy_disconnect,
1053         .pru_peeraddr =         NULL,
1054         .pru_send =             ngd_send,
1055         .pru_shutdown =         NULL,
1056         .pru_sockaddr           ng_setsockaddr,
1057 };
1058
1059 /*
1060  * Definitions of protocols supported in the NETGRAPH domain.
1061  */
1062
1063 extern struct domain ngdomain;          /* stop compiler warnings */
1064
1065 static struct protosw ngsw[] = {
1066         {
1067                 SOCK_DGRAM,             /* protocol type */
1068                 &ngdomain,              /* backpointer to domain */
1069                 NG_CONTROL,
1070                 PR_ATOMIC | PR_ADDR /* | PR_RIGHTS */,  /* flags */
1071                 0, 0, 0, 0,             /* input, output, ctlinput, ctloutput */
1072                 NULL,                   /* ousrreq */
1073                 0, 0, 0, 0,             /* init, fasttimeo, slowtimo, drain */
1074                 &ngc_usrreqs,           /* usrreq table (above) */
1075                 /*{NULL}*/              /* pffh (protocol filter head?) */
1076         },
1077         {
1078                 SOCK_DGRAM,             /* protocol type */
1079                 &ngdomain,              /* backpointer to domain */
1080                 NG_DATA,
1081                 PR_ATOMIC | PR_ADDR,    /* flags */
1082                 0, 0, 0, 0,             /* input, output, ctlinput, ctloutput */
1083                 NULL,                   /* ousrreq() */
1084                 0, 0, 0, 0,             /* init, fasttimeo, slowtimo, drain */
1085                 &ngd_usrreqs,           /* usrreq table (above) */
1086                 /*{NULL}*/              /* pffh (protocol filter head?) */
1087         }
1088 };
1089
1090 struct domain ngdomain = {
1091         AF_NETGRAPH,
1092         "netgraph",
1093         NULL,                                   /* init() */
1094         NULL,                                   /* externalise() */
1095         NULL,                                   /* dispose() */
1096         ngsw,                                   /* protosw entry */
1097         &ngsw[sizeof(ngsw) / sizeof(ngsw[0])],  /* Number of protosw entries */
1098         NULL,                                   /* next domain in list */
1099         NULL,                                   /* rtattach() */
1100         0,                                      /* arg to rtattach in bits */
1101         0                                       /* maxrtkey */
1102 };
1103
1104 /*
1105  * Handle loading and unloading for this node type
1106  * This is to handle auxiliary linkages (e.g protocol domain addition).
1107  */
1108 static int
1109 ngs_mod_event(module_t mod, int event, void *data)
1110 {
1111         int error = 0;
1112
1113         switch (event) {
1114         case MOD_LOAD:
1115                 mtx_init(&ngsocketlist_mtx, "ng_socketlist", NULL, MTX_DEF);
1116                 /* Register protocol domain */
1117                 net_add_domain(&ngdomain);
1118                 break;
1119         case MOD_UNLOAD:
1120                 /* Insure there are no open netgraph sockets */
1121                 if (!LIST_EMPTY(&ngsocklist)) {
1122                         error = EBUSY;
1123                         break;
1124                 }
1125
1126 #ifdef NOTYET
1127                 if ((LIST_EMPTY(&ngsocklist)) && (typestruct.refs == 0)) {
1128                 /* Unregister protocol domain XXX can't do this yet.. */
1129                         if ((error = net_rm_domain(&ngdomain)) != 0)
1130                                 break;
1131                         mtx_destroy(&ngsocketlist_mtx);
1132                 } else
1133 #endif
1134                         error = EBUSY;
1135                 break;
1136         default:
1137                 error = EOPNOTSUPP;
1138                 break;
1139         }
1140         return (error);
1141 }
1142
1143 SYSCTL_INT(_net_graph, OID_AUTO, family, CTLFLAG_RD, 0, AF_NETGRAPH, "");
1144 SYSCTL_NODE(_net_graph, OID_AUTO, data, CTLFLAG_RW, 0, "DATA");
1145 SYSCTL_INT(_net_graph_data, OID_AUTO, proto, CTLFLAG_RD, 0, NG_DATA, "");
1146 SYSCTL_NODE(_net_graph, OID_AUTO, control, CTLFLAG_RW, 0, "CONTROL");
1147 SYSCTL_INT(_net_graph_control, OID_AUTO, proto, CTLFLAG_RD, 0, NG_CONTROL, "");
1148