blob: 6115fef926d6590d35f9b172c45442d8e808b1fb [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
Isaac Levya7bc1132011-07-06 13:54:48 -070017package android.net;
Isaac Levybc7dfb52011-06-06 15:34:01 -070018
Isaac Levybc7dfb52011-06-06 15:34:01 -070019import android.content.Context;
Isaac Levyd2fe04b2011-07-22 08:48:26 -070020import android.os.Handler;
21import android.os.Looper;
22import android.os.Message;
Isaac Levybc7dfb52011-06-06 15:34:01 -070023import android.os.SystemClock;
Isaac Levy3541ce02011-06-28 17:05:26 -070024import android.provider.Settings;
Isaac Levybc7dfb52011-06-06 15:34:01 -070025import android.util.Slog;
26
Isaac Levyd2fe04b2011-07-22 08:48:26 -070027import com.android.internal.util.Protocol;
28
29import java.io.IOException;
Isaac Levybc7dfb52011-06-06 15:34:01 -070030import java.net.DatagramPacket;
31import java.net.DatagramSocket;
32import java.net.InetAddress;
Isaac Levy3ee9d052011-06-27 22:37:12 -070033import java.net.NetworkInterface;
Isaac Levybc7dfb52011-06-06 15:34:01 -070034import java.net.SocketTimeoutException;
Isaac Levyd2fe04b2011-07-22 08:48:26 -070035import java.util.ArrayList;
Isaac Levybc7dfb52011-06-06 15:34:01 -070036import java.util.Collection;
Isaac Levyd2fe04b2011-07-22 08:48:26 -070037import java.util.Iterator;
38import java.util.List;
Isaac Levybc7dfb52011-06-06 15:34:01 -070039import java.util.Random;
Isaac Levyd2fe04b2011-07-22 08:48:26 -070040import java.util.concurrent.atomic.AtomicInteger;
Isaac Levybc7dfb52011-06-06 15:34:01 -070041
42/**
43 * Performs a simple DNS "ping" by sending a "server status" query packet to the
44 * DNS server. As long as the server replies, we consider it a success.
45 * <p>
46 * We do not use a simple hostname lookup because that could be cached and the
47 * API may not differentiate between a time out and a failure lookup (which we
48 * really care about).
49 * <p>
Isaac Levybc7dfb52011-06-06 15:34:01 -070050 *
51 * @hide
52 */
Isaac Levyd2fe04b2011-07-22 08:48:26 -070053public final class DnsPinger extends Handler {
Isaac Levybc7dfb52011-06-06 15:34:01 -070054 private static final boolean V = true;
55
Isaac Levyd2fe04b2011-07-22 08:48:26 -070056 private static final int RECEIVE_POLL_INTERVAL_MS = 30;
Isaac Levybc7dfb52011-06-06 15:34:01 -070057 private static final int DNS_PORT = 53;
58
Isaac Levyd2fe04b2011-07-22 08:48:26 -070059 /** Short socket timeout so we don't block one any 'receive' call */
60 private static final int SOCKET_TIMEOUT_MS = 1;
61
Isaac Levybc7dfb52011-06-06 15:34:01 -070062 /** Used to generate IDs */
Isaac Levyd2fe04b2011-07-22 08:48:26 -070063 private static final Random sRandom = new Random();
64 private static final AtomicInteger sCounter = new AtomicInteger();
Isaac Levybc7dfb52011-06-06 15:34:01 -070065
66 private ConnectivityManager mConnectivityManager = null;
Isaac Levyd2fe04b2011-07-22 08:48:26 -070067 private final Context mContext;
68 private final int mConnectionType;
69 private final Handler mTarget;
70 private final InetAddress mDefaultDns;
Isaac Levybc7dfb52011-06-06 15:34:01 -070071 private String TAG;
72
Isaac Levyd2fe04b2011-07-22 08:48:26 -070073 private static final int BASE = Protocol.BASE_DNS_PINGER;
74
Isaac Levyb1ef2922011-06-27 10:02:50 -070075 /**
Isaac Levyd2fe04b2011-07-22 08:48:26 -070076 * Async response packet for dns pings.
77 * arg1 is the ID of the ping, also returned by {@link #pingDnsAsync(InetAddress, int, int)}
78 * arg2 is the delay, or is negative on error.
Isaac Levyb1ef2922011-06-27 10:02:50 -070079 */
Isaac Levyd2fe04b2011-07-22 08:48:26 -070080 public static final int DNS_PING_RESULT = BASE;
81 /** An error code for a {@link #DNS_PING_RESULT} packet */
82 public static final int TIMEOUT = -1;
83 /** An error code for a {@link #DNS_PING_RESULT} packet */
84 public static final int SOCKET_EXCEPTION = -2;
85
86 /**
87 * Send a new ping via a socket. arg1 is ID, arg2 is timeout, obj is InetAddress to ping
88 */
89 private static final int ACTION_PING_DNS = BASE + 1;
90 private static final int ACTION_LISTEN_FOR_RESPONSE = BASE + 2;
91 private static final int ACTION_CANCEL_ALL_PINGS = BASE + 3;
92
93 private List<ActivePing> mActivePings = new ArrayList<ActivePing>();
94 private int mEventCounter;
95
96 private class ActivePing {
97 DatagramSocket socket;
98 int internalId;
99 short packetId;
100 int timeout;
101 Integer result;
102 long start = SystemClock.elapsedRealtime();
103 }
104
105 public DnsPinger(Context context, String TAG, Looper looper,
106 Handler target, int connectionType) {
107 super(looper);
108 this.TAG = TAG;
Isaac Levybc7dfb52011-06-06 15:34:01 -0700109 mContext = context;
Isaac Levyd2fe04b2011-07-22 08:48:26 -0700110 mTarget = target;
Isaac Levyb1ef2922011-06-27 10:02:50 -0700111 mConnectionType = connectionType;
Isaac Levy3541ce02011-06-28 17:05:26 -0700112 if (!ConnectivityManager.isNetworkTypeValid(connectionType)) {
Isaac Levyd2fe04b2011-07-22 08:48:26 -0700113 throw new IllegalArgumentException("Invalid connectionType in constructor: "
114 + connectionType);
Isaac Levy3541ce02011-06-28 17:05:26 -0700115 }
Isaac Levy3541ce02011-06-28 17:05:26 -0700116 mDefaultDns = getDefaultDns();
Isaac Levyd2fe04b2011-07-22 08:48:26 -0700117 mEventCounter = 0;
118 }
119
120 @Override
121 public void handleMessage(Message msg) {
122 switch (msg.what) {
123 case ACTION_PING_DNS:
124 try {
125 ActivePing newActivePing = new ActivePing();
126 InetAddress dnsAddress = (InetAddress) msg.obj;
127 newActivePing.internalId = msg.arg1;
128 newActivePing.timeout = msg.arg2;
129 newActivePing.socket = new DatagramSocket();
130 // Set some socket properties
131 newActivePing.socket.setSoTimeout(SOCKET_TIMEOUT_MS);
132
133 // Try to bind but continue ping if bind fails
134 try {
135 newActivePing.socket.setNetworkInterface(NetworkInterface.getByName(
136 getCurrentLinkProperties().getInterfaceName()));
137 } catch (Exception e) {
138 Slog.w(TAG,"sendDnsPing::Error binding to socket", e);
139 }
140
141 newActivePing.packetId = (short) sRandom.nextInt();
142 byte[] buf = mDnsQuery.clone();
143 buf[0] = (byte) (newActivePing.packetId >> 8);
144 buf[1] = (byte) newActivePing.packetId;
145
146 // Send the DNS query
147 DatagramPacket packet = new DatagramPacket(buf,
148 buf.length, dnsAddress, DNS_PORT);
149 if (V) {
Isaac Levy26a8d712011-08-09 15:35:59 -0700150 Slog.v(TAG, "Sending a ping " + newActivePing.internalId +
151 " to " + dnsAddress.getHostAddress()
152 + " with packetId " + newActivePing.packetId + ".");
Isaac Levyd2fe04b2011-07-22 08:48:26 -0700153 }
154
155 newActivePing.socket.send(packet);
156 mActivePings.add(newActivePing);
157 mEventCounter++;
158 sendMessageDelayed(obtainMessage(ACTION_LISTEN_FOR_RESPONSE, mEventCounter, 0),
159 RECEIVE_POLL_INTERVAL_MS);
160 } catch (IOException e) {
Isaac Levy26a8d712011-08-09 15:35:59 -0700161 sendResponse(msg.arg1, -9999, SOCKET_EXCEPTION);
Isaac Levyd2fe04b2011-07-22 08:48:26 -0700162 }
163 break;
164 case ACTION_LISTEN_FOR_RESPONSE:
165 if (msg.arg1 != mEventCounter) {
166 break;
167 }
168 for (ActivePing curPing : mActivePings) {
169 try {
170 /** Each socket will block for {@link #SOCKET_TIMEOUT_MS} in receive() */
171 byte[] responseBuf = new byte[2];
172 DatagramPacket replyPacket = new DatagramPacket(responseBuf, 2);
173 curPing.socket.receive(replyPacket);
174 // Check that ID field matches (we're throwing out the rest of the packet)
175 if (responseBuf[0] == (byte) (curPing.packetId >> 8) &&
176 responseBuf[1] == (byte) curPing.packetId) {
177 curPing.result =
178 (int) (SystemClock.elapsedRealtime() - curPing.start);
179 } else {
180 if (V) {
181 Slog.v(TAG, "response ID didn't match, ignoring packet");
182 }
183 }
184 } catch (SocketTimeoutException e) {
185 // A timeout here doesn't mean anything - squelsh this exception
186 } catch (Exception e) {
187 if (V) {
188 Slog.v(TAG, "DnsPinger.pingDns got socket exception: ", e);
189 }
190 curPing.result = SOCKET_EXCEPTION;
191 }
192 }
193 Iterator<ActivePing> iter = mActivePings.iterator();
194 while (iter.hasNext()) {
195 ActivePing curPing = iter.next();
196 if (curPing.result != null) {
Isaac Levy26a8d712011-08-09 15:35:59 -0700197 sendResponse(curPing.internalId, curPing.packetId, curPing.result);
Isaac Levyd2fe04b2011-07-22 08:48:26 -0700198 curPing.socket.close();
199 iter.remove();
200 } else if (SystemClock.elapsedRealtime() >
201 curPing.start + curPing.timeout) {
Isaac Levy26a8d712011-08-09 15:35:59 -0700202 sendResponse(curPing.internalId, curPing.packetId, TIMEOUT);
Isaac Levyd2fe04b2011-07-22 08:48:26 -0700203 curPing.socket.close();
204 iter.remove();
205 }
206 }
207 if (!mActivePings.isEmpty()) {
208 sendMessageDelayed(obtainMessage(ACTION_LISTEN_FOR_RESPONSE, mEventCounter, 0),
209 RECEIVE_POLL_INTERVAL_MS);
210 }
211 break;
212 case ACTION_CANCEL_ALL_PINGS:
213 for (ActivePing activePing : mActivePings)
214 activePing.socket.close();
215 mActivePings.clear();
216 removeMessages(ACTION_PING_DNS);
217 break;
218 }
Isaac Levybc7dfb52011-06-06 15:34:01 -0700219 }
220
221 /**
Isaac Levy3541ce02011-06-28 17:05:26 -0700222 * @return The first DNS in the link properties of the specified connection
223 * type or the default system DNS if the link properties has null
224 * dns set. Should not be null.
Isaac Levybc7dfb52011-06-06 15:34:01 -0700225 */
226 public InetAddress getDns() {
Isaac Levy3ee9d052011-06-27 22:37:12 -0700227 LinkProperties curLinkProps = getCurrentLinkProperties();
Isaac Levy3541ce02011-06-28 17:05:26 -0700228 if (curLinkProps == null) {
229 Slog.e(TAG, "getCurLinkProperties:: LP for type" + mConnectionType + " is null!");
230 return mDefaultDns;
231 }
232
233 Collection<InetAddress> dnses = curLinkProps.getDnses();
234 if (dnses == null || dnses.size() == 0) {
235 Slog.v(TAG, "getDns::LinkProps has null dns - returning default");
236 return mDefaultDns;
237 }
238
239 return dnses.iterator().next();
240 }
241
Isaac Levyd2fe04b2011-07-22 08:48:26 -0700242 /**
243 * Send a ping. The response will come via a {@link #DNS_PING_RESULT} to the handler
244 * specified at creation.
245 * @param dns address of dns server to ping
246 * @param timeout timeout for ping
247 * @return an ID field, which will also be included in the {@link #DNS_PING_RESULT} message.
248 */
249 public int pingDnsAsync(InetAddress dns, int timeout, int delay) {
250 int id = sCounter.incrementAndGet();
251 sendMessageDelayed(obtainMessage(ACTION_PING_DNS, id, timeout, dns), delay);
252 return id;
253 }
254
255 public void cancelPings() {
256 obtainMessage(ACTION_CANCEL_ALL_PINGS).sendToTarget();
257 }
258
Isaac Levy26a8d712011-08-09 15:35:59 -0700259 private void sendResponse(int internalId, int externalId, int responseVal) {
Isaac Levyd2fe04b2011-07-22 08:48:26 -0700260 if(V) {
Isaac Levy26a8d712011-08-09 15:35:59 -0700261 Slog.d(TAG, "Responding to packet " + internalId +
262 " externalId " + externalId +
263 " and val " + responseVal);
Isaac Levyd2fe04b2011-07-22 08:48:26 -0700264 }
265 mTarget.sendMessage(obtainMessage(DNS_PING_RESULT, internalId, responseVal));
266 }
267
Isaac Levy3ee9d052011-06-27 22:37:12 -0700268 private LinkProperties getCurrentLinkProperties() {
269 if (mConnectivityManager == null) {
270 mConnectivityManager = (ConnectivityManager) mContext.getSystemService(
271 Context.CONNECTIVITY_SERVICE);
272 }
273
274 return mConnectivityManager.getLinkProperties(mConnectionType);
275 }
276
Isaac Levy3541ce02011-06-28 17:05:26 -0700277 private InetAddress getDefaultDns() {
278 String dns = Settings.Secure.getString(mContext.getContentResolver(),
279 Settings.Secure.DEFAULT_DNS_SERVER);
280 if (dns == null || dns.length() == 0) {
281 dns = mContext.getResources().getString(
282 com.android.internal.R.string.config_default_dns_server);
283 }
284 try {
285 return NetworkUtils.numericToInetAddress(dns);
286 } catch (IllegalArgumentException e) {
287 Slog.w(TAG, "getDefaultDns::malformed default dns address");
288 return null;
289 }
Isaac Levyb1ef2922011-06-27 10:02:50 -0700290 }
291
Isaac Levyd2fe04b2011-07-22 08:48:26 -0700292 private static final byte[] mDnsQuery = new byte[] {
293 0, 0, // [0-1] is for ID (will set each time)
Isaac Levy26a8d712011-08-09 15:35:59 -0700294 1, 0, // [2-3] are flags. Set byte[2] = 1 for recursion desired (RD) on. Currently on.
Isaac Levyd2fe04b2011-07-22 08:48:26 -0700295 0, 1, // [4-5] bytes are for number of queries (QCOUNT)
296 0, 0, // [6-7] unused count field for dns response packets
297 0, 0, // [8-9] unused count field for dns response packets
298 0, 0, // [10-11] unused count field for dns response packets
299 3, 'w', 'w', 'w',
300 6, 'g', 'o', 'o', 'g', 'l', 'e',
301 3, 'c', 'o', 'm',
302 0, // null terminator of address (also called empty TLD)
303 0, 1, // QTYPE, set to 1 = A (host address)
304 0, 1 // QCLASS, set to 1 = IN (internet)
305 };
Isaac Levybc7dfb52011-06-06 15:34:01 -0700306}