blob: a7324d9a958d5fe4918c45b8323d8e5b8798a45a [file] [log] [blame]
Isaac Levybc7dfb52011-06-06 15:34:01 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import android.content.ContentResolver;
20import android.content.Context;
21import android.net.ConnectivityManager;
22import android.net.LinkProperties;
Isaac Levy3541ce02011-06-28 17:05:26 -070023import android.net.NetworkUtils;
Isaac Levybc7dfb52011-06-06 15:34:01 -070024import android.os.SystemClock;
Isaac Levy3541ce02011-06-28 17:05:26 -070025import android.provider.Settings;
Isaac Levybc7dfb52011-06-06 15:34:01 -070026import android.util.Slog;
27
28import java.net.DatagramPacket;
29import java.net.DatagramSocket;
30import java.net.InetAddress;
31import java.net.SocketTimeoutException;
32import java.util.Collection;
33import java.util.Random;
34
35/**
36 * Performs a simple DNS "ping" by sending a "server status" query packet to the
37 * DNS server. As long as the server replies, we consider it a success.
38 * <p>
39 * We do not use a simple hostname lookup because that could be cached and the
40 * API may not differentiate between a time out and a failure lookup (which we
41 * really care about).
42 * <p>
Isaac Levy3541ce02011-06-28 17:05:26 -070043 * TODO : More general API. Socket does not bind to specified connection type
Isaac Levybc7dfb52011-06-06 15:34:01 -070044 * TODO : Choice of DNS query location - current looks up www.android.com
45 *
46 * @hide
47 */
48public final class DnsPinger {
49 private static final boolean V = true;
50
51 /** Number of bytes for the query */
52 private static final int DNS_QUERY_BASE_SIZE = 33;
53
54 /** The DNS port */
55 private static final int DNS_PORT = 53;
56
57 /** Used to generate IDs */
58 private static Random sRandom = new Random();
59
60 private ConnectivityManager mConnectivityManager = null;
Isaac Levybc7dfb52011-06-06 15:34:01 -070061 private Context mContext;
Isaac Levyb1ef2922011-06-27 10:02:50 -070062 private int mConnectionType;
Isaac Levy3541ce02011-06-28 17:05:26 -070063 private InetAddress mDefaultDns;
Isaac Levybc7dfb52011-06-06 15:34:01 -070064
65 private String TAG;
66
Isaac Levyb1ef2922011-06-27 10:02:50 -070067 /**
Isaac Levy3541ce02011-06-28 17:05:26 -070068 * @param connectionType The connection type from {@link ConnectivityManager}
Isaac Levyb1ef2922011-06-27 10:02:50 -070069 */
70 public DnsPinger(String TAG, Context context, int connectionType) {
Isaac Levybc7dfb52011-06-06 15:34:01 -070071 mContext = context;
Isaac Levyb1ef2922011-06-27 10:02:50 -070072 mConnectionType = connectionType;
Isaac Levy3541ce02011-06-28 17:05:26 -070073 if (!ConnectivityManager.isNetworkTypeValid(connectionType)) {
74 Slog.e(TAG, "Invalid connectionType in constructor: " + connectionType);
75 }
Isaac Levybc7dfb52011-06-06 15:34:01 -070076 this.TAG = TAG;
Isaac Levy3541ce02011-06-28 17:05:26 -070077
78 mDefaultDns = getDefaultDns();
Isaac Levybc7dfb52011-06-06 15:34:01 -070079 }
80
81 /**
Isaac Levy3541ce02011-06-28 17:05:26 -070082 * @return The first DNS in the link properties of the specified connection
83 * type or the default system DNS if the link properties has null
84 * dns set. Should not be null.
Isaac Levybc7dfb52011-06-06 15:34:01 -070085 */
86 public InetAddress getDns() {
Isaac Levyb1ef2922011-06-27 10:02:50 -070087 if (mConnectivityManager == null) {
88 mConnectivityManager = (ConnectivityManager) mContext.getSystemService(
89 Context.CONNECTIVITY_SERVICE);
90 }
Isaac Levy3541ce02011-06-28 17:05:26 -070091
92 LinkProperties curLinkProps = mConnectivityManager.getLinkProperties(mConnectionType);
93 if (curLinkProps == null) {
94 Slog.e(TAG, "getCurLinkProperties:: LP for type" + mConnectionType + " is null!");
95 return mDefaultDns;
96 }
97
98 Collection<InetAddress> dnses = curLinkProps.getDnses();
99 if (dnses == null || dnses.size() == 0) {
100 Slog.v(TAG, "getDns::LinkProps has null dns - returning default");
101 return mDefaultDns;
102 }
103
104 return dnses.iterator().next();
105 }
106
107 private InetAddress getDefaultDns() {
108 String dns = Settings.Secure.getString(mContext.getContentResolver(),
109 Settings.Secure.DEFAULT_DNS_SERVER);
110 if (dns == null || dns.length() == 0) {
111 dns = mContext.getResources().getString(
112 com.android.internal.R.string.config_default_dns_server);
113 }
114 try {
115 return NetworkUtils.numericToInetAddress(dns);
116 } catch (IllegalArgumentException e) {
117 Slog.w(TAG, "getDefaultDns::malformed default dns address");
118 return null;
119 }
Isaac Levyb1ef2922011-06-27 10:02:50 -0700120 }
121
Isaac Levybc7dfb52011-06-06 15:34:01 -0700122 /**
123 * @return time to response. Negative value on error.
124 */
125 public long pingDns(InetAddress dnsAddress, int timeout) {
126 DatagramSocket socket = null;
127 try {
128 socket = new DatagramSocket();
129
130 // Set some socket properties
131 socket.setSoTimeout(timeout);
132
133 byte[] buf = new byte[DNS_QUERY_BASE_SIZE];
134 fillQuery(buf);
135
136 // Send the DNS query
137
138 DatagramPacket packet = new DatagramPacket(buf,
139 buf.length, dnsAddress, DNS_PORT);
140 long start = SystemClock.elapsedRealtime();
141 socket.send(packet);
142
143 // Wait for reply (blocks for the above timeout)
144 DatagramPacket replyPacket = new DatagramPacket(buf, buf.length);
145 socket.receive(replyPacket);
146
147 // If a timeout occurred, an exception would have been thrown. We
148 // got a reply!
149 return SystemClock.elapsedRealtime() - start;
150
151 } catch (SocketTimeoutException e) {
152 // Squelch this exception.
153 return -1;
154 } catch (Exception e) {
155 if (V) {
156 Slog.v(TAG, "DnsPinger.pingDns got socket exception: ", e);
157 }
158 return -2;
159 } finally {
160 if (socket != null) {
161 socket.close();
162 }
163 }
164
165 }
166
167 private static void fillQuery(byte[] buf) {
168
169 /*
170 * See RFC2929 (though the bit tables in there are misleading for us.
171 * For example, the recursion desired bit is the 0th bit for us, but
172 * looking there it would appear as the 7th bit of the byte
173 */
174
175 // Make sure it's all zeroed out
176 for (int i = 0; i < buf.length; i++)
177 buf[i] = 0;
178
179 // Form a query for www.android.com
180
181 // [0-1] bytes are an ID, generate random ID for this query
182 buf[0] = (byte) sRandom.nextInt(256);
183 buf[1] = (byte) sRandom.nextInt(256);
184
185 // [2-3] bytes are for flags.
186 buf[2] = 1; // Recursion desired
187
188 // [4-5] bytes are for the query count
189 buf[5] = 1; // One query
190
191 // [6-7] [8-9] [10-11] are all counts of other fields we don't use
192
193 // [12-15] for www
194 writeString(buf, 12, "www");
195
196 // [16-23] for android
197 writeString(buf, 16, "android");
198
199 // [24-27] for com
200 writeString(buf, 24, "com");
201
202 // [29-30] bytes are for QTYPE, set to 1
203 buf[30] = 1;
204
205 // [31-32] bytes are for QCLASS, set to 1
206 buf[32] = 1;
207 }
208
209 private static void writeString(byte[] buf, int startPos, String string) {
210 int pos = startPos;
211
212 // Write the length first
213 buf[pos++] = (byte) string.length();
214 for (int i = 0; i < string.length(); i++) {
215 buf[pos++] = (byte) string.charAt(i);
216 }
217 }
218}