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_incoming(struct socket *so, void *arg, int waitflag);
156 static int ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
157 const char *s, int family);
158 static void ng_ksocket_incoming2(node_p node, hook_p hook,
159 void *arg1, int arg2);
161 /************************************************************************
162 STRUCT SOCKADDR PARSE TYPE
163 ************************************************************************/
165 /* Get the length of the data portion of a generic struct sockaddr */
167 ng_parse_generic_sockdata_getLength(const struct ng_parse_type *type,
168 const u_char *start, const u_char *buf)
170 const struct sockaddr *sa;
172 sa = (const struct sockaddr *)(buf - SADATA_OFFSET);
173 return (sa->sa_len < SADATA_OFFSET) ? 0 : sa->sa_len - SADATA_OFFSET;
176 /* Type for the variable length data portion of a generic struct sockaddr */
177 static const struct ng_parse_type ng_ksocket_generic_sockdata_type = {
178 &ng_parse_bytearray_type,
179 &ng_parse_generic_sockdata_getLength
182 /* Type for a generic struct sockaddr */
183 static const struct ng_parse_struct_field
184 ng_parse_generic_sockaddr_type_fields[] = {
185 { "len", &ng_parse_uint8_type },
186 { "family", &ng_parse_uint8_type },
187 { "data", &ng_ksocket_generic_sockdata_type },
190 static const struct ng_parse_type ng_ksocket_generic_sockaddr_type = {
191 &ng_parse_struct_type,
192 &ng_parse_generic_sockaddr_type_fields
195 /* Convert a struct sockaddr from ASCII to binary. If its a protocol
196 family that we specially handle, do that, otherwise defer to the
197 generic parse type ng_ksocket_generic_sockaddr_type. */
199 ng_ksocket_sockaddr_parse(const struct ng_parse_type *type,
200 const char *s, int *off, const u_char *const start,
201 u_char *const buf, int *buflen)
203 struct sockaddr *const sa = (struct sockaddr *)buf;
204 enum ng_parse_token tok;
209 /* If next token is a left curly brace, use generic parse type */
210 if ((tok = ng_parse_get_token(s, off, &len)) == T_LBRACE) {
211 return (*ng_ksocket_generic_sockaddr_type.supertype->parse)
212 (&ng_ksocket_generic_sockaddr_type,
213 s, off, start, buf, buflen);
216 /* Get socket address family followed by a slash */
217 while (isspace(s[*off]))
219 if ((t = strchr(s + *off, '/')) == NULL)
221 if ((len = t - (s + *off)) > sizeof(fambuf) - 1)
223 strncpy(fambuf, s + *off, len);
226 if ((family = ng_ksocket_parse(ng_ksocket_families, fambuf, 0)) == -1)
230 if (*buflen < SADATA_OFFSET)
232 sa->sa_family = family;
234 /* Set family-specific data and length */
235 switch (sa->sa_family) {
236 case PF_LOCAL: /* Get pathname */
238 const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
239 struct sockaddr_un *const sun = (struct sockaddr_un *)sa;
243 if ((path = ng_get_string_token(s, off, &toklen, NULL)) == NULL)
245 pathlen = strlen(path);
246 if (pathlen > SOCK_MAXADDRLEN) {
247 free(path, M_NETGRAPH_KSOCKET);
250 if (*buflen < pathoff + pathlen) {
251 free(path, M_NETGRAPH_KSOCKET);
255 bcopy(path, sun->sun_path, pathlen);
256 sun->sun_len = pathoff + pathlen;
257 free(path, M_NETGRAPH_KSOCKET);
261 case PF_INET: /* Get an IP address with optional port */
263 struct sockaddr_in *const sin = (struct sockaddr_in *)sa;
266 /* Parse this: <ipaddress>[:port] */
267 for (i = 0; i < 4; i++) {
271 val = strtoul(s + *off, &eptr, 10);
272 if (val > 0xff || eptr == s + *off)
274 *off += (eptr - (s + *off));
275 ((u_char *)&sin->sin_addr)[i] = (u_char)val;
280 } else if (s[*off] == ':') {
282 val = strtoul(s + *off, &eptr, 10);
283 if (val > 0xffff || eptr == s + *off)
285 *off += (eptr - (s + *off));
286 sin->sin_port = htons(val);
290 bzero(&sin->sin_zero, sizeof(sin->sin_zero));
291 sin->sin_len = sizeof(*sin);
296 case PF_INET6: /* XXX implement this someday */
304 *buflen = sa->sa_len;
308 /* Convert a struct sockaddr from binary to ASCII */
310 ng_ksocket_sockaddr_unparse(const struct ng_parse_type *type,
311 const u_char *data, int *off, char *cbuf, int cbuflen)
313 const struct sockaddr *sa = (const struct sockaddr *)(data + *off);
316 /* Output socket address, either in special or generic format */
317 switch (sa->sa_family) {
320 const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
321 const struct sockaddr_un *sun = (const struct sockaddr_un *)sa;
322 const int pathlen = sun->sun_len - pathoff;
323 char pathbuf[SOCK_MAXADDRLEN + 1];
326 bcopy(sun->sun_path, pathbuf, pathlen);
327 if ((pathtoken = ng_encode_string(pathbuf, pathlen)) == NULL)
329 slen += snprintf(cbuf, cbuflen, "local/%s", pathtoken);
330 free(pathtoken, M_NETGRAPH_KSOCKET);
333 *off += sun->sun_len;
339 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
341 slen += snprintf(cbuf, cbuflen, "inet/%d.%d.%d.%d",
342 ((const u_char *)&sin->sin_addr)[0],
343 ((const u_char *)&sin->sin_addr)[1],
344 ((const u_char *)&sin->sin_addr)[2],
345 ((const u_char *)&sin->sin_addr)[3]);
346 if (sin->sin_port != 0) {
347 slen += snprintf(cbuf + strlen(cbuf),
348 cbuflen - strlen(cbuf), ":%d",
349 (u_int)ntohs(sin->sin_port));
353 *off += sizeof(*sin);
358 case PF_INET6: /* XXX implement this someday */
362 return (*ng_ksocket_generic_sockaddr_type.supertype->unparse)
363 (&ng_ksocket_generic_sockaddr_type,
364 data, off, cbuf, cbuflen);
368 /* Parse type for struct sockaddr */
369 static const struct ng_parse_type ng_ksocket_sockaddr_type = {
373 &ng_ksocket_sockaddr_parse,
374 &ng_ksocket_sockaddr_unparse,
375 NULL /* no such thing as a default struct sockaddr */
378 /************************************************************************
379 STRUCT NG_KSOCKET_SOCKOPT PARSE TYPE
380 ************************************************************************/
382 /* Get length of the struct ng_ksocket_sockopt value field, which is the
383 just the excess of the message argument portion over the length of
384 the struct ng_ksocket_sockopt. */
386 ng_parse_sockoptval_getLength(const struct ng_parse_type *type,
387 const u_char *start, const u_char *buf)
389 static const int offset = OFFSETOF(struct ng_ksocket_sockopt, value);
390 const struct ng_ksocket_sockopt *sopt;
391 const struct ng_mesg *msg;
393 sopt = (const struct ng_ksocket_sockopt *)(buf - offset);
394 msg = (const struct ng_mesg *)((const u_char *)sopt - sizeof(*msg));
395 return msg->header.arglen - sizeof(*sopt);
398 /* Parse type for the option value part of a struct ng_ksocket_sockopt
399 XXX Eventually, we should handle the different socket options specially.
400 XXX This would avoid byte order problems, eg an integer value of 1 is
401 XXX going to be "[1]" for little endian or "[3=1]" for big endian. */
402 static const struct ng_parse_type ng_ksocket_sockoptval_type = {
403 &ng_parse_bytearray_type,
404 &ng_parse_sockoptval_getLength
407 /* Parse type for struct ng_ksocket_sockopt */
408 static const struct ng_parse_struct_field ng_ksocket_sockopt_type_fields[]
409 = NG_KSOCKET_SOCKOPT_INFO(&ng_ksocket_sockoptval_type);
410 static const struct ng_parse_type ng_ksocket_sockopt_type = {
411 &ng_parse_struct_type,
412 &ng_ksocket_sockopt_type_fields
415 /* Parse type for struct ng_ksocket_accept */
416 static const struct ng_parse_struct_field ng_ksocket_accept_type_fields[]
417 = NGM_KSOCKET_ACCEPT_INFO;
418 static const struct ng_parse_type ng_ksocket_accept_type = {
419 &ng_parse_struct_type,
420 &ng_ksocket_accept_type_fields
423 /* List of commands and how to convert arguments to/from ASCII */
424 static const struct ng_cmdlist ng_ksocket_cmds[] = {
429 &ng_ksocket_sockaddr_type,
436 &ng_parse_int32_type,
444 &ng_ksocket_accept_type
450 &ng_ksocket_sockaddr_type,
458 &ng_ksocket_sockaddr_type
462 NGM_KSOCKET_GETPEERNAME,
465 &ng_ksocket_sockaddr_type
471 &ng_ksocket_sockopt_type,
478 &ng_ksocket_sockopt_type,
479 &ng_ksocket_sockopt_type
484 /* Node type descriptor */
485 static struct ng_type ng_ksocket_typestruct = {
486 .version = NG_ABI_VERSION,
487 .name = NG_KSOCKET_NODE_TYPE,
488 .constructor = ng_ksocket_constructor,
489 .rcvmsg = ng_ksocket_rcvmsg,
490 .shutdown = ng_ksocket_shutdown,
491 .newhook = ng_ksocket_newhook,
492 .connect = ng_ksocket_connect,
493 .rcvdata = ng_ksocket_rcvdata,
494 .disconnect = ng_ksocket_disconnect,
495 .cmdlist = ng_ksocket_cmds,
497 NETGRAPH_INIT(ksocket, &ng_ksocket_typestruct);
499 #define ERROUT(x) do { error = (x); goto done; } while (0)
501 /************************************************************************
503 ************************************************************************/
506 * Node type constructor
507 * The NODE part is assumed to be all set up.
508 * There is already a reference to the node for us.
511 ng_ksocket_constructor(node_p node)
515 /* Allocate private structure */
516 priv = malloc(sizeof(*priv), M_NETGRAPH_KSOCKET, M_NOWAIT | M_ZERO);
520 LIST_INIT(&priv->embryos);
521 /* cross link them */
523 NG_NODE_SET_PRIVATE(node, priv);
530 * Give our OK for a hook to be added. The hook name is of the
531 * form "<family>/<type>/<proto>" where the three components may
532 * be decimal numbers or else aliases from the above lists.
534 * Connecting a hook amounts to opening the socket. Disconnecting
535 * the hook closes the socket and destroys the node as well.
538 ng_ksocket_newhook(node_p node, hook_p hook, const char *name0)
540 struct thread *td = curthread; /* XXX broken */
541 const priv_p priv = NG_NODE_PRIVATE(node);
542 char *s1, *s2, name[NG_HOOKSIZ];
543 int family, type, protocol, error;
545 /* Check if we're already connected */
546 if (priv->hook != NULL)
549 if (priv->flags & KSF_CLONED) {
550 if (priv->flags & KSF_EMBRYONIC) {
551 /* Remove ourselves from our parent's embryo list */
552 LIST_REMOVE(priv, siblings);
553 priv->flags &= ~KSF_EMBRYONIC;
556 /* Extract family, type, and protocol from hook name */
557 snprintf(name, sizeof(name), "%s", name0);
559 if ((s2 = strchr(s1, '/')) == NULL)
562 family = ng_ksocket_parse(ng_ksocket_families, s1, 0);
566 if ((s2 = strchr(s1, '/')) == NULL)
569 type = ng_ksocket_parse(ng_ksocket_types, s1, 0);
573 protocol = ng_ksocket_parse(ng_ksocket_protos, s1, family);
577 /* Create the socket */
578 error = socreate(family, &priv->so, type, protocol,
583 /* XXX call soreserve() ? */
590 * In case of misconfigured routing a packet may reenter
591 * ksocket node recursively. Decouple stack to avoid possible
592 * panics about sleeping with locks held.
594 NG_HOOK_FORCE_QUEUE(hook);
600 ng_ksocket_connect(hook_p hook)
602 node_p node = NG_HOOK_NODE(hook);
603 const priv_p priv = NG_NODE_PRIVATE(node);
604 struct socket *const so = priv->so;
606 /* Add our hook for incoming data and other events */
607 SOCKBUF_LOCK(&priv->so->so_rcv);
608 soupcall_set(priv->so, SO_RCV, ng_ksocket_incoming, node);
609 SOCKBUF_UNLOCK(&priv->so->so_rcv);
610 SOCKBUF_LOCK(&priv->so->so_snd);
611 soupcall_set(priv->so, SO_SND, ng_ksocket_incoming, node);
612 SOCKBUF_UNLOCK(&priv->so->so_snd);
614 priv->so->so_state |= SS_NBIO;
615 SOCK_UNLOCK(priv->so);
617 * --Original comment--
618 * On a cloned socket we may have already received one or more
619 * upcalls which we couldn't handle without a hook. Handle
621 * We cannot call the upcall function directly
622 * from here, because until this function has returned our
623 * hook isn't connected.
625 * ---meta comment for -current ---
626 * XXX This is dubius.
627 * Upcalls between the time that the hook was
628 * first created and now (on another processesor) will
629 * be earlier on the queue than the request to finalise the hook.
630 * By the time the hook is finalised,
631 * The queued upcalls will have happened and the code
632 * will have discarded them because of a lack of a hook.
635 * This is a bad byproduct of the complicated way in which hooks
636 * are now created (3 daisy chained async events).
638 * Since we are a netgraph operation
639 * We know that we hold a lock on this node. This forces the
640 * request we make below to be queued rather than implemented
641 * immediately which will cause the upcall function to be called a bit
643 * However, as we will run any waiting queued operations immediately
644 * after doing this one, if we have not finalised the other end
645 * of the hook, those queued operations will fail.
647 if (priv->flags & KSF_CLONED) {
648 ng_send_fn(node, NULL, &ng_ksocket_incoming2, so, M_NOWAIT);
655 * Receive a control message
658 ng_ksocket_rcvmsg(node_p node, item_p item, hook_p lasthook)
660 struct thread *td = curthread; /* XXX broken */
661 const priv_p priv = NG_NODE_PRIVATE(node);
662 struct socket *const so = priv->so;
663 struct ng_mesg *resp = NULL;
667 NGI_GET_MSG(item, msg);
668 switch (msg->header.typecookie) {
669 case NGM_KSOCKET_COOKIE:
670 switch (msg->header.cmd) {
671 case NGM_KSOCKET_BIND:
673 struct sockaddr *const sa
674 = (struct sockaddr *)msg->data;
677 if (msg->header.arglen < SADATA_OFFSET
678 || msg->header.arglen < sa->sa_len)
684 error = sobind(so, sa, td);
687 case NGM_KSOCKET_LISTEN:
690 if (msg->header.arglen != sizeof(int32_t))
696 so->so_state |= SS_NBIO;
697 error = solisten(so, *((int32_t *)msg->data), td);
701 case NGM_KSOCKET_ACCEPT:
704 if (msg->header.arglen != 0)
709 /* Make sure the socket is capable of accepting */
710 if (!(so->so_options & SO_ACCEPTCONN))
712 if (priv->flags & KSF_ACCEPTING)
716 * If a connection is already complete, take it.
717 * Otherwise let the upcall function deal with
718 * the connection when it comes in.
720 error = ng_ksocket_accept(priv);
721 if (error != 0 && error != EWOULDBLOCK)
723 priv->response_token = msg->header.token;
724 priv->response_addr = NGI_RETADDR(item);
728 case NGM_KSOCKET_CONNECT:
730 struct sockaddr *const sa
731 = (struct sockaddr *)msg->data;
734 if (msg->header.arglen < SADATA_OFFSET
735 || msg->header.arglen < sa->sa_len)
741 if ((so->so_state & SS_ISCONNECTING) != 0)
743 if ((error = soconnect(so, sa, td)) != 0) {
744 so->so_state &= ~SS_ISCONNECTING;
747 if ((so->so_state & SS_ISCONNECTING) != 0) {
748 /* We will notify the sender when we connect */
749 priv->response_token = msg->header.token;
750 priv->response_addr = NGI_RETADDR(item);
751 priv->flags |= KSF_CONNECTING;
757 case NGM_KSOCKET_GETNAME:
758 case NGM_KSOCKET_GETPEERNAME:
760 int (*func)(struct socket *so, struct sockaddr **nam);
761 struct sockaddr *sa = NULL;
765 if (msg->header.arglen != 0)
771 if (msg->header.cmd == NGM_KSOCKET_GETPEERNAME) {
773 & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0)
775 func = so->so_proto->pr_peeraddr;
777 func = so->so_proto->pr_sockaddr;
779 /* Get local or peer address */
780 if ((error = (*func)(so, &sa)) != 0)
782 len = (sa == NULL) ? 0 : sa->sa_len;
784 /* Send it back in a response */
785 NG_MKRESPONSE(resp, msg, len, M_NOWAIT);
790 bcopy(sa, resp->data, len);
799 case NGM_KSOCKET_GETOPT:
801 struct ng_ksocket_sockopt *ksopt =
802 (struct ng_ksocket_sockopt *)msg->data;
806 if (msg->header.arglen != sizeof(*ksopt))
811 /* Get response with room for option value */
812 NG_MKRESPONSE(resp, msg, sizeof(*ksopt)
813 + NG_KSOCKET_MAX_OPTLEN, M_NOWAIT);
817 /* Get socket option, and put value in the response */
818 sopt.sopt_dir = SOPT_GET;
819 sopt.sopt_level = ksopt->level;
820 sopt.sopt_name = ksopt->name;
822 sopt.sopt_valsize = NG_KSOCKET_MAX_OPTLEN;
823 ksopt = (struct ng_ksocket_sockopt *)resp->data;
824 sopt.sopt_val = ksopt->value;
825 if ((error = sogetopt(so, &sopt)) != 0) {
830 /* Set actual value length */
831 resp->header.arglen = sizeof(*ksopt)
836 case NGM_KSOCKET_SETOPT:
838 struct ng_ksocket_sockopt *const ksopt =
839 (struct ng_ksocket_sockopt *)msg->data;
840 const int valsize = msg->header.arglen - sizeof(*ksopt);
849 /* Set socket option */
850 sopt.sopt_dir = SOPT_SET;
851 sopt.sopt_level = ksopt->level;
852 sopt.sopt_name = ksopt->name;
853 sopt.sopt_val = ksopt->value;
854 sopt.sopt_valsize = valsize;
856 error = sosetopt(so, &sopt);
870 NG_RESPOND_MSG(error, node, item, resp);
876 * Receive incoming data on our hook. Send it out the socket.
879 ng_ksocket_rcvdata(hook_p hook, item_p item)
881 struct thread *td = curthread; /* XXX broken */
882 const node_p node = NG_HOOK_NODE(hook);
883 const priv_p priv = NG_NODE_PRIVATE(node);
884 struct socket *const so = priv->so;
885 struct sockaddr *sa = NULL;
888 #ifdef ALIGNED_POINTER
890 #endif /* ALIGNED_POINTER */
896 #ifdef ALIGNED_POINTER
897 if (!ALIGNED_POINTER(mtod(m, caddr_t), uint32_t)) {
898 n = m_defrag(m, M_NOWAIT);
905 #endif /* ALIGNED_POINTER */
907 * Look if socket address is stored in packet tags.
908 * If sockaddr is ours, or provided by a third party (zero id),
911 if (((stag = (struct sa_tag *)m_tag_locate(m, NGM_KSOCKET_COOKIE,
912 NG_KSOCKET_TAG_SOCKADDR, NULL)) != NULL) &&
913 (stag->id == NG_NODE_ID(node) || stag->id == 0))
916 /* Reset specific mbuf flags to prevent addressing problems. */
917 m->m_flags &= ~(M_BCAST|M_MCAST);
920 error = sosend(so, sa, 0, m, 0, 0, td);
929 ng_ksocket_shutdown(node_p node)
931 const priv_p priv = NG_NODE_PRIVATE(node);
934 /* Close our socket (if any) */
935 if (priv->so != NULL) {
936 SOCKBUF_LOCK(&priv->so->so_rcv);
937 soupcall_clear(priv->so, SO_RCV);
938 SOCKBUF_UNLOCK(&priv->so->so_rcv);
939 SOCKBUF_LOCK(&priv->so->so_snd);
940 soupcall_clear(priv->so, SO_SND);
941 SOCKBUF_UNLOCK(&priv->so->so_snd);
946 /* If we are an embryo, take ourselves out of the parent's list */
947 if (priv->flags & KSF_EMBRYONIC) {
948 LIST_REMOVE(priv, siblings);
949 priv->flags &= ~KSF_EMBRYONIC;
952 /* Remove any embryonic children we have */
953 while (!LIST_EMPTY(&priv->embryos)) {
954 embryo = LIST_FIRST(&priv->embryos);
955 ng_rmnode_self(embryo->node);
958 /* Take down netgraph node */
959 bzero(priv, sizeof(*priv));
960 free(priv, M_NETGRAPH_KSOCKET);
961 NG_NODE_SET_PRIVATE(node, NULL);
962 NG_NODE_UNREF(node); /* let the node escape */
970 ng_ksocket_disconnect(hook_p hook)
972 KASSERT(NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0,
973 ("%s: numhooks=%d?", __func__,
974 NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook))));
975 if (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))
976 ng_rmnode_self(NG_HOOK_NODE(hook));
980 /************************************************************************
982 ************************************************************************/
984 * You should not "just call" a netgraph node function from an external
985 * asynchronous event. This is because in doing so you are ignoring the
986 * locking on the netgraph nodes. Instead call your function via ng_send_fn().
987 * This will call the function you chose, but will first do all the
988 * locking rigmarole. Your function MAY only be called at some distant future
989 * time (several millisecs away) so don't give it any arguments
990 * that may be revoked soon (e.g. on your stack).
992 * To decouple stack, we use queue version of ng_send_fn().
996 ng_ksocket_incoming(struct socket *so, void *arg, int waitflag)
998 const node_p node = arg;
999 const priv_p priv = NG_NODE_PRIVATE(node);
1000 int wait = ((waitflag & M_WAITOK) ? NG_WAITOK : 0) | NG_QUEUE;
1003 * Even if node is not locked, as soon as we are called, we assume
1004 * it exist and it's private area is valid. With some care we can
1005 * access it. Mark node that incoming event for it was sent to
1006 * avoid unneded queue trashing.
1008 if (atomic_cmpset_int(&priv->fn_sent, 0, 1) &&
1009 ng_send_fn1(node, NULL, &ng_ksocket_incoming2, so, 0, wait)) {
1010 atomic_store_rel_int(&priv->fn_sent, 0);
1016 * When incoming data is appended to the socket, we get notified here.
1017 * This is also called whenever a significant event occurs for the socket.
1018 * Our original caller may have queued this even some time ago and
1019 * we cannot trust that he even still exists. The node however is being
1020 * held with a reference by the queueing code and guarantied to be valid.
1023 ng_ksocket_incoming2(node_p node, hook_p hook, void *arg1, int arg2)
1025 struct socket *so = arg1;
1026 const priv_p priv = NG_NODE_PRIVATE(node);
1027 struct ng_mesg *response;
1030 KASSERT(so == priv->so, ("%s: wrong socket", __func__));
1032 /* Allow next incoming event to be queued. */
1033 atomic_store_rel_int(&priv->fn_sent, 0);
1035 /* Check whether a pending connect operation has completed */
1036 if (priv->flags & KSF_CONNECTING) {
1037 if ((error = so->so_error) != 0) {
1039 so->so_state &= ~SS_ISCONNECTING;
1041 if (!(so->so_state & SS_ISCONNECTING)) {
1042 NG_MKMESSAGE(response, NGM_KSOCKET_COOKIE,
1043 NGM_KSOCKET_CONNECT, sizeof(int32_t), M_NOWAIT);
1044 if (response != NULL) {
1045 response->header.flags |= NGF_RESP;
1046 response->header.token = priv->response_token;
1047 *(int32_t *)response->data = error;
1049 * send an async "response" message
1050 * to the node that set us up
1051 * (if it still exists)
1053 NG_SEND_MSG_ID(error, node,
1054 response, priv->response_addr, 0);
1056 priv->flags &= ~KSF_CONNECTING;
1060 /* Check whether a pending accept operation has completed */
1061 if (priv->flags & KSF_ACCEPTING)
1062 (void )ng_ksocket_accept(priv);
1065 * If we don't have a hook, we must handle data events later. When
1066 * the hook gets created and is connected, this upcall function
1067 * will be called again.
1069 if (priv->hook == NULL)
1072 /* Read and forward available mbufs. */
1075 struct sockaddr *sa;
1079 /* Try to get next packet from socket. */
1081 uio.uio_resid = IP_MAXPACKET;
1082 flags = MSG_DONTWAIT;
1084 if ((error = soreceive(so, (so->so_state & SS_ISCONNECTED) ?
1085 NULL : &sa, &uio, &m, NULL, &flags)) != 0)
1088 /* See if we got anything. */
1089 if (flags & MSG_TRUNC) {
1099 KASSERT(m->m_nextpkt == NULL, ("%s: nextpkt", __func__));
1102 * Stream sockets do not have packet boundaries, so
1103 * we have to allocate a header mbuf and attach the
1104 * stream of data to it.
1106 if (so->so_type == SOCK_STREAM) {
1109 mh = m_gethdr(M_NOWAIT, MT_DATA);
1118 for (; m; m = m->m_next)
1119 mh->m_pkthdr.len += m->m_len;
1123 /* Put peer's socket address (if any) into a tag */
1125 struct sa_tag *stag;
1127 stag = (struct sa_tag *)m_tag_alloc(NGM_KSOCKET_COOKIE,
1128 NG_KSOCKET_TAG_SOCKADDR, sizeof(ng_ID_t) +
1129 sa->sa_len, M_NOWAIT);
1134 bcopy(sa, &stag->sa, sa->sa_len);
1136 stag->id = NG_NODE_ID(node);
1137 m_tag_prepend(m, &stag->tag);
1140 sendit: /* Forward data with optional peer sockaddr as packet tag */
1141 NG_SEND_DATA_ONLY(error, priv->hook, m);
1145 * If the peer has closed the connection, forward a 0-length mbuf
1146 * to indicate end-of-file.
1148 if (so->so_rcv.sb_state & SBS_CANTRCVMORE &&
1149 !(priv->flags & KSF_EOFSEEN)) {
1152 m = m_gethdr(M_NOWAIT, MT_DATA);
1154 NG_SEND_DATA_ONLY(error, priv->hook, m);
1155 priv->flags |= KSF_EOFSEEN;
1160 ng_ksocket_accept(priv_p priv)
1162 struct socket *const head = priv->so;
1164 struct sockaddr *sa = NULL;
1165 struct ng_mesg *resp;
1166 struct ng_ksocket_accept *resp_data;
1172 SOLISTEN_LOCK(head);
1173 error = solisten_dequeue(head, &so, SOCK_NONBLOCK);
1174 if (error == EWOULDBLOCK) {
1175 priv->flags |= KSF_ACCEPTING;
1178 priv->flags &= ~KSF_ACCEPTING;
1182 if ((error = soaccept(so, &sa)) != 0)
1185 len = OFFSETOF(struct ng_ksocket_accept, addr);
1189 NG_MKMESSAGE(resp, NGM_KSOCKET_COOKIE, NGM_KSOCKET_ACCEPT, len,
1195 resp->header.flags |= NGF_RESP;
1196 resp->header.token = priv->response_token;
1198 /* Clone a ksocket node to wrap the new socket */
1199 error = ng_make_node_common(&ng_ksocket_typestruct, &node);
1201 free(resp, M_NETGRAPH);
1206 if (ng_ksocket_constructor(node) != 0) {
1207 NG_NODE_UNREF(node);
1208 free(resp, M_NETGRAPH);
1213 priv2 = NG_NODE_PRIVATE(node);
1215 priv2->flags |= KSF_CLONED | KSF_EMBRYONIC;
1218 * Insert the cloned node into a list of embryonic children
1219 * on the parent node. When a hook is created on the cloned
1220 * node it will be removed from this list. When the parent
1221 * is destroyed it will destroy any embryonic children it has.
1223 LIST_INSERT_HEAD(&priv->embryos, priv2, siblings);
1225 SOCKBUF_LOCK(&so->so_rcv);
1226 soupcall_set(so, SO_RCV, ng_ksocket_incoming, node);
1227 SOCKBUF_UNLOCK(&so->so_rcv);
1228 SOCKBUF_LOCK(&so->so_snd);
1229 soupcall_set(so, SO_SND, ng_ksocket_incoming, node);
1230 SOCKBUF_UNLOCK(&so->so_snd);
1232 /* Fill in the response data and send it or return it to the caller */
1233 resp_data = (struct ng_ksocket_accept *)resp->data;
1234 resp_data->nodeid = NG_NODE_ID(node);
1236 bcopy(sa, &resp_data->addr, sa->sa_len);
1237 NG_SEND_MSG_ID(error, node, resp, priv->response_addr, 0);
1247 * Parse out either an integer value or an alias.
1250 ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
1251 const char *s, int family)
1257 for (k = 0; aliases[k].name != NULL; k++) {
1258 if (strcmp(s, aliases[k].name) == 0
1259 && aliases[k].family == family)
1260 return aliases[k].value;
1263 /* Try parsing as a number */
1264 val = (int)strtoul(s, &eptr, 10);
1265 if (val < 0 || *eptr != '\0')