dnsquery.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <bio.h>
  4. #include <ndb.h>
  5. #include "dns.h"
  6. #include "ip.h"
  7. void
  8. main(int argc, char *argv[])
  9. {
  10. int fd, n, len, domount;
  11. Biobuf in;
  12. char line[1024], *lp, *p, *np, *mtpt, *srv, *dns;
  13. char buf[1024];
  14. dns = "/net/dns";
  15. mtpt = "/net";
  16. srv = "/srv/dns";
  17. domount = 1;
  18. ARGBEGIN {
  19. case 'x':
  20. dns = "/net.alt/dns";
  21. mtpt = "/net.alt";
  22. srv = "/srv/dns_net.alt";
  23. break;
  24. default:
  25. fprint(2, "usage: %s -x [dns-mount-point]\n", argv0);
  26. exits("usage");
  27. } ARGEND;
  28. if(argc == 1){
  29. domount = 0;
  30. mtpt = argv[0];
  31. }
  32. fd = open(dns, ORDWR);
  33. if(fd < 0){
  34. if(domount == 0){
  35. fprint(2, "can't open %s: %r\n", mtpt);
  36. exits(0);
  37. }
  38. fd = open(srv, ORDWR);
  39. if(fd < 0){
  40. print("can't open %s: %r\n", srv);
  41. exits(0);
  42. }
  43. if(mount(fd, -1, mtpt, MBEFORE, "") < 0){
  44. print("can't mount(%s, %s): %r\n", srv, mtpt);
  45. exits(0);
  46. }
  47. fd = open(mtpt, ORDWR);
  48. if(fd < 0){
  49. print("can't open %s: %r\n", mtpt);
  50. exits(0);
  51. }
  52. }
  53. Binit(&in, 0, OREAD);
  54. for(print("> "); lp = Brdline(&in, '\n'); print("> ")){
  55. n = Blinelen(&in)-1;
  56. strncpy(line, lp, n);
  57. line[n] = 0;
  58. if (n<=1)
  59. continue;
  60. /* default to an "ip" request if alpha, "ptr" if numeric */
  61. if (strchr(line, ' ')==0) {
  62. if(strcmp(ipattr(line), "ip") == 0) {
  63. strcat(line, " ptr");
  64. n += 4;
  65. } else {
  66. strcat(line, " ip");
  67. n += 3;
  68. }
  69. }
  70. /* inverse queries may need to be permuted */
  71. if(n > 4 && strcmp("ptr", &line[n-3]) == 0
  72. && strstr(line, "IN-ADDR") == 0 && strstr(line, "in-addr") == 0){
  73. for(p = line; *p; p++)
  74. if(*p == ' '){
  75. *p = '.';
  76. break;
  77. }
  78. np = buf;
  79. len = 0;
  80. while(p >= line){
  81. len++;
  82. p--;
  83. if(*p == '.'){
  84. memmove(np, p+1, len);
  85. np += len;
  86. len = 0;
  87. }
  88. }
  89. memmove(np, p+1, len);
  90. np += len;
  91. strcpy(np, "in-addr.arpa ptr");
  92. strcpy(line, buf);
  93. n = strlen(line);
  94. }
  95. seek(fd, 0, 0);
  96. if(write(fd, line, n) < 0) {
  97. print("!%r\n");
  98. continue;
  99. }
  100. seek(fd, 0, 0);
  101. while((n = read(fd, buf, sizeof(buf))) > 0){
  102. buf[n] = 0;
  103. print("%s\n", buf);
  104. }
  105. }
  106. exits(0);
  107. }