2 * Copyright (c) 2000 Brian Somers <brian@Awfulhak.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/param.h>
30 #include <sys/socket.h>
32 #include <netinet/in.h>
33 #include <arpa/inet.h>
36 #include <net/ethernet.h>
37 #include <netinet/in_systm.h>
38 #include <netinet/ip.h>
39 #include <netgraph/ng_ether.h>
40 #include <netgraph/ng_message.h>
41 #include <netgraph/ng_socket.h>
48 #include <sys/fcntl.h>
61 #include "throughput.h"
67 #include "descriptor.h"
76 #include "slcompress.h"
92 struct device dev; /* What struct physical knows about */
93 int cs; /* Control socket */
94 char hook[NG_HOOKLEN + 1]; /* Our socket node hook */
97 #define device2ng(d) ((d)->type == NG_DEVICE ? (struct ngdevice *)d : NULL)
98 #define NG_MSGBUFSZ 4096
99 #define NETGRAPH_PREFIX "netgraph:"
104 return sizeof(struct ngdevice);
108 ng_MessageOut(struct ngdevice *dev, struct physical *p, const char *data)
110 char path[NG_PATHLEN + 1];
115 * We expect a node path, one or more spaces, a command, one or more
116 * spaces and an ascii netgraph structure.
118 data += strspn(data, " \t");
119 len = strcspn(data, " \t");
120 if (len >= sizeof path) {
121 log_Printf(LogWARN, "%s: %.*s: Node path too long\n",
122 dev->dev.name, len, data);
125 memcpy(path, data, len);
129 data += strspn(data, " \t");
130 len = strcspn(data, " \t");
131 for (pos = len; pos >= 0; pos--)
132 if (data[pos] == '%')
134 if ((fmt = alloca(len + 4)) == NULL) {
135 log_Printf(LogWARN, "%s: alloca(%d) failure... %s\n",
136 dev->dev.name, len + 4, strerror(errno));
141 * This is probably a waste of time, but we really don't want to end
142 * up stuffing unexpected % escapes into the kernel....
144 for (pos = dpos = 0; pos < len;) {
145 if (data[dpos] == '%')
147 fmt[pos++] = data[dpos++];
149 strcpy(fmt + pos, " %s");
152 data += strspn(data, " \t");
153 if (NgSendAsciiMsg(dev->cs, path, fmt, data) < 0) {
154 log_Printf(LogDEBUG, "%s: NgSendAsciiMsg (to %s): \"%s\", \"%s\": %s\n",
155 dev->dev.name, path, fmt, data, strerror(errno));
163 * Get a netgraph message
166 ng_MessageIn(struct physical *p, char *buf, size_t sz)
168 char msgbuf[sizeof(struct ng_mesg) * 2 + NG_MSGBUFSZ];
169 struct ngdevice *dev = device2ng(p->handler);
170 struct ng_mesg *rep = (struct ng_mesg *)msgbuf;
171 char path[NG_PATHLEN + 1];
182 if ((r = mkfdset()) == NULL) {
183 log_Printf(LogERROR, "DoLoop: Cannot create fd_set\n");
188 t.tv_sec = t.tv_usec = 0;
189 ret = select(dev->cs + 1, r, NULL, NULL, &t);
196 if (NgRecvAsciiMsg(dev->cs, rep, sizeof msgbuf, path)) {
197 log_Printf(LogWARN, "%s: NgRecvAsciiMsg: %s\n",
198 dev->dev.name, strerror(errno));
202 /* XXX: Should we check rep->header.version ? */
205 log_Printf(LogWARN, "%s: Unexpected message: %s\n", dev->dev.name,
208 log_Printf(LogDEBUG, "%s: Received message: %s\n", dev->dev.name,
210 len = strlen(rep->header.cmdstr);
213 memcpy(buf, rep->header.cmdstr, sz);
220 ng_Write(struct physical *p, const void *v, size_t n)
222 struct ngdevice *dev = device2ng(p->handler);
224 switch (p->dl->state) {
227 return ng_MessageOut(dev, p, v) ? n : -1;
229 return NgSendData(p->fd, dev->hook, v, n) == -1 ? -1 : n;
233 ng_Read(struct physical *p, void *v, size_t n)
235 char hook[NG_HOOKLEN + 1];
237 log_Printf(LogDEBUG, "ng_Read\n");
238 switch (p->dl->state) {
241 return ng_MessageIn(p, v, n);
244 return NgRecvData(p->fd, v, n, hook);
248 ng_RemoveFromSet(struct physical *p, fd_set *r, fd_set *w, fd_set *e)
250 struct ngdevice *dev = device2ng(p->handler);
253 if (r && dev->cs >= 0 && FD_ISSET(dev->cs, r)) {
255 log_Printf(LogTIMER, "%s: fdunset(ctrl) %d\n", p->link.name, dev->cs);
260 /* Careful... physical_RemoveFromSet() called us ! */
262 p->handler->removefromset = NULL;
263 result += physical_RemoveFromSet(p, r, w, e);
264 p->handler->removefromset = ng_RemoveFromSet;
270 ng_Free(struct physical *p)
272 struct ngdevice *dev = device2ng(p->handler);
274 physical_SetDescriptor(p);
281 ng_device2iov(struct device *d, struct iovec *iov, int *niov,
282 int maxiov, int *auxfd, int *nauxfd)
284 struct ngdevice *dev = device2ng(d);
285 int sz = physical_MaxDeviceSize();
287 iov[*niov].iov_base = realloc(d, sz);
288 if (iov[*niov].iov_base == NULL) {
289 log_Printf(LogALERT, "Failed to allocate memory: %d\n", sz);
290 AbortProgram(EX_OSERR);
292 iov[*niov].iov_len = sz;
299 static const struct device basengdevice = {
303 { CD_REQUIRED, DEF_NGCDDELAY },
320 ng_iov2device(int type, struct physical *p, struct iovec *iov, int *niov,
321 int maxiov, int *auxfd, int *nauxfd)
323 if (type == NG_DEVICE) {
324 struct ngdevice *dev = (struct ngdevice *)iov[(*niov)++].iov_base;
326 dev = realloc(dev, sizeof *dev); /* Reduce to the correct size */
328 log_Printf(LogALERT, "Failed to allocate memory: %d\n",
330 AbortProgram(EX_OSERR);
339 /* Refresh function pointers etc */
340 memcpy(&dev->dev, &basengdevice, sizeof dev->dev);
342 /* XXX: Are netgraph always synchronous ? */
343 physical_SetupStack(p, dev->dev.name, PHYSICAL_FORCE_SYNCNOACF);
351 ng_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
353 struct physical *p = descriptor2physical(d);
354 struct ngdevice *dev = device2ng(p->handler);
357 switch (p->dl->state) {
362 log_Printf(LogTIMER, "%s(ctrl): fdset(r) %d\n", p->link.name, dev->cs);
369 result = physical_doUpdateSet(d, r, w, e, n, 0);
377 ng_IsSet(struct fdescriptor *d, const fd_set *fdset)
379 struct physical *p = descriptor2physical(d);
380 struct ngdevice *dev = device2ng(p->handler);
383 result = dev->cs >= 0 && FD_ISSET(dev->cs, fdset);
384 result += physical_IsSet(d, fdset);
390 ng_DescriptorRead(struct fdescriptor *d, struct bundle *bundle,
393 struct physical *p = descriptor2physical(d);
394 struct ngdevice *dev = device2ng(p->handler);
396 if (dev->cs >= 0 && FD_ISSET(dev->cs, fdset))
397 ng_MessageIn(p, NULL, 0);
399 if (physical_IsSet(d, fdset))
400 physical_DescriptorRead(d, bundle, fdset);
403 static struct device *
404 ng_Abandon(struct ngdevice *dev, struct physical *p)
406 /* Abandon our node construction */
409 p->fd = -2; /* Nobody else need try.. */
417 * Populate the ``word'' (of size ``sz'') named ``what'' from ``from''
418 * ending with any character from ``sep''. Point ``endp'' at the next
422 #define GETSEGMENT(what, from, sep, endp) \
423 getsegment(#what, (what), sizeof(what), from, sep, endp)
426 getsegment(const char *what, char *word, size_t sz, const char *from,
427 const char *sep, const char **endp)
431 if ((len = strcspn(from, sep)) == 0) {
432 log_Printf(LogWARN, "%s name should not be empty !\n", what);
437 log_Printf(LogWARN, "%s name too long, max %d !\n", what, sz - 1);
441 strncpy(word, from, len);
445 *endp += strspn(*endp, sep);
451 ng_Create(struct physical *p)
453 struct sockaddr_ng ngsock;
455 struct sockaddr *sock = (struct sockaddr *)&ngsock;
456 const struct hooklist *hlist;
457 const struct nodeinfo *ninfo;
458 const struct linkinfo *nlink;
459 struct ngdevice *dev;
460 struct ng_mesg *resp;
461 struct ngm_mkpeer mkp;
462 struct ngm_connect ngc;
463 const char *devp, *endp;
464 char lasthook[NG_HOOKLEN + 1];
465 char hook[NG_HOOKLEN + 1];
466 char nodetype[NG_TYPELEN + NG_NODELEN + 2];
467 char modname[NG_TYPELEN + 4];
468 char path[NG_PATHLEN + 1];
470 int len, sz, done, f;
473 if (p->fd < 0 && !strncasecmp(p->name.full, NETGRAPH_PREFIX,
474 sizeof NETGRAPH_PREFIX - 1)) {
475 p->fd--; /* We own the device - change fd */
477 if ((dev = malloc(sizeof *dev)) == NULL)
480 loadmodules(LOAD_VERBOSLY, "netgraph", "ng_socket", NULL);
482 /* Create a socket node */
483 if (ID0NgMkSockNode(NULL, &dev->cs, &p->fd) == -1) {
484 log_Printf(LogWARN, "Cannot create netgraph socket node: %s\n",
491 devp = p->name.full + sizeof NETGRAPH_PREFIX - 1;
492 *lasthook = *path = '\0';
493 log_Printf(LogDEBUG, "%s: Opening netgraph device \"%s\"\n",
497 while (*devp != '\0' && !done) {
499 if (*lasthook == '\0') {
500 log_Printf(LogWARN, "%s: Netgraph devices must start with"
501 " [nodetype:nodename]\n", p->link.name);
502 return ng_Abandon(dev, p);
505 /* Get the hook name of the new node */
506 if (!GETSEGMENT(hook, devp, ".[", &endp))
507 return ng_Abandon(dev, p);
508 log_Printf(LogDEBUG, "%s: Got hook \"%s\"\n", p->link.name, hook);
511 log_Printf(LogWARN, "%s: Netgraph device must not end with a second"
512 " hook\n", p->link.name);
513 return ng_Abandon(dev, p);
515 if (devp[-1] != '[') {
516 log_Printf(LogWARN, "%s: Expected a [nodetype:nodename] at device"
517 " pos %d\n", p->link.name, devp - p->link.name - 1);
518 return ng_Abandon(dev, p);
521 /* Use lasthook as the hook name */
522 strcpy(hook, lasthook);
526 /* We've got ``lasthook'' and ``hook'', get the node type */
527 if (!GETSEGMENT(nodetype, devp, "]", &endp))
528 return ng_Abandon(dev, p);
529 log_Printf(LogDEBUG, "%s: Got node \"%s\"\n", p->link.name, nodetype);
531 if ((nodename = strchr(nodetype, ':')) != NULL) {
533 if (*nodename == '\0' && *nodetype == '\0') {
534 log_Printf(LogWARN, "%s: Empty [nodetype:nodename] at device"
535 " pos %d\n", p->link.name, devp - p->link.name - 1);
536 return ng_Abandon(dev, p);
540 /* Ignore optional colons after nodes */
541 devp = *endp == ':' ? endp + 1 : endp;
545 if (*lasthook == '\0') {
546 /* This is the first node in the chain */
547 if (nodename == NULL || *nodename == '\0') {
548 log_Printf(LogWARN, "%s: %s: No initial device nodename\n",
550 return ng_Abandon(dev, p);
553 if (*nodetype != '\0') {
554 /* Attempt to load the module */
555 snprintf(modname, sizeof modname, "ng_%s", nodetype);
556 log_Printf(LogDEBUG, "%s: Attempting to load %s.ko\n",
557 p->link.name, modname);
558 loadmodules(LOAD_QUIETLY, modname, NULL);
561 snprintf(path, sizeof path, "%s:", nodename);
562 /* XXX: If we have a node type, ensure it's correct */
565 * Ask for a list of hooks attached to the previous node. If we
566 * find the one we're interested in, and if it's connected to a
567 * node of the right type using the correct hook, use that.
568 * If we find the hook connected to something else, fail.
569 * If we find no match, mkpeer the new node.
571 if (*nodetype == '\0') {
572 log_Printf(LogWARN, "%s: Nodetype missing at device offset %d\n",
574 devp - p->name.full + sizeof NETGRAPH_PREFIX - 1);
575 return ng_Abandon(dev, p);
578 /* Get a list of node hooks */
579 if (NgSendMsg(dev->cs, path, NGM_GENERIC_COOKIE, NGM_LISTHOOKS,
581 log_Printf(LogWARN, "%s: %s Cannot send a LISTHOOOKS message: %s\n",
582 p->link.name, path, strerror(errno));
583 return ng_Abandon(dev, p);
586 /* Get our list back */
587 resp = (struct ng_mesg *)rbuf;
588 if (NgRecvMsg(dev->cs, resp, sizeof rbuf, NULL) <= 0) {
589 log_Printf(LogWARN, "%s: Cannot get netgraph response: %s\n",
590 p->link.name, strerror(errno));
591 return ng_Abandon(dev, p);
594 hlist = (const struct hooklist *)resp->data;
595 ninfo = &hlist->nodeinfo;
597 log_Printf(LogDEBUG, "List of netgraph node ``%s'' (id %x) hooks:\n",
600 /* look for a hook already attached. */
601 for (f = 0; f < ninfo->hooks; f++) {
602 nlink = &hlist->link[f];
604 log_Printf(LogDEBUG, " Found %s -> %s (type %s)\n", nlink->ourhook,
605 nlink->peerhook, nlink->nodeinfo.type);
607 if (!strcmp(nlink->ourhook, lasthook)) {
608 if (strcmp(nlink->peerhook, hook) ||
609 strcmp(nlink->nodeinfo.type, nodetype)) {
610 log_Printf(LogWARN, "%s: hook %s:%s is already in use\n",
611 p->link.name, nlink->ourhook, path);
612 return ng_Abandon(dev, p);
614 /* The node is already hooked up nicely.... reuse it */
619 if (f == ninfo->hooks) {
620 /* Attempt to load the module */
621 snprintf(modname, sizeof modname, "ng_%s", nodetype);
622 log_Printf(LogDEBUG, "%s: Attempting to load %s.ko\n",
623 p->link.name, modname);
624 loadmodules(LOAD_QUIETLY, modname, NULL);
626 /* Create (mkpeer) the new node */
628 snprintf(mkp.type, sizeof mkp.type, "%s", nodetype);
629 snprintf(mkp.ourhook, sizeof mkp.ourhook, "%s", lasthook);
630 snprintf(mkp.peerhook, sizeof mkp.peerhook, "%s", hook);
632 log_Printf(LogDEBUG, "%s: Doing MKPEER %s%s -> %s (type %s)\n",
633 p->link.name, path, mkp.ourhook, mkp.peerhook, nodetype);
635 if (NgSendMsg(dev->cs, path, NGM_GENERIC_COOKIE,
636 NGM_MKPEER, &mkp, sizeof mkp) < 0) {
637 log_Printf(LogWARN, "%s Cannot create %s netgraph node: %s\n",
638 path, nodetype, strerror(errno));
639 return ng_Abandon(dev, p);
643 snprintf(path + len, sizeof path - len, "%s%s",
644 path[len - 1] == ':' ? "" : ".", lasthook);
647 /* Get a list of node hooks */
648 if (NgSendMsg(dev->cs, path, NGM_GENERIC_COOKIE, NGM_LISTHOOKS,
650 log_Printf(LogWARN, "%s: %s Cannot send a LISTHOOOKS message: %s\n",
651 p->link.name, path, strerror(errno));
652 return ng_Abandon(dev, p);
655 /* Get our list back */
656 resp = (struct ng_mesg *)rbuf;
657 if (NgRecvMsg(dev->cs, resp, sizeof rbuf, NULL) <= 0) {
658 log_Printf(LogWARN, "%s: Cannot get netgraph response: %s\n",
659 p->link.name, strerror(errno));
660 return ng_Abandon(dev, p);
663 hlist = (const struct hooklist *)resp->data;
664 ninfo = &hlist->nodeinfo;
666 if (*lasthook != '\0' && nodename != NULL && *nodename != '\0' &&
667 strcmp(ninfo->name, nodename) &&
668 NgNameNode(dev->cs, path, "%s", nodename) < 0) {
669 log_Printf(LogWARN, "%s: %s: Cannot name netgraph node: %s\n",
670 p->link.name, path, strerror(errno));
671 return ng_Abandon(dev, p);
674 if (!GETSEGMENT(lasthook, devp, " \t.[", &endp))
675 return ng_Abandon(dev, p);
676 log_Printf(LogDEBUG, "%s: Got hook \"%s\"\n", p->link.name, lasthook);
678 len = strlen(lasthook);
679 done = strchr(" \t", devp[len]) ? 1 : 0;
685 } /* else should moan about devp[-1] being '[' ? */
688 snprintf(dev->hook, sizeof dev->hook, "%s", lasthook);
690 /* Connect the node to our socket node */
691 snprintf(ngc.path, sizeof ngc.path, "%s", path);
692 snprintf(ngc.ourhook, sizeof ngc.ourhook, "%s", dev->hook);
693 memcpy(ngc.peerhook, ngc.ourhook, sizeof ngc.peerhook);
695 log_Printf(LogDEBUG, "Connecting netgraph socket .:%s -> %s.%s\n",
696 ngc.ourhook, ngc.path, ngc.peerhook);
697 if (NgSendMsg(dev->cs, ".:", NGM_GENERIC_COOKIE,
698 NGM_CONNECT, &ngc, sizeof ngc) < 0) {
699 log_Printf(LogWARN, "Cannot connect %s and socket netgraph "
700 "nodes: %s\n", path, strerror(errno));
701 return ng_Abandon(dev, p);
704 /* Hook things up so that we monitor dev->cs */
705 p->desc.UpdateSet = ng_UpdateSet;
706 p->desc.IsSet = ng_IsSet;
707 p->desc.Read = ng_DescriptorRead;
709 memcpy(&dev->dev, &basengdevice, sizeof dev->dev);
712 /* See if we're a netgraph socket */
715 if (getsockname(p->fd, sock, &sz) != -1 && sock->sa_family == AF_NETGRAPH) {
717 * It's a netgraph node... We can't determine hook names etc, so we
718 * stay pretty impartial....
720 log_Printf(LogPHASE, "%s: Link is a netgraph node\n", p->link.name);
722 if ((dev = malloc(sizeof *dev)) == NULL) {
723 log_Printf(LogWARN, "%s: Cannot allocate an ether device: %s\n",
724 p->link.name, strerror(errno));
728 memcpy(&dev->dev, &basengdevice, sizeof dev->dev);
735 physical_SetupStack(p, dev->dev.name, PHYSICAL_FORCE_SYNCNOACF);