csgetval.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. char*
  13. csgetvalue(char *netroot, char *attr, char *val, char *rattr, Ndbtuple **pp)
  14. {
  15. Ndbtuple *t, *first, *last;
  16. int n, linefound;
  17. char line[1024];
  18. int fd;
  19. int oops = 0;
  20. char *rv;
  21. if(pp)
  22. *pp = nil;
  23. rv = nil;
  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 0;
  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 0;
  36. }
  37. seek(fd, 0, 0);
  38. first = last = 0;
  39. linefound = 0;
  40. for(;;){
  41. n = read(fd, line, sizeof(line)-2);
  42. if(n <= 0)
  43. break;
  44. line[n] = '\n';
  45. line[n+1] = 0;
  46. t = _ndbparseline(line);
  47. if(t == 0)
  48. continue;
  49. if(first)
  50. last->entry = t;
  51. else
  52. first = t;
  53. last = t;
  54. while(last->entry)
  55. last = last->entry;
  56. for(; t; t = t->entry){
  57. if(linefound == 0){
  58. if(strcmp(rattr, t->attr) == 0){
  59. linefound = 1;
  60. rv = strdup(t->val);
  61. }
  62. }
  63. }
  64. }
  65. close(fd);
  66. if(oops){
  67. werrstr("buffer too short");
  68. ndbfree(first);
  69. return nil;
  70. }
  71. if(pp){
  72. setmalloctag(first, getcallerpc(&netroot));
  73. *pp = first;
  74. } else
  75. ndbfree(first);
  76. return rv;
  77. }
  78. Ndbtuple*
  79. csgetval(char *netroot, char *attr, char *val, char *rattr, char *buf)
  80. {
  81. Ndbtuple *t;
  82. char *p;
  83. p = csgetvalue(netroot, attr, val, rattr, &t);
  84. if(p == nil){
  85. if(buf != nil)
  86. *buf = 0;
  87. } else {
  88. if(buf != nil){
  89. strncpy(buf, p, Ndbvlen-1);
  90. buf[Ndbvlen-1] = 0;
  91. }
  92. free(p);
  93. }
  94. ndbsetmalloctag(t, getcallerpc(&netroot));
  95. return t;
  96. }