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