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>
39 * $Whistle: ng_ksocket.c,v 1.1 1999/11/16 20:04:40 archie Exp $
43 * Kernel socket node type. This node type is basically a kernel-mode
44 * version of a socket... kindof like the reverse of the socket node type.
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/kernel.h>
52 #include <sys/malloc.h>
53 #include <sys/ctype.h>
54 #include <sys/protosw.h>
55 #include <sys/errno.h>
56 #include <sys/socket.h>
57 #include <sys/socketvar.h>
61 #include <netgraph/ng_message.h>
62 #include <netgraph/netgraph.h>
63 #include <netgraph/ng_parse.h>
64 #include <netgraph/ng_ksocket.h>
66 #include <netinet/in.h>
67 #include <netinet/ip.h>
69 #ifdef NG_SEPARATE_MALLOC
70 static MALLOC_DEFINE(M_NETGRAPH_KSOCKET, "netgraph_ksock",
71 "netgraph ksock node");
73 #define M_NETGRAPH_KSOCKET M_NETGRAPH
76 #define OFFSETOF(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
77 #define SADATA_OFFSET (OFFSETOF(struct sockaddr, sa_data))
79 /* Node private data */
80 struct ng_ksocket_private {
84 int fn_sent; /* FN call on incoming event was sent */
85 LIST_HEAD(, ng_ksocket_private) embryos;
86 LIST_ENTRY(ng_ksocket_private) siblings;
88 u_int32_t response_token;
89 ng_ID_t response_addr;
91 typedef struct ng_ksocket_private *priv_p;
93 /* Flags for priv_p */
94 #define KSF_CONNECTING 0x00000001 /* Waiting for connection complete */
95 #define KSF_ACCEPTING 0x00000002 /* Waiting for accept complete */
96 #define KSF_EOFSEEN 0x00000004 /* Have sent 0-length EOF mbuf */
97 #define KSF_CLONED 0x00000008 /* Cloned from an accepting socket */
98 #define KSF_EMBRYONIC 0x00000010 /* Cloned node with no hooks yet */
100 /* Netgraph node methods */
101 static ng_constructor_t ng_ksocket_constructor;
102 static ng_rcvmsg_t ng_ksocket_rcvmsg;
103 static ng_shutdown_t ng_ksocket_shutdown;
104 static ng_newhook_t ng_ksocket_newhook;
105 static ng_rcvdata_t ng_ksocket_rcvdata;
106 static ng_connect_t ng_ksocket_connect;
107 static ng_disconnect_t ng_ksocket_disconnect;
109 /* Alias structure */
110 struct ng_ksocket_alias {
116 /* Protocol family aliases */
117 static const struct ng_ksocket_alias ng_ksocket_families[] = {
118 { "local", PF_LOCAL },
120 { "inet6", PF_INET6 },
122 { "divert", PF_DIVERT },
126 /* Socket type aliases */
127 static const struct ng_ksocket_alias ng_ksocket_types[] = {
128 { "stream", SOCK_STREAM },
129 { "dgram", SOCK_DGRAM },
132 { "seqpacket", SOCK_SEQPACKET },
136 /* Protocol aliases */
137 static const struct ng_ksocket_alias ng_ksocket_protos[] = {
138 { "ip", IPPROTO_IP, PF_INET },
139 { "raw", IPPROTO_RAW, PF_INET },
140 { "icmp", IPPROTO_ICMP, PF_INET },
141 { "igmp", IPPROTO_IGMP, PF_INET },
142 { "tcp", IPPROTO_TCP, PF_INET },
143 { "udp", IPPROTO_UDP, PF_INET },
144 { "gre", IPPROTO_GRE, PF_INET },
145 { "esp", IPPROTO_ESP, PF_INET },
146 { "ah", IPPROTO_AH, PF_INET },
147 { "swipe", IPPROTO_SWIPE, PF_INET },
148 { "encap", IPPROTO_ENCAP, PF_INET },
149 { "pim", IPPROTO_PIM, PF_INET },
153 /* Helper functions */
154 static int ng_ksocket_accept(priv_p);
155 static int ng_ksocket_listen_upcall(struct socket *so, void *arg,
157 static void ng_ksocket_listen_upcall2(node_p node, hook_p hook,
158 void *arg1, int arg2);
159 static int ng_ksocket_incoming(struct socket *so, void *arg, int waitflag);
160 static int ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
161 const char *s, int family);
162 static void ng_ksocket_incoming2(node_p node, hook_p hook,
163 void *arg1, int arg2);
165 /************************************************************************
166 STRUCT SOCKADDR PARSE TYPE
167 ************************************************************************/
169 /* Get the length of the data portion of a generic struct sockaddr */
171 ng_parse_generic_sockdata_getLength(const struct ng_parse_type *type,
172 const u_char *start, const u_char *buf)
174 const struct sockaddr *sa;
176 sa = (const struct sockaddr *)(buf - SADATA_OFFSET);
177 return (sa->sa_len < SADATA_OFFSET) ? 0 : sa->sa_len - SADATA_OFFSET;
180 /* Type for the variable length data portion of a generic struct sockaddr */
181 static const struct ng_parse_type ng_ksocket_generic_sockdata_type = {
182 &ng_parse_bytearray_type,
183 &ng_parse_generic_sockdata_getLength
186 /* Type for a generic struct sockaddr */
187 static const struct ng_parse_struct_field
188 ng_parse_generic_sockaddr_type_fields[] = {
189 { "len", &ng_parse_uint8_type },
190 { "family", &ng_parse_uint8_type },
191 { "data", &ng_ksocket_generic_sockdata_type },
194 static const struct ng_parse_type ng_ksocket_generic_sockaddr_type = {
195 &ng_parse_struct_type,
196 &ng_parse_generic_sockaddr_type_fields
199 /* Convert a struct sockaddr from ASCII to binary. If its a protocol
200 family that we specially handle, do that, otherwise defer to the
201 generic parse type ng_ksocket_generic_sockaddr_type. */
203 ng_ksocket_sockaddr_parse(const struct ng_parse_type *type,
204 const char *s, int *off, const u_char *const start,
205 u_char *const buf, int *buflen)
207 struct sockaddr *const sa = (struct sockaddr *)buf;
208 enum ng_parse_token tok;
213 /* If next token is a left curly brace, use generic parse type */
214 if ((tok = ng_parse_get_token(s, off, &len)) == T_LBRACE) {
215 return (*ng_ksocket_generic_sockaddr_type.supertype->parse)
216 (&ng_ksocket_generic_sockaddr_type,
217 s, off, start, buf, buflen);
220 /* Get socket address family followed by a slash */
221 while (isspace(s[*off]))
223 if ((t = strchr(s + *off, '/')) == NULL)
225 if ((len = t - (s + *off)) > sizeof(fambuf) - 1)
227 strncpy(fambuf, s + *off, len);
230 if ((family = ng_ksocket_parse(ng_ksocket_families, fambuf, 0)) == -1)
234 if (*buflen < SADATA_OFFSET)
236 sa->sa_family = family;
238 /* Set family-specific data and length */
239 switch (sa->sa_family) {
240 case PF_LOCAL: /* Get pathname */
242 const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
243 struct sockaddr_un *const sun = (struct sockaddr_un *)sa;
247 if ((path = ng_get_string_token(s, off, &toklen, NULL)) == NULL)
249 pathlen = strlen(path);
250 if (pathlen > SOCK_MAXADDRLEN) {
251 free(path, M_NETGRAPH_KSOCKET);
254 if (*buflen < pathoff + pathlen) {
255 free(path, M_NETGRAPH_KSOCKET);
259 bcopy(path, sun->sun_path, pathlen);
260 sun->sun_len = pathoff + pathlen;
261 free(path, M_NETGRAPH_KSOCKET);
265 case PF_INET: /* Get an IP address with optional port */
267 struct sockaddr_in *const sin = (struct sockaddr_in *)sa;
270 /* Parse this: <ipaddress>[:port] */
271 for (i = 0; i < 4; i++) {
275 val = strtoul(s + *off, &eptr, 10);
276 if (val > 0xff || eptr == s + *off)
278 *off += (eptr - (s + *off));
279 ((u_char *)&sin->sin_addr)[i] = (u_char)val;
284 } else if (s[*off] == ':') {
286 val = strtoul(s + *off, &eptr, 10);
287 if (val > 0xffff || eptr == s + *off)
289 *off += (eptr - (s + *off));
290 sin->sin_port = htons(val);
294 bzero(&sin->sin_zero, sizeof(sin->sin_zero));
295 sin->sin_len = sizeof(*sin);
300 case PF_INET6: /* XXX implement this someday */
308 *buflen = sa->sa_len;
312 /* Convert a struct sockaddr from binary to ASCII */
314 ng_ksocket_sockaddr_unparse(const struct ng_parse_type *type,
315 const u_char *data, int *off, char *cbuf, int cbuflen)
317 const struct sockaddr *sa = (const struct sockaddr *)(data + *off);
320 /* Output socket address, either in special or generic format */
321 switch (sa->sa_family) {
324 const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
325 const struct sockaddr_un *sun = (const struct sockaddr_un *)sa;
326 const int pathlen = sun->sun_len - pathoff;
327 char pathbuf[SOCK_MAXADDRLEN + 1];
330 bcopy(sun->sun_path, pathbuf, pathlen);
331 if ((pathtoken = ng_encode_string(pathbuf, pathlen)) == NULL)
333 slen += snprintf(cbuf, cbuflen, "local/%s", pathtoken);
334 free(pathtoken, M_NETGRAPH_KSOCKET);
337 *off += sun->sun_len;
343 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
345 slen += snprintf(cbuf, cbuflen, "inet/%d.%d.%d.%d",
346 ((const u_char *)&sin->sin_addr)[0],
347 ((const u_char *)&sin->sin_addr)[1],
348 ((const u_char *)&sin->sin_addr)[2],
349 ((const u_char *)&sin->sin_addr)[3]);
350 if (sin->sin_port != 0) {
351 slen += snprintf(cbuf + strlen(cbuf),
352 cbuflen - strlen(cbuf), ":%d",
353 (u_int)ntohs(sin->sin_port));
357 *off += sizeof(*sin);
362 case PF_INET6: /* XXX implement this someday */
366 return (*ng_ksocket_generic_sockaddr_type.supertype->unparse)
367 (&ng_ksocket_generic_sockaddr_type,
368 data, off, cbuf, cbuflen);
372 /* Parse type for struct sockaddr */
373 static const struct ng_parse_type ng_ksocket_sockaddr_type = {
377 &ng_ksocket_sockaddr_parse,
378 &ng_ksocket_sockaddr_unparse,
379 NULL /* no such thing as a default struct sockaddr */
382 /************************************************************************
383 STRUCT NG_KSOCKET_SOCKOPT PARSE TYPE
384 ************************************************************************/
386 /* Get length of the struct ng_ksocket_sockopt value field, which is the
387 just the excess of the message argument portion over the length of
388 the struct ng_ksocket_sockopt. */
390 ng_parse_sockoptval_getLength(const struct ng_parse_type *type,
391 const u_char *start, const u_char *buf)
393 static const int offset = OFFSETOF(struct ng_ksocket_sockopt, value);
394 const struct ng_ksocket_sockopt *sopt;
395 const struct ng_mesg *msg;
397 sopt = (const struct ng_ksocket_sockopt *)(buf - offset);
398 msg = (const struct ng_mesg *)((const u_char *)sopt - sizeof(*msg));
399 return msg->header.arglen - sizeof(*sopt);
402 /* Parse type for the option value part of a struct ng_ksocket_sockopt
403 XXX Eventually, we should handle the different socket options specially.
404 XXX This would avoid byte order problems, eg an integer value of 1 is
405 XXX going to be "[1]" for little endian or "[3=1]" for big endian. */
406 static const struct ng_parse_type ng_ksocket_sockoptval_type = {
407 &ng_parse_bytearray_type,
408 &ng_parse_sockoptval_getLength
411 /* Parse type for struct ng_ksocket_sockopt */
412 static const struct ng_parse_struct_field ng_ksocket_sockopt_type_fields[]
413 = NG_KSOCKET_SOCKOPT_INFO(&ng_ksocket_sockoptval_type);
414 static const struct ng_parse_type ng_ksocket_sockopt_type = {
415 &ng_parse_struct_type,
416 &ng_ksocket_sockopt_type_fields
419 /* Parse type for struct ng_ksocket_accept */
420 static const struct ng_parse_struct_field ng_ksocket_accept_type_fields[]
421 = NGM_KSOCKET_ACCEPT_INFO;
422 static const struct ng_parse_type ng_ksocket_accept_type = {
423 &ng_parse_struct_type,
424 &ng_ksocket_accept_type_fields
427 /* List of commands and how to convert arguments to/from ASCII */
428 static const struct ng_cmdlist ng_ksocket_cmds[] = {
433 &ng_ksocket_sockaddr_type,
440 &ng_parse_int32_type,
448 &ng_ksocket_accept_type
454 &ng_ksocket_sockaddr_type,
462 &ng_ksocket_sockaddr_type
466 NGM_KSOCKET_GETPEERNAME,
469 &ng_ksocket_sockaddr_type
475 &ng_ksocket_sockopt_type,
482 &ng_ksocket_sockopt_type,
483 &ng_ksocket_sockopt_type
488 /* Node type descriptor */
489 static struct ng_type ng_ksocket_typestruct = {
490 .version = NG_ABI_VERSION,
491 .name = NG_KSOCKET_NODE_TYPE,
492 .constructor = ng_ksocket_constructor,
493 .rcvmsg = ng_ksocket_rcvmsg,
494 .shutdown = ng_ksocket_shutdown,
495 .newhook = ng_ksocket_newhook,
496 .connect = ng_ksocket_connect,
497 .rcvdata = ng_ksocket_rcvdata,
498 .disconnect = ng_ksocket_disconnect,
499 .cmdlist = ng_ksocket_cmds,
501 NETGRAPH_INIT(ksocket, &ng_ksocket_typestruct);
503 #define ERROUT(x) do { error = (x); goto done; } while (0)
505 /************************************************************************
507 ************************************************************************/
510 * Node type constructor
511 * The NODE part is assumed to be all set up.
512 * There is already a reference to the node for us.
515 ng_ksocket_constructor(node_p node)
519 /* Allocate private structure */
520 priv = malloc(sizeof(*priv), M_NETGRAPH_KSOCKET, M_NOWAIT | M_ZERO);
524 LIST_INIT(&priv->embryos);
525 /* cross link them */
527 NG_NODE_SET_PRIVATE(node, priv);
534 * Give our OK for a hook to be added. The hook name is of the
535 * form "<family>/<type>/<proto>" where the three components may
536 * be decimal numbers or else aliases from the above lists.
538 * Connecting a hook amounts to opening the socket. Disconnecting
539 * the hook closes the socket and destroys the node as well.
542 ng_ksocket_newhook(node_p node, hook_p hook, const char *name0)
544 struct thread *td = curthread; /* XXX broken */
545 const priv_p priv = NG_NODE_PRIVATE(node);
546 char *s1, *s2, name[NG_HOOKSIZ];
547 int family, type, protocol, error;
549 /* Check if we're already connected */
550 if (priv->hook != NULL)
553 if (priv->flags & KSF_CLONED) {
554 if (priv->flags & KSF_EMBRYONIC) {
555 /* Remove ourselves from our parent's embryo list */
556 LIST_REMOVE(priv, siblings);
557 priv->flags &= ~KSF_EMBRYONIC;
560 /* Extract family, type, and protocol from hook name */
561 snprintf(name, sizeof(name), "%s", name0);
563 if ((s2 = strchr(s1, '/')) == NULL)
566 family = ng_ksocket_parse(ng_ksocket_families, s1, 0);
570 if ((s2 = strchr(s1, '/')) == NULL)
573 type = ng_ksocket_parse(ng_ksocket_types, s1, 0);
577 protocol = ng_ksocket_parse(ng_ksocket_protos, s1, family);
581 /* Create the socket */
582 error = socreate(family, &priv->so, type, protocol,
587 /* XXX call soreserve() ? */
594 * In case of misconfigured routing a packet may reenter
595 * ksocket node recursively. Decouple stack to avoid possible
596 * panics about sleeping with locks held.
598 NG_HOOK_FORCE_QUEUE(hook);
604 ng_ksocket_connect(hook_p hook)
606 node_p node = NG_HOOK_NODE(hook);
607 const priv_p priv = NG_NODE_PRIVATE(node);
608 struct socket *const so = priv->so;
610 /* Add our hook for incoming data and other events */
611 SOCKBUF_LOCK(&priv->so->so_rcv);
612 soupcall_set(priv->so, SO_RCV, ng_ksocket_incoming, node);
613 SOCKBUF_UNLOCK(&priv->so->so_rcv);
614 SOCKBUF_LOCK(&priv->so->so_snd);
615 soupcall_set(priv->so, SO_SND, ng_ksocket_incoming, node);
616 SOCKBUF_UNLOCK(&priv->so->so_snd);
618 priv->so->so_state |= SS_NBIO;
619 SOCK_UNLOCK(priv->so);
621 * --Original comment--
622 * On a cloned socket we may have already received one or more
623 * upcalls which we couldn't handle without a hook. Handle
625 * We cannot call the upcall function directly
626 * from here, because until this function has returned our
627 * hook isn't connected.
629 * ---meta comment for -current ---
630 * XXX This is dubius.
631 * Upcalls between the time that the hook was
632 * first created and now (on another processesor) will
633 * be earlier on the queue than the request to finalise the hook.
634 * By the time the hook is finalised,
635 * The queued upcalls will have happened and the code
636 * will have discarded them because of a lack of a hook.
639 * This is a bad byproduct of the complicated way in which hooks
640 * are now created (3 daisy chained async events).
642 * Since we are a netgraph operation
643 * We know that we hold a lock on this node. This forces the
644 * request we make below to be queued rather than implemented
645 * immediately which will cause the upcall function to be called a bit
647 * However, as we will run any waiting queued operations immediately
648 * after doing this one, if we have not finalised the other end
649 * of the hook, those queued operations will fail.
651 if (priv->flags & KSF_CLONED) {
652 ng_send_fn(node, NULL, &ng_ksocket_incoming2, so, M_NOWAIT);
659 * Receive a control message
662 ng_ksocket_rcvmsg(node_p node, item_p item, hook_p lasthook)
664 struct thread *td = curthread; /* XXX broken */
665 const priv_p priv = NG_NODE_PRIVATE(node);
666 struct socket *const so = priv->so;
667 struct ng_mesg *resp = NULL;
671 NGI_GET_MSG(item, msg);
672 switch (msg->header.typecookie) {
673 case NGM_KSOCKET_COOKIE:
674 switch (msg->header.cmd) {
675 case NGM_KSOCKET_BIND:
677 struct sockaddr *const sa
678 = (struct sockaddr *)msg->data;
681 if (msg->header.arglen < SADATA_OFFSET
682 || msg->header.arglen < sa->sa_len)
688 error = sobind(so, sa, td);
691 case NGM_KSOCKET_LISTEN:
694 if (msg->header.arglen != sizeof(int32_t))
700 so->so_state |= SS_NBIO;
701 error = solisten(so, *((int32_t *)msg->data), td);
704 solisten_upcall_set(so,
705 ng_ksocket_listen_upcall, priv);
711 case NGM_KSOCKET_ACCEPT:
714 if (msg->header.arglen != 0)
719 /* Make sure the socket is capable of accepting */
720 if (!(so->so_options & SO_ACCEPTCONN))
722 if (priv->flags & KSF_ACCEPTING)
726 * If a connection is already complete, take it.
727 * Otherwise let the upcall function deal with
728 * the connection when it comes in. Don't return
729 * EWOULDBLOCK, per ng_ksocket(4) documentation.
731 error = ng_ksocket_accept(priv);
732 if (error == EWOULDBLOCK)
737 priv->response_token = msg->header.token;
738 priv->response_addr = NGI_RETADDR(item);
742 case NGM_KSOCKET_CONNECT:
744 struct sockaddr *const sa
745 = (struct sockaddr *)msg->data;
748 if (msg->header.arglen < SADATA_OFFSET
749 || msg->header.arglen < sa->sa_len)
755 if ((so->so_state & SS_ISCONNECTING) != 0)
757 if ((error = soconnect(so, sa, td)) != 0) {
758 so->so_state &= ~SS_ISCONNECTING;
761 if ((so->so_state & SS_ISCONNECTING) != 0) {
762 /* We will notify the sender when we connect */
763 priv->response_token = msg->header.token;
764 priv->response_addr = NGI_RETADDR(item);
765 priv->flags |= KSF_CONNECTING;
771 case NGM_KSOCKET_GETNAME:
772 case NGM_KSOCKET_GETPEERNAME:
774 int (*func)(struct socket *so, struct sockaddr **nam);
775 struct sockaddr *sa = NULL;
779 if (msg->header.arglen != 0)
785 if (msg->header.cmd == NGM_KSOCKET_GETPEERNAME) {
787 & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0)
789 func = so->so_proto->pr_peeraddr;
791 func = so->so_proto->pr_sockaddr;
793 /* Get local or peer address */
794 if ((error = (*func)(so, &sa)) != 0)
796 len = (sa == NULL) ? 0 : sa->sa_len;
798 /* Send it back in a response */
799 NG_MKRESPONSE(resp, msg, len, M_NOWAIT);
804 bcopy(sa, resp->data, len);
813 case NGM_KSOCKET_GETOPT:
815 struct ng_ksocket_sockopt *ksopt =
816 (struct ng_ksocket_sockopt *)msg->data;
820 if (msg->header.arglen != sizeof(*ksopt))
825 /* Get response with room for option value */
826 NG_MKRESPONSE(resp, msg, sizeof(*ksopt)
827 + NG_KSOCKET_MAX_OPTLEN, M_NOWAIT);
831 /* Get socket option, and put value in the response */
832 sopt.sopt_dir = SOPT_GET;
833 sopt.sopt_level = ksopt->level;
834 sopt.sopt_name = ksopt->name;
836 sopt.sopt_valsize = NG_KSOCKET_MAX_OPTLEN;
837 ksopt = (struct ng_ksocket_sockopt *)resp->data;
838 sopt.sopt_val = ksopt->value;
839 if ((error = sogetopt(so, &sopt)) != 0) {
844 /* Set actual value length */
845 resp->header.arglen = sizeof(*ksopt)
850 case NGM_KSOCKET_SETOPT:
852 struct ng_ksocket_sockopt *const ksopt =
853 (struct ng_ksocket_sockopt *)msg->data;
854 const int valsize = msg->header.arglen - sizeof(*ksopt);
863 /* Set socket option */
864 sopt.sopt_dir = SOPT_SET;
865 sopt.sopt_level = ksopt->level;
866 sopt.sopt_name = ksopt->name;
867 sopt.sopt_val = ksopt->value;
868 sopt.sopt_valsize = valsize;
870 error = sosetopt(so, &sopt);
884 NG_RESPOND_MSG(error, node, item, resp);
890 * Receive incoming data on our hook. Send it out the socket.
893 ng_ksocket_rcvdata(hook_p hook, item_p item)
895 struct thread *td = curthread; /* XXX broken */
896 const node_p node = NG_HOOK_NODE(hook);
897 const priv_p priv = NG_NODE_PRIVATE(node);
898 struct socket *const so = priv->so;
899 struct sockaddr *sa = NULL;
902 #ifdef ALIGNED_POINTER
904 #endif /* ALIGNED_POINTER */
910 #ifdef ALIGNED_POINTER
911 if (!ALIGNED_POINTER(mtod(m, caddr_t), uint32_t)) {
912 n = m_defrag(m, M_NOWAIT);
919 #endif /* ALIGNED_POINTER */
921 * Look if socket address is stored in packet tags.
922 * If sockaddr is ours, or provided by a third party (zero id),
925 if (((stag = (struct sa_tag *)m_tag_locate(m, NGM_KSOCKET_COOKIE,
926 NG_KSOCKET_TAG_SOCKADDR, NULL)) != NULL) &&
927 (stag->id == NG_NODE_ID(node) || stag->id == 0))
930 /* Reset specific mbuf flags to prevent addressing problems. */
931 m->m_flags &= ~(M_BCAST|M_MCAST);
934 error = sosend(so, sa, 0, m, 0, 0, td);
943 ng_ksocket_shutdown(node_p node)
945 const priv_p priv = NG_NODE_PRIVATE(node);
946 struct socket *so = priv->so;
949 /* Close our socket (if any) */
950 if (priv->so != NULL) {
951 if (SOLISTENING(so)) {
953 solisten_upcall_set(so, NULL, NULL);
956 SOCK_RECVBUF_LOCK(so);
957 soupcall_clear(so, SO_RCV);
958 SOCK_RECVBUF_UNLOCK(so);
959 SOCK_SENDBUF_LOCK(so);
960 soupcall_clear(so, SO_SND);
961 SOCK_SENDBUF_UNLOCK(so);
967 /* If we are an embryo, take ourselves out of the parent's list */
968 if (priv->flags & KSF_EMBRYONIC) {
969 LIST_REMOVE(priv, siblings);
970 priv->flags &= ~KSF_EMBRYONIC;
973 /* Remove any embryonic children we have */
974 while (!LIST_EMPTY(&priv->embryos)) {
975 embryo = LIST_FIRST(&priv->embryos);
976 ng_rmnode_self(embryo->node);
979 /* Take down netgraph node */
980 bzero(priv, sizeof(*priv));
981 free(priv, M_NETGRAPH_KSOCKET);
982 NG_NODE_SET_PRIVATE(node, NULL);
983 NG_NODE_UNREF(node); /* let the node escape */
991 ng_ksocket_disconnect(hook_p hook)
993 KASSERT(NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0,
994 ("%s: numhooks=%d?", __func__,
995 NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook))));
996 if (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))
997 ng_rmnode_self(NG_HOOK_NODE(hook));
1001 /************************************************************************
1003 ************************************************************************/
1005 * You should not "just call" a netgraph node function from an external
1006 * asynchronous event. This is because in doing so you are ignoring the
1007 * locking on the netgraph nodes. Instead call your function via ng_send_fn().
1008 * This will call the function you chose, but will first do all the
1009 * locking rigmarole. Your function MAY only be called at some distant future
1010 * time (several millisecs away) so don't give it any arguments
1011 * that may be revoked soon (e.g. on your stack).
1013 * To decouple stack, we use queue version of ng_send_fn().
1017 ng_ksocket_incoming(struct socket *so, void *arg, int waitflag)
1019 const node_p node = arg;
1020 const priv_p priv = NG_NODE_PRIVATE(node);
1021 int wait = ((waitflag & M_WAITOK) ? NG_WAITOK : 0) | NG_QUEUE;
1024 * Even if node is not locked, as soon as we are called, we assume
1025 * it exist and it's private area is valid. With some care we can
1026 * access it. Mark node that incoming event for it was sent to
1027 * avoid unneded queue trashing.
1029 if (atomic_cmpset_int(&priv->fn_sent, 0, 1) &&
1030 ng_send_fn1(node, NULL, &ng_ksocket_incoming2, so, 0, wait)) {
1031 atomic_store_rel_int(&priv->fn_sent, 0);
1037 * When incoming data is appended to the socket, we get notified here.
1038 * This is also called whenever a significant event occurs for the socket.
1039 * Our original caller may have queued this even some time ago and
1040 * we cannot trust that he even still exists. The node however is being
1041 * held with a reference by the queueing code and guarantied to be valid.
1044 ng_ksocket_incoming2(node_p node, hook_p hook, void *arg1, int arg2)
1046 struct socket *so = arg1;
1047 const priv_p priv = NG_NODE_PRIVATE(node);
1048 struct ng_mesg *response;
1051 KASSERT(so == priv->so, ("%s: wrong socket", __func__));
1053 /* Allow next incoming event to be queued. */
1054 atomic_store_rel_int(&priv->fn_sent, 0);
1056 /* Check whether a pending connect operation has completed */
1057 if (priv->flags & KSF_CONNECTING) {
1058 if ((error = so->so_error) != 0) {
1060 so->so_state &= ~SS_ISCONNECTING;
1062 if (!(so->so_state & SS_ISCONNECTING)) {
1063 NG_MKMESSAGE(response, NGM_KSOCKET_COOKIE,
1064 NGM_KSOCKET_CONNECT, sizeof(int32_t), M_NOWAIT);
1065 if (response != NULL) {
1066 response->header.flags |= NGF_RESP;
1067 response->header.token = priv->response_token;
1068 *(int32_t *)response->data = error;
1070 * send an async "response" message
1071 * to the node that set us up
1072 * (if it still exists)
1074 NG_SEND_MSG_ID(error, node,
1075 response, priv->response_addr, 0);
1077 priv->flags &= ~KSF_CONNECTING;
1082 * If we don't have a hook, we must handle data events later. When
1083 * the hook gets created and is connected, this upcall function
1084 * will be called again.
1086 if (priv->hook == NULL)
1089 /* Read and forward available mbufs. */
1092 struct sockaddr *sa;
1096 /* Try to get next packet from socket. */
1098 uio.uio_resid = IP_MAXPACKET;
1099 flags = MSG_DONTWAIT;
1101 if ((error = soreceive(so, (so->so_state & SS_ISCONNECTED) ?
1102 NULL : &sa, &uio, &m, NULL, &flags)) != 0)
1105 /* See if we got anything. */
1106 if (flags & MSG_TRUNC) {
1116 KASSERT(m->m_nextpkt == NULL, ("%s: nextpkt", __func__));
1119 * Stream sockets do not have packet boundaries, so
1120 * we have to allocate a header mbuf and attach the
1121 * stream of data to it.
1123 if (so->so_type == SOCK_STREAM) {
1126 mh = m_gethdr(M_NOWAIT, MT_DATA);
1135 for (; m; m = m->m_next)
1136 mh->m_pkthdr.len += m->m_len;
1140 /* Put peer's socket address (if any) into a tag */
1142 struct sa_tag *stag;
1144 stag = (struct sa_tag *)m_tag_alloc(NGM_KSOCKET_COOKIE,
1145 NG_KSOCKET_TAG_SOCKADDR, sizeof(ng_ID_t) +
1146 sa->sa_len, M_NOWAIT);
1151 bcopy(sa, &stag->sa, sa->sa_len);
1153 stag->id = NG_NODE_ID(node);
1154 m_tag_prepend(m, &stag->tag);
1157 sendit: /* Forward data with optional peer sockaddr as packet tag */
1158 NG_SEND_DATA_ONLY(error, priv->hook, m);
1162 * If the peer has closed the connection, forward a 0-length mbuf
1163 * to indicate end-of-file.
1165 if (so->so_rcv.sb_state & SBS_CANTRCVMORE &&
1166 !(priv->flags & KSF_EOFSEEN)) {
1169 m = m_gethdr(M_NOWAIT, MT_DATA);
1171 NG_SEND_DATA_ONLY(error, priv->hook, m);
1172 priv->flags |= KSF_EOFSEEN;
1177 ng_ksocket_accept(priv_p priv)
1179 struct socket *const head = priv->so;
1181 struct sockaddr *sa = NULL;
1182 struct ng_mesg *resp;
1183 struct ng_ksocket_accept *resp_data;
1189 SOLISTEN_LOCK(head);
1190 error = solisten_dequeue(head, &so, SOCK_NONBLOCK);
1191 if (error == EWOULDBLOCK) {
1192 priv->flags |= KSF_ACCEPTING;
1195 priv->flags &= ~KSF_ACCEPTING;
1199 if ((error = soaccept(so, &sa)) != 0)
1202 len = OFFSETOF(struct ng_ksocket_accept, addr);
1206 NG_MKMESSAGE(resp, NGM_KSOCKET_COOKIE, NGM_KSOCKET_ACCEPT, len,
1212 resp->header.flags |= NGF_RESP;
1213 resp->header.token = priv->response_token;
1215 /* Clone a ksocket node to wrap the new socket */
1216 error = ng_make_node_common(&ng_ksocket_typestruct, &node);
1218 free(resp, M_NETGRAPH);
1223 if (ng_ksocket_constructor(node) != 0) {
1224 NG_NODE_UNREF(node);
1225 free(resp, M_NETGRAPH);
1230 priv2 = NG_NODE_PRIVATE(node);
1232 priv2->flags |= KSF_CLONED | KSF_EMBRYONIC;
1235 * Insert the cloned node into a list of embryonic children
1236 * on the parent node. When a hook is created on the cloned
1237 * node it will be removed from this list. When the parent
1238 * is destroyed it will destroy any embryonic children it has.
1240 LIST_INSERT_HEAD(&priv->embryos, priv2, siblings);
1242 SOCKBUF_LOCK(&so->so_rcv);
1243 soupcall_set(so, SO_RCV, ng_ksocket_incoming, node);
1244 SOCKBUF_UNLOCK(&so->so_rcv);
1245 SOCKBUF_LOCK(&so->so_snd);
1246 soupcall_set(so, SO_SND, ng_ksocket_incoming, node);
1247 SOCKBUF_UNLOCK(&so->so_snd);
1249 /* Fill in the response data and send it or return it to the caller */
1250 resp_data = (struct ng_ksocket_accept *)resp->data;
1251 resp_data->nodeid = NG_NODE_ID(node);
1253 bcopy(sa, &resp_data->addr, sa->sa_len);
1254 NG_SEND_MSG_ID(error, node, resp, priv->response_addr, 0);
1264 ng_ksocket_listen_upcall(struct socket *so, void *arg, int waitflag)
1267 int wait = ((waitflag & M_WAITOK) ? NG_WAITOK : 0) | NG_QUEUE;
1269 ng_send_fn1(priv->node, NULL, &ng_ksocket_listen_upcall2, priv, 0,
1275 ng_ksocket_listen_upcall2(node_p node, hook_p hook, void *arg1, int arg2)
1277 const priv_p priv = NG_NODE_PRIVATE(node);
1279 (void )ng_ksocket_accept(priv);
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')