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>
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 <netinet/ip.h>
71 #ifdef NG_SEPARATE_MALLOC
72 static MALLOC_DEFINE(M_NETGRAPH_KSOCKET, "netgraph_ksock",
73 "netgraph ksock node");
75 #define M_NETGRAPH_KSOCKET M_NETGRAPH
78 #define OFFSETOF(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
79 #define SADATA_OFFSET (OFFSETOF(struct sockaddr, sa_data))
81 /* Node private data */
82 struct ng_ksocket_private {
86 int fn_sent; /* FN call on incoming event was sent */
87 LIST_HEAD(, ng_ksocket_private) embryos;
88 LIST_ENTRY(ng_ksocket_private) siblings;
90 u_int32_t response_token;
91 ng_ID_t response_addr;
93 typedef struct ng_ksocket_private *priv_p;
95 /* Flags for priv_p */
96 #define KSF_CONNECTING 0x00000001 /* Waiting for connection complete */
97 #define KSF_ACCEPTING 0x00000002 /* Waiting for accept complete */
98 #define KSF_EOFSEEN 0x00000004 /* Have sent 0-length EOF mbuf */
99 #define KSF_CLONED 0x00000008 /* Cloned from an accepting socket */
100 #define KSF_EMBRYONIC 0x00000010 /* Cloned node with no hooks yet */
102 /* Netgraph node methods */
103 static ng_constructor_t ng_ksocket_constructor;
104 static ng_rcvmsg_t ng_ksocket_rcvmsg;
105 static ng_shutdown_t ng_ksocket_shutdown;
106 static ng_newhook_t ng_ksocket_newhook;
107 static ng_rcvdata_t ng_ksocket_rcvdata;
108 static ng_connect_t ng_ksocket_connect;
109 static ng_disconnect_t ng_ksocket_disconnect;
111 /* Alias structure */
112 struct ng_ksocket_alias {
118 /* Protocol family aliases */
119 static const struct ng_ksocket_alias ng_ksocket_families[] = {
120 { "local", PF_LOCAL },
122 { "inet6", PF_INET6 },
127 /* Socket type aliases */
128 static const struct ng_ksocket_alias ng_ksocket_types[] = {
129 { "stream", SOCK_STREAM },
130 { "dgram", SOCK_DGRAM },
133 { "seqpacket", SOCK_SEQPACKET },
137 /* Protocol aliases */
138 static const struct ng_ksocket_alias ng_ksocket_protos[] = {
139 { "ip", IPPROTO_IP, PF_INET },
140 { "raw", IPPROTO_RAW, PF_INET },
141 { "icmp", IPPROTO_ICMP, PF_INET },
142 { "igmp", IPPROTO_IGMP, PF_INET },
143 { "tcp", IPPROTO_TCP, PF_INET },
144 { "udp", IPPROTO_UDP, PF_INET },
145 { "gre", IPPROTO_GRE, PF_INET },
146 { "esp", IPPROTO_ESP, PF_INET },
147 { "ah", IPPROTO_AH, PF_INET },
148 { "swipe", IPPROTO_SWIPE, PF_INET },
149 { "encap", IPPROTO_ENCAP, PF_INET },
150 { "divert", IPPROTO_DIVERT, PF_INET },
151 { "pim", IPPROTO_PIM, PF_INET },
155 /* Helper functions */
156 static int ng_ksocket_accept(priv_p);
157 static int ng_ksocket_incoming(struct socket *so, void *arg, int waitflag);
158 static int ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
159 const char *s, int family);
160 static void ng_ksocket_incoming2(node_p node, hook_p hook,
161 void *arg1, int arg2);
163 /************************************************************************
164 STRUCT SOCKADDR PARSE TYPE
165 ************************************************************************/
167 /* Get the length of the data portion of a generic struct sockaddr */
169 ng_parse_generic_sockdata_getLength(const struct ng_parse_type *type,
170 const u_char *start, const u_char *buf)
172 const struct sockaddr *sa;
174 sa = (const struct sockaddr *)(buf - SADATA_OFFSET);
175 return (sa->sa_len < SADATA_OFFSET) ? 0 : sa->sa_len - SADATA_OFFSET;
178 /* Type for the variable length data portion of a generic struct sockaddr */
179 static const struct ng_parse_type ng_ksocket_generic_sockdata_type = {
180 &ng_parse_bytearray_type,
181 &ng_parse_generic_sockdata_getLength
184 /* Type for a generic struct sockaddr */
185 static const struct ng_parse_struct_field
186 ng_parse_generic_sockaddr_type_fields[] = {
187 { "len", &ng_parse_uint8_type },
188 { "family", &ng_parse_uint8_type },
189 { "data", &ng_ksocket_generic_sockdata_type },
192 static const struct ng_parse_type ng_ksocket_generic_sockaddr_type = {
193 &ng_parse_struct_type,
194 &ng_parse_generic_sockaddr_type_fields
197 /* Convert a struct sockaddr from ASCII to binary. If its a protocol
198 family that we specially handle, do that, otherwise defer to the
199 generic parse type ng_ksocket_generic_sockaddr_type. */
201 ng_ksocket_sockaddr_parse(const struct ng_parse_type *type,
202 const char *s, int *off, const u_char *const start,
203 u_char *const buf, int *buflen)
205 struct sockaddr *const sa = (struct sockaddr *)buf;
206 enum ng_parse_token tok;
211 /* If next token is a left curly brace, use generic parse type */
212 if ((tok = ng_parse_get_token(s, off, &len)) == T_LBRACE) {
213 return (*ng_ksocket_generic_sockaddr_type.supertype->parse)
214 (&ng_ksocket_generic_sockaddr_type,
215 s, off, start, buf, buflen);
218 /* Get socket address family followed by a slash */
219 while (isspace(s[*off]))
221 if ((t = strchr(s + *off, '/')) == NULL)
223 if ((len = t - (s + *off)) > sizeof(fambuf) - 1)
225 strncpy(fambuf, s + *off, len);
228 if ((family = ng_ksocket_parse(ng_ksocket_families, fambuf, 0)) == -1)
232 if (*buflen < SADATA_OFFSET)
234 sa->sa_family = family;
236 /* Set family-specific data and length */
237 switch (sa->sa_family) {
238 case PF_LOCAL: /* Get pathname */
240 const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
241 struct sockaddr_un *const sun = (struct sockaddr_un *)sa;
245 if ((path = ng_get_string_token(s, off, &toklen, NULL)) == NULL)
247 pathlen = strlen(path);
248 if (pathlen > SOCK_MAXADDRLEN) {
249 free(path, M_NETGRAPH_KSOCKET);
252 if (*buflen < pathoff + pathlen) {
253 free(path, M_NETGRAPH_KSOCKET);
257 bcopy(path, sun->sun_path, pathlen);
258 sun->sun_len = pathoff + pathlen;
259 free(path, M_NETGRAPH_KSOCKET);
263 case PF_INET: /* Get an IP address with optional port */
265 struct sockaddr_in *const sin = (struct sockaddr_in *)sa;
268 /* Parse this: <ipaddress>[:port] */
269 for (i = 0; i < 4; i++) {
273 val = strtoul(s + *off, &eptr, 10);
274 if (val > 0xff || eptr == s + *off)
276 *off += (eptr - (s + *off));
277 ((u_char *)&sin->sin_addr)[i] = (u_char)val;
282 } else if (s[*off] == ':') {
284 val = strtoul(s + *off, &eptr, 10);
285 if (val > 0xffff || eptr == s + *off)
287 *off += (eptr - (s + *off));
288 sin->sin_port = htons(val);
292 bzero(&sin->sin_zero, sizeof(sin->sin_zero));
293 sin->sin_len = sizeof(*sin);
298 case PF_INET6: /* XXX implement this someday */
306 *buflen = sa->sa_len;
310 /* Convert a struct sockaddr from binary to ASCII */
312 ng_ksocket_sockaddr_unparse(const struct ng_parse_type *type,
313 const u_char *data, int *off, char *cbuf, int cbuflen)
315 const struct sockaddr *sa = (const struct sockaddr *)(data + *off);
318 /* Output socket address, either in special or generic format */
319 switch (sa->sa_family) {
322 const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
323 const struct sockaddr_un *sun = (const struct sockaddr_un *)sa;
324 const int pathlen = sun->sun_len - pathoff;
325 char pathbuf[SOCK_MAXADDRLEN + 1];
328 bcopy(sun->sun_path, pathbuf, pathlen);
329 if ((pathtoken = ng_encode_string(pathbuf, pathlen)) == NULL)
331 slen += snprintf(cbuf, cbuflen, "local/%s", pathtoken);
332 free(pathtoken, M_NETGRAPH_KSOCKET);
335 *off += sun->sun_len;
341 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
343 slen += snprintf(cbuf, cbuflen, "inet/%d.%d.%d.%d",
344 ((const u_char *)&sin->sin_addr)[0],
345 ((const u_char *)&sin->sin_addr)[1],
346 ((const u_char *)&sin->sin_addr)[2],
347 ((const u_char *)&sin->sin_addr)[3]);
348 if (sin->sin_port != 0) {
349 slen += snprintf(cbuf + strlen(cbuf),
350 cbuflen - strlen(cbuf), ":%d",
351 (u_int)ntohs(sin->sin_port));
355 *off += sizeof(*sin);
360 case PF_INET6: /* XXX implement this someday */
364 return (*ng_ksocket_generic_sockaddr_type.supertype->unparse)
365 (&ng_ksocket_generic_sockaddr_type,
366 data, off, cbuf, cbuflen);
370 /* Parse type for struct sockaddr */
371 static const struct ng_parse_type ng_ksocket_sockaddr_type = {
375 &ng_ksocket_sockaddr_parse,
376 &ng_ksocket_sockaddr_unparse,
377 NULL /* no such thing as a default struct sockaddr */
380 /************************************************************************
381 STRUCT NG_KSOCKET_SOCKOPT PARSE TYPE
382 ************************************************************************/
384 /* Get length of the struct ng_ksocket_sockopt value field, which is the
385 just the excess of the message argument portion over the length of
386 the struct ng_ksocket_sockopt. */
388 ng_parse_sockoptval_getLength(const struct ng_parse_type *type,
389 const u_char *start, const u_char *buf)
391 static const int offset = OFFSETOF(struct ng_ksocket_sockopt, value);
392 const struct ng_ksocket_sockopt *sopt;
393 const struct ng_mesg *msg;
395 sopt = (const struct ng_ksocket_sockopt *)(buf - offset);
396 msg = (const struct ng_mesg *)((const u_char *)sopt - sizeof(*msg));
397 return msg->header.arglen - sizeof(*sopt);
400 /* Parse type for the option value part of a struct ng_ksocket_sockopt
401 XXX Eventually, we should handle the different socket options specially.
402 XXX This would avoid byte order problems, eg an integer value of 1 is
403 XXX going to be "[1]" for little endian or "[3=1]" for big endian. */
404 static const struct ng_parse_type ng_ksocket_sockoptval_type = {
405 &ng_parse_bytearray_type,
406 &ng_parse_sockoptval_getLength
409 /* Parse type for struct ng_ksocket_sockopt */
410 static const struct ng_parse_struct_field ng_ksocket_sockopt_type_fields[]
411 = NG_KSOCKET_SOCKOPT_INFO(&ng_ksocket_sockoptval_type);
412 static const struct ng_parse_type ng_ksocket_sockopt_type = {
413 &ng_parse_struct_type,
414 &ng_ksocket_sockopt_type_fields
417 /* Parse type for struct ng_ksocket_accept */
418 static const struct ng_parse_struct_field ng_ksocket_accept_type_fields[]
419 = NGM_KSOCKET_ACCEPT_INFO;
420 static const struct ng_parse_type ng_ksocket_accept_type = {
421 &ng_parse_struct_type,
422 &ng_ksocket_accept_type_fields
425 /* List of commands and how to convert arguments to/from ASCII */
426 static const struct ng_cmdlist ng_ksocket_cmds[] = {
431 &ng_ksocket_sockaddr_type,
438 &ng_parse_int32_type,
446 &ng_ksocket_accept_type
452 &ng_ksocket_sockaddr_type,
460 &ng_ksocket_sockaddr_type
464 NGM_KSOCKET_GETPEERNAME,
467 &ng_ksocket_sockaddr_type
473 &ng_ksocket_sockopt_type,
480 &ng_ksocket_sockopt_type,
481 &ng_ksocket_sockopt_type
486 /* Node type descriptor */
487 static struct ng_type ng_ksocket_typestruct = {
488 .version = NG_ABI_VERSION,
489 .name = NG_KSOCKET_NODE_TYPE,
490 .constructor = ng_ksocket_constructor,
491 .rcvmsg = ng_ksocket_rcvmsg,
492 .shutdown = ng_ksocket_shutdown,
493 .newhook = ng_ksocket_newhook,
494 .connect = ng_ksocket_connect,
495 .rcvdata = ng_ksocket_rcvdata,
496 .disconnect = ng_ksocket_disconnect,
497 .cmdlist = ng_ksocket_cmds,
499 NETGRAPH_INIT(ksocket, &ng_ksocket_typestruct);
501 #define ERROUT(x) do { error = (x); goto done; } while (0)
503 /************************************************************************
505 ************************************************************************/
508 * Node type constructor
509 * The NODE part is assumed to be all set up.
510 * There is already a reference to the node for us.
513 ng_ksocket_constructor(node_p node)
517 /* Allocate private structure */
518 priv = malloc(sizeof(*priv), M_NETGRAPH_KSOCKET, M_NOWAIT | M_ZERO);
522 LIST_INIT(&priv->embryos);
523 /* cross link them */
525 NG_NODE_SET_PRIVATE(node, priv);
532 * Give our OK for a hook to be added. The hook name is of the
533 * form "<family>/<type>/<proto>" where the three components may
534 * be decimal numbers or else aliases from the above lists.
536 * Connecting a hook amounts to opening the socket. Disconnecting
537 * the hook closes the socket and destroys the node as well.
540 ng_ksocket_newhook(node_p node, hook_p hook, const char *name0)
542 struct thread *td = curthread; /* XXX broken */
543 const priv_p priv = NG_NODE_PRIVATE(node);
544 char *s1, *s2, name[NG_HOOKSIZ];
545 int family, type, protocol, error;
547 /* Check if we're already connected */
548 if (priv->hook != NULL)
551 if (priv->flags & KSF_CLONED) {
552 if (priv->flags & KSF_EMBRYONIC) {
553 /* Remove ourselves from our parent's embryo list */
554 LIST_REMOVE(priv, siblings);
555 priv->flags &= ~KSF_EMBRYONIC;
558 /* Extract family, type, and protocol from hook name */
559 snprintf(name, sizeof(name), "%s", name0);
561 if ((s2 = strchr(s1, '/')) == NULL)
564 family = ng_ksocket_parse(ng_ksocket_families, s1, 0);
568 if ((s2 = strchr(s1, '/')) == NULL)
571 type = ng_ksocket_parse(ng_ksocket_types, s1, 0);
575 protocol = ng_ksocket_parse(ng_ksocket_protos, s1, family);
579 /* Create the socket */
580 error = socreate(family, &priv->so, type, protocol,
585 /* XXX call soreserve() ? */
592 * In case of misconfigured routing a packet may reenter
593 * ksocket node recursively. Decouple stack to avoid possible
594 * panics about sleeping with locks held.
596 NG_HOOK_FORCE_QUEUE(hook);
602 ng_ksocket_connect(hook_p hook)
604 node_p node = NG_HOOK_NODE(hook);
605 const priv_p priv = NG_NODE_PRIVATE(node);
606 struct socket *const so = priv->so;
608 /* Add our hook for incoming data and other events */
609 SOCKBUF_LOCK(&priv->so->so_rcv);
610 soupcall_set(priv->so, SO_RCV, ng_ksocket_incoming, node);
611 SOCKBUF_UNLOCK(&priv->so->so_rcv);
612 SOCKBUF_LOCK(&priv->so->so_snd);
613 soupcall_set(priv->so, SO_SND, ng_ksocket_incoming, node);
614 SOCKBUF_UNLOCK(&priv->so->so_snd);
616 priv->so->so_state |= SS_NBIO;
617 SOCK_UNLOCK(priv->so);
619 * --Original comment--
620 * On a cloned socket we may have already received one or more
621 * upcalls which we couldn't handle without a hook. Handle
623 * We cannot call the upcall function directly
624 * from here, because until this function has returned our
625 * hook isn't connected.
627 * ---meta comment for -current ---
628 * XXX This is dubius.
629 * Upcalls between the time that the hook was
630 * first created and now (on another processesor) will
631 * be earlier on the queue than the request to finalise the hook.
632 * By the time the hook is finalised,
633 * The queued upcalls will have happened and the code
634 * will have discarded them because of a lack of a hook.
637 * This is a bad byproduct of the complicated way in which hooks
638 * are now created (3 daisy chained async events).
640 * Since we are a netgraph operation
641 * We know that we hold a lock on this node. This forces the
642 * request we make below to be queued rather than implemented
643 * immediately which will cause the upcall function to be called a bit
645 * However, as we will run any waiting queued operations immediately
646 * after doing this one, if we have not finalised the other end
647 * of the hook, those queued operations will fail.
649 if (priv->flags & KSF_CLONED) {
650 ng_send_fn(node, NULL, &ng_ksocket_incoming2, so, M_NOWAIT);
657 * Receive a control message
660 ng_ksocket_rcvmsg(node_p node, item_p item, hook_p lasthook)
662 struct thread *td = curthread; /* XXX broken */
663 const priv_p priv = NG_NODE_PRIVATE(node);
664 struct socket *const so = priv->so;
665 struct ng_mesg *resp = NULL;
670 NGI_GET_MSG(item, msg);
671 switch (msg->header.typecookie) {
672 case NGM_KSOCKET_COOKIE:
673 switch (msg->header.cmd) {
674 case NGM_KSOCKET_BIND:
676 struct sockaddr *const sa
677 = (struct sockaddr *)msg->data;
680 if (msg->header.arglen < SADATA_OFFSET
681 || msg->header.arglen < sa->sa_len)
687 error = sobind(so, sa, td);
690 case NGM_KSOCKET_LISTEN:
693 if (msg->header.arglen != sizeof(int32_t))
699 so->so_state |= SS_NBIO;
700 error = solisten(so, *((int32_t *)msg->data), td);
704 case NGM_KSOCKET_ACCEPT:
707 if (msg->header.arglen != 0)
712 /* Make sure the socket is capable of accepting */
713 if (!(so->so_options & SO_ACCEPTCONN))
715 if (priv->flags & KSF_ACCEPTING)
719 * If a connection is already complete, take it.
720 * Otherwise let the upcall function deal with
721 * the connection when it comes in.
723 error = ng_ksocket_accept(priv);
724 if (error != 0 && error != EWOULDBLOCK)
726 priv->response_token = msg->header.token;
727 raddr = priv->response_addr = NGI_RETADDR(item);
731 case NGM_KSOCKET_CONNECT:
733 struct sockaddr *const sa
734 = (struct sockaddr *)msg->data;
737 if (msg->header.arglen < SADATA_OFFSET
738 || msg->header.arglen < sa->sa_len)
744 if ((so->so_state & SS_ISCONNECTING) != 0)
746 if ((error = soconnect(so, sa, td)) != 0) {
747 so->so_state &= ~SS_ISCONNECTING;
750 if ((so->so_state & SS_ISCONNECTING) != 0) {
751 /* We will notify the sender when we connect */
752 priv->response_token = msg->header.token;
753 raddr = priv->response_addr = NGI_RETADDR(item);
754 priv->flags |= KSF_CONNECTING;
760 case NGM_KSOCKET_GETNAME:
761 case NGM_KSOCKET_GETPEERNAME:
763 int (*func)(struct socket *so, struct sockaddr **nam);
764 struct sockaddr *sa = NULL;
768 if (msg->header.arglen != 0)
774 if (msg->header.cmd == NGM_KSOCKET_GETPEERNAME) {
776 & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0)
778 func = so->so_proto->pr_usrreqs->pru_peeraddr;
780 func = so->so_proto->pr_usrreqs->pru_sockaddr;
782 /* Get local or peer address */
783 if ((error = (*func)(so, &sa)) != 0)
785 len = (sa == NULL) ? 0 : sa->sa_len;
787 /* Send it back in a response */
788 NG_MKRESPONSE(resp, msg, len, M_NOWAIT);
793 bcopy(sa, resp->data, len);
802 case NGM_KSOCKET_GETOPT:
804 struct ng_ksocket_sockopt *ksopt =
805 (struct ng_ksocket_sockopt *)msg->data;
809 if (msg->header.arglen != sizeof(*ksopt))
814 /* Get response with room for option value */
815 NG_MKRESPONSE(resp, msg, sizeof(*ksopt)
816 + NG_KSOCKET_MAX_OPTLEN, M_NOWAIT);
820 /* Get socket option, and put value in the response */
821 sopt.sopt_dir = SOPT_GET;
822 sopt.sopt_level = ksopt->level;
823 sopt.sopt_name = ksopt->name;
825 sopt.sopt_valsize = NG_KSOCKET_MAX_OPTLEN;
826 ksopt = (struct ng_ksocket_sockopt *)resp->data;
827 sopt.sopt_val = ksopt->value;
828 if ((error = sogetopt(so, &sopt)) != 0) {
833 /* Set actual value length */
834 resp->header.arglen = sizeof(*ksopt)
839 case NGM_KSOCKET_SETOPT:
841 struct ng_ksocket_sockopt *const ksopt =
842 (struct ng_ksocket_sockopt *)msg->data;
843 const int valsize = msg->header.arglen - sizeof(*ksopt);
852 /* Set socket option */
853 sopt.sopt_dir = SOPT_SET;
854 sopt.sopt_level = ksopt->level;
855 sopt.sopt_name = ksopt->name;
856 sopt.sopt_val = ksopt->value;
857 sopt.sopt_valsize = valsize;
859 error = sosetopt(so, &sopt);
873 NG_RESPOND_MSG(error, node, item, resp);
879 * Receive incoming data on our hook. Send it out the socket.
882 ng_ksocket_rcvdata(hook_p hook, item_p item)
884 struct thread *td = curthread; /* XXX broken */
885 const node_p node = NG_HOOK_NODE(hook);
886 const priv_p priv = NG_NODE_PRIVATE(node);
887 struct socket *const so = priv->so;
888 struct sockaddr *sa = NULL;
891 #ifdef ALIGNED_POINTER
893 #endif /* ALIGNED_POINTER */
899 #ifdef ALIGNED_POINTER
900 if (!ALIGNED_POINTER(mtod(m, caddr_t), uint32_t)) {
901 n = m_defrag(m, M_NOWAIT);
908 #endif /* ALIGNED_POINTER */
910 * Look if socket address is stored in packet tags.
911 * If sockaddr is ours, or provided by a third party (zero id),
914 if (((stag = (struct sa_tag *)m_tag_locate(m, NGM_KSOCKET_COOKIE,
915 NG_KSOCKET_TAG_SOCKADDR, NULL)) != NULL) &&
916 (stag->id == NG_NODE_ID(node) || stag->id == 0))
919 /* Reset specific mbuf flags to prevent addressing problems. */
920 m->m_flags &= ~(M_BCAST|M_MCAST);
923 error = sosend(so, sa, 0, m, 0, 0, td);
932 ng_ksocket_shutdown(node_p node)
934 const priv_p priv = NG_NODE_PRIVATE(node);
937 /* Close our socket (if any) */
938 if (priv->so != NULL) {
939 SOCKBUF_LOCK(&priv->so->so_rcv);
940 soupcall_clear(priv->so, SO_RCV);
941 SOCKBUF_UNLOCK(&priv->so->so_rcv);
942 SOCKBUF_LOCK(&priv->so->so_snd);
943 soupcall_clear(priv->so, SO_SND);
944 SOCKBUF_UNLOCK(&priv->so->so_snd);
949 /* If we are an embryo, take ourselves out of the parent's list */
950 if (priv->flags & KSF_EMBRYONIC) {
951 LIST_REMOVE(priv, siblings);
952 priv->flags &= ~KSF_EMBRYONIC;
955 /* Remove any embryonic children we have */
956 while (!LIST_EMPTY(&priv->embryos)) {
957 embryo = LIST_FIRST(&priv->embryos);
958 ng_rmnode_self(embryo->node);
961 /* Take down netgraph node */
962 bzero(priv, sizeof(*priv));
963 free(priv, M_NETGRAPH_KSOCKET);
964 NG_NODE_SET_PRIVATE(node, NULL);
965 NG_NODE_UNREF(node); /* let the node escape */
973 ng_ksocket_disconnect(hook_p hook)
975 KASSERT(NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0,
976 ("%s: numhooks=%d?", __func__,
977 NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook))));
978 if (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))
979 ng_rmnode_self(NG_HOOK_NODE(hook));
983 /************************************************************************
985 ************************************************************************/
987 * You should not "just call" a netgraph node function from an external
988 * asynchronous event. This is because in doing so you are ignoring the
989 * locking on the netgraph nodes. Instead call your function via ng_send_fn().
990 * This will call the function you chose, but will first do all the
991 * locking rigmarole. Your function MAY only be called at some distant future
992 * time (several millisecs away) so don't give it any arguments
993 * that may be revoked soon (e.g. on your stack).
995 * To decouple stack, we use queue version of ng_send_fn().
999 ng_ksocket_incoming(struct socket *so, void *arg, int waitflag)
1001 const node_p node = arg;
1002 const priv_p priv = NG_NODE_PRIVATE(node);
1003 int wait = ((waitflag & M_WAITOK) ? NG_WAITOK : 0) | NG_QUEUE;
1006 * Even if node is not locked, as soon as we are called, we assume
1007 * it exist and it's private area is valid. With some care we can
1008 * access it. Mark node that incoming event for it was sent to
1009 * avoid unneded queue trashing.
1011 if (atomic_cmpset_int(&priv->fn_sent, 0, 1) &&
1012 ng_send_fn1(node, NULL, &ng_ksocket_incoming2, so, 0, wait)) {
1013 atomic_store_rel_int(&priv->fn_sent, 0);
1019 * When incoming data is appended to the socket, we get notified here.
1020 * This is also called whenever a significant event occurs for the socket.
1021 * Our original caller may have queued this even some time ago and
1022 * we cannot trust that he even still exists. The node however is being
1023 * held with a reference by the queueing code and guarantied to be valid.
1026 ng_ksocket_incoming2(node_p node, hook_p hook, void *arg1, int arg2)
1028 struct socket *so = arg1;
1029 const priv_p priv = NG_NODE_PRIVATE(node);
1030 struct ng_mesg *response;
1033 KASSERT(so == priv->so, ("%s: wrong socket", __func__));
1035 /* Allow next incoming event to be queued. */
1036 atomic_store_rel_int(&priv->fn_sent, 0);
1038 /* Check whether a pending connect operation has completed */
1039 if (priv->flags & KSF_CONNECTING) {
1040 if ((error = so->so_error) != 0) {
1042 so->so_state &= ~SS_ISCONNECTING;
1044 if (!(so->so_state & SS_ISCONNECTING)) {
1045 NG_MKMESSAGE(response, NGM_KSOCKET_COOKIE,
1046 NGM_KSOCKET_CONNECT, sizeof(int32_t), M_NOWAIT);
1047 if (response != NULL) {
1048 response->header.flags |= NGF_RESP;
1049 response->header.token = priv->response_token;
1050 *(int32_t *)response->data = error;
1052 * send an async "response" message
1053 * to the node that set us up
1054 * (if it still exists)
1056 NG_SEND_MSG_ID(error, node,
1057 response, priv->response_addr, 0);
1059 priv->flags &= ~KSF_CONNECTING;
1063 /* Check whether a pending accept operation has completed */
1064 if (priv->flags & KSF_ACCEPTING)
1065 (void )ng_ksocket_accept(priv);
1068 * If we don't have a hook, we must handle data events later. When
1069 * the hook gets created and is connected, this upcall function
1070 * will be called again.
1072 if (priv->hook == NULL)
1075 /* Read and forward available mbufs. */
1078 struct sockaddr *sa;
1082 /* Try to get next packet from socket. */
1084 uio.uio_resid = IP_MAXPACKET;
1085 flags = MSG_DONTWAIT;
1087 if ((error = soreceive(so, (so->so_state & SS_ISCONNECTED) ?
1088 NULL : &sa, &uio, &m, NULL, &flags)) != 0)
1091 /* See if we got anything. */
1092 if (flags & MSG_TRUNC) {
1102 KASSERT(m->m_nextpkt == NULL, ("%s: nextpkt", __func__));
1105 * Stream sockets do not have packet boundaries, so
1106 * we have to allocate a header mbuf and attach the
1107 * stream of data to it.
1109 if (so->so_type == SOCK_STREAM) {
1112 mh = m_gethdr(M_NOWAIT, MT_DATA);
1121 for (; m; m = m->m_next)
1122 mh->m_pkthdr.len += m->m_len;
1126 /* Put peer's socket address (if any) into a tag */
1128 struct sa_tag *stag;
1130 stag = (struct sa_tag *)m_tag_alloc(NGM_KSOCKET_COOKIE,
1131 NG_KSOCKET_TAG_SOCKADDR, sizeof(ng_ID_t) +
1132 sa->sa_len, M_NOWAIT);
1137 bcopy(sa, &stag->sa, sa->sa_len);
1139 stag->id = NG_NODE_ID(node);
1140 m_tag_prepend(m, &stag->tag);
1143 sendit: /* Forward data with optional peer sockaddr as packet tag */
1144 NG_SEND_DATA_ONLY(error, priv->hook, m);
1148 * If the peer has closed the connection, forward a 0-length mbuf
1149 * to indicate end-of-file.
1151 if (so->so_rcv.sb_state & SBS_CANTRCVMORE &&
1152 !(priv->flags & KSF_EOFSEEN)) {
1155 m = m_gethdr(M_NOWAIT, MT_DATA);
1157 NG_SEND_DATA_ONLY(error, priv->hook, m);
1158 priv->flags |= KSF_EOFSEEN;
1163 ng_ksocket_accept(priv_p priv)
1165 struct socket *const head = priv->so;
1167 struct sockaddr *sa = NULL;
1168 struct ng_mesg *resp;
1169 struct ng_ksocket_accept *resp_data;
1175 SOLISTEN_LOCK(head);
1176 error = solisten_dequeue(head, &so, SOCK_NONBLOCK);
1177 if (error == EWOULDBLOCK) {
1178 priv->flags |= KSF_ACCEPTING;
1181 priv->flags &= ~KSF_ACCEPTING;
1185 if ((error = soaccept(so, &sa)) != 0)
1188 len = OFFSETOF(struct ng_ksocket_accept, addr);
1192 NG_MKMESSAGE(resp, NGM_KSOCKET_COOKIE, NGM_KSOCKET_ACCEPT, len,
1198 resp->header.flags |= NGF_RESP;
1199 resp->header.token = priv->response_token;
1201 /* Clone a ksocket node to wrap the new socket */
1202 error = ng_make_node_common(&ng_ksocket_typestruct, &node);
1204 free(resp, M_NETGRAPH);
1209 if (ng_ksocket_constructor(node) != 0) {
1210 NG_NODE_UNREF(node);
1211 free(resp, M_NETGRAPH);
1216 priv2 = NG_NODE_PRIVATE(node);
1218 priv2->flags |= KSF_CLONED | KSF_EMBRYONIC;
1221 * Insert the cloned node into a list of embryonic children
1222 * on the parent node. When a hook is created on the cloned
1223 * node it will be removed from this list. When the parent
1224 * is destroyed it will destroy any embryonic children it has.
1226 LIST_INSERT_HEAD(&priv->embryos, priv2, siblings);
1228 SOCKBUF_LOCK(&so->so_rcv);
1229 soupcall_set(so, SO_RCV, ng_ksocket_incoming, node);
1230 SOCKBUF_UNLOCK(&so->so_rcv);
1231 SOCKBUF_LOCK(&so->so_snd);
1232 soupcall_set(so, SO_SND, ng_ksocket_incoming, node);
1233 SOCKBUF_UNLOCK(&so->so_snd);
1235 /* Fill in the response data and send it or return it to the caller */
1236 resp_data = (struct ng_ksocket_accept *)resp->data;
1237 resp_data->nodeid = NG_NODE_ID(node);
1239 bcopy(sa, &resp_data->addr, sa->sa_len);
1240 NG_SEND_MSG_ID(error, node, resp, priv->response_addr, 0);
1250 * Parse out either an integer value or an alias.
1253 ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
1254 const char *s, int family)
1260 for (k = 0; aliases[k].name != NULL; k++) {
1261 if (strcmp(s, aliases[k].name) == 0
1262 && aliases[k].family == family)
1263 return aliases[k].value;
1266 /* Try parsing as a number */
1267 val = (int)strtoul(s, &eptr, 10);
1268 if (val < 0 || *eptr != '\0')