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