1/*
2 * Copyright 2015-2016 the original author or authors
3 *
4 * This software is licensed under the Apache License, Version 2.0,
5 * the GNU Lesser General Public License version 2 or later ("LGPL")
6 * and the WTFPL.
7 * You may choose either license to govern your use of this software only
8 * upon the condition that you accept all of the terms of either
9 * the Apache License 2.0, the LGPL 2.1+ or the WTFPL.
10 */
11package eu.siacs.conversations.utils;
12
13
14import java.io.IOException;
15import java.io.InputStream;
16import java.io.InputStreamReader;
17import java.io.LineNumberReader;
18import java.net.InetAddress;
19import java.util.HashSet;
20import java.util.logging.Level;
21
22import de.measite.minidns.dnsserverlookup.AbstractDNSServerLookupMechanism;
23import de.measite.minidns.dnsserverlookup.AndroidUsingReflection;
24import de.measite.minidns.dnsserverlookup.DNSServerLookupMechanism;
25import de.measite.minidns.util.PlatformDetection;
26
27/**
28 * Try to retrieve the list of DNS server by executing getprop.
29 */
30public class AndroidUsingExecLowPriority extends AbstractDNSServerLookupMechanism {
31
32 public static final DNSServerLookupMechanism INSTANCE = new AndroidUsingExecLowPriority();
33 public static final int PRIORITY = AndroidUsingReflection.PRIORITY + 1;
34
35 private AndroidUsingExecLowPriority() {
36 super(AndroidUsingExecLowPriority.class.getSimpleName(), PRIORITY);
37 }
38
39 @Override
40 public String[] getDnsServerAddresses() {
41 try {
42 Process process = Runtime.getRuntime().exec("getprop");
43 InputStream inputStream = process.getInputStream();
44 LineNumberReader lnr = new LineNumberReader(
45 new InputStreamReader(inputStream));
46 String line;
47 HashSet<String> server = new HashSet<>(6);
48 while ((line = lnr.readLine()) != null) {
49 int split = line.indexOf("]: [");
50 if (split == -1) {
51 continue;
52 }
53 String property = line.substring(1, split);
54 String value = line.substring(split + 4, line.length() - 1);
55
56 if (value.isEmpty()) {
57 continue;
58 }
59
60 if (property.endsWith(".dns") || property.endsWith(".dns1") ||
61 property.endsWith(".dns2") || property.endsWith(".dns3") ||
62 property.endsWith(".dns4")) {
63
64 // normalize the address
65
66 InetAddress ip = InetAddress.getByName(value);
67
68 if (ip == null) continue;
69
70 value = ip.getHostAddress();
71
72 if (value == null) continue;
73 if (value.length() == 0) continue;
74
75 server.add(value);
76 }
77 }
78 if (server.size() > 0) {
79 return server.toArray(new String[server.size()]);
80 }
81 } catch (IOException e) {
82 LOGGER.log(Level.WARNING, "Exception in findDNSByExec", e);
83 }
84 return null;
85 }
86
87 @Override
88 public boolean isAvailable() {
89 return PlatformDetection.isAndroid();
90 }
91
92}