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
26 * $FreeBSD: src/usr.sbin/ppp/netgraph.c,v 1.4.2.1 2002/09/01 02:12:29 brian Exp $
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 },
321 ng_iov2device(int type, struct physical *p, struct iovec *iov, int *niov,
322 int maxiov, int *auxfd, int *nauxfd)
324 if (type == NG_DEVICE) {
325 struct ngdevice *dev = (struct ngdevice *)iov[(*niov)++].iov_base;
327 dev = realloc(dev, sizeof *dev); /* Reduce to the correct size */
329 log_Printf(LogALERT, "Failed to allocate memory: %d\n",
331 AbortProgram(EX_OSERR);
340 /* Refresh function pointers etc */
341 memcpy(&dev->dev, &basengdevice, sizeof dev->dev);
343 /* XXX: Are netgraph always synchronous ? */
344 physical_SetupStack(p, dev->dev.name, PHYSICAL_FORCE_SYNCNOACF);
352 ng_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
354 struct physical *p = descriptor2physical(d);
355 struct ngdevice *dev = device2ng(p->handler);
358 switch (p->dl->state) {
363 log_Printf(LogTIMER, "%s(ctrl): fdset(r) %d\n", p->link.name, dev->cs);
370 result = physical_doUpdateSet(d, r, w, e, n, 0);
378 ng_IsSet(struct fdescriptor *d, const fd_set *fdset)
380 struct physical *p = descriptor2physical(d);
381 struct ngdevice *dev = device2ng(p->handler);
384 result = dev->cs >= 0 && FD_ISSET(dev->cs, fdset);
385 result += physical_IsSet(d, fdset);
391 ng_DescriptorRead(struct fdescriptor *d, struct bundle *bundle,
394 struct physical *p = descriptor2physical(d);
395 struct ngdevice *dev = device2ng(p->handler);
397 if (dev->cs >= 0 && FD_ISSET(dev->cs, fdset))
398 ng_MessageIn(p, NULL, 0);
400 if (physical_IsSet(d, fdset))
401 physical_DescriptorRead(d, bundle, fdset);
404 static struct device *
405 ng_Abandon(struct ngdevice *dev, struct physical *p)
407 /* Abandon our node construction */
410 p->fd = -2; /* Nobody else need try.. */
418 * Populate the ``word'' (of size ``sz'') named ``what'' from ``from''
419 * ending with any character from ``sep''. Point ``endp'' at the next
423 #define GETSEGMENT(what, from, sep, endp) \
424 getsegment(#what, (what), sizeof(what), from, sep, endp)
427 getsegment(const char *what, char *word, size_t sz, const char *from,
428 const char *sep, const char **endp)
432 if ((len = strcspn(from, sep)) == 0) {
433 log_Printf(LogWARN, "%s name should not be empty !\n", what);
438 log_Printf(LogWARN, "%s name too long, max %d !\n", what, sz - 1);
442 strncpy(word, from, len);
446 *endp += strspn(*endp, sep);
452 ng_Create(struct physical *p)
454 struct sockaddr_ng ngsock;
456 struct sockaddr *sock = (struct sockaddr *)&ngsock;
457 const struct hooklist *hlist;
458 const struct nodeinfo *ninfo;
459 const struct linkinfo *nlink;
460 struct ngdevice *dev;
461 struct ng_mesg *resp;
462 struct ngm_mkpeer mkp;
463 struct ngm_connect ngc;
464 const char *devp, *endp;
465 char lasthook[NG_HOOKLEN + 1];
466 char hook[NG_HOOKLEN + 1];
467 char nodetype[NG_TYPELEN + NG_NODELEN + 2];
468 char modname[NG_TYPELEN + 4];
469 char path[NG_PATHLEN + 1];
471 int len, sz, done, f;
474 if (p->fd < 0 && !strncasecmp(p->name.full, NETGRAPH_PREFIX,
475 sizeof NETGRAPH_PREFIX - 1)) {
476 p->fd--; /* We own the device - change fd */
478 if ((dev = malloc(sizeof *dev)) == NULL)
481 loadmodules(LOAD_VERBOSLY, "netgraph", "ng_socket", NULL);
483 /* Create a socket node */
484 if (ID0NgMkSockNode(NULL, &dev->cs, &p->fd) == -1) {
485 log_Printf(LogWARN, "Cannot create netgraph socket node: %s\n",
492 devp = p->name.full + sizeof NETGRAPH_PREFIX - 1;
493 *lasthook = *path = '\0';
494 log_Printf(LogDEBUG, "%s: Opening netgraph device \"%s\"\n",
498 while (*devp != '\0' && !done) {
500 if (*lasthook == '\0') {
501 log_Printf(LogWARN, "%s: Netgraph devices must start with"
502 " [nodetype:nodename]\n", p->link.name);
503 return ng_Abandon(dev, p);
506 /* Get the hook name of the new node */
507 if (!GETSEGMENT(hook, devp, ".[", &endp))
508 return ng_Abandon(dev, p);
509 log_Printf(LogDEBUG, "%s: Got hook \"%s\"\n", p->link.name, hook);
512 log_Printf(LogWARN, "%s: Netgraph device must not end with a second"
513 " hook\n", p->link.name);
514 return ng_Abandon(dev, p);
516 if (devp[-1] != '[') {
517 log_Printf(LogWARN, "%s: Expected a [nodetype:nodename] at device"
518 " pos %d\n", p->link.name, devp - p->link.name - 1);
519 return ng_Abandon(dev, p);
522 /* Use lasthook as the hook name */
523 strcpy(hook, lasthook);
527 /* We've got ``lasthook'' and ``hook'', get the node type */
528 if (!GETSEGMENT(nodetype, devp, "]", &endp))
529 return ng_Abandon(dev, p);
530 log_Printf(LogDEBUG, "%s: Got node \"%s\"\n", p->link.name, nodetype);
532 if ((nodename = strchr(nodetype, ':')) != NULL) {
534 if (*nodename == '\0' && *nodetype == '\0') {
535 log_Printf(LogWARN, "%s: Empty [nodetype:nodename] at device"
536 " pos %d\n", p->link.name, devp - p->link.name - 1);
537 return ng_Abandon(dev, p);
541 /* Ignore optional colons after nodes */
542 devp = *endp == ':' ? endp + 1 : endp;
546 if (*lasthook == '\0') {
547 /* This is the first node in the chain */
548 if (nodename == NULL || *nodename == '\0') {
549 log_Printf(LogWARN, "%s: %s: No initial device nodename\n",
551 return ng_Abandon(dev, p);
554 if (*nodetype != '\0') {
555 /* Attempt to load the module */
556 snprintf(modname, sizeof modname, "ng_%s", nodetype);
557 log_Printf(LogDEBUG, "%s: Attempting to load %s.ko\n",
558 p->link.name, modname);
559 loadmodules(LOAD_QUIETLY, modname, NULL);
562 snprintf(path, sizeof path, "%s:", nodename);
563 /* XXX: If we have a node type, ensure it's correct */
566 * Ask for a list of hooks attached to the previous node. If we
567 * find the one we're interested in, and if it's connected to a
568 * node of the right type using the correct hook, use that.
569 * If we find the hook connected to something else, fail.
570 * If we find no match, mkpeer the new node.
572 if (*nodetype == '\0') {
573 log_Printf(LogWARN, "%s: Nodetype missing at device offset %d\n",
575 devp - p->name.full + sizeof NETGRAPH_PREFIX - 1);
576 return ng_Abandon(dev, p);
579 /* Get a list of node hooks */
580 if (NgSendMsg(dev->cs, path, NGM_GENERIC_COOKIE, NGM_LISTHOOKS,
582 log_Printf(LogWARN, "%s: %s Cannot send a LISTHOOOKS message: %s\n",
583 p->link.name, path, strerror(errno));
584 return ng_Abandon(dev, p);
587 /* Get our list back */
588 resp = (struct ng_mesg *)rbuf;
589 if (NgRecvMsg(dev->cs, resp, sizeof rbuf, NULL) <= 0) {
590 log_Printf(LogWARN, "%s: Cannot get netgraph response: %s\n",
591 p->link.name, strerror(errno));
592 return ng_Abandon(dev, p);
595 hlist = (const struct hooklist *)resp->data;
596 ninfo = &hlist->nodeinfo;
598 log_Printf(LogDEBUG, "List of netgraph node ``%s'' (id %x) hooks:\n",
601 /* look for a hook already attached. */
602 for (f = 0; f < ninfo->hooks; f++) {
603 nlink = &hlist->link[f];
605 log_Printf(LogDEBUG, " Found %s -> %s (type %s)\n", nlink->ourhook,
606 nlink->peerhook, nlink->nodeinfo.type);
608 if (!strcmp(nlink->ourhook, lasthook)) {
609 if (strcmp(nlink->peerhook, hook) ||
610 strcmp(nlink->nodeinfo.type, nodetype)) {
611 log_Printf(LogWARN, "%s: hook %s:%s is already in use\n",
612 p->link.name, nlink->ourhook, path);
613 return ng_Abandon(dev, p);
615 /* The node is already hooked up nicely.... reuse it */
620 if (f == ninfo->hooks) {
621 /* Attempt to load the module */
622 snprintf(modname, sizeof modname, "ng_%s", nodetype);
623 log_Printf(LogDEBUG, "%s: Attempting to load %s.ko\n",
624 p->link.name, modname);
625 loadmodules(LOAD_QUIETLY, modname, NULL);
627 /* Create (mkpeer) the new node */
629 snprintf(mkp.type, sizeof mkp.type, "%s", nodetype);
630 snprintf(mkp.ourhook, sizeof mkp.ourhook, "%s", lasthook);
631 snprintf(mkp.peerhook, sizeof mkp.peerhook, "%s", hook);
633 log_Printf(LogDEBUG, "%s: Doing MKPEER %s%s -> %s (type %s)\n",
634 p->link.name, path, mkp.ourhook, mkp.peerhook, nodetype);
636 if (NgSendMsg(dev->cs, path, NGM_GENERIC_COOKIE,
637 NGM_MKPEER, &mkp, sizeof mkp) < 0) {
638 log_Printf(LogWARN, "%s Cannot create %s netgraph node: %s\n",
639 path, nodetype, strerror(errno));
640 return ng_Abandon(dev, p);
644 snprintf(path + len, sizeof path - len, "%s%s",
645 path[len - 1] == ':' ? "" : ".", lasthook);
648 /* Get a list of node hooks */
649 if (NgSendMsg(dev->cs, path, NGM_GENERIC_COOKIE, NGM_LISTHOOKS,
651 log_Printf(LogWARN, "%s: %s Cannot send a LISTHOOOKS message: %s\n",
652 p->link.name, path, strerror(errno));
653 return ng_Abandon(dev, p);
656 /* Get our list back */
657 resp = (struct ng_mesg *)rbuf;
658 if (NgRecvMsg(dev->cs, resp, sizeof rbuf, NULL) <= 0) {
659 log_Printf(LogWARN, "%s: Cannot get netgraph response: %s\n",
660 p->link.name, strerror(errno));
661 return ng_Abandon(dev, p);
664 hlist = (const struct hooklist *)resp->data;
665 ninfo = &hlist->nodeinfo;
667 if (*lasthook != '\0' && nodename != NULL && *nodename != '\0' &&
668 strcmp(ninfo->name, nodename) &&
669 NgNameNode(dev->cs, path, "%s", nodename) < 0) {
670 log_Printf(LogWARN, "%s: %s: Cannot name netgraph node: %s\n",
671 p->link.name, path, strerror(errno));
672 return ng_Abandon(dev, p);
675 if (!GETSEGMENT(lasthook, devp, " \t.[", &endp))
676 return ng_Abandon(dev, p);
677 log_Printf(LogDEBUG, "%s: Got hook \"%s\"\n", p->link.name, lasthook);
679 len = strlen(lasthook);
680 done = strchr(" \t", devp[len]) ? 1 : 0;
686 } /* else should moan about devp[-1] being '[' ? */
689 snprintf(dev->hook, sizeof dev->hook, "%s", lasthook);
691 /* Connect the node to our socket node */
692 snprintf(ngc.path, sizeof ngc.path, "%s", path);
693 snprintf(ngc.ourhook, sizeof ngc.ourhook, "%s", dev->hook);
694 memcpy(ngc.peerhook, ngc.ourhook, sizeof ngc.peerhook);
696 log_Printf(LogDEBUG, "Connecting netgraph socket .:%s -> %s.%s\n",
697 ngc.ourhook, ngc.path, ngc.peerhook);
698 if (NgSendMsg(dev->cs, ".:", NGM_GENERIC_COOKIE,
699 NGM_CONNECT, &ngc, sizeof ngc) < 0) {
700 log_Printf(LogWARN, "Cannot connect %s and socket netgraph "
701 "nodes: %s\n", path, strerror(errno));
702 return ng_Abandon(dev, p);
705 /* Hook things up so that we monitor dev->cs */
706 p->desc.UpdateSet = ng_UpdateSet;
707 p->desc.IsSet = ng_IsSet;
708 p->desc.Read = ng_DescriptorRead;
710 memcpy(&dev->dev, &basengdevice, sizeof dev->dev);
713 /* See if we're a netgraph socket */
716 if (getsockname(p->fd, sock, &sz) != -1 && sock->sa_family == AF_NETGRAPH) {
718 * It's a netgraph node... We can't determine hook names etc, so we
719 * stay pretty impartial....
721 log_Printf(LogPHASE, "%s: Link is a netgraph node\n", p->link.name);
723 if ((dev = malloc(sizeof *dev)) == NULL) {
724 log_Printf(LogWARN, "%s: Cannot allocate an ether device: %s\n",
725 p->link.name, strerror(errno));
729 memcpy(&dev->dev, &basengdevice, sizeof dev->dev);
736 physical_SetupStack(p, dev->dev.name, PHYSICAL_FORCE_SYNCNOACF);