xref: /plan9/sys/src/cmd/upas/filterkit/readaddrs.c (revision b85a83648eec38fe82b6f00adfd7828ceec5ee8d)
1 #include <u.h>
2 #include <libc.h>
3 #include "dat.h"
4 
5 void*
emalloc(int size)6 emalloc(int size)
7 {
8 	void *a;
9 
10 	a = mallocz(size, 1);
11 	if(a == nil)
12 		sysfatal("%r");
13 	return a;
14 }
15 
16 char*
estrdup(char * s)17 estrdup(char *s)
18 {
19 	s = strdup(s);
20 	if(s == nil)
21 		sysfatal("%r");
22 	return s;
23 }
24 
25 /*
26  * like tokenize but obey "" quoting
27  */
28 int
tokenize822(char * str,char ** args,int max)29 tokenize822(char *str, char **args, int max)
30 {
31 	int na;
32 	int intok = 0, inquote = 0;
33 
34 	if(max <= 0)
35 		return 0;
36 	for(na=0; ;str++)
37 		switch(*str) {
38 		case ' ':
39 		case '\t':
40 			if(inquote)
41 				goto Default;
42 			/* fall through */
43 		case '\n':
44 			*str = 0;
45 			if(!intok)
46 				continue;
47 			intok = 0;
48 			if(na < max)
49 				continue;
50 			/* fall through */
51 		case 0:
52 			return na;
53 		case '"':
54 			inquote ^= 1;
55 			/* fall through */
56 		Default:
57 		default:
58 			if(intok)
59 				continue;
60 			args[na++] = str;
61 			intok = 1;
62 		}
63 }
64 
65 Addr*
readaddrs(char * file,Addr * a)66 readaddrs(char *file, Addr *a)
67 {
68 	int fd;
69 	int i, n;
70 	char buf[8*1024];
71 	char *f[128];
72 	Addr **l;
73 	Addr *first;
74 
75 	/* add to end */
76 	first = a;
77 	for(l = &first; *l != nil; l = &(*l)->next)
78 		;
79 
80 	/* read in the addresses */
81 	fd = open(file, OREAD);
82 	if(fd < 0)
83 		return first;
84 	n = read(fd, buf, sizeof(buf)-1);
85 	close(fd);
86 	if(n <= 0)
87 		return first;
88 	buf[n] = 0;
89 
90 	n = tokenize822(buf, f, nelem(f));
91 	for(i = 0; i < n; i++){
92 		*l = a = emalloc(sizeof *a);
93 		l = &a->next;
94 		a->val = estrdup(f[i]);
95 	}
96 	return first;
97 }
98