xref: /plan9-contrib/sys/src/cmd/ndb/dnsquery.c (revision 219b2ee8daee37f4aad58d63f21287faa8e4ffdc)
1 #include <u.h>
2 #include <libc.h>
3 #include <bio.h>
4 #include "dns.h"
5 #include "ip.h"
6 
7 void
8 main(void)
9 {
10 	int fd, n, len;
11 	Biobuf in;
12 	char *line, *p, *np;
13 	char buf[1024];
14 
15 	fd = open("/net/dns", ORDWR);
16 	if(fd < 0){
17 		fd = open("/srv/dns", ORDWR);
18 		if(fd < 0){
19 			print("can't open /srv/dns: %r\n");
20 			exits(0);
21 		}
22 		if(mount(fd, "/net", MBEFORE, "") < 0){
23 			print("can't mount /srv/dns: %r\n");
24 			exits(0);
25 		}
26 		fd = open("/net/dns", ORDWR);
27 		if(fd < 0){
28 			print("can't open /net/dns: %r\n");
29 			exits(0);
30 		}
31 	}
32 	Binit(&in, 0, OREAD);
33 	print("> ");
34 	while(line = Brdline(&in, '\n')){
35 		n = Blinelen(&in)-1;
36 		line[n] = 0;
37 
38 		/* inverse queries may need to be permuted */
39 		if(n > 4 && strcmp("ptr", &line[n-3]) == 0
40 		&& strstr(line, "IN-ADDR") == 0 && strstr(line, "in-addr") == 0){
41 			for(p = line; *p; p++)
42 				if(*p == ' '){
43 					*p = '.';
44 					break;
45 				}
46 			np = buf;
47 			len = 0;
48 			while(p >= line){
49 				len++;
50 				p--;
51 				if(*p == '.'){
52 					memmove(np, p+1, len);
53 					np += len;
54 					len = 0;
55 				}
56 			}
57 			memmove(np, p+1, len);
58 			np += len;
59 			strcpy(np, "in-addr.arpa ptr");
60 			line = buf;
61 			n = strlen(line);
62 		}
63 
64 		seek(fd, 0, 0);
65 		if(write(fd, line, n) < 0){
66 			print("!%r\n> ");
67 			continue;
68 		}
69 		seek(fd, 0, 0);
70 		while((n = read(fd, buf, sizeof(buf))) > 0){
71 			buf[n] = 0;
72 			print("%s\n", buf);
73 		}
74 		print("> ");
75 	}
76 	exits(0);
77 }
78