1package de.measite.minidns;
2
3import java.io.IOException;
4import java.io.InputStream;
5import java.io.InputStreamReader;
6import java.io.LineNumberReader;
7import java.lang.reflect.Method;
8import java.net.DatagramPacket;
9import java.net.DatagramSocket;
10import java.net.InetAddress;
11import java.security.NoSuchAlgorithmException;
12import java.security.SecureRandom;
13import java.util.ArrayList;
14import java.util.Arrays;
15import java.util.HashSet;
16import java.util.Random;
17import java.util.logging.Logger;
18
19import de.measite.minidns.Record.CLASS;
20import de.measite.minidns.Record.TYPE;
21
22/**
23 * A minimal DNS client for SRV/A/AAAA/NS and CNAME lookups, with IDN support.
24 * This circumvents the missing javax.naming package on android.
25 */
26public class Client {
27
28 private static final Logger LOGGER = Logger.getLogger(Client.class.getName());
29
30 /**
31 * The internal random class for sequence generation.
32 */
33 protected Random random;
34
35 /**
36 * The buffer size for dns replies.
37 */
38 protected int bufferSize = 1500;
39
40 /**
41 * DNS timeout.
42 */
43 protected int timeout = 5000;
44
45 /**
46 * Create a new DNS client.
47 */
48 public Client() {
49 try {
50 random = SecureRandom.getInstance("SHA1PRNG");
51 } catch (NoSuchAlgorithmException e1) {
52 random = new SecureRandom();
53 }
54 }
55
56 /**
57 * Query a nameserver for a single entry.
58 * @param name The DNS name to request.
59 * @param type The DNS type to request (SRV, A, AAAA, ...).
60 * @param clazz The class of the request (usually IN for Internet).
61 * @param host The DNS server host.
62 * @param port The DNS server port.
63 * @return
64 * @throws IOException On IO Errors.
65 */
66 public DNSMessage query(String name, TYPE type, CLASS clazz, String host, int port)
67 throws IOException
68 {
69 Question q = new Question();
70 q.setClazz(clazz);
71 q.setType(type);
72 q.setName(name);
73 return query(q, host, port);
74 }
75
76 /**
77 * Query a nameserver for a single entry.
78 * @param name The DNS name to request.
79 * @param type The DNS type to request (SRV, A, AAAA, ...).
80 * @param clazz The class of the request (usually IN for Internet).
81 * @param host The DNS server host.
82 * @return
83 * @throws IOException On IO Errors.
84 */
85 public DNSMessage query(String name, TYPE type, CLASS clazz, String host)
86 throws IOException
87 {
88 Question q = new Question();
89 q.setClazz(clazz);
90 q.setType(type);
91 q.setName(name);
92 return query(q, host);
93 }
94
95 /**
96 * Query the system nameserver for a single entry.
97 * @param name The DNS name to request.
98 * @param type The DNS type to request (SRV, A, AAAA, ...).
99 * @param clazz The class of the request (usually IN for Internet).
100 * @return The DNSMessage reply or null.
101 */
102 public DNSMessage query(String name, TYPE type, CLASS clazz)
103 {
104 Question q = new Question();
105 q.setClazz(clazz);
106 q.setType(type);
107 q.setName(name);
108 return query(q);
109 }
110
111 /**
112 * Query a specific server for one entry.
113 * @param q The question section of the DNS query.
114 * @param host The dns server host.
115 * @throws IOException On IOErrors.
116 */
117 public DNSMessage query(Question q, String host) throws IOException {
118 return query(q, host, 53);
119 }
120
121 /**
122 * Query a specific server for one entry.
123 * @param q The question section of the DNS query.
124 * @param host The dns server host.
125 * @param port the dns port.
126 * @throws IOException On IOErrors.
127 */
128 public DNSMessage query(Question q, String host, int port) throws IOException {
129 DNSMessage message = new DNSMessage();
130 message.setQuestions(new Question[]{q});
131 message.setRecursionDesired(true);
132 message.setId(random.nextInt());
133 byte[] buf = message.toArray();
134 try (DatagramSocket socket = new DatagramSocket()) {
135 DatagramPacket packet = new DatagramPacket(buf, buf.length,
136 InetAddress.getByName(host), port);
137 socket.setSoTimeout(timeout);
138 socket.send(packet);
139 packet = new DatagramPacket(new byte[bufferSize], bufferSize);
140 socket.receive(packet);
141 DNSMessage dnsMessage = DNSMessage.parse(packet.getData());
142 if (dnsMessage.getId() != message.getId()) {
143 return null;
144 }
145 return dnsMessage;
146 }
147 }
148
149 /**
150 * Query the system DNS server for one entry.
151 * @param q The question section of the DNS query.
152 */
153 public DNSMessage query(Question q) {
154 String dnsServer[] = findDNS();
155 for (String dns : dnsServer) {
156 try {
157 DNSMessage message = query(q, dns);
158 if (message == null) {
159 continue;
160 }
161 if (message.getResponseCode() !=
162 DNSMessage.RESPONSE_CODE.NO_ERROR) {
163 continue;
164 }
165 for (Record record: message.getAnswers()) {
166 if (record.isAnswer(q)) {
167 return message;
168 }
169 }
170 } catch (IOException ioe) {
171 }
172 }
173 return null;
174 }
175
176 /**
177 * Retrieve a list of currently configured DNS servers.
178 * @return The server array.
179 */
180 public String[] findDNS() {
181 String[] result = findDNSByReflection();
182 if (result != null) {
183 LOGGER.fine("Got DNS servers via reflection: " + Arrays.toString(result));
184 return result;
185 }
186
187 result = findDNSByExec();
188 if (result != null) {
189 LOGGER.fine("Got DNS servers via exec: " + Arrays.toString(result));
190 return result;
191 }
192
193 // fallback for ipv4 and ipv6 connectivity
194 // see https://developers.google.com/speed/public-dns/docs/using
195 LOGGER.fine("No DNS found? Using fallback [8.8.8.8, [2001:4860:4860::8888]]");
196
197 return new String[]{"8.8.8.8", "[2001:4860:4860::8888]"};
198 }
199
200 /**
201 * Try to retrieve the list of dns server by executing getprop.
202 * @return Array of servers, or null on failure.
203 */
204 protected String[] findDNSByExec() {
205 try {
206 Process process = Runtime.getRuntime().exec("getprop");
207 InputStream inputStream = process.getInputStream();
208 LineNumberReader lnr = new LineNumberReader(
209 new InputStreamReader(inputStream));
210 String line = null;
211 HashSet<String> server = new HashSet<String>(6);
212 while ((line = lnr.readLine()) != null) {
213 int split = line.indexOf("]: [");
214 if (split == -1) {
215 continue;
216 }
217 String property = line.substring(1, split);
218 String value = line.substring(split + 4, line.length() - 1);
219 if (property.endsWith(".dns") || property.endsWith(".dns1") ||
220 property.endsWith(".dns2") || property.endsWith(".dns3") ||
221 property.endsWith(".dns4")) {
222
223 // normalize the address
224
225 InetAddress ip = InetAddress.getByName(value);
226
227 if (ip == null) continue;
228
229 value = ip.getHostAddress();
230
231 if (value == null) continue;
232 if (value.length() == 0) continue;
233
234 server.add(value);
235 }
236 }
237 if (server.size() > 0) {
238 return server.toArray(new String[server.size()]);
239 }
240 } catch (IOException e) {
241 e.printStackTrace();
242 }
243 return null;
244 }
245
246 /**
247 * Try to retrieve the list of dns server by calling SystemProperties.
248 * @return Array of servers, or null on failure.
249 */
250 protected String[] findDNSByReflection() {
251 try {
252 Class<?> SystemProperties =
253 Class.forName("android.os.SystemProperties");
254 Method method = SystemProperties.getMethod("get",
255 new Class[] { String.class });
256
257 ArrayList<String> servers = new ArrayList<String>(5);
258
259 for (String propKey : new String[] {
260 "net.dns1", "net.dns2", "net.dns3", "net.dns4"}) {
261
262 String value = (String)method.invoke(null, propKey);
263
264 if (value == null) continue;
265 if (value.length() == 0) continue;
266 if (servers.contains(value)) continue;
267
268 InetAddress ip = InetAddress.getByName(value);
269
270 if (ip == null) continue;
271
272 value = ip.getHostAddress();
273
274 if (value == null) continue;
275 if (value.length() == 0) continue;
276 if (servers.contains(value)) continue;
277
278 servers.add(value);
279 }
280
281 if (servers.size() > 0) {
282 return servers.toArray(new String[servers.size()]);
283 }
284 } catch (Exception e) {
285 // we might trigger some problems this way
286 e.printStackTrace();
287 }
288 return null;
289 }
290
291}