Initial import from FreeBSD RELENG_4:
[dragonfly.git] / sys / netgraph / ksocket / ng_ksocket.c
CommitLineData
984263bc
MD
1
2/*
3 * ng_ksocket.c
4 *
5 * Copyright (c) 1996-1999 Whistle Communications, Inc.
6 * All rights reserved.
7 *
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.
18 *
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
35 * OF SUCH DAMAGE.
36 *
37 * Author: Archie Cobbs <archie@freebsd.org>
38 *
39 * $FreeBSD: src/sys/netgraph/ng_ksocket.c,v 1.5.2.13 2003/04/28 20:41:09 archie Exp $
40 * $Whistle: ng_ksocket.c,v 1.1 1999/11/16 20:04:40 archie Exp $
41 */
42
43/*
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.
46 */
47
48#include <sys/param.h>
49#include <sys/systm.h>
50#include <sys/kernel.h>
51#include <sys/mbuf.h>
52#include <sys/proc.h>
53#include <sys/malloc.h>
54#include <sys/ctype.h>
55#include <sys/protosw.h>
56#include <sys/errno.h>
57#include <sys/socket.h>
58#include <sys/socketvar.h>
59#include <sys/uio.h>
60#include <sys/un.h>
61
62#include <netgraph/ng_message.h>
63#include <netgraph/netgraph.h>
64#include <netgraph/ng_parse.h>
65#include <netgraph/ng_ksocket.h>
66
67#include <netinet/in.h>
68#include <netatalk/at.h>
69
70#define OFFSETOF(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
71#define SADATA_OFFSET (OFFSETOF(struct sockaddr, sa_data))
72
73/* Node private data */
74struct ng_ksocket_private {
75 node_p node;
76 hook_p hook;
77 struct socket *so;
78 LIST_HEAD(, ng_ksocket_private) embryos;
79 LIST_ENTRY(ng_ksocket_private) siblings;
80 u_int32_t flags;
81 u_int32_t response_token;
82 char response_addr[NG_PATHLEN+1];
83};
84typedef struct ng_ksocket_private *priv_p;
85
86/* Flags for priv_p */
87#define KSF_CONNECTING 0x00000001 /* Waiting for connection complete */
88#define KSF_ACCEPTING 0x00000002 /* Waiting for accept complete */
89#define KSF_EOFSEEN 0x00000004 /* Have sent 0-length EOF mbuf */
90#define KSF_CLONED 0x00000008 /* Cloned from an accepting socket */
91#define KSF_EMBRYONIC 0x00000010 /* Cloned node with no hooks yet */
92#define KSF_SENDING 0x00000020 /* Sending on socket */
93
94/* Internal commands which we send to ourselves */
95#define NGM_KSOCKET_INTERNAL_COOKIE (NGM_KSOCKET_COOKIE + 1)
96
97enum {
98 NGM_KSOCKET_INTERNAL_UPCALL = 1
99};
100
101/* Netgraph node methods */
102static ng_constructor_t ng_ksocket_constructor;
103static ng_rcvmsg_t ng_ksocket_rcvmsg;
104static ng_shutdown_t ng_ksocket_rmnode;
105static ng_newhook_t ng_ksocket_newhook;
106static ng_rcvdata_t ng_ksocket_rcvdata;
107static ng_disconnect_t ng_ksocket_disconnect;
108
109/* Alias structure */
110struct ng_ksocket_alias {
111 const char *name;
112 const int value;
113 const int family;
114};
115
116/* Protocol family aliases */
117static const struct ng_ksocket_alias ng_ksocket_families[] = {
118 { "local", PF_LOCAL },
119 { "inet", PF_INET },
120 { "inet6", PF_INET6 },
121 { "atalk", PF_APPLETALK },
122 { "ipx", PF_IPX },
123 { "atm", PF_ATM },
124 { NULL, -1 },
125};
126
127/* Socket type aliases */
128static const struct ng_ksocket_alias ng_ksocket_types[] = {
129 { "stream", SOCK_STREAM },
130 { "dgram", SOCK_DGRAM },
131 { "raw", SOCK_RAW },
132 { "rdm", SOCK_RDM },
133 { "seqpacket", SOCK_SEQPACKET },
134 { NULL, -1 },
135};
136
137/* Protocol aliases */
138static 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 { "ddp", ATPROTO_DDP, PF_APPLETALK },
152 { "aarp", ATPROTO_AARP, PF_APPLETALK },
153 { NULL, -1 },
154};
155
156/* Helper functions */
157static int ng_ksocket_check_accept(priv_p);
158static void ng_ksocket_finish_accept(priv_p, struct ng_mesg **);
159static void ng_ksocket_incoming(struct socket *so, void *arg, int waitflag);
160static int ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
161 const char *s, int family);
162
163/************************************************************************
164 STRUCT SOCKADDR PARSE TYPE
165 ************************************************************************/
166
167/* Get the length of the data portion of a generic struct sockaddr */
168static int
169ng_parse_generic_sockdata_getLength(const struct ng_parse_type *type,
170 const u_char *start, const u_char *buf)
171{
172 const struct sockaddr *sa;
173
174 sa = (const struct sockaddr *)(buf - SADATA_OFFSET);
175 return (sa->sa_len < SADATA_OFFSET) ? 0 : sa->sa_len - SADATA_OFFSET;
176}
177
178/* Type for the variable length data portion of a generic struct sockaddr */
179static const struct ng_parse_type ng_ksocket_generic_sockdata_type = {
180 &ng_parse_bytearray_type,
181 &ng_parse_generic_sockdata_getLength
182};
183
184/* Type for a generic struct sockaddr */
185static 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 },
190 { NULL }
191};
192static const struct ng_parse_type ng_ksocket_generic_sockaddr_type = {
193 &ng_parse_struct_type,
194 &ng_parse_generic_sockaddr_type_fields
195};
196
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. */
200static int
201ng_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)
204{
205 struct sockaddr *const sa = (struct sockaddr *)buf;
206 enum ng_parse_token tok;
207 char fambuf[32];
208 int family, len;
209 char *t;
210
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);
216 }
217
218 /* Get socket address family followed by a slash */
219 while (isspace(s[*off]))
220 (*off)++;
221 if ((t = index(s + *off, '/')) == NULL)
222 return (EINVAL);
223 if ((len = t - (s + *off)) > sizeof(fambuf) - 1)
224 return (EINVAL);
225 strncpy(fambuf, s + *off, len);
226 fambuf[len] = '\0';
227 *off += len + 1;
228 if ((family = ng_ksocket_parse(ng_ksocket_families, fambuf, 0)) == -1)
229 return (EINVAL);
230
231 /* Set family */
232 if (*buflen < SADATA_OFFSET)
233 return (ERANGE);
234 sa->sa_family = family;
235
236 /* Set family-specific data and length */
237 switch (sa->sa_family) {
238 case PF_LOCAL: /* Get pathname */
239 {
240 const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
241 struct sockaddr_un *const sun = (struct sockaddr_un *)sa;
242 int toklen, pathlen;
243 char *path;
244
245 if ((path = ng_get_string_token(s, off, &toklen)) == NULL)
246 return (EINVAL);
247 pathlen = strlen(path);
248 if (pathlen > SOCK_MAXADDRLEN) {
249 FREE(path, M_NETGRAPH);
250 return (E2BIG);
251 }
252 if (*buflen < pathoff + pathlen) {
253 FREE(path, M_NETGRAPH);
254 return (ERANGE);
255 }
256 *off += toklen;
257 bcopy(path, sun->sun_path, pathlen);
258 sun->sun_len = pathoff + pathlen;
259 FREE(path, M_NETGRAPH);
260 break;
261 }
262
263 case PF_INET: /* Get an IP address with optional port */
264 {
265 struct sockaddr_in *const sin = (struct sockaddr_in *)sa;
266 int i;
267
268 /* Parse this: <ipaddress>[:port] */
269 for (i = 0; i < 4; i++) {
270 u_long val;
271 char *eptr;
272
273 val = strtoul(s + *off, &eptr, 10);
274 if (val > 0xff || eptr == s + *off)
275 return (EINVAL);
276 *off += (eptr - (s + *off));
277 ((u_char *)&sin->sin_addr)[i] = (u_char)val;
278 if (i < 3) {
279 if (s[*off] != '.')
280 return (EINVAL);
281 (*off)++;
282 } else if (s[*off] == ':') {
283 (*off)++;
284 val = strtoul(s + *off, &eptr, 10);
285 if (val > 0xffff || eptr == s + *off)
286 return (EINVAL);
287 *off += (eptr - (s + *off));
288 sin->sin_port = htons(val);
289 } else
290 sin->sin_port = 0;
291 }
292 bzero(&sin->sin_zero, sizeof(sin->sin_zero));
293 sin->sin_len = sizeof(*sin);
294 break;
295 }
296
297#if 0
298 case PF_APPLETALK: /* XXX implement these someday */
299 case PF_INET6:
300 case PF_IPX:
301#endif
302
303 default:
304 return (EINVAL);
305 }
306
307 /* Done */
308 *buflen = sa->sa_len;
309 return (0);
310}
311
312/* Convert a struct sockaddr from binary to ASCII */
313static int
314ng_ksocket_sockaddr_unparse(const struct ng_parse_type *type,
315 const u_char *data, int *off, char *cbuf, int cbuflen)
316{
317 const struct sockaddr *sa = (const struct sockaddr *)(data + *off);
318 int slen = 0;
319
320 /* Output socket address, either in special or generic format */
321 switch (sa->sa_family) {
322 case PF_LOCAL:
323 {
324 const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
325 const struct sockaddr_un *sun = (const struct sockaddr_un *)sa;
326 const int pathlen = sun->sun_len - pathoff;
327 char pathbuf[SOCK_MAXADDRLEN + 1];
328 char *pathtoken;
329
330 bcopy(sun->sun_path, pathbuf, pathlen);
331 pathbuf[pathlen] = '\0';
332 if ((pathtoken = ng_encode_string(pathbuf)) == NULL)
333 return (ENOMEM);
334 slen += snprintf(cbuf, cbuflen, "local/%s", pathtoken);
335 FREE(pathtoken, M_NETGRAPH);
336 if (slen >= cbuflen)
337 return (ERANGE);
338 *off += sun->sun_len;
339 return (0);
340 }
341
342 case PF_INET:
343 {
344 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
345
346 slen += snprintf(cbuf, cbuflen, "inet/%d.%d.%d.%d",
347 ((const u_char *)&sin->sin_addr)[0],
348 ((const u_char *)&sin->sin_addr)[1],
349 ((const u_char *)&sin->sin_addr)[2],
350 ((const u_char *)&sin->sin_addr)[3]);
351 if (sin->sin_port != 0) {
352 slen += snprintf(cbuf + strlen(cbuf),
353 cbuflen - strlen(cbuf), ":%d",
354 (u_int)ntohs(sin->sin_port));
355 }
356 if (slen >= cbuflen)
357 return (ERANGE);
358 *off += sizeof(*sin);
359 return(0);
360 }
361
362#if 0
363 case PF_APPLETALK: /* XXX implement these someday */
364 case PF_INET6:
365 case PF_IPX:
366#endif
367
368 default:
369 return (*ng_ksocket_generic_sockaddr_type.supertype->unparse)
370 (&ng_ksocket_generic_sockaddr_type,
371 data, off, cbuf, cbuflen);
372 }
373}
374
375/* Parse type for struct sockaddr */
376static const struct ng_parse_type ng_ksocket_sockaddr_type = {
377 NULL,
378 NULL,
379 NULL,
380 &ng_ksocket_sockaddr_parse,
381 &ng_ksocket_sockaddr_unparse,
382 NULL /* no such thing as a default struct sockaddr */
383};
384
385/************************************************************************
386 STRUCT NG_KSOCKET_SOCKOPT PARSE TYPE
387 ************************************************************************/
388
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. */
392static int
393ng_parse_sockoptval_getLength(const struct ng_parse_type *type,
394 const u_char *start, const u_char *buf)
395{
396 static const int offset = OFFSETOF(struct ng_ksocket_sockopt, value);
397 const struct ng_ksocket_sockopt *sopt;
398 const struct ng_mesg *msg;
399
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);
403}
404
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. */
409static const struct ng_parse_type ng_ksocket_sockoptval_type = {
410 &ng_parse_bytearray_type,
411 &ng_parse_sockoptval_getLength
412};
413
414/* Parse type for struct ng_ksocket_sockopt */
415static const struct ng_parse_struct_field ng_ksocket_sockopt_type_fields[]
416 = NG_KSOCKET_SOCKOPT_INFO(&ng_ksocket_sockoptval_type);
417static const struct ng_parse_type ng_ksocket_sockopt_type = {
418 &ng_parse_struct_type,
419 &ng_ksocket_sockopt_type_fields
420};
421
422/* Parse type for struct ng_ksocket_accept */
423static const struct ng_parse_struct_field ng_ksocket_accept_type_fields[]
424 = NGM_KSOCKET_ACCEPT_INFO;
425static const struct ng_parse_type ng_ksocket_accept_type = {
426 &ng_parse_struct_type,
427 &ng_ksocket_accept_type_fields
428};
429
430/* List of commands and how to convert arguments to/from ASCII */
431static const struct ng_cmdlist ng_ksocket_cmds[] = {
432 {
433 NGM_KSOCKET_COOKIE,
434 NGM_KSOCKET_BIND,
435 "bind",
436 &ng_ksocket_sockaddr_type,
437 NULL
438 },
439 {
440 NGM_KSOCKET_COOKIE,
441 NGM_KSOCKET_LISTEN,
442 "listen",
443 &ng_parse_int32_type,
444 NULL
445 },
446 {
447 NGM_KSOCKET_COOKIE,
448 NGM_KSOCKET_ACCEPT,
449 "accept",
450 NULL,
451 &ng_ksocket_accept_type
452 },
453 {
454 NGM_KSOCKET_COOKIE,
455 NGM_KSOCKET_CONNECT,
456 "connect",
457 &ng_ksocket_sockaddr_type,
458 &ng_parse_int32_type
459 },
460 {
461 NGM_KSOCKET_COOKIE,
462 NGM_KSOCKET_GETNAME,
463 "getname",
464 NULL,
465 &ng_ksocket_sockaddr_type
466 },
467 {
468 NGM_KSOCKET_COOKIE,
469 NGM_KSOCKET_GETPEERNAME,
470 "getpeername",
471 NULL,
472 &ng_ksocket_sockaddr_type
473 },
474 {
475 NGM_KSOCKET_COOKIE,
476 NGM_KSOCKET_SETOPT,
477 "setopt",
478 &ng_ksocket_sockopt_type,
479 NULL
480 },
481 {
482 NGM_KSOCKET_COOKIE,
483 NGM_KSOCKET_GETOPT,
484 "getopt",
485 &ng_ksocket_sockopt_type,
486 &ng_ksocket_sockopt_type
487 },
488
489 /* Internal commands */
490 {
491 NGM_KSOCKET_INTERNAL_COOKIE,
492 NGM_KSOCKET_INTERNAL_UPCALL,
493 "upcall",
494 NULL,
495 NULL
496 },
497 { 0 }
498};
499
500/* Node type descriptor */
501static struct ng_type ng_ksocket_typestruct = {
502 NG_VERSION,
503 NG_KSOCKET_NODE_TYPE,
504 NULL,
505 ng_ksocket_constructor,
506 ng_ksocket_rcvmsg,
507 ng_ksocket_rmnode,
508 ng_ksocket_newhook,
509 NULL,
510 NULL,
511 ng_ksocket_rcvdata,
512 ng_ksocket_rcvdata,
513 ng_ksocket_disconnect,
514 ng_ksocket_cmds
515};
516NETGRAPH_INIT(ksocket, &ng_ksocket_typestruct);
517
518#define ERROUT(x) do { error = (x); goto done; } while (0)
519
520/************************************************************************
521 NETGRAPH NODE STUFF
522 ************************************************************************/
523
524/*
525 * Node type constructor
526 */
527static int
528ng_ksocket_constructor(node_p *nodep)
529{
530 priv_p priv;
531 int error;
532
533 /* Allocate private structure */
534 MALLOC(priv, priv_p, sizeof(*priv), M_NETGRAPH, M_NOWAIT);
535 if (priv == NULL)
536 return (ENOMEM);
537 bzero(priv, sizeof(*priv));
538
539 /* Call generic node constructor */
540 if ((error = ng_make_node_common(&ng_ksocket_typestruct, nodep))) {
541 FREE(priv, M_NETGRAPH);
542 return (error);
543 }
544 (*nodep)->private = priv;
545 priv->node = *nodep;
546 LIST_INIT(&priv->embryos);
547
548 /* Done */
549 return (0);
550}
551
552/*
553 * Give our OK for a hook to be added. The hook name is of the
554 * form "<family>/<type>/<proto>" where the three components may
555 * be decimal numbers or else aliases from the above lists.
556 *
557 * Connecting a hook amounts to opening the socket. Disconnecting
558 * the hook closes the socket and destroys the node as well.
559 */
560static int
561ng_ksocket_newhook(node_p node, hook_p hook, const char *name0)
562{
563 struct proc *p = curproc ? curproc : &proc0; /* XXX broken */
564 const priv_p priv = node->private;
565 struct ng_mesg *msg;
566 char *s1, *s2, name[NG_HOOKLEN+1];
567 int family, type, protocol, error;
568
569 /* Check if we're already connected */
570 if (priv->hook != NULL)
571 return (EISCONN);
572
573 if (priv->flags & KSF_CLONED) {
574 if (priv->flags & KSF_EMBRYONIC) {
575 /* Remove ourselves from our parent's embryo list */
576 LIST_REMOVE(priv, siblings);
577 priv->flags &= ~KSF_EMBRYONIC;
578 }
579 } else {
580 /* Extract family, type, and protocol from hook name */
581 snprintf(name, sizeof(name), "%s", name0);
582 s1 = name;
583 if ((s2 = index(s1, '/')) == NULL)
584 return (EINVAL);
585 *s2++ = '\0';
586 family = ng_ksocket_parse(ng_ksocket_families, s1, 0);
587 if (family == -1)
588 return (EINVAL);
589 s1 = s2;
590 if ((s2 = index(s1, '/')) == NULL)
591 return (EINVAL);
592 *s2++ = '\0';
593 type = ng_ksocket_parse(ng_ksocket_types, s1, 0);
594 if (type == -1)
595 return (EINVAL);
596 s1 = s2;
597 protocol = ng_ksocket_parse(ng_ksocket_protos, s1, family);
598 if (protocol == -1)
599 return (EINVAL);
600
601 /* Create the socket */
602 error = socreate(family, &priv->so, type, protocol, p);
603 if (error != 0)
604 return (error);
605
606 /* XXX call soreserve() ? */
607
608 /* Add our hook for incoming data and other events */
609 priv->so->so_upcallarg = (caddr_t)node;
610 priv->so->so_upcall = ng_ksocket_incoming;
611 priv->so->so_rcv.sb_flags |= SB_UPCALL;
612 priv->so->so_snd.sb_flags |= SB_UPCALL;
613 priv->so->so_state |= SS_NBIO;
614 }
615
616 /* OK */
617 priv->hook = hook;
618
619 /*
620 * On a cloned socket we may have already received one or more
621 * upcalls which we couldn't handle without a hook. Handle
622 * those now. We cannot call the upcall function directly
623 * from here, because until this function has returned our
624 * hook isn't connected. So we queue a message to ourselves
625 * which will cause the upcall function to be called a bit
626 * later.
627 */
628 if (priv->flags & KSF_CLONED) {
629 NG_MKMESSAGE(msg, NGM_KSOCKET_INTERNAL_COOKIE,
630 NGM_KSOCKET_INTERNAL_UPCALL, 0, M_NOWAIT);
631 if (msg != NULL)
632 ng_queue_msg(node, msg, ".:");
633 }
634
635 return (0);
636}
637
638/*
639 * Receive a control message
640 */
641static int
642ng_ksocket_rcvmsg(node_p node, struct ng_mesg *msg,
643 const char *raddr, struct ng_mesg **rptr)
644{
645 struct proc *p = curproc ? curproc : &proc0; /* XXX broken */
646 const priv_p priv = node->private;
647 struct socket *const so = priv->so;
648 struct ng_mesg *resp = NULL;
649 int error = 0;
650
651 switch (msg->header.typecookie) {
652 case NGM_KSOCKET_COOKIE:
653 switch (msg->header.cmd) {
654 case NGM_KSOCKET_BIND:
655 {
656 struct sockaddr *const sa
657 = (struct sockaddr *)msg->data;
658
659 /* Sanity check */
660 if (msg->header.arglen < SADATA_OFFSET
661 || msg->header.arglen < sa->sa_len)
662 ERROUT(EINVAL);
663 if (so == NULL)
664 ERROUT(ENXIO);
665
666 /* Bind */
667 error = sobind(so, sa, p);
668 break;
669 }
670 case NGM_KSOCKET_LISTEN:
671 {
672 /* Sanity check */
673 if (msg->header.arglen != sizeof(int32_t))
674 ERROUT(EINVAL);
675 if (so == NULL)
676 ERROUT(ENXIO);
677
678 /* Listen */
679 error = solisten(so, *((int32_t *)msg->data), p);
680 break;
681 }
682
683 case NGM_KSOCKET_ACCEPT:
684 {
685 /* Sanity check */
686 if (msg->header.arglen != 0)
687 ERROUT(EINVAL);
688 if (so == NULL)
689 ERROUT(ENXIO);
690
691 /* Make sure the socket is capable of accepting */
692 if (!(so->so_options & SO_ACCEPTCONN))
693 ERROUT(EINVAL);
694 if (priv->flags & KSF_ACCEPTING)
695 ERROUT(EALREADY);
696
697 error = ng_ksocket_check_accept(priv);
698 if (error != 0 && error != EWOULDBLOCK)
699 ERROUT(error);
700
701 /*
702 * If a connection is already complete, take it.
703 * Otherwise let the upcall function deal with
704 * the connection when it comes in.
705 */
706 priv->response_token = msg->header.token;
707 strcpy(priv->response_addr, raddr);
708 if (error == 0) {
709 ng_ksocket_finish_accept(priv,
710 rptr != NULL ? &resp : NULL);
711 } else
712 priv->flags |= KSF_ACCEPTING;
713 break;
714 }
715
716 case NGM_KSOCKET_CONNECT:
717 {
718 struct sockaddr *const sa
719 = (struct sockaddr *)msg->data;
720
721 /* Sanity check */
722 if (msg->header.arglen < SADATA_OFFSET
723 || msg->header.arglen < sa->sa_len)
724 ERROUT(EINVAL);
725 if (so == NULL)
726 ERROUT(ENXIO);
727
728 /* Do connect */
729 if ((so->so_state & SS_ISCONNECTING) != 0)
730 ERROUT(EALREADY);
731 if ((error = soconnect(so, sa, p)) != 0) {
732 so->so_state &= ~SS_ISCONNECTING;
733 ERROUT(error);
734 }
735 if ((so->so_state & SS_ISCONNECTING) != 0) {
736 /* We will notify the sender when we connect */
737 priv->response_token = msg->header.token;
738 strcpy(priv->response_addr, raddr);
739 priv->flags |= KSF_CONNECTING;
740 ERROUT(EINPROGRESS);
741 }
742 break;
743 }
744
745 case NGM_KSOCKET_GETNAME:
746 case NGM_KSOCKET_GETPEERNAME:
747 {
748 int (*func)(struct socket *so, struct sockaddr **nam);
749 struct sockaddr *sa = NULL;
750 int len;
751
752 /* Sanity check */
753 if (msg->header.arglen != 0)
754 ERROUT(EINVAL);
755 if (so == NULL)
756 ERROUT(ENXIO);
757
758 /* Get function */
759 if (msg->header.cmd == NGM_KSOCKET_GETPEERNAME) {
760 if ((so->so_state
761 & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0)
762 ERROUT(ENOTCONN);
763 func = so->so_proto->pr_usrreqs->pru_peeraddr;
764 } else
765 func = so->so_proto->pr_usrreqs->pru_sockaddr;
766
767 /* Get local or peer address */
768 if ((error = (*func)(so, &sa)) != 0)
769 goto bail;
770 len = (sa == NULL) ? 0 : sa->sa_len;
771
772 /* Send it back in a response */
773 NG_MKRESPONSE(resp, msg, len, M_NOWAIT);
774 if (resp == NULL) {
775 error = ENOMEM;
776 goto bail;
777 }
778 bcopy(sa, resp->data, len);
779
780 bail:
781 /* Cleanup */
782 if (sa != NULL)
783 FREE(sa, M_SONAME);
784 break;
785 }
786
787 case NGM_KSOCKET_GETOPT:
788 {
789 struct ng_ksocket_sockopt *ksopt =
790 (struct ng_ksocket_sockopt *)msg->data;
791 struct sockopt sopt;
792
793 /* Sanity check */
794 if (msg->header.arglen != sizeof(*ksopt))
795 ERROUT(EINVAL);
796 if (so == NULL)
797 ERROUT(ENXIO);
798
799 /* Get response with room for option value */
800 NG_MKRESPONSE(resp, msg, sizeof(*ksopt)
801 + NG_KSOCKET_MAX_OPTLEN, M_NOWAIT);
802 if (resp == NULL)
803 ERROUT(ENOMEM);
804
805 /* Get socket option, and put value in the response */
806 sopt.sopt_dir = SOPT_GET;
807 sopt.sopt_level = ksopt->level;
808 sopt.sopt_name = ksopt->name;
809 sopt.sopt_p = NULL;
810 sopt.sopt_valsize = NG_KSOCKET_MAX_OPTLEN;
811 ksopt = (struct ng_ksocket_sockopt *)resp->data;
812 sopt.sopt_val = ksopt->value;
813 if ((error = sogetopt(so, &sopt)) != 0) {
814 FREE(resp, M_NETGRAPH);
815 break;
816 }
817
818 /* Set actual value length */
819 resp->header.arglen = sizeof(*ksopt)
820 + sopt.sopt_valsize;
821 break;
822 }
823
824 case NGM_KSOCKET_SETOPT:
825 {
826 struct ng_ksocket_sockopt *const ksopt =
827 (struct ng_ksocket_sockopt *)msg->data;
828 const int valsize = msg->header.arglen - sizeof(*ksopt);
829 struct sockopt sopt;
830
831 /* Sanity check */
832 if (valsize < 0)
833 ERROUT(EINVAL);
834 if (so == NULL)
835 ERROUT(ENXIO);
836
837 /* Set socket option */
838 sopt.sopt_dir = SOPT_SET;
839 sopt.sopt_level = ksopt->level;
840 sopt.sopt_name = ksopt->name;
841 sopt.sopt_val = ksopt->value;
842 sopt.sopt_valsize = valsize;
843 sopt.sopt_p = NULL;
844 error = sosetopt(so, &sopt);
845 break;
846 }
847
848 default:
849 error = EINVAL;
850 break;
851 }
852 break;
853 case NGM_KSOCKET_INTERNAL_COOKIE:
854 switch (msg->header.cmd) {
855 case NGM_KSOCKET_INTERNAL_UPCALL:
856 if (so == NULL)
857 ERROUT(ENXIO);
858 (*priv->so->so_upcall)(so, so->so_upcallarg, M_NOWAIT);
859 break;
860 default:
861 error = EINVAL;
862 break;
863 }
864 break;
865 default:
866 error = EINVAL;
867 break;
868 }
869 if (rptr)
870 *rptr = resp;
871 else if (resp)
872 FREE(resp, M_NETGRAPH);
873
874done:
875 FREE(msg, M_NETGRAPH);
876 return (error);
877}
878
879/*
880 * Receive incoming data on our hook. Send it out the socket.
881 */
882static int
883ng_ksocket_rcvdata(hook_p hook, struct mbuf *m, meta_p meta)
884{
885 struct proc *p = curproc ? curproc : &proc0; /* XXX broken */
886 const node_p node = hook->node;
887 const priv_p priv = node->private;
888 struct socket *const so = priv->so;
889 struct sockaddr *sa = NULL;
890 int error;
891
892 /* Avoid reentrantly sending on the socket */
893 if ((priv->flags & KSF_SENDING) != 0) {
894 NG_FREE_DATA(m, meta);
895 return (EDEADLK);
896 }
897
898 /* If any meta info, look for peer socket address */
899 if (meta != NULL) {
900 struct meta_field_header *field;
901
902 /* Look for peer socket address */
903 for (field = &meta->options[0];
904 (caddr_t)field < (caddr_t)meta + meta->used_len;
905 field = (struct meta_field_header *)
906 ((caddr_t)field + field->len)) {
907 if (field->cookie != NGM_KSOCKET_COOKIE
908 || field->type != NG_KSOCKET_META_SOCKADDR)
909 continue;
910 sa = (struct sockaddr *)field->data;
911 break;
912 }
913 }
914
915 /* Send packet */
916 priv->flags |= KSF_SENDING;
917 error = (*so->so_proto->pr_usrreqs->pru_sosend)(so, sa, 0, m, 0, 0, p);
918 priv->flags &= ~KSF_SENDING;
919
920 /* Clean up and exit */
921 NG_FREE_META(meta);
922 return (error);
923}
924
925/*
926 * Destroy node
927 */
928static int
929ng_ksocket_rmnode(node_p node)
930{
931 const priv_p priv = node->private;
932 priv_p embryo;
933
934 /* Close our socket (if any) */
935 if (priv->so != NULL) {
936 priv->so->so_upcall = NULL;
937 priv->so->so_rcv.sb_flags &= ~SB_UPCALL;
938 priv->so->so_snd.sb_flags &= ~SB_UPCALL;
939 soclose(priv->so);
940 priv->so = NULL;
941 }
942
943 /* If we are an embryo, take ourselves out of the parent's list */
944 if (priv->flags & KSF_EMBRYONIC) {
945 LIST_REMOVE(priv, siblings);
946 priv->flags &= ~KSF_EMBRYONIC;
947 }
948
949 /* Remove any embryonic children we have */
950 while (!LIST_EMPTY(&priv->embryos)) {
951 embryo = LIST_FIRST(&priv->embryos);
952 ng_rmnode(embryo->node);
953 }
954
955 /* Take down netgraph node */
956 node->flags |= NG_INVALID;
957 ng_cutlinks(node);
958 ng_unname(node);
959 bzero(priv, sizeof(*priv));
960 FREE(priv, M_NETGRAPH);
961 node->private = NULL;
962 ng_unref(node); /* let the node escape */
963 return (0);
964}
965
966/*
967 * Hook disconnection
968 */
969static int
970ng_ksocket_disconnect(hook_p hook)
971{
972 KASSERT(hook->node->numhooks == 0,
973 ("%s: numhooks=%d?", __FUNCTION__, hook->node->numhooks));
974 ng_rmnode(hook->node);
975 return (0);
976}
977
978/************************************************************************
979 HELPER STUFF
980 ************************************************************************/
981
982/*
983 * When incoming data is appended to the socket, we get notified here.
984 * This is also called whenever a significant event occurs for the socket.
985 */
986static void
987ng_ksocket_incoming(struct socket *so, void *arg, int waitflag)
988{
989 const node_p node = arg;
990 const priv_p priv = node->private;
991 struct mbuf *m;
992 struct ng_mesg *response;
993 struct uio auio;
994 int s, flags, error;
995
996 s = splnet();
997
998 /* Sanity check */
999 if ((node->flags & NG_INVALID) != 0) {
1000 splx(s);
1001 return;
1002 }
1003 KASSERT(so == priv->so, ("%s: wrong socket", __FUNCTION__));
1004
1005 /* Check whether a pending connect operation has completed */
1006 if (priv->flags & KSF_CONNECTING) {
1007 if ((error = so->so_error) != 0) {
1008 so->so_error = 0;
1009 so->so_state &= ~SS_ISCONNECTING;
1010 }
1011 if (!(so->so_state & SS_ISCONNECTING)) {
1012 NG_MKMESSAGE(response, NGM_KSOCKET_COOKIE,
1013 NGM_KSOCKET_CONNECT, sizeof(int32_t), waitflag);
1014 if (response != NULL) {
1015 response->header.flags |= NGF_RESP;
1016 response->header.token = priv->response_token;
1017 *(int32_t *)response->data = error;
1018 /*
1019 * XXX We use ng_queue_msg here because we are
1020 * being called from deep in the bowels of the TCP
1021 * stack. Is this right, or should we let the
1022 * receiver of the message worry about that?
1023 */
1024 ng_queue_msg(node, response,
1025 priv->response_addr);
1026 }
1027 priv->flags &= ~KSF_CONNECTING;
1028 }
1029 }
1030
1031 /* Check whether a pending accept operation has completed */
1032 if (priv->flags & KSF_ACCEPTING) {
1033 error = ng_ksocket_check_accept(priv);
1034 if (error != EWOULDBLOCK)
1035 priv->flags &= ~KSF_ACCEPTING;
1036 if (error == 0)
1037 ng_ksocket_finish_accept(priv, NULL);
1038 }
1039
1040 /*
1041 * If we don't have a hook, we must handle data events later. When
1042 * the hook gets created and is connected, this upcall function
1043 * will be called again.
1044 */
1045 if (priv->hook == NULL) {
1046 splx(s);
1047 return;
1048 }
1049
1050 /* Read and forward available mbuf's */
1051 auio.uio_procp = NULL;
1052 auio.uio_resid = 1000000000;
1053 flags = MSG_DONTWAIT;
1054 while (1) {
1055 struct sockaddr *sa = NULL;
1056 meta_p meta = NULL;
1057 struct mbuf *n;
1058
1059 /* Try to get next packet from socket */
1060 if ((error = (*so->so_proto->pr_usrreqs->pru_soreceive)
1061 (so, (so->so_state & SS_ISCONNECTED) ? NULL : &sa,
1062 &auio, &m, (struct mbuf **)0, &flags)) != 0)
1063 break;
1064
1065 /* See if we got anything */
1066 if (m == NULL) {
1067 if (sa != NULL)
1068 FREE(sa, M_SONAME);
1069 break;
1070 }
1071
1072 /* Don't trust the various socket layers to get the
1073 packet header and length correct (eg. kern/15175) */
1074 for (n = m, m->m_pkthdr.len = 0; n != NULL; n = n->m_next)
1075 m->m_pkthdr.len += n->m_len;
1076
1077 /* Put peer's socket address (if any) into a meta info blob */
1078 if (sa != NULL) {
1079 struct meta_field_header *mhead;
1080 u_int len;
1081
1082 len = sizeof(*meta) + sizeof(*mhead) + sa->sa_len;
1083 MALLOC(meta, meta_p, len, M_NETGRAPH, M_NOWAIT);
1084 if (meta == NULL) {
1085 FREE(sa, M_SONAME);
1086 goto sendit;
1087 }
1088 mhead = &meta->options[0];
1089 bzero(meta, sizeof(*meta));
1090 bzero(mhead, sizeof(*mhead));
1091 meta->allocated_len = len;
1092 meta->used_len = len;
1093 mhead->cookie = NGM_KSOCKET_COOKIE;
1094 mhead->type = NG_KSOCKET_META_SOCKADDR;
1095 mhead->len = sizeof(*mhead) + sa->sa_len;
1096 bcopy(sa, mhead->data, sa->sa_len);
1097 FREE(sa, M_SONAME);
1098 }
1099sendit: /* Forward data with optional peer sockaddr as meta info */
1100 NG_SEND_DATA(error, priv->hook, m, meta);
1101 }
1102
1103 /*
1104 * If the peer has closed the connection, forward a 0-length mbuf
1105 * to indicate end-of-file.
1106 */
1107 if (so->so_state & SS_CANTRCVMORE && !(priv->flags & KSF_EOFSEEN)) {
1108 MGETHDR(m, waitflag, MT_DATA);
1109 if (m != NULL) {
1110 m->m_len = m->m_pkthdr.len = 0;
1111 NG_SEND_DATA_ONLY(error, priv->hook, m);
1112 }
1113 priv->flags |= KSF_EOFSEEN;
1114 }
1115
1116 splx(s);
1117}
1118
1119/*
1120 * Check for a completed incoming connection and return 0 if one is found.
1121 * Otherwise return the appropriate error code.
1122 */
1123static int
1124ng_ksocket_check_accept(priv_p priv)
1125{
1126 struct socket *const head = priv->so;
1127 int error;
1128
1129 if ((error = head->so_error) != 0) {
1130 head->so_error = 0;
1131 return error;
1132 }
1133 if (TAILQ_EMPTY(&head->so_comp)) {
1134 if (head->so_state & SS_CANTRCVMORE)
1135 return ECONNABORTED;
1136 return EWOULDBLOCK;
1137 }
1138 return 0;
1139}
1140
1141/*
1142 * Handle the first completed incoming connection, assumed to be already
1143 * on the socket's so_comp queue.
1144 */
1145static void
1146ng_ksocket_finish_accept(priv_p priv, struct ng_mesg **rptr)
1147{
1148 struct socket *const head = priv->so;
1149 struct socket *so;
1150 struct sockaddr *sa = NULL;
1151 struct ng_mesg *resp;
1152 struct ng_ksocket_accept *resp_data;
1153 node_p node2;
1154 priv_p priv2;
1155 int len;
1156
1157 so = TAILQ_FIRST(&head->so_comp);
1158 if (so == NULL) /* Should never happen */
1159 return;
1160 TAILQ_REMOVE(&head->so_comp, so, so_list);
1161 head->so_qlen--;
1162
1163 /* XXX KNOTE(&head->so_rcv.sb_sel.si_note, 0); */
1164
1165 so->so_state &= ~SS_COMP;
1166 so->so_state |= SS_NBIO;
1167 so->so_head = NULL;
1168
1169 soaccept(so, &sa);
1170
1171 len = OFFSETOF(struct ng_ksocket_accept, addr);
1172 if (sa != NULL)
1173 len += sa->sa_len;
1174
1175 NG_MKMESSAGE(resp, NGM_KSOCKET_COOKIE, NGM_KSOCKET_ACCEPT, len,
1176 M_NOWAIT);
1177 if (resp == NULL) {
1178 soclose(so);
1179 goto out;
1180 }
1181 resp->header.flags |= NGF_RESP;
1182 resp->header.token = priv->response_token;
1183
1184 /* Clone a ksocket node to wrap the new socket */
1185 if (ng_ksocket_constructor(&node2) != 0) {
1186 FREE(resp, M_NETGRAPH);
1187 soclose(so);
1188 goto out;
1189 }
1190 priv2 = (priv_p)node2->private;
1191 priv2->so = so;
1192 priv2->flags |= KSF_CLONED | KSF_EMBRYONIC;
1193
1194 /*
1195 * Insert the cloned node into a list of embryonic children
1196 * on the parent node. When a hook is created on the cloned
1197 * node it will be removed from this list. When the parent
1198 * is destroyed it will destroy any embryonic children it has.
1199 */
1200 LIST_INSERT_HEAD(&priv->embryos, priv2, siblings);
1201
1202 so->so_upcallarg = (caddr_t)node2;
1203 so->so_upcall = ng_ksocket_incoming;
1204 so->so_rcv.sb_flags |= SB_UPCALL;
1205 so->so_snd.sb_flags |= SB_UPCALL;
1206
1207 /* Fill in the response data and send it or return it to the caller */
1208 resp_data = (struct ng_ksocket_accept *)resp->data;
1209 resp_data->nodeid = node2->ID;
1210 if (sa != NULL)
1211 bcopy(sa, &resp_data->addr, sa->sa_len);
1212 if (rptr != NULL)
1213 *rptr = resp;
1214 else
1215 ng_queue_msg(priv->node, resp, priv->response_addr);
1216
1217out:
1218 if (sa != NULL)
1219 FREE(sa, M_SONAME);
1220}
1221
1222/*
1223 * Parse out either an integer value or an alias.
1224 */
1225static int
1226ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
1227 const char *s, int family)
1228{
1229 int k, val;
1230 char *eptr;
1231
1232 /* Try aliases */
1233 for (k = 0; aliases[k].name != NULL; k++) {
1234 if (strcmp(s, aliases[k].name) == 0
1235 && aliases[k].family == family)
1236 return aliases[k].value;
1237 }
1238
1239 /* Try parsing as a number */
1240 val = (int)strtoul(s, &eptr, 10);
1241 if (val < 0 || *eptr != '\0')
1242 return (-1);
1243 return (val);
1244}
1245