#include <sys/param.h>
#include <sys/queue.h>
#include <assert.h>
#include <err.h>
#include <fcntl.h>
#include <paths.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "extern.h"
int mpfd;
static ctbl_t ctbl_main = {
{ "rule", rule_main },
{ "ruleset", ruleset_main },
{ NULL, NULL }
};
int
main(int ac, char **av)
{
const char *mountpt;
struct cmd *c;
int ch;
mountpt = NULL;
while ((ch = getopt(ac, av, "m:")) != -1)
switch (ch) {
case 'm':
mountpt = optarg;
break;
default:
usage();
}
ac -= optind;
av += optind;
if (ac < 1)
usage();
if (mountpt == NULL)
mountpt = _PATH_DEV;
mpfd = open(mountpt, O_RDONLY);
if (mpfd == -1)
err(1, "open: %s", mountpt);
for (c = ctbl_main; c->name != NULL; ++c)
if (strcmp(c->name, av[0]) == 0)
exit((*c->handler)(ac, av));
errx(1, "unknown command: %s", av[0]);
}
int
atonum(const char *s, uint16_t *num)
{
unsigned long ul;
char *cp;
ul = strtoul(s, &cp, 10);
if (ul > UINT16_MAX || *cp != '\0')
return (0);
*num = (uint16_t)ul;
return (1);
}
int
eatoi(const char *s)
{
char *cp;
long l;
l = strtol(s, &cp, 10);
if (l > INT_MAX || *cp != '\0')
errx(1, "error converting to integer: %s", s);
return ((int)l);
}
uint16_t
eatonum(const char *s)
{
uint16_t num;
if (!atonum(s, &num))
errx(1, "error converting to number: %s", s);
return (num);
}
size_t
efgetln(FILE *fp, char **line)
{
size_t rv;
char *cp;
cp = fgetln(fp, &rv);
if (cp == NULL) {
*line = NULL;
return (rv);
}
if (cp[rv - 1] == '\n') {
cp[rv - 1] = '\0';
*line = strdup(cp);
if (*line == NULL)
errx(1, "cannot allocate memory");
--rv;
} else {
*line = malloc(rv + 1);
if (*line == NULL)
errx(1, "cannot allocate memory");
memcpy(*line, cp, rv);
(*line)[rv] = '\0';
}
assert(rv == strlen(*line));
return (rv);
}
struct ptrstq {
STAILQ_ENTRY(ptrstq) tq;
void *ptr;
};
void
tokenize(const char *line, int *acp, char ***avp)
{
static const char *delims = " \t\n";
struct ptrstq *pt;
STAILQ_HEAD(, ptrstq) plist;
char **ap, *cp, *wline, *xcp;
line += strspn(line, delims);
wline = strdup(line);
if (wline == NULL)
errx(1, "cannot allocate memory");
STAILQ_INIT(&plist);
for (xcp = wline, *acp = 0;
(cp = strsep(&xcp, delims)) != NULL;)
if (*cp != '\0') {
pt = calloc(1, sizeof(*pt));
if (pt == NULL)
errx(1, "cannot allocate memory");
pt->ptr = cp;
STAILQ_INSERT_TAIL(&plist, pt, tq);
++*acp;
}
if (*acp == 0)
return;
assert(STAILQ_FIRST(&plist)->ptr == wline);
*avp = malloc(sizeof(**avp) * (*acp + 1));
if (*avp == NULL)
errx(1, "cannot allocate memory");
for (ap = *avp; !STAILQ_EMPTY(&plist);) {
pt = STAILQ_FIRST(&plist);
*ap = pt->ptr;
++ap;
assert(ap <= *avp + (*acp));
STAILQ_REMOVE_HEAD(&plist, tq);
free(pt);
}
*ap = NULL;
}
void
usage(void)
{
fprintf(stderr, "usage: %s\n%s\n",
"\tdevfs [-m mount-point] rule [-s ruleset] ...",
"\tdevfs [-m mount-point] ruleset ...");
exit(1);
}