DnsPinger.java revision d2fe04b71a89a0608eb7c67065dead2a1f540122
1/* 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 android.net; 18 19import android.content.Context; 20import android.os.Handler; 21import android.os.Looper; 22import android.os.Message; 23import android.os.SystemClock; 24import android.provider.Settings; 25import android.util.Slog; 26 27import com.android.internal.util.Protocol; 28 29import java.io.IOException; 30import java.net.DatagramPacket; 31import java.net.DatagramSocket; 32import java.net.InetAddress; 33import java.net.NetworkInterface; 34import java.net.SocketTimeoutException; 35import java.util.ArrayList; 36import java.util.Collection; 37import java.util.Iterator; 38import java.util.List; 39import java.util.Random; 40import java.util.concurrent.atomic.AtomicInteger; 41 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> 50 * 51 * @hide 52 */ 53public final class DnsPinger extends Handler { 54 private static final boolean V = true; 55 56 private static final int RECEIVE_POLL_INTERVAL_MS = 30; 57 private static final int DNS_PORT = 53; 58 59 /** Short socket timeout so we don't block one any 'receive' call */ 60 private static final int SOCKET_TIMEOUT_MS = 1; 61 62 /** Used to generate IDs */ 63 private static final Random sRandom = new Random(); 64 private static final AtomicInteger sCounter = new AtomicInteger(); 65 66 private ConnectivityManager mConnectivityManager = null; 67 private final Context mContext; 68 private final int mConnectionType; 69 private final Handler mTarget; 70 private final InetAddress mDefaultDns; 71 private String TAG; 72 73 private static final int BASE = Protocol.BASE_DNS_PINGER; 74 75 /** 76 * 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. 79 */ 80 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; 109 mContext = context; 110 mTarget = target; 111 mConnectionType = connectionType; 112 if (!ConnectivityManager.isNetworkTypeValid(connectionType)) { 113 throw new IllegalArgumentException("Invalid connectionType in constructor: " 114 + connectionType); 115 } 116 mDefaultDns = getDefaultDns(); 117 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) { 150 Slog.v(TAG, "Sending a ping to " + dnsAddress.getHostAddress() 151 + " with ID " + newActivePing.packetId + "."); 152 } 153 154 newActivePing.socket.send(packet); 155 mActivePings.add(newActivePing); 156 mEventCounter++; 157 sendMessageDelayed(obtainMessage(ACTION_LISTEN_FOR_RESPONSE, mEventCounter, 0), 158 RECEIVE_POLL_INTERVAL_MS); 159 } catch (IOException e) { 160 sendResponse((short) msg.arg1, SOCKET_EXCEPTION); 161 } 162 break; 163 case ACTION_LISTEN_FOR_RESPONSE: 164 if (msg.arg1 != mEventCounter) { 165 break; 166 } 167 for (ActivePing curPing : mActivePings) { 168 try { 169 /** Each socket will block for {@link #SOCKET_TIMEOUT_MS} in receive() */ 170 byte[] responseBuf = new byte[2]; 171 DatagramPacket replyPacket = new DatagramPacket(responseBuf, 2); 172 curPing.socket.receive(replyPacket); 173 // Check that ID field matches (we're throwing out the rest of the packet) 174 if (responseBuf[0] == (byte) (curPing.packetId >> 8) && 175 responseBuf[1] == (byte) curPing.packetId) { 176 curPing.result = 177 (int) (SystemClock.elapsedRealtime() - curPing.start); 178 } else { 179 if (V) { 180 Slog.v(TAG, "response ID didn't match, ignoring packet"); 181 } 182 } 183 } catch (SocketTimeoutException e) { 184 // A timeout here doesn't mean anything - squelsh this exception 185 } catch (Exception e) { 186 if (V) { 187 Slog.v(TAG, "DnsPinger.pingDns got socket exception: ", e); 188 } 189 curPing.result = SOCKET_EXCEPTION; 190 } 191 } 192 Iterator<ActivePing> iter = mActivePings.iterator(); 193 while (iter.hasNext()) { 194 ActivePing curPing = iter.next(); 195 if (curPing.result != null) { 196 sendResponse(curPing.internalId, curPing.result); 197 curPing.socket.close(); 198 iter.remove(); 199 } else if (SystemClock.elapsedRealtime() > 200 curPing.start + curPing.timeout) { 201 sendResponse(curPing.internalId, TIMEOUT); 202 curPing.socket.close(); 203 iter.remove(); 204 } 205 } 206 if (!mActivePings.isEmpty()) { 207 sendMessageDelayed(obtainMessage(ACTION_LISTEN_FOR_RESPONSE, mEventCounter, 0), 208 RECEIVE_POLL_INTERVAL_MS); 209 } 210 break; 211 case ACTION_CANCEL_ALL_PINGS: 212 for (ActivePing activePing : mActivePings) 213 activePing.socket.close(); 214 mActivePings.clear(); 215 removeMessages(ACTION_PING_DNS); 216 break; 217 } 218 } 219 220 /** 221 * @return The first DNS in the link properties of the specified connection 222 * type or the default system DNS if the link properties has null 223 * dns set. Should not be null. 224 */ 225 public InetAddress getDns() { 226 LinkProperties curLinkProps = getCurrentLinkProperties(); 227 if (curLinkProps == null) { 228 Slog.e(TAG, "getCurLinkProperties:: LP for type" + mConnectionType + " is null!"); 229 return mDefaultDns; 230 } 231 232 Collection<InetAddress> dnses = curLinkProps.getDnses(); 233 if (dnses == null || dnses.size() == 0) { 234 Slog.v(TAG, "getDns::LinkProps has null dns - returning default"); 235 return mDefaultDns; 236 } 237 238 return dnses.iterator().next(); 239 } 240 241 /** 242 * Send a ping. The response will come via a {@link #DNS_PING_RESULT} to the handler 243 * specified at creation. 244 * @param dns address of dns server to ping 245 * @param timeout timeout for ping 246 * @return an ID field, which will also be included in the {@link #DNS_PING_RESULT} message. 247 */ 248 public int pingDnsAsync(InetAddress dns, int timeout, int delay) { 249 int id = sCounter.incrementAndGet(); 250 sendMessageDelayed(obtainMessage(ACTION_PING_DNS, id, timeout, dns), delay); 251 return id; 252 } 253 254 public void cancelPings() { 255 obtainMessage(ACTION_CANCEL_ALL_PINGS).sendToTarget(); 256 } 257 258 private void sendResponse(int internalId, int responseVal) { 259 if(V) { 260 Slog.v(TAG, "Responding with id " + internalId + " and val " + responseVal); 261 } 262 mTarget.sendMessage(obtainMessage(DNS_PING_RESULT, internalId, responseVal)); 263 } 264 265 private LinkProperties getCurrentLinkProperties() { 266 if (mConnectivityManager == null) { 267 mConnectivityManager = (ConnectivityManager) mContext.getSystemService( 268 Context.CONNECTIVITY_SERVICE); 269 } 270 271 return mConnectivityManager.getLinkProperties(mConnectionType); 272 } 273 274 private InetAddress getDefaultDns() { 275 String dns = Settings.Secure.getString(mContext.getContentResolver(), 276 Settings.Secure.DEFAULT_DNS_SERVER); 277 if (dns == null || dns.length() == 0) { 278 dns = mContext.getResources().getString( 279 com.android.internal.R.string.config_default_dns_server); 280 } 281 try { 282 return NetworkUtils.numericToInetAddress(dns); 283 } catch (IllegalArgumentException e) { 284 Slog.w(TAG, "getDefaultDns::malformed default dns address"); 285 return null; 286 } 287 } 288 289 private static final byte[] mDnsQuery = new byte[] { 290 0, 0, // [0-1] is for ID (will set each time) 291 0, 0, // [2-3] are flags. Set byte[2] = 1 for recursion desired (RD) on. Currently off. 292 0, 1, // [4-5] bytes are for number of queries (QCOUNT) 293 0, 0, // [6-7] unused count field for dns response packets 294 0, 0, // [8-9] unused count field for dns response packets 295 0, 0, // [10-11] unused count field for dns response packets 296 3, 'w', 'w', 'w', 297 6, 'g', 'o', 'o', 'g', 'l', 'e', 298 3, 'c', 'o', 'm', 299 0, // null terminator of address (also called empty TLD) 300 0, 1, // QTYPE, set to 1 = A (host address) 301 0, 1 // QCLASS, set to 1 = IN (internet) 302 }; 303} 304