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 java.util.ArrayList;
23import java.util.List;
24
25import org.minidns.dnsserverlookup.AbstractDnsServerLookupMechanism;
26import org.minidns.dnsserverlookup.AndroidUsingReflection;
27import org.minidns.dnsserverlookup.DnsServerLookupMechanism;
28import org.minidns.util.PlatformDetection;
29
30/**
31 * Try to retrieve the list of DNS server by executing getprop.
32 */
33public class AndroidUsingExecLowPriority extends AbstractDnsServerLookupMechanism {
34
35 public static final DnsServerLookupMechanism INSTANCE = new AndroidUsingExecLowPriority();
36 public static final int PRIORITY = AndroidUsingReflection.PRIORITY + 1;
37
38 private AndroidUsingExecLowPriority() {
39 super(AndroidUsingExecLowPriority.class.getSimpleName(), PRIORITY);
40 }
41
42 @Override
43 public List<String> getDnsServerAddresses() {
44 try {
45 Process process = Runtime.getRuntime().exec("getprop");
46 InputStream inputStream = process.getInputStream();
47 LineNumberReader lnr = new LineNumberReader(
48 new InputStreamReader(inputStream));
49 String line;
50 HashSet<String> server = new HashSet<>(6);
51 while ((line = lnr.readLine()) != null) {
52 int split = line.indexOf("]: [");
53 if (split == -1) {
54 continue;
55 }
56 String property = line.substring(1, split);
57 String value = line.substring(split + 4, line.length() - 1);
58
59 if (value.isEmpty()) {
60 continue;
61 }
62
63 if (property.endsWith(".dns") || property.endsWith(".dns1") ||
64 property.endsWith(".dns2") || property.endsWith(".dns3") ||
65 property.endsWith(".dns4")) {
66
67 // normalize the address
68
69 InetAddress ip = InetAddress.getByName(value);
70
71 if (ip == null) continue;
72
73 value = ip.getHostAddress();
74
75 if (value == null) continue;
76 if (value.length() == 0) continue;
77
78 server.add(value);
79 }
80 }
81 if (server.size() > 0) {
82 return new ArrayList<>(server);
83 }
84 } catch (IOException e) {
85 LOGGER.log(Level.WARNING, "Exception in findDNSByExec", e);
86 }
87 return null;
88 }
89
90 @Override
91 public boolean isAvailable() {
92 return PlatformDetection.isAndroid();
93 }
94
95}