NetworkStateTracker.java revision ec9fe4672a46eb928ab710d8e3caf2ce046100d4
1/* 2 * Copyright (C) 2008 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 java.io.FileWriter; 20import java.io.IOException; 21 22import android.os.Handler; 23import android.os.Message; 24import android.os.SystemProperties; 25import android.content.Context; 26import android.text.TextUtils; 27import android.util.Config; 28import android.util.Log; 29 30 31/** 32 * Each subclass of this class keeps track of the state of connectivity 33 * of a network interface. All state information for a network should 34 * be kept in a Tracker class. This superclass manages the 35 * network-type-independent aspects of network state. 36 * 37 * {@hide} 38 */ 39public abstract class NetworkStateTracker extends Handler { 40 41 protected NetworkInfo mNetworkInfo; 42 protected Context mContext; 43 protected Handler mTarget; 44 protected String mInterfaceName; 45 protected String[] mDnsPropNames; 46 private boolean mPrivateDnsRouteSet; 47 protected int mDefaultGatewayAddr; 48 private boolean mDefaultRouteSet; 49 private boolean mTeardownRequested; 50 51 private static boolean DBG = true; 52 private static final String TAG = "NetworkStateTracker"; 53 54 public static final int EVENT_STATE_CHANGED = 1; 55 public static final int EVENT_SCAN_RESULTS_AVAILABLE = 2; 56 /** 57 * arg1: 1 to show, 0 to hide 58 * arg2: ID of the notification 59 * obj: Notification (if showing) 60 */ 61 public static final int EVENT_NOTIFICATION_CHANGED = 3; 62 public static final int EVENT_CONFIGURATION_CHANGED = 4; 63 public static final int EVENT_ROAMING_CHANGED = 5; 64 public static final int EVENT_NETWORK_SUBTYPE_CHANGED = 6; 65 public static final int EVENT_RESTORE_DEFAULT_NETWORK = 7; 66 67 public NetworkStateTracker(Context context, 68 Handler target, 69 int networkType, 70 int subType, 71 String typeName, 72 String subtypeName) { 73 super(); 74 mContext = context; 75 mTarget = target; 76 mTeardownRequested = false; 77 78 this.mNetworkInfo = new NetworkInfo(networkType, subType, typeName, subtypeName); 79 } 80 81 public NetworkInfo getNetworkInfo() { 82 return mNetworkInfo; 83 } 84 85 /** 86 * Return the system properties name associated with the tcp buffer sizes 87 * for this network. 88 */ 89 public abstract String getTcpBufferSizesPropName(); 90 91 /** 92 * Return the IP addresses of the DNS servers available for the mobile data 93 * network interface. 94 * @return a list of DNS addresses, with no holes. 95 */ 96 public String[] getNameServers() { 97 return getNameServerList(mDnsPropNames); 98 } 99 100 /** 101 * Return the IP addresses of the DNS servers available for this 102 * network interface. 103 * @param propertyNames the names of the system properties whose values 104 * give the IP addresses. Properties with no values are skipped. 105 * @return an array of {@code String}s containing the IP addresses 106 * of the DNS servers, in dot-notation. This may have fewer 107 * non-null entries than the list of names passed in, since 108 * some of the passed-in names may have empty values. 109 */ 110 static protected String[] getNameServerList(String[] propertyNames) { 111 String[] dnsAddresses = new String[propertyNames.length]; 112 int i, j; 113 114 for (i = 0, j = 0; i < propertyNames.length; i++) { 115 String value = SystemProperties.get(propertyNames[i]); 116 // The GSM layer sometimes sets a bogus DNS server address of 117 // 0.0.0.0 118 if (!TextUtils.isEmpty(value) && !TextUtils.equals(value, "0.0.0.0")) { 119 dnsAddresses[j++] = value; 120 } 121 } 122 return dnsAddresses; 123 } 124 125 public void addPrivateDnsRoutes() { 126 if (DBG) Log.d(TAG, "addPrivateDnsRoutes for " + this + 127 "(" + mInterfaceName + ")"); 128 if (mInterfaceName != null && !mPrivateDnsRouteSet) { 129 for (String addrString : getNameServers()) { 130 int addr = NetworkUtils.lookupHost(addrString); 131 if (addr != -1) { 132 NetworkUtils.addHostRoute(mInterfaceName, addr); 133 } 134 } 135 mPrivateDnsRouteSet = true; 136 } 137 } 138 139 public void removePrivateDnsRoutes() { 140 if (DBG) Log.d(TAG, "removePrivateDnsRoutes for " + this + 141 "(" + mInterfaceName + ")"); 142 // TODO - we should do this explicitly but the NetUtils api doesnt 143 // support this yet - must remove all. No worse than before 144 if (mInterfaceName != null && mPrivateDnsRouteSet) { 145 NetworkUtils.removeHostRoutes(mInterfaceName); 146 mPrivateDnsRouteSet = false; 147 } 148 } 149 150 public void addDefaultRoute() { 151 if (DBG) Log.d(TAG, "addDefaultRoute for " + this + "(" + 152 mInterfaceName + "), GatewayAddr=" + mDefaultGatewayAddr); 153 if ((mInterfaceName != null) && (mDefaultGatewayAddr != 0) && 154 mDefaultRouteSet == false) { 155 NetworkUtils.setDefaultRoute(mInterfaceName, mDefaultGatewayAddr); 156 mDefaultRouteSet = true; 157 } 158 } 159 160 public void removeDefaultRoute() { 161 if (DBG) Log.d(TAG, "removeDefaultRoute for " + this + "(" + 162 mInterfaceName + ")"); 163 if (mInterfaceName != null && mDefaultRouteSet == true) { 164 NetworkUtils.removeDefaultRoute(mInterfaceName); 165 mDefaultRouteSet = false; 166 } 167 } 168 169 /** 170 * Reads the network specific TCP buffer sizes from SystemProperties 171 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system 172 * wide use 173 */ 174 public void updateNetworkSettings() { 175 String key = getTcpBufferSizesPropName(); 176 String bufferSizes = SystemProperties.get(key); 177 178 if (bufferSizes.length() == 0) { 179 Log.e(TAG, key + " not found in system properties. Using defaults"); 180 181 // Setting to default values so we won't be stuck to previous values 182 key = "net.tcp.buffersize.default"; 183 bufferSizes = SystemProperties.get(key); 184 } 185 186 // Set values in kernel 187 if (bufferSizes.length() != 0) { 188 if (DBG) { 189 Log.v(TAG, "Setting TCP values: [" + bufferSizes 190 + "] which comes from [" + key + "]"); 191 } 192 setBufferSize(bufferSizes); 193 } 194 } 195 196 /** 197 * Release the wakelock, if any, that may be held while handling a 198 * disconnect operation. 199 */ 200 public void releaseWakeLock() { 201 } 202 203 /** 204 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max] 205 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem 206 * 207 * @param bufferSizes in the format of "readMin, readInitial, readMax, 208 * writeMin, writeInitial, writeMax" 209 */ 210 private void setBufferSize(String bufferSizes) { 211 try { 212 String[] values = bufferSizes.split(","); 213 214 if (values.length == 6) { 215 final String prefix = "/sys/kernel/ipv4/tcp_"; 216 stringToFile(prefix + "rmem_min", values[0]); 217 stringToFile(prefix + "rmem_def", values[1]); 218 stringToFile(prefix + "rmem_max", values[2]); 219 stringToFile(prefix + "wmem_min", values[3]); 220 stringToFile(prefix + "wmem_def", values[4]); 221 stringToFile(prefix + "wmem_max", values[5]); 222 } else { 223 Log.e(TAG, "Invalid buffersize string: " + bufferSizes); 224 } 225 } catch (IOException e) { 226 Log.e(TAG, "Can't set tcp buffer sizes:" + e); 227 } 228 } 229 230 /** 231 * Writes string to file. Basically same as "echo -n $string > $filename" 232 * 233 * @param filename 234 * @param string 235 * @throws IOException 236 */ 237 private void stringToFile(String filename, String string) throws IOException { 238 FileWriter out = new FileWriter(filename); 239 try { 240 out.write(string); 241 } finally { 242 out.close(); 243 } 244 } 245 246 /** 247 * Record the detailed state of a network, and if it is a 248 * change from the previous state, send a notification to 249 * any listeners. 250 * @param state the new @{code DetailedState} 251 */ 252 public void setDetailedState(NetworkInfo.DetailedState state) { 253 setDetailedState(state, null, null); 254 } 255 256 /** 257 * Record the detailed state of a network, and if it is a 258 * change from the previous state, send a notification to 259 * any listeners. 260 * @param state the new @{code DetailedState} 261 * @param reason a {@code String} indicating a reason for the state change, 262 * if one was supplied. May be {@code null}. 263 * @param extraInfo optional {@code String} providing extra information about the state change 264 */ 265 public void setDetailedState(NetworkInfo.DetailedState state, String reason, String extraInfo) { 266 if (DBG) Log.d(TAG, "setDetailed state, old ="+mNetworkInfo.getDetailedState()+" and new state="+state); 267 if (state != mNetworkInfo.getDetailedState()) { 268 boolean wasConnecting = (mNetworkInfo.getState() == NetworkInfo.State.CONNECTING); 269 String lastReason = mNetworkInfo.getReason(); 270 /* 271 * If a reason was supplied when the CONNECTING state was entered, and no 272 * reason was supplied for entering the CONNECTED state, then retain the 273 * reason that was supplied when going to CONNECTING. 274 */ 275 if (wasConnecting && state == NetworkInfo.DetailedState.CONNECTED && reason == null 276 && lastReason != null) 277 reason = lastReason; 278 mNetworkInfo.setDetailedState(state, reason, extraInfo); 279 Message msg = mTarget.obtainMessage(EVENT_STATE_CHANGED, mNetworkInfo); 280 msg.sendToTarget(); 281 } 282 } 283 284 protected void setDetailedStateInternal(NetworkInfo.DetailedState state) { 285 mNetworkInfo.setDetailedState(state, null, null); 286 } 287 288 public void setTeardownRequested(boolean isRequested) { 289 mTeardownRequested = isRequested; 290 } 291 292 public boolean isTeardownRequested() { 293 return mTeardownRequested; 294 } 295 296 /** 297 * Send a notification that the results of a scan for network access 298 * points has completed, and results are available. 299 */ 300 protected void sendScanResultsAvailable() { 301 Message msg = mTarget.obtainMessage(EVENT_SCAN_RESULTS_AVAILABLE, mNetworkInfo); 302 msg.sendToTarget(); 303 } 304 305 /** 306 * Record the roaming status of the device, and if it is a change from the previous 307 * status, send a notification to any listeners. 308 * @param isRoaming {@code true} if the device is now roaming, {@code false} 309 * if it is no longer roaming. 310 */ 311 protected void setRoamingStatus(boolean isRoaming) { 312 if (isRoaming != mNetworkInfo.isRoaming()) { 313 mNetworkInfo.setRoaming(isRoaming); 314 Message msg = mTarget.obtainMessage(EVENT_ROAMING_CHANGED, mNetworkInfo); 315 msg.sendToTarget(); 316 } 317 } 318 319 protected void setSubtype(int subtype, String subtypeName) { 320 if (mNetworkInfo.isConnected()) { 321 int oldSubtype = mNetworkInfo.getSubtype(); 322 if (subtype != oldSubtype) { 323 mNetworkInfo.setSubtype(subtype, subtypeName); 324 Message msg = mTarget.obtainMessage( 325 EVENT_NETWORK_SUBTYPE_CHANGED, oldSubtype, 0, mNetworkInfo); 326 msg.sendToTarget(); 327 } 328 } 329 } 330 331 public abstract void startMonitoring(); 332 333 /** 334 * Disable connectivity to a network 335 * @return {@code true} if a teardown occurred, {@code false} if the 336 * teardown did not occur. 337 */ 338 public abstract boolean teardown(); 339 340 /** 341 * Reenable connectivity to a network after a {@link #teardown()}. 342 */ 343 public abstract boolean reconnect(); 344 345 /** 346 * Turn the wireless radio off for a network. 347 * @param turnOn {@code true} to turn the radio on, {@code false} 348 */ 349 public abstract boolean setRadio(boolean turnOn); 350 351 /** 352 * Returns an indication of whether this network is available for 353 * connections. A value of {@code false} means that some quasi-permanent 354 * condition prevents connectivity to this network. 355 */ 356 public abstract boolean isAvailable(); 357 358 /** 359 * Tells the underlying networking system that the caller wants to 360 * begin using the named feature. The interpretation of {@code feature} 361 * is completely up to each networking implementation. 362 * @param feature the name of the feature to be used 363 * @param callingPid the process ID of the process that is issuing this request 364 * @param callingUid the user ID of the process that is issuing this request 365 * @return an integer value representing the outcome of the request. 366 * The interpretation of this value is specific to each networking 367 * implementation+feature combination, except that the value {@code -1} 368 * always indicates failure. 369 */ 370 public abstract int startUsingNetworkFeature(String feature, int callingPid, int callingUid); 371 372 /** 373 * Tells the underlying networking system that the caller is finished 374 * using the named feature. The interpretation of {@code feature} 375 * is completely up to each networking implementation. 376 * @param feature the name of the feature that is no longer needed. 377 * @param callingPid the process ID of the process that is issuing this request 378 * @param callingUid the user ID of the process that is issuing this request 379 * @return an integer value representing the outcome of the request. 380 * The interpretation of this value is specific to each networking 381 * implementation+feature combination, except that the value {@code -1} 382 * always indicates failure. 383 */ 384 public abstract int stopUsingNetworkFeature(String feature, int callingPid, int callingUid); 385 386 /** 387 * Ensure that a network route exists to deliver traffic to the specified 388 * host via this network interface. 389 * @param hostAddress the IP address of the host to which the route is desired 390 * @return {@code true} on success, {@code false} on failure 391 */ 392 public boolean requestRouteToHost(int hostAddress) { 393 return false; 394 } 395 396 /** 397 * Interprets scan results. This will be called at a safe time for 398 * processing, and from a safe thread. 399 */ 400 public void interpretScanResultsAvailable() { 401 } 402 403} 404