5 * Copyright (c) 1996-1999 Whistle Communications, Inc.
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.
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
37 * Author: Archie Cobbs <archie@freebsd.org>
39 * $FreeBSD: src/sys/netgraph/ng_ksocket.c,v 1.5.2.14 2003/08/24 08:24:38 hsu Exp $
40 * $Whistle: ng_ksocket.c,v 1.1 1999/11/16 20:04:40 archie Exp $
44 * Kernel socket node type. This node type is basically a kernel-mode
45 * version of a socket... kindof like the reverse of the socket node type.
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/kernel.h>
53 #include <sys/malloc.h>
54 #include <sys/ctype.h>
55 #include <sys/protosw.h>
56 #include <sys/errno.h>
57 #include <sys/fcntl.h>
58 #include <sys/socket.h>
59 #include <sys/socketvar.h>
60 #include <sys/socketops.h>
64 #include <sys/thread2.h>
65 #include <sys/socketvar2.h>
67 #include <netgraph/ng_message.h>
68 #include <netgraph/netgraph.h>
69 #include <netgraph/ng_parse.h>
70 #include "ng_ksocket.h"
72 #include <netinet/in.h>
74 #define OFFSETOF(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
75 #define SADATA_OFFSET (OFFSETOF(struct sockaddr, sa_data))
77 /* Node private data */
78 struct ng_ksocket_private {
82 LIST_HEAD(, ng_ksocket_private) embryos;
83 LIST_ENTRY(ng_ksocket_private) siblings;
85 u_int32_t response_token;
86 char response_addr[NG_PATHSIZ];
88 typedef struct ng_ksocket_private *priv_p;
90 /* Flags for priv_p */
91 #define KSF_CONNECTING 0x00000001 /* Waiting for connection complete */
92 #define KSF_ACCEPTING 0x00000002 /* Waiting for accept complete */
93 #define KSF_EOFSEEN 0x00000004 /* Have sent 0-length EOF mbuf */
94 #define KSF_CLONED 0x00000008 /* Cloned from an accepting socket */
95 #define KSF_EMBRYONIC 0x00000010 /* Cloned node with no hooks yet */
96 #define KSF_SENDING 0x00000020 /* Sending on socket */
98 /* Internal commands which we send to ourselves */
99 #define NGM_KSOCKET_INTERNAL_COOKIE (NGM_KSOCKET_COOKIE + 1)
102 NGM_KSOCKET_INTERNAL_UPCALL = 1
105 /* Netgraph node methods */
106 static ng_constructor_t ng_ksocket_constructor;
107 static ng_rcvmsg_t ng_ksocket_rcvmsg;
108 static ng_shutdown_t ng_ksocket_rmnode;
109 static ng_newhook_t ng_ksocket_newhook;
110 static ng_rcvdata_t ng_ksocket_rcvdata;
111 static ng_disconnect_t ng_ksocket_disconnect;
113 /* Alias structure */
114 struct ng_ksocket_alias {
120 /* Protocol family aliases */
121 static const struct ng_ksocket_alias ng_ksocket_families[] = {
122 { "local", PF_LOCAL },
124 { "inet6", PF_INET6 },
130 /* Socket type aliases */
131 static const struct ng_ksocket_alias ng_ksocket_types[] = {
132 { "stream", SOCK_STREAM },
133 { "dgram", SOCK_DGRAM },
136 { "seqpacket", SOCK_SEQPACKET },
140 /* Protocol aliases */
141 static const struct ng_ksocket_alias ng_ksocket_protos[] = {
142 { "ip", IPPROTO_IP, PF_INET },
143 { "raw", IPPROTO_RAW, PF_INET },
144 { "icmp", IPPROTO_ICMP, PF_INET },
145 { "igmp", IPPROTO_IGMP, PF_INET },
146 { "tcp", IPPROTO_TCP, PF_INET },
147 { "udp", IPPROTO_UDP, PF_INET },
148 { "gre", IPPROTO_GRE, PF_INET },
149 { "esp", IPPROTO_ESP, PF_INET },
150 { "ah", IPPROTO_AH, PF_INET },
151 { "swipe", IPPROTO_SWIPE, PF_INET },
152 { "encap", IPPROTO_ENCAP, PF_INET },
153 { "divert", IPPROTO_DIVERT, PF_INET },
154 { "pim", IPPROTO_PIM, PF_INET },
158 /* Helper functions */
159 static int ng_ksocket_check_accept(priv_p);
160 static void ng_ksocket_finish_accept(priv_p, struct ng_mesg **);
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);
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 = index(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)
249 pathlen = strlen(path);
250 if (pathlen > SOCK_MAXADDRLEN) {
251 kfree(path, M_NETGRAPH);
254 if (*buflen < pathoff + pathlen) {
255 kfree(path, M_NETGRAPH);
259 bcopy(path, sun->sun_path, pathlen);
260 sun->sun_len = pathoff + pathlen;
261 kfree(path, M_NETGRAPH);
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);
309 *buflen = sa->sa_len;
313 /* Convert a struct sockaddr from binary to ASCII */
315 ng_ksocket_sockaddr_unparse(const struct ng_parse_type *type,
316 const u_char *data, int *off, char *cbuf, int cbuflen)
318 const struct sockaddr *sa = (const struct sockaddr *)(data + *off);
321 /* Output socket address, either in special or generic format */
322 switch (sa->sa_family) {
325 const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
326 const struct sockaddr_un *sun = (const struct sockaddr_un *)sa;
327 const int pathlen = sun->sun_len - pathoff;
328 char pathbuf[SOCK_MAXADDRLEN + 1];
331 bcopy(sun->sun_path, pathbuf, pathlen);
332 pathbuf[pathlen] = '\0';
333 if ((pathtoken = ng_encode_string(pathbuf)) == NULL)
335 slen += ksnprintf(cbuf, cbuflen, "local/%s", pathtoken);
336 kfree(pathtoken, M_NETGRAPH);
339 *off += sun->sun_len;
345 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
347 slen += ksnprintf(cbuf, cbuflen, "inet/%d.%d.%d.%d",
348 ((const u_char *)&sin->sin_addr)[0],
349 ((const u_char *)&sin->sin_addr)[1],
350 ((const u_char *)&sin->sin_addr)[2],
351 ((const u_char *)&sin->sin_addr)[3]);
352 if (sin->sin_port != 0) {
353 slen += ksnprintf(cbuf + strlen(cbuf),
354 cbuflen - strlen(cbuf), ":%d",
355 (u_int)ntohs(sin->sin_port));
359 *off += sizeof(*sin);
369 return (*ng_ksocket_generic_sockaddr_type.supertype->unparse)
370 (&ng_ksocket_generic_sockaddr_type,
371 data, off, cbuf, cbuflen);
375 /* Parse type for struct sockaddr */
376 static const struct ng_parse_type ng_ksocket_sockaddr_type = {
380 &ng_ksocket_sockaddr_parse,
381 &ng_ksocket_sockaddr_unparse,
382 NULL /* no such thing as a default struct sockaddr */
385 /************************************************************************
386 STRUCT NG_KSOCKET_SOCKOPT PARSE TYPE
387 ************************************************************************/
389 /* Get length of the struct ng_ksocket_sockopt value field, which is the
390 just the excess of the message argument portion over the length of
391 the struct ng_ksocket_sockopt. */
393 ng_parse_sockoptval_getLength(const struct ng_parse_type *type,
394 const u_char *start, const u_char *buf)
396 static const int offset = OFFSETOF(struct ng_ksocket_sockopt, value);
397 const struct ng_ksocket_sockopt *sopt;
398 const struct ng_mesg *msg;
400 sopt = (const struct ng_ksocket_sockopt *)(buf - offset);
401 msg = (const struct ng_mesg *)((const u_char *)sopt - sizeof(*msg));
402 return msg->header.arglen - sizeof(*sopt);
405 /* Parse type for the option value part of a struct ng_ksocket_sockopt
406 XXX Eventually, we should handle the different socket options specially.
407 XXX This would avoid byte order problems, eg an integer value of 1 is
408 XXX going to be "[1]" for little endian or "[3=1]" for big endian. */
409 static const struct ng_parse_type ng_ksocket_sockoptval_type = {
410 &ng_parse_bytearray_type,
411 &ng_parse_sockoptval_getLength
414 /* Parse type for struct ng_ksocket_sockopt */
415 static const struct ng_parse_struct_field ng_ksocket_sockopt_type_fields[]
416 = NG_KSOCKET_SOCKOPT_INFO(&ng_ksocket_sockoptval_type);
417 static const struct ng_parse_type ng_ksocket_sockopt_type = {
418 &ng_parse_struct_type,
419 &ng_ksocket_sockopt_type_fields
422 /* Parse type for struct ng_ksocket_accept */
423 static const struct ng_parse_struct_field ng_ksocket_accept_type_fields[]
424 = NGM_KSOCKET_ACCEPT_INFO;
425 static const struct ng_parse_type ng_ksocket_accept_type = {
426 &ng_parse_struct_type,
427 &ng_ksocket_accept_type_fields
430 /* List of commands and how to convert arguments to/from ASCII */
431 static const struct ng_cmdlist ng_ksocket_cmds[] = {
436 &ng_ksocket_sockaddr_type,
443 &ng_parse_int32_type,
451 &ng_ksocket_accept_type
457 &ng_ksocket_sockaddr_type,
465 &ng_ksocket_sockaddr_type
469 NGM_KSOCKET_GETPEERNAME,
472 &ng_ksocket_sockaddr_type
478 &ng_ksocket_sockopt_type,
485 &ng_ksocket_sockopt_type,
486 &ng_ksocket_sockopt_type
489 /* Internal commands */
491 NGM_KSOCKET_INTERNAL_COOKIE,
492 NGM_KSOCKET_INTERNAL_UPCALL,
500 /* Node type descriptor */
501 static struct ng_type ng_ksocket_typestruct = {
503 NG_KSOCKET_NODE_TYPE,
505 ng_ksocket_constructor,
513 ng_ksocket_disconnect,
516 NETGRAPH_INIT(ksocket, &ng_ksocket_typestruct);
518 #define ERROUT(x) do { error = (x); goto done; } while (0)
520 /************************************************************************
522 ************************************************************************/
525 * Node type constructor
528 ng_ksocket_constructor(node_p *nodep)
533 /* Allocate private structure */
534 priv = kmalloc(sizeof(*priv), M_NETGRAPH, M_NOWAIT | M_ZERO);
538 /* Call generic node constructor */
539 if ((error = ng_make_node_common(&ng_ksocket_typestruct, nodep))) {
540 kfree(priv, M_NETGRAPH);
543 (*nodep)->private = priv;
545 LIST_INIT(&priv->embryos);
552 * Give our OK for a hook to be added. The hook name is of the
553 * form "<family>/<type>/<proto>" where the three components may
554 * be decimal numbers or else aliases from the above lists.
556 * Connecting a hook amounts to opening the socket. Disconnecting
557 * the hook closes the socket and destroys the node as well.
560 ng_ksocket_newhook(node_p node, hook_p hook, const char *name0)
562 struct thread *td = curthread->td_proc ? curthread : &thread0; /* XXX broken */
563 const priv_p priv = node->private;
565 char *s1, *s2, name[NG_HOOKSIZ];
566 int family, type, protocol, error;
568 /* Check if we're already connected */
569 if (priv->hook != NULL)
572 if (priv->flags & KSF_CLONED) {
573 if (priv->flags & KSF_EMBRYONIC) {
574 /* Remove ourselves from our parent's embryo list */
575 LIST_REMOVE(priv, siblings);
576 priv->flags &= ~KSF_EMBRYONIC;
579 /* Extract family, type, and protocol from hook name */
580 ksnprintf(name, sizeof(name), "%s", name0);
582 if ((s2 = index(s1, '/')) == NULL)
585 family = ng_ksocket_parse(ng_ksocket_families, s1, 0);
589 if ((s2 = index(s1, '/')) == NULL)
592 type = ng_ksocket_parse(ng_ksocket_types, s1, 0);
596 protocol = ng_ksocket_parse(ng_ksocket_protos, s1, family);
600 /* Create the socket */
601 error = socreate(family, &priv->so, type, protocol, td);
605 /* XXX call soreserve() ? */
607 /* Add our hook for incoming data and other events */
608 priv->so->so_upcallarg = (caddr_t)node;
609 priv->so->so_upcall = ng_ksocket_incoming;
610 atomic_set_int(&priv->so->so_rcv.ssb_flags, SSB_UPCALL);
611 atomic_set_int(&priv->so->so_snd.ssb_flags, SSB_UPCALL);
618 * On a cloned socket we may have already received one or more
619 * upcalls which we couldn't handle without a hook. Handle
620 * those now. We cannot call the upcall function directly
621 * from here, because until this function has returned our
622 * hook isn't connected. So we queue a message to ourselves
623 * which will cause the upcall function to be called a bit
626 if (priv->flags & KSF_CLONED) {
627 NG_MKMESSAGE(msg, NGM_KSOCKET_INTERNAL_COOKIE,
628 NGM_KSOCKET_INTERNAL_UPCALL, 0, M_NOWAIT);
630 ng_queue_msg(node, msg, ".:");
637 * Receive a control message
640 ng_ksocket_rcvmsg(node_p node, struct ng_mesg *msg,
641 const char *raddr, struct ng_mesg **rptr)
643 struct thread *td = curthread->td_proc ? curthread : &thread0; /* XXX broken */
644 const priv_p priv = node->private;
645 struct socket *const so = priv->so;
646 struct ng_mesg *resp = NULL;
649 switch (msg->header.typecookie) {
650 case NGM_KSOCKET_COOKIE:
651 switch (msg->header.cmd) {
652 case NGM_KSOCKET_BIND:
654 struct sockaddr *const sa
655 = (struct sockaddr *)msg->data;
658 if (msg->header.arglen < SADATA_OFFSET
659 || msg->header.arglen < sa->sa_len)
665 error = sobind(so, sa, td);
668 case NGM_KSOCKET_LISTEN:
671 if (msg->header.arglen != sizeof(int32_t))
677 error = solisten(so, *((int32_t *)msg->data), td);
681 case NGM_KSOCKET_ACCEPT:
684 if (msg->header.arglen != 0)
689 /* Make sure the socket is capable of accepting */
690 if (!(so->so_options & SO_ACCEPTCONN))
692 if (priv->flags & KSF_ACCEPTING)
695 error = ng_ksocket_check_accept(priv);
696 if (error != 0 && error != EWOULDBLOCK)
700 * If a connection is already complete, take it.
701 * Otherwise let the upcall function deal with
702 * the connection when it comes in.
704 priv->response_token = msg->header.token;
705 strcpy(priv->response_addr, raddr);
707 ng_ksocket_finish_accept(priv,
708 rptr != NULL ? &resp : NULL);
710 priv->flags |= KSF_ACCEPTING;
714 case NGM_KSOCKET_CONNECT:
716 struct sockaddr *const sa
717 = (struct sockaddr *)msg->data;
720 if (msg->header.arglen < SADATA_OFFSET
721 || msg->header.arglen < sa->sa_len)
727 if ((so->so_state & SS_ISCONNECTING) != 0)
729 if ((error = soconnect(so, sa, td)) != 0) {
730 soclrstate(so, SS_ISCONNECTING);
733 if ((so->so_state & SS_ISCONNECTING) != 0) {
734 /* We will notify the sender when we connect */
735 priv->response_token = msg->header.token;
736 strcpy(priv->response_addr, raddr);
737 priv->flags |= KSF_CONNECTING;
743 case NGM_KSOCKET_GETNAME:
744 case NGM_KSOCKET_GETPEERNAME:
746 struct sockaddr *sa = NULL;
750 if (msg->header.arglen != 0)
756 if (msg->header.cmd == NGM_KSOCKET_GETPEERNAME) {
758 & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0)
760 error = so_pru_peeraddr(so, &sa);
762 error = so_pru_sockaddr(so, &sa);
764 /* Get local or peer address */
767 len = (sa == NULL) ? 0 : sa->sa_len;
769 /* Send it back in a response */
770 NG_MKRESPONSE(resp, msg, len, M_NOWAIT);
775 bcopy(sa, resp->data, len);
784 case NGM_KSOCKET_GETOPT:
786 struct ng_ksocket_sockopt *ksopt =
787 (struct ng_ksocket_sockopt *)msg->data;
791 if (msg->header.arglen != sizeof(*ksopt))
796 /* Get response with room for option value */
797 NG_MKRESPONSE(resp, msg, sizeof(*ksopt)
798 + NG_KSOCKET_MAX_OPTLEN, M_NOWAIT);
802 /* Get socket option, and put value in the response */
803 sopt.sopt_dir = SOPT_GET;
804 sopt.sopt_level = ksopt->level;
805 sopt.sopt_name = ksopt->name;
807 sopt.sopt_valsize = NG_KSOCKET_MAX_OPTLEN;
808 ksopt = (struct ng_ksocket_sockopt *)resp->data;
809 sopt.sopt_val = ksopt->value;
810 if ((error = sogetopt(so, &sopt)) != 0) {
811 kfree(resp, M_NETGRAPH);
815 /* Set actual value length */
816 resp->header.arglen = sizeof(*ksopt)
821 case NGM_KSOCKET_SETOPT:
823 struct ng_ksocket_sockopt *const ksopt =
824 (struct ng_ksocket_sockopt *)msg->data;
825 const int valsize = msg->header.arglen - sizeof(*ksopt);
834 /* Set socket option */
835 sopt.sopt_dir = SOPT_SET;
836 sopt.sopt_level = ksopt->level;
837 sopt.sopt_name = ksopt->name;
838 sopt.sopt_val = ksopt->value;
839 sopt.sopt_valsize = valsize;
841 error = sosetopt(so, &sopt);
850 case NGM_KSOCKET_INTERNAL_COOKIE:
851 switch (msg->header.cmd) {
852 case NGM_KSOCKET_INTERNAL_UPCALL:
855 (*priv->so->so_upcall)(so, so->so_upcallarg, M_NOWAIT);
869 kfree(resp, M_NETGRAPH);
872 kfree(msg, M_NETGRAPH);
877 * Receive incoming data on our hook. Send it out the socket.
880 ng_ksocket_rcvdata(hook_p hook, struct mbuf *m, meta_p meta)
882 struct thread *td = curthread->td_proc ? curthread : &thread0; /* XXX broken */
883 const node_p node = hook->node;
884 const priv_p priv = node->private;
885 struct socket *const so = priv->so;
886 struct sockaddr *sa = NULL;
889 /* Avoid reentrantly sending on the socket */
890 if ((priv->flags & KSF_SENDING) != 0) {
891 NG_FREE_DATA(m, meta);
895 /* If any meta info, look for peer socket address */
897 struct meta_field_header *field;
899 /* Look for peer socket address */
900 for (field = &meta->options[0];
901 (caddr_t)field < (caddr_t)meta + meta->used_len;
902 field = (struct meta_field_header *)
903 ((caddr_t)field + field->len)) {
904 if (field->cookie != NGM_KSOCKET_COOKIE
905 || field->type != NG_KSOCKET_META_SOCKADDR)
907 sa = (struct sockaddr *)field->data;
913 priv->flags |= KSF_SENDING;
914 error = so_pru_sosend(so, sa, NULL, m, NULL, 0, td);
915 priv->flags &= ~KSF_SENDING;
917 /* Clean up and exit */
926 ng_ksocket_rmnode(node_p node)
928 const priv_p priv = node->private;
931 /* Close our socket (if any) */
932 if (priv->so != NULL) {
933 priv->so->so_upcall = NULL;
934 atomic_clear_int(&priv->so->so_rcv.ssb_flags, SSB_UPCALL);
935 atomic_clear_int(&priv->so->so_snd.ssb_flags, SSB_UPCALL);
936 soclose(priv->so, FNONBLOCK);
940 /* If we are an embryo, take ourselves out of the parent's list */
941 if (priv->flags & KSF_EMBRYONIC) {
942 LIST_REMOVE(priv, siblings);
943 priv->flags &= ~KSF_EMBRYONIC;
946 /* Remove any embryonic children we have */
947 while (!LIST_EMPTY(&priv->embryos)) {
948 embryo = LIST_FIRST(&priv->embryos);
949 ng_rmnode(embryo->node);
952 /* Take down netgraph node */
953 node->flags |= NG_INVALID;
956 bzero(priv, sizeof(*priv));
957 kfree(priv, M_NETGRAPH);
958 node->private = NULL;
959 ng_unref(node); /* let the node escape */
967 ng_ksocket_disconnect(hook_p hook)
969 KASSERT(hook->node->numhooks == 0,
970 ("%s: numhooks=%d?", __func__, hook->node->numhooks));
971 ng_rmnode(hook->node);
975 /************************************************************************
977 ************************************************************************/
980 * When incoming data is appended to the socket, we get notified here.
981 * This is also called whenever a significant event occurs for the socket.
984 ng_ksocket_incoming(struct socket *so, void *arg, int waitflag)
986 const node_p node = arg;
987 const priv_p priv = node->private;
988 struct ng_mesg *response;
994 if ((node->flags & NG_INVALID) != 0) {
998 KASSERT(so == priv->so, ("%s: wrong socket", __func__));
1000 /* Check whether a pending connect operation has completed */
1001 if (priv->flags & KSF_CONNECTING) {
1002 if ((error = so->so_error) != 0) {
1004 soclrstate(so, SS_ISCONNECTING);
1006 if (!(so->so_state & SS_ISCONNECTING)) {
1007 NG_MKMESSAGE(response, NGM_KSOCKET_COOKIE,
1008 NGM_KSOCKET_CONNECT, sizeof(int32_t), waitflag);
1009 if (response != NULL) {
1010 response->header.flags |= NGF_RESP;
1011 response->header.token = priv->response_token;
1012 *(int32_t *)response->data = error;
1014 * XXX We use ng_queue_msg here because we are
1015 * being called from deep in the bowels of the TCP
1016 * stack. Is this right, or should we let the
1017 * receiver of the message worry about that?
1019 ng_queue_msg(node, response,
1020 priv->response_addr);
1022 priv->flags &= ~KSF_CONNECTING;
1026 /* Check whether a pending accept operation has completed */
1027 if (priv->flags & KSF_ACCEPTING) {
1028 error = ng_ksocket_check_accept(priv);
1029 if (error != EWOULDBLOCK)
1030 priv->flags &= ~KSF_ACCEPTING;
1032 ng_ksocket_finish_accept(priv, NULL);
1036 * If we don't have a hook, we must handle data events later. When
1037 * the hook gets created and is connected, this upcall function
1038 * will be called again.
1040 if (priv->hook == NULL) {
1045 /* Read and forward available mbuf's */
1047 struct sockaddr *sa = NULL;
1053 sbinit(&sio, 1000000000);
1054 flags = MSG_DONTWAIT;
1056 /* Try to get next packet from socket */
1057 error = so_pru_soreceive(so,
1058 ((so->so_state & SS_ISCONNECTED) ? NULL : &sa),
1059 NULL, &sio, NULL, &flags);
1063 /* See if we got anything */
1064 if (sio.sb_mb == NULL) {
1066 kfree(sa, M_SONAME);
1070 /* Don't trust the various socket layers to get the
1071 packet header and length correct (eg. kern/15175) */
1072 sio.sb_mb->m_pkthdr.len = 0;
1073 for (n = sio.sb_mb; n != NULL; n = n->m_next)
1074 sio.sb_mb->m_pkthdr.len += n->m_len;
1076 /* Put peer's socket address (if any) into a meta info blob */
1078 struct meta_field_header *mhead;
1081 len = sizeof(*meta) + sizeof(*mhead) + sa->sa_len;
1082 meta = kmalloc(len, M_NETGRAPH, M_NOWAIT);
1084 kfree(sa, M_SONAME);
1087 mhead = &meta->options[0];
1088 bzero(meta, sizeof(*meta));
1089 bzero(mhead, sizeof(*mhead));
1090 meta->allocated_len = len;
1091 meta->used_len = len;
1092 mhead->cookie = NGM_KSOCKET_COOKIE;
1093 mhead->type = NG_KSOCKET_META_SOCKADDR;
1094 mhead->len = sizeof(*mhead) + sa->sa_len;
1095 bcopy(sa, mhead->data, sa->sa_len);
1096 kfree(sa, M_SONAME);
1098 sendit: /* Forward data with optional peer sockaddr as meta info */
1099 NG_SEND_DATA(error, priv->hook, sio.sb_mb, meta);
1103 * If the peer has closed the connection, forward a 0-length mbuf
1104 * to indicate end-of-file.
1106 if (so->so_state & SS_CANTRCVMORE && !(priv->flags & KSF_EOFSEEN)) {
1109 MGETHDR(m, waitflag, MT_DATA);
1111 m->m_len = m->m_pkthdr.len = 0;
1112 NG_SEND_DATA_ONLY(error, priv->hook, m);
1114 priv->flags |= KSF_EOFSEEN;
1121 * Check for a completed incoming connection and return 0 if one is found.
1122 * Otherwise return the appropriate error code.
1125 ng_ksocket_check_accept(priv_p priv)
1127 struct socket *const head = priv->so;
1130 lwkt_gettoken(&head->so_rcv.ssb_token);
1131 if ((error = head->so_error) != 0) {
1133 lwkt_reltoken(&head->so_rcv.ssb_token);
1136 if (TAILQ_EMPTY(&head->so_comp)) {
1137 if (head->so_state & SS_CANTRCVMORE)
1138 error = ECONNABORTED;
1140 error = EWOULDBLOCK;
1142 lwkt_reltoken(&head->so_rcv.ssb_token);
1147 * Handle the first completed incoming connection, assumed to be already
1148 * on the socket's so_comp queue.
1151 ng_ksocket_finish_accept(priv_p priv, struct ng_mesg **rptr)
1153 struct socket *const head = priv->so;
1155 struct sockaddr *sa = NULL;
1156 struct ng_mesg *resp;
1157 struct ng_ksocket_accept *resp_data;
1162 lwkt_getpooltoken(head);
1163 so = TAILQ_FIRST(&head->so_comp);
1164 if (so == NULL) { /* Should never happen */
1165 lwkt_relpooltoken(head);
1168 TAILQ_REMOVE(&head->so_comp, so, so_list);
1170 soclrstate(so, SS_COMP);
1174 lwkt_relpooltoken(head);
1176 /* XXX KNOTE(&head->so_rcv.ssb_sel.si_note, 0); */
1180 len = OFFSETOF(struct ng_ksocket_accept, addr);
1184 NG_MKMESSAGE(resp, NGM_KSOCKET_COOKIE, NGM_KSOCKET_ACCEPT, len,
1187 soclose(so, FNONBLOCK);
1190 resp->header.flags |= NGF_RESP;
1191 resp->header.token = priv->response_token;
1193 /* Clone a ksocket node to wrap the new socket */
1194 if (ng_ksocket_constructor(&node2) != 0) {
1195 kfree(resp, M_NETGRAPH);
1196 soclose(so, FNONBLOCK);
1199 priv2 = (priv_p)node2->private;
1201 priv2->flags |= KSF_CLONED | KSF_EMBRYONIC;
1204 * Insert the cloned node into a list of embryonic children
1205 * on the parent node. When a hook is created on the cloned
1206 * node it will be removed from this list. When the parent
1207 * is destroyed it will destroy any embryonic children it has.
1209 LIST_INSERT_HEAD(&priv->embryos, priv2, siblings);
1211 so->so_upcallarg = (caddr_t)node2;
1212 so->so_upcall = ng_ksocket_incoming;
1213 atomic_set_int(&so->so_rcv.ssb_flags, SSB_UPCALL);
1214 atomic_set_int(&so->so_snd.ssb_flags, SSB_UPCALL);
1216 /* Fill in the response data and send it or return it to the caller */
1217 resp_data = (struct ng_ksocket_accept *)resp->data;
1218 resp_data->nodeid = node2->ID;
1220 bcopy(sa, &resp_data->addr, sa->sa_len);
1224 ng_queue_msg(priv->node, resp, priv->response_addr);
1228 kfree(sa, M_SONAME);
1232 * Parse out either an integer value or an alias.
1235 ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
1236 const char *s, int family)
1242 for (k = 0; aliases[k].name != NULL; k++) {
1243 if (strcmp(s, aliases[k].name) == 0
1244 && aliases[k].family == family)
1245 return aliases[k].value;
1248 /* Try parsing as a number */
1249 val = (int)strtoul(s, &eptr, 10);
1250 if (val < 0 || *eptr != '\0')