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