]> git.lizzy.rs Git - plan9front.git/blob - sys/src/libndb/csgetval.c
games/nes: workaround for truncated chr
[plan9front.git] / sys / src / libndb / csgetval.c
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 char*
14 csgetvalue(char *netroot, char *attr, char *val, char *rattr, Ndbtuple **pp)
15 {
16         Ndbtuple *t, *first, *last;
17         char line[1024];
18         int fd, n;
19         char *rv;
20
21         if(pp != nil)
22                 *pp = nil;
23
24         if(netroot)
25                 snprint(line, sizeof(line), "%s/cs", netroot);
26         else
27                 strcpy(line, "/net/cs");
28         fd = open(line, ORDWR);
29         if(fd < 0)
30                 return nil;
31         seek(fd, 0, 0);
32         snprint(line, sizeof(line), "!%s=%s %s=*", attr, val, rattr);
33         if(write(fd, line, strlen(line)) < 0){
34                 close(fd);
35                 return nil;
36         }
37         seek(fd, 0, 0);
38
39         rv = nil;
40         first = last = nil;
41         for(;;){
42                 n = read(fd, line, sizeof(line)-2);
43                 if(n <= 0)
44                         break;
45                 line[n] = '\n';
46                 line[n+1] = 0;
47
48                 t = _ndbparseline(line);
49                 if(t == nil)
50                         continue;
51                 if(first != nil)
52                         last->entry = t;
53                 else
54                         first = t;
55                 do {
56                         last = t;
57                         if(rv == nil && strcmp(rattr, t->attr) == 0)
58                                 rv = strdup(t->val);
59                         t = t->entry;
60                 } while(t != nil);
61         }
62         close(fd);
63
64         if(pp != nil){
65                 setmalloctag(first, getcallerpc(&netroot));
66                 *pp = first;
67         } else
68                 ndbfree(first);
69
70         return rv;
71 }