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