csgetval.c 1.2 KB

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