6 * Copyright (c) 1996-1999 Whistle Communications, Inc.
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.
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
38 * Author: Archie Cobbs <archie@freebsd.org>
40 * $FreeBSD: src/sys/netgraph/ng_ksocket.c,v 1.61 2008/03/07 21:12:56 mav Exp $
41 * $Whistle: ng_ksocket.c,v 1.1 1999/11/16 20:04:40 archie Exp $
45 * Kernel socket node type. This node type is basically a kernel-mode
46 * version of a socket... kindof like the reverse of the socket node type.
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/kernel.h>
54 #include <sys/malloc.h>
55 #include <sys/ctype.h>
56 #include <sys/protosw.h>
57 #include <sys/errno.h>
58 #include <sys/socket.h>
59 #include <sys/socketvar.h>
63 #include <netgraph/ng_message.h>
64 #include <netgraph/netgraph.h>
65 #include <netgraph/ng_parse.h>
66 #include <netgraph/ng_ksocket.h>
68 #include <netinet/in.h>
69 #include <netatalk/at.h>
71 #ifdef NG_SEPARATE_MALLOC
72 MALLOC_DEFINE(M_NETGRAPH_KSOCKET
, "netgraph_ksock", "netgraph ksock node ");
74 #define M_NETGRAPH_KSOCKET M_NETGRAPH
77 #define OFFSETOF(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
78 #define SADATA_OFFSET (OFFSETOF(struct sockaddr, sa_data))
80 /* Node private data */
81 struct ng_ksocket_private
{
85 int fn_sent
; /* FN call on incoming event was sent */
86 LIST_HEAD(, ng_ksocket_private
) embryos
;
87 LIST_ENTRY(ng_ksocket_private
) siblings
;
89 u_int32_t response_token
;
90 ng_ID_t response_addr
;
92 typedef struct ng_ksocket_private
*priv_p
;
94 /* Flags for priv_p */
95 #define KSF_CONNECTING 0x00000001 /* Waiting for connection complete */
96 #define KSF_ACCEPTING 0x00000002 /* Waiting for accept complete */
97 #define KSF_EOFSEEN 0x00000004 /* Have sent 0-length EOF mbuf */
98 #define KSF_CLONED 0x00000008 /* Cloned from an accepting socket */
99 #define KSF_EMBRYONIC 0x00000010 /* Cloned node with no hooks yet */
101 /* Netgraph node methods */
102 static ng_constructor_t ng_ksocket_constructor
;
103 static ng_rcvmsg_t ng_ksocket_rcvmsg
;
104 static ng_shutdown_t ng_ksocket_shutdown
;
105 static ng_newhook_t ng_ksocket_newhook
;
106 static ng_rcvdata_t ng_ksocket_rcvdata
;
107 static ng_connect_t ng_ksocket_connect
;
108 static ng_disconnect_t ng_ksocket_disconnect
;
110 /* Alias structure */
111 struct ng_ksocket_alias
{
117 /* Protocol family aliases */
118 static const struct ng_ksocket_alias ng_ksocket_families
[] = {
119 { "local", PF_LOCAL
},
121 { "inet6", PF_INET6
},
122 { "atalk", PF_APPLETALK
},
128 /* Socket type aliases */
129 static const struct ng_ksocket_alias ng_ksocket_types
[] = {
130 { "stream", SOCK_STREAM
},
131 { "dgram", SOCK_DGRAM
},
134 { "seqpacket", SOCK_SEQPACKET
},
138 /* Protocol aliases */
139 static const struct ng_ksocket_alias ng_ksocket_protos
[] = {
140 { "ip", IPPROTO_IP
, PF_INET
},
141 { "raw", IPPROTO_RAW
, PF_INET
},
142 { "icmp", IPPROTO_ICMP
, PF_INET
},
143 { "igmp", IPPROTO_IGMP
, PF_INET
},
144 { "tcp", IPPROTO_TCP
, PF_INET
},
145 { "udp", IPPROTO_UDP
, PF_INET
},
146 { "gre", IPPROTO_GRE
, PF_INET
},
147 { "esp", IPPROTO_ESP
, PF_INET
},
148 { "ah", IPPROTO_AH
, PF_INET
},
149 { "swipe", IPPROTO_SWIPE
, PF_INET
},
150 { "encap", IPPROTO_ENCAP
, PF_INET
},
151 { "divert", IPPROTO_DIVERT
, PF_INET
},
152 { "pim", IPPROTO_PIM
, PF_INET
},
153 { "ddp", ATPROTO_DDP
, PF_APPLETALK
},
154 { "aarp", ATPROTO_AARP
, PF_APPLETALK
},
158 /* Helper functions */
159 static int ng_ksocket_check_accept(priv_p
);
160 static void ng_ksocket_finish_accept(priv_p
);
161 static void ng_ksocket_incoming(struct socket
*so
, void *arg
, int waitflag
);
162 static int ng_ksocket_parse(const struct ng_ksocket_alias
*aliases
,
163 const char *s
, int family
);
164 static void ng_ksocket_incoming2(node_p node
, hook_p hook
,
165 void *arg1
, int arg2
);
167 /************************************************************************
168 STRUCT SOCKADDR PARSE TYPE
169 ************************************************************************/
171 /* Get the length of the data portion of a generic struct sockaddr */
173 ng_parse_generic_sockdata_getLength(const struct ng_parse_type
*type
,
174 const u_char
*start
, const u_char
*buf
)
176 const struct sockaddr
*sa
;
178 sa
= (const struct sockaddr
*)(buf
- SADATA_OFFSET
);
179 return (sa
->sa_len
< SADATA_OFFSET
) ? 0 : sa
->sa_len
- SADATA_OFFSET
;
182 /* Type for the variable length data portion of a generic struct sockaddr */
183 static const struct ng_parse_type ng_ksocket_generic_sockdata_type
= {
184 &ng_parse_bytearray_type
,
185 &ng_parse_generic_sockdata_getLength
188 /* Type for a generic struct sockaddr */
189 static const struct ng_parse_struct_field
190 ng_parse_generic_sockaddr_type_fields
[] = {
191 { "len", &ng_parse_uint8_type
},
192 { "family", &ng_parse_uint8_type
},
193 { "data", &ng_ksocket_generic_sockdata_type
},
196 static const struct ng_parse_type ng_ksocket_generic_sockaddr_type
= {
197 &ng_parse_struct_type
,
198 &ng_parse_generic_sockaddr_type_fields
201 /* Convert a struct sockaddr from ASCII to binary. If its a protocol
202 family that we specially handle, do that, otherwise defer to the
203 generic parse type ng_ksocket_generic_sockaddr_type. */
205 ng_ksocket_sockaddr_parse(const struct ng_parse_type
*type
,
206 const char *s
, int *off
, const u_char
*const start
,
207 u_char
*const buf
, int *buflen
)
209 struct sockaddr
*const sa
= (struct sockaddr
*)buf
;
210 enum ng_parse_token tok
;
215 /* If next token is a left curly brace, use generic parse type */
216 if ((tok
= ng_parse_get_token(s
, off
, &len
)) == T_LBRACE
) {
217 return (*ng_ksocket_generic_sockaddr_type
.supertype
->parse
)
218 (&ng_ksocket_generic_sockaddr_type
,
219 s
, off
, start
, buf
, buflen
);
222 /* Get socket address family followed by a slash */
223 while (isspace(s
[*off
]))
225 if ((t
= index(s
+ *off
, '/')) == NULL
)
227 if ((len
= t
- (s
+ *off
)) > sizeof(fambuf
) - 1)
229 strncpy(fambuf
, s
+ *off
, len
);
232 if ((family
= ng_ksocket_parse(ng_ksocket_families
, fambuf
, 0)) == -1)
236 if (*buflen
< SADATA_OFFSET
)
238 sa
->sa_family
= family
;
240 /* Set family-specific data and length */
241 switch (sa
->sa_family
) {
242 case PF_LOCAL
: /* Get pathname */
244 const int pathoff
= OFFSETOF(struct sockaddr_un
, sun_path
);
245 struct sockaddr_un
*const sun
= (struct sockaddr_un
*)sa
;
249 if ((path
= ng_get_string_token(s
, off
, &toklen
, NULL
)) == NULL
)
251 pathlen
= strlen(path
);
252 if (pathlen
> SOCK_MAXADDRLEN
) {
253 FREE(path
, M_NETGRAPH_KSOCKET
);
256 if (*buflen
< pathoff
+ pathlen
) {
257 FREE(path
, M_NETGRAPH_KSOCKET
);
261 bcopy(path
, sun
->sun_path
, pathlen
);
262 sun
->sun_len
= pathoff
+ pathlen
;
263 FREE(path
, M_NETGRAPH_KSOCKET
);
267 case PF_INET
: /* Get an IP address with optional port */
269 struct sockaddr_in
*const sin
= (struct sockaddr_in
*)sa
;
272 /* Parse this: <ipaddress>[:port] */
273 for (i
= 0; i
< 4; i
++) {
277 val
= strtoul(s
+ *off
, &eptr
, 10);
278 if (val
> 0xff || eptr
== s
+ *off
)
280 *off
+= (eptr
- (s
+ *off
));
281 ((u_char
*)&sin
->sin_addr
)[i
] = (u_char
)val
;
286 } else if (s
[*off
] == ':') {
288 val
= strtoul(s
+ *off
, &eptr
, 10);
289 if (val
> 0xffff || eptr
== s
+ *off
)
291 *off
+= (eptr
- (s
+ *off
));
292 sin
->sin_port
= htons(val
);
296 bzero(&sin
->sin_zero
, sizeof(sin
->sin_zero
));
297 sin
->sin_len
= sizeof(*sin
);
302 case PF_APPLETALK
: /* XXX implement these someday */
312 *buflen
= sa
->sa_len
;
316 /* Convert a struct sockaddr from binary to ASCII */
318 ng_ksocket_sockaddr_unparse(const struct ng_parse_type
*type
,
319 const u_char
*data
, int *off
, char *cbuf
, int cbuflen
)
321 const struct sockaddr
*sa
= (const struct sockaddr
*)(data
+ *off
);
324 /* Output socket address, either in special or generic format */
325 switch (sa
->sa_family
) {
328 const int pathoff
= OFFSETOF(struct sockaddr_un
, sun_path
);
329 const struct sockaddr_un
*sun
= (const struct sockaddr_un
*)sa
;
330 const int pathlen
= sun
->sun_len
- pathoff
;
331 char pathbuf
[SOCK_MAXADDRLEN
+ 1];
334 bcopy(sun
->sun_path
, pathbuf
, pathlen
);
335 if ((pathtoken
= ng_encode_string(pathbuf
, pathlen
)) == NULL
)
337 slen
+= snprintf(cbuf
, cbuflen
, "local/%s", pathtoken
);
338 FREE(pathtoken
, M_NETGRAPH_KSOCKET
);
341 *off
+= sun
->sun_len
;
347 const struct sockaddr_in
*sin
= (const struct sockaddr_in
*)sa
;
349 slen
+= snprintf(cbuf
, cbuflen
, "inet/%d.%d.%d.%d",
350 ((const u_char
*)&sin
->sin_addr
)[0],
351 ((const u_char
*)&sin
->sin_addr
)[1],
352 ((const u_char
*)&sin
->sin_addr
)[2],
353 ((const u_char
*)&sin
->sin_addr
)[3]);
354 if (sin
->sin_port
!= 0) {
355 slen
+= snprintf(cbuf
+ strlen(cbuf
),
356 cbuflen
- strlen(cbuf
), ":%d",
357 (u_int
)ntohs(sin
->sin_port
));
361 *off
+= sizeof(*sin
);
366 case PF_APPLETALK
: /* XXX implement these someday */
372 return (*ng_ksocket_generic_sockaddr_type
.supertype
->unparse
)
373 (&ng_ksocket_generic_sockaddr_type
,
374 data
, off
, cbuf
, cbuflen
);
378 /* Parse type for struct sockaddr */
379 static const struct ng_parse_type ng_ksocket_sockaddr_type
= {
383 &ng_ksocket_sockaddr_parse
,
384 &ng_ksocket_sockaddr_unparse
,
385 NULL
/* no such thing as a default struct sockaddr */
388 /************************************************************************
389 STRUCT NG_KSOCKET_SOCKOPT PARSE TYPE
390 ************************************************************************/
392 /* Get length of the struct ng_ksocket_sockopt value field, which is the
393 just the excess of the message argument portion over the length of
394 the struct ng_ksocket_sockopt. */
396 ng_parse_sockoptval_getLength(const struct ng_parse_type
*type
,
397 const u_char
*start
, const u_char
*buf
)
399 static const int offset
= OFFSETOF(struct ng_ksocket_sockopt
, value
);
400 const struct ng_ksocket_sockopt
*sopt
;
401 const struct ng_mesg
*msg
;
403 sopt
= (const struct ng_ksocket_sockopt
*)(buf
- offset
);
404 msg
= (const struct ng_mesg
*)((const u_char
*)sopt
- sizeof(*msg
));
405 return msg
->header
.arglen
- sizeof(*sopt
);
408 /* Parse type for the option value part of a struct ng_ksocket_sockopt
409 XXX Eventually, we should handle the different socket options specially.
410 XXX This would avoid byte order problems, eg an integer value of 1 is
411 XXX going to be "[1]" for little endian or "[3=1]" for big endian. */
412 static const struct ng_parse_type ng_ksocket_sockoptval_type
= {
413 &ng_parse_bytearray_type
,
414 &ng_parse_sockoptval_getLength
417 /* Parse type for struct ng_ksocket_sockopt */
418 static const struct ng_parse_struct_field ng_ksocket_sockopt_type_fields
[]
419 = NG_KSOCKET_SOCKOPT_INFO(&ng_ksocket_sockoptval_type
);
420 static const struct ng_parse_type ng_ksocket_sockopt_type
= {
421 &ng_parse_struct_type
,
422 &ng_ksocket_sockopt_type_fields
425 /* Parse type for struct ng_ksocket_accept */
426 static const struct ng_parse_struct_field ng_ksocket_accept_type_fields
[]
427 = NGM_KSOCKET_ACCEPT_INFO
;
428 static const struct ng_parse_type ng_ksocket_accept_type
= {
429 &ng_parse_struct_type
,
430 &ng_ksocket_accept_type_fields
433 /* List of commands and how to convert arguments to/from ASCII */
434 static const struct ng_cmdlist ng_ksocket_cmds
[] = {
439 &ng_ksocket_sockaddr_type
,
446 &ng_parse_int32_type
,
454 &ng_ksocket_accept_type
460 &ng_ksocket_sockaddr_type
,
468 &ng_ksocket_sockaddr_type
472 NGM_KSOCKET_GETPEERNAME
,
475 &ng_ksocket_sockaddr_type
481 &ng_ksocket_sockopt_type
,
488 &ng_ksocket_sockopt_type
,
489 &ng_ksocket_sockopt_type
494 /* Node type descriptor */
495 static struct ng_type ng_ksocket_typestruct
= {
496 .version
= NG_ABI_VERSION
,
497 .name
= NG_KSOCKET_NODE_TYPE
,
498 .constructor
= ng_ksocket_constructor
,
499 .rcvmsg
= ng_ksocket_rcvmsg
,
500 .shutdown
= ng_ksocket_shutdown
,
501 .newhook
= ng_ksocket_newhook
,
502 .connect
= ng_ksocket_connect
,
503 .rcvdata
= ng_ksocket_rcvdata
,
504 .disconnect
= ng_ksocket_disconnect
,
505 .cmdlist
= ng_ksocket_cmds
,
507 NETGRAPH_INIT(ksocket
, &ng_ksocket_typestruct
);
509 #define ERROUT(x) do { error = (x); goto done; } while (0)
511 /************************************************************************
513 ************************************************************************/
516 * Node type constructor
517 * The NODE part is assumed to be all set up.
518 * There is already a reference to the node for us.
521 ng_ksocket_constructor(node_p node
)
525 /* Allocate private structure */
526 MALLOC(priv
, priv_p
, sizeof(*priv
),
527 M_NETGRAPH_KSOCKET
, M_NOWAIT
| M_ZERO
);
531 LIST_INIT(&priv
->embryos
);
532 /* cross link them */
534 NG_NODE_SET_PRIVATE(node
, priv
);
541 * Give our OK for a hook to be added. The hook name is of the
542 * form "<family>/<type>/<proto>" where the three components may
543 * be decimal numbers or else aliases from the above lists.
545 * Connecting a hook amounts to opening the socket. Disconnecting
546 * the hook closes the socket and destroys the node as well.
549 ng_ksocket_newhook(node_p node
, hook_p hook
, const char *name0
)
551 struct thread
*td
= curthread
; /* XXX broken */
552 const priv_p priv
= NG_NODE_PRIVATE(node
);
553 char *s1
, *s2
, name
[NG_HOOKSIZ
];
554 int family
, type
, protocol
, error
;
556 /* Check if we're already connected */
557 if (priv
->hook
!= NULL
)
560 if (priv
->flags
& KSF_CLONED
) {
561 if (priv
->flags
& KSF_EMBRYONIC
) {
562 /* Remove ourselves from our parent's embryo list */
563 LIST_REMOVE(priv
, siblings
);
564 priv
->flags
&= ~KSF_EMBRYONIC
;
567 /* Extract family, type, and protocol from hook name */
568 snprintf(name
, sizeof(name
), "%s", name0
);
570 if ((s2
= index(s1
, '/')) == NULL
)
573 family
= ng_ksocket_parse(ng_ksocket_families
, s1
, 0);
577 if ((s2
= index(s1
, '/')) == NULL
)
580 type
= ng_ksocket_parse(ng_ksocket_types
, s1
, 0);
584 protocol
= ng_ksocket_parse(ng_ksocket_protos
, s1
, family
);
588 /* Create the socket */
589 error
= socreate(family
, &priv
->so
, type
, protocol
,
594 /* XXX call soreserve() ? */
602 * In case of misconfigured routing a packet may reenter
603 * ksocket node recursively. Decouple stack to avoid possible
604 * panics about sleeping with locks held.
606 NG_HOOK_FORCE_QUEUE(hook
);
612 ng_ksocket_connect(hook_p hook
)
614 node_p node
= NG_HOOK_NODE(hook
);
615 const priv_p priv
= NG_NODE_PRIVATE(node
);
616 struct socket
*const so
= priv
->so
;
618 /* Add our hook for incoming data and other events */
619 priv
->so
->so_upcallarg
= (caddr_t
)node
;
620 priv
->so
->so_upcall
= ng_ksocket_incoming
;
621 SOCKBUF_LOCK(&priv
->so
->so_rcv
);
622 priv
->so
->so_rcv
.sb_flags
|= SB_UPCALL
;
623 SOCKBUF_UNLOCK(&priv
->so
->so_rcv
);
624 SOCKBUF_LOCK(&priv
->so
->so_snd
);
625 priv
->so
->so_snd
.sb_flags
|= SB_UPCALL
;
626 SOCKBUF_UNLOCK(&priv
->so
->so_snd
);
628 priv
->so
->so_state
|= SS_NBIO
;
629 SOCK_UNLOCK(priv
->so
);
631 * --Original comment--
632 * On a cloned socket we may have already received one or more
633 * upcalls which we couldn't handle without a hook. Handle
635 * We cannot call the upcall function directly
636 * from here, because until this function has returned our
637 * hook isn't connected.
639 * ---meta comment for -current ---
640 * XXX This is dubius.
641 * Upcalls between the time that the hook was
642 * first created and now (on another processesor) will
643 * be earlier on the queue than the request to finalise the hook.
644 * By the time the hook is finalised,
645 * The queued upcalls will have happenned and the code
646 * will have discarded them because of a lack of a hook.
649 * This is a bad byproduct of the complicated way in which hooks
650 * are now created (3 daisy chained async events).
652 * Since we are a netgraph operation
653 * We know that we hold a lock on this node. This forces the
654 * request we make below to be queued rather than implemented
655 * immediatly which will cause the upcall function to be called a bit
657 * However, as we will run any waiting queued operations immediatly
658 * after doing this one, if we have not finalised the other end
659 * of the hook, those queued operations will fail.
661 if (priv
->flags
& KSF_CLONED
) {
662 ng_send_fn(node
, NULL
, &ng_ksocket_incoming2
, so
, M_NOWAIT
);
669 * Receive a control message
672 ng_ksocket_rcvmsg(node_p node
, item_p item
, hook_p lasthook
)
674 struct thread
*td
= curthread
; /* XXX broken */
675 const priv_p priv
= NG_NODE_PRIVATE(node
);
676 struct socket
*const so
= priv
->so
;
677 struct ng_mesg
*resp
= NULL
;
682 NGI_GET_MSG(item
, msg
);
683 switch (msg
->header
.typecookie
) {
684 case NGM_KSOCKET_COOKIE
:
685 switch (msg
->header
.cmd
) {
686 case NGM_KSOCKET_BIND
:
688 struct sockaddr
*const sa
689 = (struct sockaddr
*)msg
->data
;
692 if (msg
->header
.arglen
< SADATA_OFFSET
693 || msg
->header
.arglen
< sa
->sa_len
)
699 error
= sobind(so
, sa
, td
);
702 case NGM_KSOCKET_LISTEN
:
705 if (msg
->header
.arglen
!= sizeof(int32_t))
711 error
= solisten(so
, *((int32_t *)msg
->data
), td
);
715 case NGM_KSOCKET_ACCEPT
:
718 if (msg
->header
.arglen
!= 0)
723 /* Make sure the socket is capable of accepting */
724 if (!(so
->so_options
& SO_ACCEPTCONN
))
726 if (priv
->flags
& KSF_ACCEPTING
)
729 error
= ng_ksocket_check_accept(priv
);
730 if (error
!= 0 && error
!= EWOULDBLOCK
)
734 * If a connection is already complete, take it.
735 * Otherwise let the upcall function deal with
736 * the connection when it comes in.
738 priv
->response_token
= msg
->header
.token
;
739 raddr
= priv
->response_addr
= NGI_RETADDR(item
);
741 ng_ksocket_finish_accept(priv
);
743 priv
->flags
|= KSF_ACCEPTING
;
747 case NGM_KSOCKET_CONNECT
:
749 struct sockaddr
*const sa
750 = (struct sockaddr
*)msg
->data
;
753 if (msg
->header
.arglen
< SADATA_OFFSET
754 || msg
->header
.arglen
< sa
->sa_len
)
760 if ((so
->so_state
& SS_ISCONNECTING
) != 0)
762 if ((error
= soconnect(so
, sa
, td
)) != 0) {
763 so
->so_state
&= ~SS_ISCONNECTING
;
766 if ((so
->so_state
& SS_ISCONNECTING
) != 0) {
767 /* We will notify the sender when we connect */
768 priv
->response_token
= msg
->header
.token
;
769 raddr
= priv
->response_addr
= NGI_RETADDR(item
);
770 priv
->flags
|= KSF_CONNECTING
;
776 case NGM_KSOCKET_GETNAME
:
777 case NGM_KSOCKET_GETPEERNAME
:
779 int (*func
)(struct socket
*so
, struct sockaddr
**nam
);
780 struct sockaddr
*sa
= NULL
;
784 if (msg
->header
.arglen
!= 0)
790 if (msg
->header
.cmd
== NGM_KSOCKET_GETPEERNAME
) {
792 & (SS_ISCONNECTED
|SS_ISCONFIRMING
)) == 0)
794 func
= so
->so_proto
->pr_usrreqs
->pru_peeraddr
;
796 func
= so
->so_proto
->pr_usrreqs
->pru_sockaddr
;
798 /* Get local or peer address */
799 if ((error
= (*func
)(so
, &sa
)) != 0)
801 len
= (sa
== NULL
) ? 0 : sa
->sa_len
;
803 /* Send it back in a response */
804 NG_MKRESPONSE(resp
, msg
, len
, M_NOWAIT
);
809 bcopy(sa
, resp
->data
, len
);
818 case NGM_KSOCKET_GETOPT
:
820 struct ng_ksocket_sockopt
*ksopt
=
821 (struct ng_ksocket_sockopt
*)msg
->data
;
825 if (msg
->header
.arglen
!= sizeof(*ksopt
))
830 /* Get response with room for option value */
831 NG_MKRESPONSE(resp
, msg
, sizeof(*ksopt
)
832 + NG_KSOCKET_MAX_OPTLEN
, M_NOWAIT
);
836 /* Get socket option, and put value in the response */
837 sopt
.sopt_dir
= SOPT_GET
;
838 sopt
.sopt_level
= ksopt
->level
;
839 sopt
.sopt_name
= ksopt
->name
;
841 sopt
.sopt_valsize
= NG_KSOCKET_MAX_OPTLEN
;
842 ksopt
= (struct ng_ksocket_sockopt
*)resp
->data
;
843 sopt
.sopt_val
= ksopt
->value
;
844 if ((error
= sogetopt(so
, &sopt
)) != 0) {
849 /* Set actual value length */
850 resp
->header
.arglen
= sizeof(*ksopt
)
855 case NGM_KSOCKET_SETOPT
:
857 struct ng_ksocket_sockopt
*const ksopt
=
858 (struct ng_ksocket_sockopt
*)msg
->data
;
859 const int valsize
= msg
->header
.arglen
- sizeof(*ksopt
);
868 /* Set socket option */
869 sopt
.sopt_dir
= SOPT_SET
;
870 sopt
.sopt_level
= ksopt
->level
;
871 sopt
.sopt_name
= ksopt
->name
;
872 sopt
.sopt_val
= ksopt
->value
;
873 sopt
.sopt_valsize
= valsize
;
875 error
= sosetopt(so
, &sopt
);
889 NG_RESPOND_MSG(error
, node
, item
, resp
);
895 * Receive incoming data on our hook. Send it out the socket.
898 ng_ksocket_rcvdata(hook_p hook
, item_p item
)
900 struct thread
*td
= curthread
; /* XXX broken */
901 const node_p node
= NG_HOOK_NODE(hook
);
902 const priv_p priv
= NG_NODE_PRIVATE(node
);
903 struct socket
*const so
= priv
->so
;
904 struct sockaddr
*sa
= NULL
;
914 * Look if socket address is stored in packet tags.
915 * If sockaddr is ours, or provided by a third party (zero id),
918 if (((stag
= (struct sa_tag
*)m_tag_locate(m
, NGM_KSOCKET_COOKIE
,
919 NG_KSOCKET_TAG_SOCKADDR
, NULL
)) != NULL
) &&
920 (stag
->id
== NG_NODE_ID(node
) || stag
->id
== 0))
923 /* Reset specific mbuf flags to prevent addressing problems. */
924 m
->m_flags
&= ~(M_BCAST
|M_MCAST
);
927 error
= sosend(so
, sa
, 0, m
, 0, 0, td
);
936 ng_ksocket_shutdown(node_p node
)
938 const priv_p priv
= NG_NODE_PRIVATE(node
);
941 /* Close our socket (if any) */
942 if (priv
->so
!= NULL
) {
943 SOCKBUF_LOCK(&priv
->so
->so_rcv
);
944 priv
->so
->so_rcv
.sb_flags
&= ~SB_UPCALL
;
945 SOCKBUF_UNLOCK(&priv
->so
->so_rcv
);
946 SOCKBUF_LOCK(&priv
->so
->so_snd
);
947 priv
->so
->so_snd
.sb_flags
&= ~SB_UPCALL
;
948 SOCKBUF_UNLOCK(&priv
->so
->so_snd
);
949 priv
->so
->so_upcall
= NULL
;
954 /* If we are an embryo, take ourselves out of the parent's list */
955 if (priv
->flags
& KSF_EMBRYONIC
) {
956 LIST_REMOVE(priv
, siblings
);
957 priv
->flags
&= ~KSF_EMBRYONIC
;
960 /* Remove any embryonic children we have */
961 while (!LIST_EMPTY(&priv
->embryos
)) {
962 embryo
= LIST_FIRST(&priv
->embryos
);
963 ng_rmnode_self(embryo
->node
);
966 /* Take down netgraph node */
967 bzero(priv
, sizeof(*priv
));
968 FREE(priv
, M_NETGRAPH_KSOCKET
);
969 NG_NODE_SET_PRIVATE(node
, NULL
);
970 NG_NODE_UNREF(node
); /* let the node escape */
978 ng_ksocket_disconnect(hook_p hook
)
980 KASSERT(NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook
)) == 0,
981 ("%s: numhooks=%d?", __func__
,
982 NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook
))));
983 if (NG_NODE_IS_VALID(NG_HOOK_NODE(hook
)))
984 ng_rmnode_self(NG_HOOK_NODE(hook
));
988 /************************************************************************
990 ************************************************************************/
992 * You should not "just call" a netgraph node function from an external
993 * asynchronous event. This is because in doing so you are ignoring the
994 * locking on the netgraph nodes. Instead call your function via ng_send_fn().
995 * This will call the function you chose, but will first do all the
996 * locking rigmarole. Your function MAY only be called at some distant future
997 * time (several millisecs away) so don't give it any arguments
998 * that may be revoked soon (e.g. on your stack).
1000 * To decouple stack, we use queue version of ng_send_fn().
1004 ng_ksocket_incoming(struct socket
*so
, void *arg
, int waitflag
)
1006 const node_p node
= arg
;
1007 const priv_p priv
= NG_NODE_PRIVATE(node
);
1008 int wait
= ((waitflag
& M_WAITOK
) ? NG_WAITOK
: 0) | NG_QUEUE
;
1011 * Even if node is not locked, as soon as we are called, we assume
1012 * it exist and it's private area is valid. With some care we can
1013 * access it. Mark node that incoming event for it was sent to
1014 * avoid unneded queue trashing.
1016 if (atomic_cmpset_int(&priv
->fn_sent
, 0, 1) &&
1017 ng_send_fn1(node
, NULL
, &ng_ksocket_incoming2
, so
, 0, wait
)) {
1018 atomic_store_rel_int(&priv
->fn_sent
, 0);
1024 * When incoming data is appended to the socket, we get notified here.
1025 * This is also called whenever a significant event occurs for the socket.
1026 * Our original caller may have queued this even some time ago and
1027 * we cannot trust that he even still exists. The node however is being
1028 * held with a reference by the queueing code and guarantied to be valid.
1031 ng_ksocket_incoming2(node_p node
, hook_p hook
, void *arg1
, int arg2
)
1033 struct socket
*so
= arg1
;
1034 const priv_p priv
= NG_NODE_PRIVATE(node
);
1036 struct ng_mesg
*response
;
1038 int s
, flags
, error
;
1042 /* so = priv->so; *//* XXX could have derived this like so */
1043 KASSERT(so
== priv
->so
, ("%s: wrong socket", __func__
));
1045 /* Allow next incoming event to be queued. */
1046 atomic_store_rel_int(&priv
->fn_sent
, 0);
1048 /* Check whether a pending connect operation has completed */
1049 if (priv
->flags
& KSF_CONNECTING
) {
1050 if ((error
= so
->so_error
) != 0) {
1052 so
->so_state
&= ~SS_ISCONNECTING
;
1054 if (!(so
->so_state
& SS_ISCONNECTING
)) {
1055 NG_MKMESSAGE(response
, NGM_KSOCKET_COOKIE
,
1056 NGM_KSOCKET_CONNECT
, sizeof(int32_t), M_NOWAIT
);
1057 if (response
!= NULL
) {
1058 response
->header
.flags
|= NGF_RESP
;
1059 response
->header
.token
= priv
->response_token
;
1060 *(int32_t *)response
->data
= error
;
1062 * send an async "response" message
1063 * to the node that set us up
1064 * (if it still exists)
1066 NG_SEND_MSG_ID(error
, node
,
1067 response
, priv
->response_addr
, 0);
1069 priv
->flags
&= ~KSF_CONNECTING
;
1073 /* Check whether a pending accept operation has completed */
1074 if (priv
->flags
& KSF_ACCEPTING
) {
1075 error
= ng_ksocket_check_accept(priv
);
1076 if (error
!= EWOULDBLOCK
)
1077 priv
->flags
&= ~KSF_ACCEPTING
;
1079 ng_ksocket_finish_accept(priv
);
1083 * If we don't have a hook, we must handle data events later. When
1084 * the hook gets created and is connected, this upcall function
1085 * will be called again.
1087 if (priv
->hook
== NULL
) {
1092 /* Read and forward available mbuf's */
1094 auio
.uio_resid
= 1000000000;
1095 flags
= MSG_DONTWAIT
;
1097 struct sockaddr
*sa
= NULL
;
1100 /* Try to get next packet from socket */
1101 if ((error
= soreceive(so
, (so
->so_state
& SS_ISCONNECTED
) ?
1102 NULL
: &sa
, &auio
, &m
, (struct mbuf
**)0, &flags
)) != 0)
1105 /* See if we got anything */
1113 * Don't trust the various socket layers to get the
1114 * packet header and length correct (e.g. kern/15175).
1116 * Also, do not trust that soreceive() will clear m_nextpkt
1117 * for us (e.g. kern/84952, kern/82413).
1119 m
->m_pkthdr
.csum_flags
= 0;
1120 for (n
= m
, m
->m_pkthdr
.len
= 0; n
!= NULL
; n
= n
->m_next
) {
1121 m
->m_pkthdr
.len
+= n
->m_len
;
1122 n
->m_nextpkt
= NULL
;
1125 /* Put peer's socket address (if any) into a tag */
1127 struct sa_tag
*stag
;
1129 stag
= (struct sa_tag
*)m_tag_alloc(NGM_KSOCKET_COOKIE
,
1130 NG_KSOCKET_TAG_SOCKADDR
, sizeof(ng_ID_t
) +
1131 sa
->sa_len
, M_NOWAIT
);
1136 bcopy(sa
, &stag
->sa
, sa
->sa_len
);
1138 stag
->id
= NG_NODE_ID(node
);
1139 m_tag_prepend(m
, &stag
->tag
);
1142 sendit
: /* Forward data with optional peer sockaddr as packet tag */
1143 NG_SEND_DATA_ONLY(error
, priv
->hook
, m
);
1147 * If the peer has closed the connection, forward a 0-length mbuf
1148 * to indicate end-of-file.
1150 if (so
->so_rcv
.sb_state
& SBS_CANTRCVMORE
&& !(priv
->flags
& KSF_EOFSEEN
)) {
1151 MGETHDR(m
, M_NOWAIT
, MT_DATA
);
1153 m
->m_len
= m
->m_pkthdr
.len
= 0;
1154 NG_SEND_DATA_ONLY(error
, priv
->hook
, m
);
1156 priv
->flags
|= KSF_EOFSEEN
;
1162 * Check for a completed incoming connection and return 0 if one is found.
1163 * Otherwise return the appropriate error code.
1166 ng_ksocket_check_accept(priv_p priv
)
1168 struct socket
*const head
= priv
->so
;
1171 if ((error
= head
->so_error
) != 0) {
1175 /* Unlocked read. */
1176 if (TAILQ_EMPTY(&head
->so_comp
)) {
1177 if (head
->so_rcv
.sb_state
& SBS_CANTRCVMORE
)
1178 return ECONNABORTED
;
1185 * Handle the first completed incoming connection, assumed to be already
1186 * on the socket's so_comp queue.
1189 ng_ksocket_finish_accept(priv_p priv
)
1191 struct socket
*const head
= priv
->so
;
1193 struct sockaddr
*sa
= NULL
;
1194 struct ng_mesg
*resp
;
1195 struct ng_ksocket_accept
*resp_data
;
1202 so
= TAILQ_FIRST(&head
->so_comp
);
1203 if (so
== NULL
) { /* Should never happen */
1207 TAILQ_REMOVE(&head
->so_comp
, so
, so_list
);
1209 so
->so_qstate
&= ~SQ_COMP
;
1213 so
->so_state
|= SS_NBIO
;
1217 /* XXX KNOTE(&head->so_rcv.sb_sel.si_note, 0); */
1221 len
= OFFSETOF(struct ng_ksocket_accept
, addr
);
1225 NG_MKMESSAGE(resp
, NGM_KSOCKET_COOKIE
, NGM_KSOCKET_ACCEPT
, len
,
1231 resp
->header
.flags
|= NGF_RESP
;
1232 resp
->header
.token
= priv
->response_token
;
1234 /* Clone a ksocket node to wrap the new socket */
1235 error
= ng_make_node_common(&ng_ksocket_typestruct
, &node
);
1237 FREE(resp
, M_NETGRAPH
);
1242 if (ng_ksocket_constructor(node
) != 0) {
1243 NG_NODE_UNREF(node
);
1244 FREE(resp
, M_NETGRAPH
);
1249 priv2
= NG_NODE_PRIVATE(node
);
1251 priv2
->flags
|= KSF_CLONED
| KSF_EMBRYONIC
;
1254 * Insert the cloned node into a list of embryonic children
1255 * on the parent node. When a hook is created on the cloned
1256 * node it will be removed from this list. When the parent
1257 * is destroyed it will destroy any embryonic children it has.
1259 LIST_INSERT_HEAD(&priv
->embryos
, priv2
, siblings
);
1261 so
->so_upcallarg
= (caddr_t
)node
;
1262 so
->so_upcall
= ng_ksocket_incoming
;
1263 SOCKBUF_LOCK(&so
->so_rcv
);
1264 so
->so_rcv
.sb_flags
|= SB_UPCALL
;
1265 SOCKBUF_UNLOCK(&so
->so_rcv
);
1266 SOCKBUF_LOCK(&so
->so_snd
);
1267 so
->so_snd
.sb_flags
|= SB_UPCALL
;
1268 SOCKBUF_UNLOCK(&so
->so_snd
);
1270 /* Fill in the response data and send it or return it to the caller */
1271 resp_data
= (struct ng_ksocket_accept
*)resp
->data
;
1272 resp_data
->nodeid
= NG_NODE_ID(node
);
1274 bcopy(sa
, &resp_data
->addr
, sa
->sa_len
);
1275 NG_SEND_MSG_ID(error
, node
, resp
, priv
->response_addr
, 0);
1283 * Parse out either an integer value or an alias.
1286 ng_ksocket_parse(const struct ng_ksocket_alias
*aliases
,
1287 const char *s
, int family
)
1293 for (k
= 0; aliases
[k
].name
!= NULL
; k
++) {
1294 if (strcmp(s
, aliases
[k
].name
) == 0
1295 && aliases
[k
].family
== family
)
1296 return aliases
[k
].value
;
1299 /* Try parsing as a number */
1300 val
= (int)strtoul(s
, &eptr
, 10);
1301 if (val
< 0 || *eptr
!= '\0')