aboutsummaryrefslogtreecommitdiff
path: root/src/cmd/upas/filterkit/readaddrs.c
blob: 9aadc1ab188ecd8a280acc8fbbc1a7f59e682bae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <u.h>
#include <libc.h>
#include "dat.h"

void*
emalloc(int size)
{
	void *a;

	a = mallocz(size, 1);
	if(a == nil)
		sysfatal("%r");
	return a;
}

char*
estrdup(char *s)
{
	s = strdup(s);
	if(s == nil)
		sysfatal("%r");
	return s;
}

/*
 * like tokenize but obey "" quoting
 */
int
tokenize822(char *str, char **args, int max)
{
	int na;
	int intok = 0, inquote = 0;

	if(max <= 0)
		return 0;	
	for(na=0; ;str++)
		switch(*str) {
		case ' ':
		case '\t':
			if(inquote)
				goto Default;
			/* fall through */
		case '\n':
			*str = 0;
			if(!intok)
				continue;
			intok = 0;
			if(na < max)
				continue;
			/* fall through */
		case 0:
			return na;
		case '"':
			inquote ^= 1;
			/* fall through */
		Default:
		default:
			if(intok)
				continue;
			args[na++] = str;
			intok = 1;
		}
	return 0;	/* can't get here; silence compiler */
}

Addr*
readaddrs(char *file, Addr *a)
{
	int fd;
	int i, n;
	char buf[8*1024];
	char *f[128];
	Addr **l;
	Addr *first;

	/* add to end */
	first = a;
	for(l = &first; *l != nil; l = &(*l)->next)
		;

	/* read in the addresses */
	fd = open(file, OREAD);
	if(fd < 0)
		return first;
	n = read(fd, buf, sizeof(buf)-1);
	close(fd);
	if(n <= 0)
		return first;
	buf[n] = 0;

	n = tokenize822(buf, f, nelem(f));
	for(i = 0; i < n; i++){
		*l = a = emalloc(sizeof *a);
		l = &a->next;
		a->val = estrdup(f[i]);
	}
	return first;
}