xref: /plan9/sys/src/libndb/csgetval.c (revision 219b2ee8daee37f4aad58d63f21287faa8e4ffdc)
1 #include <u.h>
2 #include <libc.h>
3 #include <bio.h>
4 #include <ndb.h>
5 #include <ndbhf.h>
6 
7 /*
8  *  search for a tuple that has the given 'attr=val' and also 'rattr=x'.
9  *  copy 'x' into 'buf' and return the whole tuple.
10  *
11  *  return 0 if not found.
12  */
13 Ndbtuple*
14 csgetval(char *attr, char *val, char *rattr, char *buf)
15 {
16 	Ndbtuple *t, *first, *last;
17 	int n, fd, linefound;
18 	char line[1024];
19 
20 	buf[0] = 0;
21 	fd = open("/net/cs", ORDWR);
22 	if(fd < 0)
23 		return 0;
24 	fprint(fd, "!%s=%s", attr, val);
25 	seek(fd, 0, 0);
26 
27 	first = last = 0;
28 	linefound = 0;
29 	for(;;){
30 		n = read(fd, line, sizeof(line)-2);
31 		if(n <= 0)
32 			break;
33 		line[n] = '\n';
34 		line[n+1] = 0;
35 
36 		t = _ndbparseline(line);
37 		if(t == 0)
38 			continue;
39 		if(first)
40 			last->entry = t;
41 		else
42 			first = t;
43 		last = t;
44 
45 		while(last->entry)
46 			last = last->entry;
47 
48 		for(; t; t = t->entry){
49 			if(buf[0] == 0 || linefound == 0)
50 				if(strcmp(rattr, t->attr) == 0)
51 					strcpy(buf, t->val);
52 			if(linefound == 0)
53 				if(strcmp(attr, t->attr) == 0)
54 					linefound = 1;
55 		}
56 	}
57 	close(fd);
58 	return first;
59 }
60