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

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


#include <u.h>
#include <libc.h>
#include <fcall.h>
#include <thread.h>
#include <9p.h>
#include "dat.h"
#include "fns.h"

void
netloginit(Netlog *l)
{
	memset(l, 0, sizeof(Netlog));
	l->ping = chancreate(sizeof(int), 0);
}

void
netlogopen(Netlog *l)
{
	qlock(l);
	if(l->opens == 0){
		if(l->buf == nil)
			l->buf = emalloc9p(Nlog);
		l->rptr = l->buf;
		l->end = l->buf + Nlog;
	}
	l->opens++;
	qunlock(l);
}

void
netlogclose(Netlog *l)
{
	qlock(l);
	l->opens--;
	if(l->opens == 0){
		free(l->buf);
		l->buf = nil;
	}
	qunlock(l);
}


long
netlogread(Netlog *l, void *a, long n, vlong o, int *off)
{
	int i, d, od;
	char *p, *rptr, *eptr;

//	syslog(0, logname, "netlogread %p n=%ld l->len=%d o=%lld l->o=%lld", l, n, l->len, o, l->offset);

	qlock(l);

	if (o + *off < l->offset)
		*off = l->offset - o;

	if(l->len){
		od = 0;
		o += *off;
		if (o > l->offset)
			od = o - l->offset;
//		syslog(0, logname, "netlogread %p: n=%ld od=%d l->len=%d", l, n, od, l->len);
		if (od >= l->len) {
			qunlock(l);
			return 0;
		}
		if(n > l->len - od)
			n = l->len - od;
		if (n < 0)
			logfatal(0, "netlogread n < 0");
		else if (n == 0) {
			qunlock(l);
			return 0;
		}
		d = 0;
		rptr = l->rptr;
		rptr += od;
		if (rptr >= l->end){
			d = rptr - l->end;
			rptr = l->buf + d;
		}
		d = 0;
		eptr = rptr + n;
		if(eptr >= l->end){
			d = eptr - l->end;
			eptr = l->buf + d;
		}

		i = n-d;

		p = a;
		memmove(p, rptr, i);
		memmove(p+i, l->buf, d);
	} else
		n = 0;

	qunlock(l);

	return n;
}

int
netlog(Netlog *l, char *fmt, va_list arg)
{
	vlong ns;
	char buf[1024], *t, *fp;
	char *ctim, *p, *pp;
	int i, n;

	if (l->opens == 0)
		return 0;

	ns = nsec();
	ctim = nsctime(ns);
	p = buf + snprint(buf, sizeof(buf)-1, "%s ", ctim);

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

//	syslog( 0, logname, "%s", buf);

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

	n = p - buf;

	qlock(l);
	i = l->len + n - Nlog;
	if(i > 0){
		l->offset += i;
		l->len -= i;
		l->rptr += i;
		if(l->rptr >= l->end)
			l->rptr = l->buf + (l->rptr - l->end);
	}
	t = l->rptr + l->len;
	fp = buf;
	l->len += n;
	while(n-- > 0){
		if(t >= l->end)
			t = l->buf + (t - l->end);
		*t++ = *fp++;
	}
	qunlock(l);
	send(l->ping, nil);
	return n;
}

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.