Plan 9 from Bell Labs’s /usr/web/sources/contrib/steve/root/sys/src/cmd/snmpfs/map.c

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


#include <u.h>
#include <libc.h>
#include <bio.h>

typedef struct Map Map;
struct Map {
	char *oid;
	char *path;
};

static int used;
static int alloc;
static Map *Maptab;

/* bsearch lifted from /sys/src/ape/lib/ap/gen/bsearch.c */
void*
bsearch(void* key, const void* base, int nmemb, int size,
		int (*compar)(void*, void*))
{
	long i, bot, top, new;
	void *p;

	bot = 0;
	top = bot + nmemb - 1;
	while(bot <= top){
		new = (top + bot)/2;
		p = (char *)base+new*size;
		i = (*compar)(key, p);
		if(i == 0)
			return p;
		if(i > 0)
			bot = new + 1;
		else
			top = new - 1;
	}
	return 0;
}

static int
mapcmp(void *a, void *b)
{
	return strcmp(((Map *)a)->oid, ((Map *)b)->oid);
}

int
load1map(char *fn)
{
	Biobuf *bp;
	char *line, *arr[3];

	if((bp = Bopen(fn, OREAD)) == nil)
		return -1;

	while((line = Brdline(bp, '\n')) != nil){
		line[Blinelen(bp)-1] = 0;
		if(tokenize(line, arr, nelem(arr)) < 2)
			continue;
		if(*arr[0] == '#')
			continue;

		if(used >= alloc){
			alloc += 64;
			if((Maptab = realloc(Maptab, alloc*sizeof(Map))) == nil)
				sysfatal("No memory\n");
		}
		Maptab[used].oid = strdup(arr[0]);
		if(Maptab[used].oid == nil)
			sysfatal("No memory - %r\n");
		Maptab[used].path = strdup(arr[1]);
		if(Maptab[used].path == nil)
			sysfatal("No memory - %r\n");
		used++;
	}
	Bterm(bp);
	qsort(Maptab, used, sizeof(Map), mapcmp);
	return 0;
}

void
loadmap(void)
{
	Dir *d;
	char *p, *fn;
	int fd, n, i;
	char *mapdir = "/lib/snmp";

	if((fd = open(mapdir, OREAD)) == -1){
		fprint(2, "%s: warning: %s cannot open directory - %r\n", mapdir, argv0);
		return;
	}
	n = dirreadall(fd, &d);
	close(fd);

	for(i = 0; i < n; i++){
		if((p = strrchr(d[i].name, '.')) == nil)
			continue;
		if(strcmp(p, ".map") == 0){
			fn = smprint("%s/%s", mapdir, d[i].name);
			if(load1map(fn) < 0)
				fprint(2, "%s: warning: %s cannot open file - %r\n", argv0, fn);
			free(fn);
		}
	}
	free(d);
}

char *
lookmap(char *oid)
{
	Map m, *mp;

	m.oid = oid;
	mp = bsearch(&m, Maptab, used, sizeof(Map), mapcmp);
	if(mp == nil)
		return nil;
	return mp->path;
}


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.