Plan 9 from Bell Labs’s /usr/web/sources/contrib/axel/8021x/v212/util.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


#include <u.h>
#include <libc.h>
#include <thread.h>
#include <ip.h>
#include "dat.h"
#include "fns.h"

void
put24(uchar *p, int x)
{
	p[0] = x>>16;
	p[1] = x>>8;
	p[2] = x;
}

int
apetheraddr(uchar *eaddr, char *dir)
{
	char fname[256];
	char buf[2048];
	int fd;
	int n;
	char *p, *e;
	char *s;
	int l;

	s = "Base station: ";
	l = strlen(s);
	snprint(fname, sizeof(fname), "%s/ifstats", dir);
	fd = open(fname, OREAD);
	if (fd < 0) {
		logall("apetheraddr: cannot open %s: %r", fname);
		return -1;
	}

	n = read(fd, buf, sizeof(buf));
	if (n < 0) {
		logall("apetheraddr: cannot read ifstats %s: %r", fname);
		close(fd);
		return -1;
	}
	close(fd);

	p = buf;
	e = p + n;
	while ((e - p > l) && strncmp(p, s, l) != 0) {
		p = strchr(p, '\n');
		p++;
	}
	if ((e - p > l) && strncmp(p, s, l) == 0) {
		p += l;
		if (parseether(eaddr, p) < 0) {
			logall("cannot parse ether from ifstats");
			return -1;
		}
	}
	return 0;
}

char*
nsctime(vlong ns)
{
	static char buf[1024];
	vlong ms;
	long sec, rest;
	char *ctim, *p;

	if (ns == 0)
		return "";

	ms = ns/1000000LL;
	sec = ms/1000;
	rest = ms % 1000;
	ctim = ctime(sec);
	p = buf + snprint(buf, sizeof(buf)-1, "%.*s.%03ld ", 15, ctim+4, rest);
	*p = '\0';
	return buf;
}

long
nsec2sec(vlong ns)
{
	vlong ms;
	long sec;

	ms = ns/1000000LL;
	sec = ms/1000;
	return sec;
}

char*
getstring(char *s)
{
	if (s != nil)
		return s;
	return "";
}

void
clearlog(ReadBuf *b)
{
	memset(b->data, 0, b->sz);
	b->ndata = 0;
}

void
appendlog(ReadBuf *b, int timestamp, char *fmt, ...)
{
	vlong ns;
	char buf[1024];
	char *ctim, *p, *pp;
	va_list arg;
	int n;

	if (timestamp) {
		ns = nsec();
		ctim = nsctime(ns);
		p = buf + snprint(buf, sizeof(buf)-1, "%s", ctim);
	} else
		p = buf;

	va_start(arg, fmt);
	p = vseprint(p, buf+sizeof(buf)-1, fmt, arg);
	va_end(arg);

	pp = p - 1;
	if (pp >= buf && *pp != '\n') {
		*p = '\n';
		p++;
	}

	n = p - buf;

	if (b->sz < b->ndata + n) {
		b->data = realloc(b->data, b->ndata + n);
		b->sz = b->ndata + n;
	}
	memcpy(b->data + b->ndata, buf, n);
	b->ndata += n;
}

static char errbuf[1024];

void
logall(char *fmt, ...)
{
	va_list arg;

	va_start(arg, fmt);
	vseprint(errbuf, errbuf+sizeof(errbuf)-1, fmt, arg);
	va_end(arg);

	syslog(0, logname, "%s", errbuf);
	loglog("%s", errbuf);
}

void
logfatal(int verbose, char *fmt, ...)
{
	va_list arg;

	va_start(arg, fmt);
	vseprint(errbuf, errbuf+sizeof(errbuf)-1, fmt, arg);
	va_end(arg);

	syslog(0, logname, "%s", errbuf);
	loglog("%s", errbuf);
	if (verbose)
		sysfatal(errbuf);
	else
		threadexitsall(errbuf);
}

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.