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/socketops.h>
60 #include <sys/socketvar.h>
61 #include <sys/socketvar2.h>
62 #include <sys/thread2.h>
66 #include <netgraph7/ng_message.h>
67 #include <netgraph7/netgraph.h>
68 #include <netgraph7/ng_parse.h>
69 #include "ng_ksocket.h"
71 #include <netinet/in.h>
73 #ifdef NG_SEPARATE_MALLOC
74 MALLOC_DEFINE(M_NETGRAPH_KSOCKET, "netgraph_ksock", "netgraph ksock node ");
76 #define M_NETGRAPH_KSOCKET M_NETGRAPH
79 #define OFFSETOF(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
80 #define SADATA_OFFSET (OFFSETOF(struct sockaddr, sa_data))
82 /* Node private data */
83 struct ng_ksocket_private {
87 int fn_sent; /* FN call on incoming event was sent */
88 LIST_HEAD(, ng_ksocket_private) embryos;
89 LIST_ENTRY(ng_ksocket_private) siblings;
91 u_int32_t response_token;
92 ng_ID_t response_addr;
94 typedef struct ng_ksocket_private *priv_p;
96 /* Flags for priv_p */
97 #define KSF_CONNECTING 0x00000001 /* Waiting for connection complete */
98 #define KSF_ACCEPTING 0x00000002 /* Waiting for accept complete */
99 #define KSF_EOFSEEN 0x00000004 /* Have sent 0-length EOF mbuf */
100 #define KSF_CLONED 0x00000008 /* Cloned from an accepting socket */
101 #define KSF_EMBRYONIC 0x00000010 /* Cloned node with no hooks yet */
103 /* Netgraph node methods */
104 static ng_constructor_t ng_ksocket_constructor;
105 static ng_rcvmsg_t ng_ksocket_rcvmsg;
106 static ng_shutdown_t ng_ksocket_shutdown;
107 static ng_newhook_t ng_ksocket_newhook;
108 static ng_rcvdata_t ng_ksocket_rcvdata;
109 static ng_connect_t ng_ksocket_connect;
110 static ng_disconnect_t ng_ksocket_disconnect;
112 /* Alias structure */
113 struct ng_ksocket_alias {
119 /* Protocol family aliases */
120 static const struct ng_ksocket_alias ng_ksocket_families[] = {
121 { "local", PF_LOCAL },
123 { "inet6", PF_INET6 },
129 /* Socket type aliases */
130 static const struct ng_ksocket_alias ng_ksocket_types[] = {
131 { "stream", SOCK_STREAM },
132 { "dgram", SOCK_DGRAM },
135 { "seqpacket", SOCK_SEQPACKET },
139 /* Protocol aliases */
140 static const struct ng_ksocket_alias ng_ksocket_protos[] = {
141 { "ip", IPPROTO_IP, PF_INET },
142 { "raw", IPPROTO_RAW, PF_INET },
143 { "icmp", IPPROTO_ICMP, PF_INET },
144 { "igmp", IPPROTO_IGMP, PF_INET },
145 { "tcp", IPPROTO_TCP, PF_INET },
146 { "udp", IPPROTO_UDP, PF_INET },
147 { "gre", IPPROTO_GRE, PF_INET },
148 { "esp", IPPROTO_ESP, PF_INET },
149 { "ah", IPPROTO_AH, PF_INET },
150 { "swipe", IPPROTO_SWIPE, PF_INET },
151 { "encap", IPPROTO_ENCAP, PF_INET },
152 { "divert", IPPROTO_DIVERT, PF_INET },
153 { "pim", IPPROTO_PIM, PF_INET },
157 /* Helper functions */
158 static int ng_ksocket_check_accept(priv_p);
159 static void ng_ksocket_finish_accept(priv_p);
160 static void ng_ksocket_incoming(struct socket *so, void *arg, int waitflag);
161 static int ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
162 const char *s, int family);
163 static void ng_ksocket_incoming2(node_p node, hook_p hook,
164 void *arg1, int arg2);
166 /************************************************************************
167 STRUCT SOCKADDR PARSE TYPE
168 ************************************************************************/
170 /* Get the length of the data portion of a generic struct sockaddr */
172 ng_parse_generic_sockdata_getLength(const struct ng_parse_type *type,
173 const u_char *start, const u_char *buf)
175 const struct sockaddr *sa;
177 sa = (const struct sockaddr *)(buf - SADATA_OFFSET);
178 return (sa->sa_len < SADATA_OFFSET) ? 0 : sa->sa_len - SADATA_OFFSET;
181 /* Type for the variable length data portion of a generic struct sockaddr */
182 static const struct ng_parse_type ng_ksocket_generic_sockdata_type = {
183 &ng_parse_bytearray_type,
184 &ng_parse_generic_sockdata_getLength
187 /* Type for a generic struct sockaddr */
188 static const struct ng_parse_struct_field
189 ng_parse_generic_sockaddr_type_fields[] = {
190 { "len", &ng_parse_uint8_type },
191 { "family", &ng_parse_uint8_type },
192 { "data", &ng_ksocket_generic_sockdata_type },
195 static const struct ng_parse_type ng_ksocket_generic_sockaddr_type = {
196 &ng_parse_struct_type,
197 &ng_parse_generic_sockaddr_type_fields
200 /* Convert a struct sockaddr from ASCII to binary. If its a protocol
201 family that we specially handle, do that, otherwise defer to the
202 generic parse type ng_ksocket_generic_sockaddr_type. */
204 ng_ksocket_sockaddr_parse(const struct ng_parse_type *type,
205 const char *s, int *off, const u_char *const start,
206 u_char *const buf, int *buflen)
208 struct sockaddr *const sa = (struct sockaddr *)buf;
209 enum ng_parse_token tok;
214 /* If next token is a left curly brace, use generic parse type */
215 if ((tok = ng_parse_get_token(s, off, &len)) == T_LBRACE) {
216 return (*ng_ksocket_generic_sockaddr_type.supertype->parse)
217 (&ng_ksocket_generic_sockaddr_type,
218 s, off, start, buf, buflen);
221 /* Get socket address family followed by a slash */
222 while (isspace(s[*off]))
224 if ((t = index(s + *off, '/')) == NULL)
226 if ((len = t - (s + *off)) > sizeof(fambuf) - 1)
228 strncpy(fambuf, s + *off, len);
231 if ((family = ng_ksocket_parse(ng_ksocket_families, fambuf, 0)) == -1)
235 if (*buflen < SADATA_OFFSET)
237 sa->sa_family = family;
239 /* Set family-specific data and length */
240 switch (sa->sa_family) {
241 case PF_LOCAL: /* Get pathname */
243 const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
244 struct sockaddr_un *const sun = (struct sockaddr_un *)sa;
248 if ((path = ng_get_string_token(s, off, &toklen, NULL)) == NULL)
250 pathlen = strlen(path);
251 if (pathlen > SOCK_MAXADDRLEN) {
252 kfree(path, M_NETGRAPH_KSOCKET);
255 if (*buflen < pathoff + pathlen) {
256 kfree(path, M_NETGRAPH_KSOCKET);
260 bcopy(path, sun->sun_path, pathlen);
261 sun->sun_len = pathoff + pathlen;
262 kfree(path, M_NETGRAPH_KSOCKET);
266 case PF_INET: /* Get an IP address with optional port */
268 struct sockaddr_in *const sin = (struct sockaddr_in *)sa;
271 /* Parse this: <ipaddress>[:port] */
272 for (i = 0; i < 4; i++) {
276 val = strtoul(s + *off, &eptr, 10);
277 if (val > 0xff || eptr == s + *off)
279 *off += (eptr - (s + *off));
280 ((u_char *)&sin->sin_addr)[i] = (u_char)val;
285 } else if (s[*off] == ':') {
287 val = strtoul(s + *off, &eptr, 10);
288 if (val > 0xffff || eptr == s + *off)
290 *off += (eptr - (s + *off));
291 sin->sin_port = htons(val);
295 bzero(&sin->sin_zero, sizeof(sin->sin_zero));
296 sin->sin_len = sizeof(*sin);
310 *buflen = sa->sa_len;
314 /* Convert a struct sockaddr from binary to ASCII */
316 ng_ksocket_sockaddr_unparse(const struct ng_parse_type *type,
317 const u_char *data, int *off, char *cbuf, int cbuflen)
319 const struct sockaddr *sa = (const struct sockaddr *)(data + *off);
322 /* Output socket address, either in special or generic format */
323 switch (sa->sa_family) {
326 const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
327 const struct sockaddr_un *sun = (const struct sockaddr_un *)sa;
328 const int pathlen = sun->sun_len - pathoff;
329 char pathbuf[SOCK_MAXADDRLEN + 1];
332 bcopy(sun->sun_path, pathbuf, pathlen);
333 if ((pathtoken = ng_encode_string(pathbuf, pathlen)) == NULL)
335 slen += ksnprintf(cbuf, cbuflen, "local/%s", pathtoken);
336 kfree(pathtoken, M_NETGRAPH_KSOCKET);
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
491 /* Node type descriptor */
492 static struct ng_type ng_ksocket_typestruct = {
493 .version = NG_ABI_VERSION,
494 .name = NG_KSOCKET_NODE_TYPE,
495 .constructor = ng_ksocket_constructor,
496 .rcvmsg = ng_ksocket_rcvmsg,
497 .shutdown = ng_ksocket_shutdown,
498 .newhook = ng_ksocket_newhook,
499 .connect = ng_ksocket_connect,
500 .rcvdata = ng_ksocket_rcvdata,
501 .disconnect = ng_ksocket_disconnect,
502 .cmdlist = ng_ksocket_cmds,
504 NETGRAPH_INIT(ksocket, &ng_ksocket_typestruct);
506 #define ERROUT(x) do { error = (x); goto done; } while (0)
508 /************************************************************************
510 ************************************************************************/
513 * Node type constructor
514 * The NODE part is assumed to be all set up.
515 * There is already a reference to the node for us.
518 ng_ksocket_constructor(node_p node)
522 /* Allocate private structure */
523 priv = kmalloc(sizeof(*priv), M_NETGRAPH,
524 M_WAITOK | M_NULLOK | M_ZERO);
528 LIST_INIT(&priv->embryos);
529 /* cross link them */
531 NG_NODE_SET_PRIVATE(node, priv);
538 * Give our OK for a hook to be added. The hook name is of the
539 * form "<family>/<type>/<proto>" where the three components may
540 * be decimal numbers or else aliases from the above lists.
542 * Connecting a hook amounts to opening the socket. Disconnecting
543 * the hook closes the socket and destroys the node as well.
546 ng_ksocket_newhook(node_p node, hook_p hook, const char *name0)
548 struct thread *td = curthread->td_proc ? curthread : &thread0; /* XXX broken */
549 const priv_p priv = NG_NODE_PRIVATE(node);
550 char *s1, *s2, name[NG_HOOKSIZ];
551 int family, type, protocol, error;
553 /* Check if we're already connected */
554 if (priv->hook != NULL)
557 if (priv->flags & KSF_CLONED) {
558 if (priv->flags & KSF_EMBRYONIC) {
559 /* Remove ourselves from our parent's embryo list */
560 LIST_REMOVE(priv, siblings);
561 priv->flags &= ~KSF_EMBRYONIC;
564 /* Extract family, type, and protocol from hook name */
565 ksnprintf(name, sizeof(name), "%s", name0);
567 if ((s2 = index(s1, '/')) == NULL)
570 family = ng_ksocket_parse(ng_ksocket_families, s1, 0);
574 if ((s2 = index(s1, '/')) == NULL)
577 type = ng_ksocket_parse(ng_ksocket_types, s1, 0);
581 protocol = ng_ksocket_parse(ng_ksocket_protos, s1, family);
585 /* Create the socket */
586 error = socreate(family, &priv->so, type, protocol, td);
590 /* XXX call soreserve() ? */
598 * In case of misconfigured routing a packet may reenter
599 * ksocket node recursively. Decouple stack to avoid possible
600 * panics about sleeping with locks held.
602 NG_HOOK_FORCE_QUEUE(hook);
608 ng_ksocket_connect(hook_p hook)
610 node_p node = NG_HOOK_NODE(hook);
611 const priv_p priv = NG_NODE_PRIVATE(node);
612 struct socket *const so = priv->so;
614 /* Add our hook for incoming data and other events */
615 priv->so->so_upcallarg = (caddr_t)node;
616 priv->so->so_upcall = ng_ksocket_incoming;
617 atomic_set_int(&priv->so->so_rcv.ssb_flags, SSB_UPCALL);
618 atomic_set_int(&priv->so->so_snd.ssb_flags, SSB_UPCALL);
620 * --Original comment--
621 * On a cloned socket we may have already received one or more
622 * upcalls which we couldn't handle without a hook. Handle
624 * We cannot call the upcall function directly
625 * from here, because until this function has returned our
626 * hook isn't connected.
628 * ---meta comment for -current ---
629 * XXX This is dubius.
630 * Upcalls between the time that the hook was
631 * first created and now (on another processesor) will
632 * be earlier on the queue than the request to finalise the hook.
633 * By the time the hook is finalised,
634 * The queued upcalls will have happenned and the code
635 * will have discarded them because of a lack of a hook.
638 * This is a bad byproduct of the complicated way in which hooks
639 * are now created (3 daisy chained async events).
641 * Since we are a netgraph operation
642 * We know that we hold a lock on this node. This forces the
643 * request we make below to be queued rather than implemented
644 * immediatly which will cause the upcall function to be called a bit
646 * However, as we will run any waiting queued operations immediatly
647 * after doing this one, if we have not finalised the other end
648 * of the hook, those queued operations will fail.
650 if (priv->flags & KSF_CLONED) {
651 ng_send_fn(node, NULL, &ng_ksocket_incoming2, so, M_WAITOK | M_NULLOK);
658 * Receive a control message
661 ng_ksocket_rcvmsg(node_p node, item_p item, hook_p lasthook)
663 struct thread *td = curthread->td_proc ? curthread : &thread0; /* XXX broken */
664 const priv_p priv = NG_NODE_PRIVATE(node);
665 struct socket *const so = priv->so;
666 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 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)
718 error = ng_ksocket_check_accept(priv);
719 if (error != 0 && error != EWOULDBLOCK)
723 * If a connection is already complete, take it.
724 * Otherwise let the upcall function deal with
725 * the connection when it comes in.
727 priv->response_token = msg->header.token;
728 raddr = priv->response_addr = NGI_RETADDR(item);
730 ng_ksocket_finish_accept(priv);
732 priv->flags |= KSF_ACCEPTING;
736 case NGM_KSOCKET_CONNECT:
738 struct sockaddr *const sa
739 = (struct sockaddr *)msg->data;
742 if (msg->header.arglen < SADATA_OFFSET
743 || msg->header.arglen < sa->sa_len)
749 if ((so->so_state & SS_ISCONNECTING) != 0)
751 if ((error = soconnect(so, sa, td)) != 0) {
752 soclrstate(so, SS_ISCONNECTING);
755 if ((so->so_state & SS_ISCONNECTING) != 0) {
756 /* We will notify the sender when we connect */
757 priv->response_token = msg->header.token;
758 raddr = priv->response_addr = NGI_RETADDR(item);
759 priv->flags |= KSF_CONNECTING;
765 case NGM_KSOCKET_GETNAME:
766 case NGM_KSOCKET_GETPEERNAME:
768 struct sockaddr *sa = NULL;
772 if (msg->header.arglen != 0)
778 if (msg->header.cmd == NGM_KSOCKET_GETPEERNAME) {
780 & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0)
782 error = so_pru_peeraddr(so, &sa);
784 error = so_pru_sockaddr(so, &sa);
787 /* Get local or peer address */
790 len = (sa == NULL) ? 0 : sa->sa_len;
792 /* Send it back in a response */
793 NG_MKRESPONSE(resp, msg, len, M_WAITOK | M_NULLOK);
798 bcopy(sa, resp->data, len);
807 case NGM_KSOCKET_GETOPT:
809 struct ng_ksocket_sockopt *ksopt =
810 (struct ng_ksocket_sockopt *)msg->data;
814 if (msg->header.arglen != sizeof(*ksopt))
819 /* Get response with room for option value */
820 NG_MKRESPONSE(resp, msg, sizeof(*ksopt)
821 + NG_KSOCKET_MAX_OPTLEN, M_WAITOK | M_NULLOK);
825 /* Get socket option, and put value in the response */
826 sopt.sopt_dir = SOPT_GET;
827 sopt.sopt_level = ksopt->level;
828 sopt.sopt_name = ksopt->name;
830 sopt.sopt_valsize = NG_KSOCKET_MAX_OPTLEN;
831 ksopt = (struct ng_ksocket_sockopt *)resp->data;
832 sopt.sopt_val = ksopt->value;
833 if ((error = sogetopt(so, &sopt)) != 0) {
838 /* Set actual value length */
839 resp->header.arglen = sizeof(*ksopt)
844 case NGM_KSOCKET_SETOPT:
846 struct ng_ksocket_sockopt *const ksopt =
847 (struct ng_ksocket_sockopt *)msg->data;
848 const int valsize = msg->header.arglen - sizeof(*ksopt);
857 /* Set socket option */
858 sopt.sopt_dir = SOPT_SET;
859 sopt.sopt_level = ksopt->level;
860 sopt.sopt_name = ksopt->name;
861 sopt.sopt_val = ksopt->value;
862 sopt.sopt_valsize = valsize;
864 error = sosetopt(so, &sopt);
878 NG_RESPOND_MSG(error, node, item, resp);
884 * Receive incoming data on our hook. Send it out the socket.
887 ng_ksocket_rcvdata(hook_p hook, item_p item)
889 struct thread *td = curthread->td_proc ? curthread : &thread0; /* XXX broken */
890 const node_p node = NG_HOOK_NODE(hook);
891 const priv_p priv = NG_NODE_PRIVATE(node);
892 struct socket *const so = priv->so;
893 struct sockaddr *sa = NULL;
903 * Look if socket address is stored in packet tags.
904 * If sockaddr is ours, or provided by a third party (zero id),
907 if (((stag = (struct sa_tag *)m_tag_locate(m, NGM_KSOCKET_COOKIE,
908 NG_KSOCKET_TAG_SOCKADDR, NULL)) != NULL) &&
909 (stag->id == NG_NODE_ID(node) || stag->id == 0))
912 /* Reset specific mbuf flags to prevent addressing problems. */
913 m->m_flags &= ~(M_BCAST|M_MCAST);
916 error = sosend(so, sa, 0, m, 0, 0, td);
925 ng_ksocket_shutdown(node_p node)
927 const priv_p priv = NG_NODE_PRIVATE(node);
930 /* Close our socket (if any) */
931 if (priv->so != NULL) {
932 atomic_clear_int(&priv->so->so_rcv.ssb_flags, SSB_UPCALL);
933 atomic_clear_int(&priv->so->so_snd.ssb_flags, SSB_UPCALL);
934 priv->so->so_upcall = NULL;
935 soclose(priv->so, FNONBLOCK);
939 /* If we are an embryo, take ourselves out of the parent's list */
940 if (priv->flags & KSF_EMBRYONIC) {
941 LIST_REMOVE(priv, siblings);
942 priv->flags &= ~KSF_EMBRYONIC;
945 /* Remove any embryonic children we have */
946 while (!LIST_EMPTY(&priv->embryos)) {
947 embryo = LIST_FIRST(&priv->embryos);
948 ng_rmnode_self(embryo->node);
951 /* Take down netgraph node */
952 bzero(priv, sizeof(*priv));
953 kfree(priv, M_NETGRAPH);
954 NG_NODE_SET_PRIVATE(node, NULL);
955 NG_NODE_UNREF(node); /* let the node escape */
963 ng_ksocket_disconnect(hook_p hook)
965 KASSERT(NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0,
966 ("%s: numhooks=%d?", __func__,
967 NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook))));
968 if (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))
969 ng_rmnode_self(NG_HOOK_NODE(hook));
973 /************************************************************************
975 ************************************************************************/
977 * You should not "just call" a netgraph node function from an external
978 * asynchronous event. This is because in doing so you are ignoring the
979 * locking on the netgraph nodes. Instead call your function via ng_send_fn().
980 * This will call the function you chose, but will first do all the
981 * locking rigmarole. Your function MAY only be called at some distant future
982 * time (several millisecs away) so don't give it any arguments
983 * that may be revoked soon (e.g. on your stack).
985 * To decouple stack, we use queue version of ng_send_fn().
989 ng_ksocket_incoming(struct socket *so, void *arg, int waitflag)
991 const node_p node = arg;
992 const priv_p priv = NG_NODE_PRIVATE(node);
993 int wait = ((waitflag & M_WAITOK) ? NG_WAITOK : 0) | NG_QUEUE;
996 * Even if node is not locked, as soon as we are called, we assume
997 * it exist and it's private area is valid. With some care we can
998 * access it. Mark node that incoming event for it was sent to
999 * avoid unneded queue trashing.
1001 if (atomic_cmpset_int(&priv->fn_sent, 0, 1) &&
1002 ng_send_fn1(node, NULL, &ng_ksocket_incoming2, so, 0, wait)) {
1003 atomic_store_rel_int(&priv->fn_sent, 0);
1009 * When incoming data is appended to the socket, we get notified here.
1010 * This is also called whenever a significant event occurs for the socket.
1011 * Our original caller may have queued this even some time ago and
1012 * we cannot trust that he even still exists. The node however is being
1013 * held with a reference by the queueing code and guarantied to be valid.
1016 ng_ksocket_incoming2(node_p node, hook_p hook, void *arg1, int arg2)
1018 struct socket *so = arg1;
1019 const priv_p priv = NG_NODE_PRIVATE(node);
1020 struct ng_mesg *response;
1025 /* so = priv->so; *//* XXX could have derived this like so */
1026 KASSERT(so == priv->so, ("%s: wrong socket", __func__));
1028 /* Allow next incoming event to be queued. */
1029 atomic_store_rel_int(&priv->fn_sent, 0);
1031 /* Check whether a pending connect operation has completed */
1032 if (priv->flags & KSF_CONNECTING) {
1033 if ((error = so->so_error) != 0) {
1035 soclrstate(so, SS_ISCONNECTING);
1037 if (!(so->so_state & SS_ISCONNECTING)) {
1038 NG_MKMESSAGE(response, NGM_KSOCKET_COOKIE,
1039 NGM_KSOCKET_CONNECT, sizeof(int32_t), M_WAITOK | M_NULLOK);
1040 if (response != NULL) {
1041 response->header.flags |= NGF_RESP;
1042 response->header.token = priv->response_token;
1043 *(int32_t *)response->data = error;
1045 * send an async "response" message
1046 * to the node that set us up
1047 * (if it still exists)
1049 NG_SEND_MSG_ID(error, node,
1050 response, priv->response_addr, 0);
1052 priv->flags &= ~KSF_CONNECTING;
1056 /* Check whether a pending accept operation has completed */
1057 if (priv->flags & KSF_ACCEPTING) {
1058 error = ng_ksocket_check_accept(priv);
1059 if (error != EWOULDBLOCK)
1060 priv->flags &= ~KSF_ACCEPTING;
1062 ng_ksocket_finish_accept(priv);
1066 * If we don't have a hook, we must handle data events later. When
1067 * the hook gets created and is connected, this upcall function
1068 * will be called again.
1070 if (priv->hook == NULL) {
1075 /* Read and forward available mbuf's */
1077 struct sockaddr *sa = NULL;
1081 sbinit(&sio, 1000000000);
1082 flags = MSG_DONTWAIT;
1084 /* Try to get next packet from socket */
1085 error = soreceive(so,
1086 ((so->so_state & SS_ISCONNECTED) ? NULL : &sa),
1087 NULL, &sio, NULL, &flags);
1091 /* See if we got anything */
1092 if (sio.sb_mb == NULL) {
1094 kfree(sa, M_SONAME);
1099 * Don't trust the various socket layers to get the
1100 * packet header and length correct (e.g. kern/15175).
1102 * Also, do not trust that soreceive() will clear m_nextpkt
1103 * for us (e.g. kern/84952, kern/82413).
1105 sio.sb_mb->m_pkthdr.csum_flags = 0;
1106 sio.sb_mb->m_pkthdr.len = 0;
1107 for (n = sio.sb_mb; n != NULL; n = n->m_next) {
1108 sio.sb_mb->m_pkthdr.len += n->m_len;
1109 n->m_nextpkt = NULL;
1112 /* Put peer's socket address (if any) into a tag */
1114 struct sa_tag *stag;
1116 stag = (struct sa_tag *)m_tag_alloc(NGM_KSOCKET_COOKIE,
1117 NG_KSOCKET_TAG_SOCKADDR, sizeof(ng_ID_t) +
1118 sa->sa_len, MB_DONTWAIT);
1120 kfree(sa, M_SONAME);
1123 bcopy(sa, &stag->sa, sa->sa_len);
1124 kfree(sa, M_SONAME);
1125 stag->id = NG_NODE_ID(node);
1126 m_tag_prepend(sio.sb_mb, &stag->tag);
1129 sendit: /* Forward data with optional peer sockaddr as packet tag */
1130 NG_SEND_DATA_ONLY(error, priv->hook, sio.sb_mb);
1134 * If the peer has closed the connection, forward a 0-length mbuf
1135 * to indicate end-of-file.
1137 if (so->so_state & SS_CANTRCVMORE && !(priv->flags & KSF_EOFSEEN)) {
1140 MGETHDR(m, MB_DONTWAIT, MT_DATA);
1142 m->m_len = m->m_pkthdr.len = 0;
1143 NG_SEND_DATA_ONLY(error, priv->hook, m);
1145 priv->flags |= KSF_EOFSEEN;
1151 * Check for a completed incoming connection and return 0 if one is found.
1152 * Otherwise return the appropriate error code.
1155 ng_ksocket_check_accept(priv_p priv)
1157 struct socket *const head = priv->so;
1160 if ((error = head->so_error) != 0) {
1164 /* Unlocked read. */
1165 if (TAILQ_EMPTY(&head->so_comp)) {
1166 if (head->so_state & SS_CANTRCVMORE)
1167 return ECONNABORTED;
1174 * Handle the first completed incoming connection, assumed to be already
1175 * on the socket's so_comp queue.
1178 ng_ksocket_finish_accept(priv_p priv)
1180 struct socket *const head = priv->so;
1182 struct sockaddr *sa = NULL;
1183 struct ng_mesg *resp;
1184 struct ng_ksocket_accept *resp_data;
1190 lwkt_getpooltoken(head);
1191 so = TAILQ_FIRST(&head->so_comp);
1192 if (so == NULL) { /* Should never happen */
1193 lwkt_relpooltoken(head);
1196 TAILQ_REMOVE(&head->so_comp, so, so_list);
1198 soclrstate(so, SS_COMP);
1201 lwkt_relpooltoken(head);
1203 /* XXX KNOTE(&head->so_rcv.ssb_sel.si_note, 0); */
1207 len = OFFSETOF(struct ng_ksocket_accept, addr);
1211 NG_MKMESSAGE(resp, NGM_KSOCKET_COOKIE, NGM_KSOCKET_ACCEPT, len,
1212 M_WAITOK | M_NULLOK);
1214 soclose(so, FNONBLOCK);
1217 resp->header.flags |= NGF_RESP;
1218 resp->header.token = priv->response_token;
1220 /* Clone a ksocket node to wrap the new socket */
1221 error = ng_make_node_common(&ng_ksocket_typestruct, &node);
1223 kfree(resp, M_NETGRAPH);
1224 soclose(so, FNONBLOCK);
1228 if (ng_ksocket_constructor(node) != 0) {
1229 NG_NODE_UNREF(node);
1230 kfree(resp, M_NETGRAPH);
1231 soclose(so, FNONBLOCK);
1235 priv2 = NG_NODE_PRIVATE(node);
1237 priv2->flags |= KSF_CLONED | KSF_EMBRYONIC;
1240 * Insert the cloned node into a list of embryonic children
1241 * on the parent node. When a hook is created on the cloned
1242 * node it will be removed from this list. When the parent
1243 * is destroyed it will destroy any embryonic children it has.
1245 LIST_INSERT_HEAD(&priv->embryos, priv2, siblings);
1247 so->so_upcallarg = (caddr_t)node;
1248 so->so_upcall = ng_ksocket_incoming;
1249 atomic_set_int(&priv->so->so_rcv.ssb_flags, SSB_UPCALL);
1250 atomic_set_int(&priv->so->so_snd.ssb_flags, SSB_UPCALL);
1252 /* Fill in the response data and send it or return it to the caller */
1253 resp_data = (struct ng_ksocket_accept *)resp->data;
1254 resp_data->nodeid = NG_NODE_ID(node);
1256 bcopy(sa, &resp_data->addr, sa->sa_len);
1257 NG_SEND_MSG_ID(error, node, resp, priv->response_addr, 0);
1261 kfree(sa, M_SONAME);
1265 * Parse out either an integer value or an alias.
1268 ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
1269 const char *s, int family)
1275 for (k = 0; aliases[k].name != NULL; k++) {
1276 if (strcmp(s, aliases[k].name) == 0
1277 && aliases[k].family == family)
1278 return aliases[k].value;
1281 /* Try parsing as a number */
1282 val = (int)strtoul(s, &eptr, 10);
1283 if (val < 0 || *eptr != '\0')