csgetval.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <bio.h>
  12. #include <ndb.h>
  13. #include <ndbhf.h>
  14. /*
  15. * search for a tuple that has the given 'attr=val' and also 'rattr=x'.
  16. * copy 'x' into 'buf' and return the whole tuple.
  17. *
  18. * return 0 if not found.
  19. */
  20. char*
  21. csgetvalue(char *netroot, char *attr, char *val, char *rattr,
  22. Ndbtuple **pp)
  23. {
  24. Ndbtuple *t, *first, *last;
  25. int n, linefound;
  26. char line[1024];
  27. int fd;
  28. int oops = 0;
  29. char *rv;
  30. if(pp)
  31. *pp = nil;
  32. rv = nil;
  33. if(netroot)
  34. snprint(line, sizeof(line), "%s/cs", netroot);
  35. else
  36. strcpy(line, "/net/cs");
  37. fd = open(line, ORDWR);
  38. if(fd < 0)
  39. return 0;
  40. seek(fd, 0, 0);
  41. snprint(line, sizeof(line), "!%s=%s %s=*", attr, val, rattr);
  42. if(write(fd, line, strlen(line)) < 0){
  43. close(fd);
  44. return 0;
  45. }
  46. seek(fd, 0, 0);
  47. first = last = 0;
  48. linefound = 0;
  49. for(;;){
  50. n = read(fd, line, sizeof(line)-2);
  51. if(n <= 0)
  52. break;
  53. line[n] = '\n';
  54. line[n+1] = 0;
  55. t = _ndbparseline(line);
  56. if(t == 0)
  57. continue;
  58. if(first)
  59. last->entry = t;
  60. else
  61. first = t;
  62. last = t;
  63. while(last->entry)
  64. last = last->entry;
  65. for(; t; t = t->entry){
  66. if(linefound == 0){
  67. if(strcmp(rattr, t->attr) == 0){
  68. linefound = 1;
  69. rv = strdup(t->val);
  70. }
  71. }
  72. }
  73. }
  74. close(fd);
  75. if(oops){
  76. werrstr("buffer too short");
  77. ndbfree(first);
  78. return nil;
  79. }
  80. if(pp){
  81. setmalloctag(first, getcallerpc(&netroot));
  82. *pp = first;
  83. } else
  84. ndbfree(first);
  85. return rv;
  86. }
  87. Ndbtuple*
  88. csgetval(char *netroot, char *attr, char *val, char *rattr,
  89. char *buf)
  90. {
  91. Ndbtuple *t;
  92. char *p;
  93. p = csgetvalue(netroot, attr, val, rattr, &t);
  94. if(p == nil){
  95. if(buf != nil)
  96. *buf = 0;
  97. } else {
  98. if(buf != nil){
  99. strncpy(buf, p, Ndbvlen-1);
  100. buf[Ndbvlen-1] = 0;
  101. }
  102. free(p);
  103. }
  104. ndbsetmalloctag(t, getcallerpc(&netroot));
  105. return t;
  106. }