ConnectivityService.java revision 8a9b22056b13477f59df934928c00c58b5871c95
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 com.android.server; 18 19import android.app.Notification; 20import android.app.NotificationManager; 21import android.content.ContentResolver; 22import android.content.Context; 23import android.content.Intent; 24import android.content.pm.PackageManager; 25import android.net.ConnectivityManager; 26import android.net.IConnectivityManager; 27import android.net.MobileDataStateTracker; 28import android.net.NetworkInfo; 29import android.net.NetworkStateTracker; 30import android.net.wifi.WifiStateTracker; 31import android.os.Binder; 32import android.os.Handler; 33import android.os.IBinder; 34import android.os.Looper; 35import android.os.Message; 36import android.os.RemoteException; 37import android.os.ServiceManager; 38import android.os.SystemProperties; 39import android.provider.Settings; 40import android.text.TextUtils; 41import android.util.EventLog; 42import android.util.Slog; 43 44import com.android.internal.telephony.Phone; 45 46import com.android.server.connectivity.Tethering; 47 48import java.io.FileDescriptor; 49import java.io.PrintWriter; 50import java.util.ArrayList; 51import java.util.List; 52 53/** 54 * @hide 55 */ 56public class ConnectivityService extends IConnectivityManager.Stub { 57 58 private static final boolean DBG = true; 59 private static final String TAG = "ConnectivityService"; 60 61 // how long to wait before switching back to a radio's default network 62 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000; 63 // system property that can override the above value 64 private static final String NETWORK_RESTORE_DELAY_PROP_NAME = 65 "android.telephony.apn-restore"; 66 67 68 private Tethering mTethering; 69 private boolean mTetheringConfigValid = false; 70 71 /** 72 * Sometimes we want to refer to the individual network state 73 * trackers separately, and sometimes we just want to treat them 74 * abstractly. 75 */ 76 private NetworkStateTracker mNetTrackers[]; 77 78 /** 79 * A per Net list of the PID's that requested access to the net 80 * used both as a refcount and for per-PID DNS selection 81 */ 82 private List mNetRequestersPids[]; 83 84 private WifiWatchdogService mWifiWatchdogService; 85 86 // priority order of the nettrackers 87 // (excluding dynamically set mNetworkPreference) 88 // TODO - move mNetworkTypePreference into this 89 private int[] mPriorityList; 90 91 private Context mContext; 92 private int mNetworkPreference; 93 private int mActiveDefaultNetwork = -1; 94 95 private int mNumDnsEntries; 96 97 private boolean mTestMode; 98 private static ConnectivityService sServiceInstance; 99 100 private Handler mHandler; 101 102 // list of DeathRecipients used to make sure features are turned off when 103 // a process dies 104 private List mFeatureUsers; 105 106 private boolean mSystemReady; 107 private Intent mInitialBroadcast; 108 109 private static class NetworkAttributes { 110 /** 111 * Class for holding settings read from resources. 112 */ 113 public String mName; 114 public int mType; 115 public int mRadio; 116 public int mPriority; 117 public NetworkInfo.State mLastState; 118 public NetworkAttributes(String init) { 119 String fragments[] = init.split(","); 120 mName = fragments[0].toLowerCase(); 121 mType = Integer.parseInt(fragments[1]); 122 mRadio = Integer.parseInt(fragments[2]); 123 mPriority = Integer.parseInt(fragments[3]); 124 mLastState = NetworkInfo.State.UNKNOWN; 125 } 126 public boolean isDefault() { 127 return (mType == mRadio); 128 } 129 } 130 NetworkAttributes[] mNetAttributes; 131 int mNetworksDefined; 132 133 private static class RadioAttributes { 134 public int mSimultaneity; 135 public int mType; 136 public RadioAttributes(String init) { 137 String fragments[] = init.split(","); 138 mType = Integer.parseInt(fragments[0]); 139 mSimultaneity = Integer.parseInt(fragments[1]); 140 } 141 } 142 RadioAttributes[] mRadioAttributes; 143 144 private static class ConnectivityThread extends Thread { 145 private Context mContext; 146 147 private ConnectivityThread(Context context) { 148 super("ConnectivityThread"); 149 mContext = context; 150 } 151 152 @Override 153 public void run() { 154 Looper.prepare(); 155 synchronized (this) { 156 sServiceInstance = new ConnectivityService(mContext); 157 notifyAll(); 158 } 159 Looper.loop(); 160 } 161 162 public static ConnectivityService getServiceInstance(Context context) { 163 ConnectivityThread thread = new ConnectivityThread(context); 164 thread.start(); 165 166 synchronized (thread) { 167 while (sServiceInstance == null) { 168 try { 169 // Wait until sServiceInstance has been initialized. 170 thread.wait(); 171 } catch (InterruptedException ignore) { 172 Slog.e(TAG, 173 "Unexpected InterruptedException while waiting"+ 174 " for ConnectivityService thread"); 175 } 176 } 177 } 178 179 return sServiceInstance; 180 } 181 } 182 183 public static ConnectivityService getInstance(Context context) { 184 return ConnectivityThread.getServiceInstance(context); 185 } 186 187 private ConnectivityService(Context context) { 188 if (DBG) Slog.v(TAG, "ConnectivityService starting up"); 189 190 // setup our unique device name 191 String id = Settings.Secure.getString(context.getContentResolver(), 192 Settings.Secure.ANDROID_ID); 193 if (id != null && id.length() > 0) { 194 String name = new String("android_").concat(id); 195 SystemProperties.set("net.hostname", name); 196 } 197 198 mContext = context; 199 mNetTrackers = new NetworkStateTracker[ 200 ConnectivityManager.MAX_NETWORK_TYPE+1]; 201 mHandler = new MyHandler(); 202 203 mNetworkPreference = getPersistedNetworkPreference(); 204 205 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1]; 206 mNetAttributes = new NetworkAttributes[ConnectivityManager.MAX_NETWORK_TYPE+1]; 207 208 // Load device network attributes from resources 209 String[] raStrings = context.getResources().getStringArray( 210 com.android.internal.R.array.radioAttributes); 211 for (String raString : raStrings) { 212 RadioAttributes r = new RadioAttributes(raString); 213 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) { 214 Slog.e(TAG, "Error in radioAttributes - ignoring attempt to define type " + r.mType); 215 continue; 216 } 217 if (mRadioAttributes[r.mType] != null) { 218 Slog.e(TAG, "Error in radioAttributes - ignoring attempt to redefine type " + 219 r.mType); 220 continue; 221 } 222 mRadioAttributes[r.mType] = r; 223 } 224 225 String[] naStrings = context.getResources().getStringArray( 226 com.android.internal.R.array.networkAttributes); 227 for (String naString : naStrings) { 228 try { 229 NetworkAttributes n = new NetworkAttributes(naString); 230 if (n.mType > ConnectivityManager.MAX_NETWORK_TYPE) { 231 Slog.e(TAG, "Error in networkAttributes - ignoring attempt to define type " + 232 n.mType); 233 continue; 234 } 235 if (mNetAttributes[n.mType] != null) { 236 Slog.e(TAG, "Error in networkAttributes - ignoring attempt to redefine type " + 237 n.mType); 238 continue; 239 } 240 if (mRadioAttributes[n.mRadio] == null) { 241 Slog.e(TAG, "Error in networkAttributes - ignoring attempt to use undefined " + 242 "radio " + n.mRadio + " in network type " + n.mType); 243 continue; 244 } 245 mNetAttributes[n.mType] = n; 246 mNetworksDefined++; 247 } catch(Exception e) { 248 // ignore it - leave the entry null 249 } 250 } 251 252 // high priority first 253 mPriorityList = new int[mNetworksDefined]; 254 { 255 int insertionPoint = mNetworksDefined-1; 256 int currentLowest = 0; 257 int nextLowest = 0; 258 while (insertionPoint > -1) { 259 for (NetworkAttributes na : mNetAttributes) { 260 if (na == null) continue; 261 if (na.mPriority < currentLowest) continue; 262 if (na.mPriority > currentLowest) { 263 if (na.mPriority < nextLowest || nextLowest == 0) { 264 nextLowest = na.mPriority; 265 } 266 continue; 267 } 268 mPriorityList[insertionPoint--] = na.mType; 269 } 270 currentLowest = nextLowest; 271 nextLowest = 0; 272 } 273 } 274 275 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1]; 276 for (int i : mPriorityList) { 277 mNetRequestersPids[i] = new ArrayList(); 278 } 279 280 mFeatureUsers = new ArrayList(); 281 282 mNumDnsEntries = 0; 283 284 mTestMode = SystemProperties.get("cm.test.mode").equals("true") 285 && SystemProperties.get("ro.build.type").equals("eng"); 286 /* 287 * Create the network state trackers for Wi-Fi and mobile 288 * data. Maybe this could be done with a factory class, 289 * but it's not clear that it's worth it, given that 290 * the number of different network types is not going 291 * to change very often. 292 */ 293 boolean noMobileData = !getMobileDataEnabled(); 294 for (int netType : mPriorityList) { 295 switch (mNetAttributes[netType].mRadio) { 296 case ConnectivityManager.TYPE_WIFI: 297 if (DBG) Slog.v(TAG, "Starting Wifi Service."); 298 WifiStateTracker wst = new WifiStateTracker(context, mHandler); 299 WifiService wifiService = new WifiService(context, wst); 300 ServiceManager.addService(Context.WIFI_SERVICE, wifiService); 301 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst; 302 wst.startMonitoring(); 303 304 // Constructing this starts it too 305 mWifiWatchdogService = new WifiWatchdogService(context, wst); 306 break; 307 case ConnectivityManager.TYPE_MOBILE: 308 mNetTrackers[netType] = new MobileDataStateTracker(context, mHandler, 309 netType, mNetAttributes[netType].mName); 310 mNetTrackers[netType].startMonitoring(); 311 if (noMobileData) { 312 if (DBG) Slog.d(TAG, "tearing down Mobile networks due to setting"); 313 mNetTrackers[netType].teardown(); 314 } 315 break; 316 default: 317 Slog.e(TAG, "Trying to create a DataStateTracker for an unknown radio type " + 318 mNetAttributes[netType].mRadio); 319 continue; 320 } 321 } 322 323 mTethering = new Tethering(mContext); 324 mTetheringConfigValid = (((mNetTrackers[ConnectivityManager.TYPE_MOBILE_DUN] != null) || 325 !mTethering.isDunRequired()) && 326 (mTethering.getTetherableUsbRegexs().length != 0 || 327 mTethering.getTetherableWifiRegexs().length != 0) && 328 mTethering.getUpstreamIfaceRegexs().length != 0); 329 330 } 331 332 333 /** 334 * Sets the preferred network. 335 * @param preference the new preference 336 */ 337 public synchronized void setNetworkPreference(int preference) { 338 enforceChangePermission(); 339 if (ConnectivityManager.isNetworkTypeValid(preference) && 340 mNetAttributes[preference] != null && 341 mNetAttributes[preference].isDefault()) { 342 if (mNetworkPreference != preference) { 343 persistNetworkPreference(preference); 344 mNetworkPreference = preference; 345 enforcePreference(); 346 } 347 } 348 } 349 350 public int getNetworkPreference() { 351 enforceAccessPermission(); 352 return mNetworkPreference; 353 } 354 355 private void persistNetworkPreference(int networkPreference) { 356 final ContentResolver cr = mContext.getContentResolver(); 357 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, 358 networkPreference); 359 } 360 361 private int getPersistedNetworkPreference() { 362 final ContentResolver cr = mContext.getContentResolver(); 363 364 final int networkPrefSetting = Settings.Secure 365 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1); 366 if (networkPrefSetting != -1) { 367 return networkPrefSetting; 368 } 369 370 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE; 371 } 372 373 /** 374 * Make the state of network connectivity conform to the preference settings 375 * In this method, we only tear down a non-preferred network. Establishing 376 * a connection to the preferred network is taken care of when we handle 377 * the disconnect event from the non-preferred network 378 * (see {@link #handleDisconnect(NetworkInfo)}). 379 */ 380 private void enforcePreference() { 381 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected()) 382 return; 383 384 if (!mNetTrackers[mNetworkPreference].isAvailable()) 385 return; 386 387 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) { 388 if (t != mNetworkPreference && mNetTrackers[t] != null && 389 mNetTrackers[t].getNetworkInfo().isConnected()) { 390 if (DBG) { 391 Slog.d(TAG, "tearing down " + 392 mNetTrackers[t].getNetworkInfo() + 393 " in enforcePreference"); 394 } 395 teardown(mNetTrackers[t]); 396 } 397 } 398 } 399 400 private boolean teardown(NetworkStateTracker netTracker) { 401 if (netTracker.teardown()) { 402 netTracker.setTeardownRequested(true); 403 return true; 404 } else { 405 return false; 406 } 407 } 408 409 /** 410 * Return NetworkInfo for the active (i.e., connected) network interface. 411 * It is assumed that at most one network is active at a time. If more 412 * than one is active, it is indeterminate which will be returned. 413 * @return the info for the active network, or {@code null} if none is 414 * active 415 */ 416 public NetworkInfo getActiveNetworkInfo() { 417 enforceAccessPermission(); 418 for (int type=0; type <= ConnectivityManager.MAX_NETWORK_TYPE; type++) { 419 if (mNetAttributes[type] == null || !mNetAttributes[type].isDefault()) { 420 continue; 421 } 422 NetworkStateTracker t = mNetTrackers[type]; 423 NetworkInfo info = t.getNetworkInfo(); 424 if (info.isConnected()) { 425 if (DBG && type != mActiveDefaultNetwork) Slog.e(TAG, 426 "connected default network is not " + 427 "mActiveDefaultNetwork!"); 428 return info; 429 } 430 } 431 return null; 432 } 433 434 public NetworkInfo getNetworkInfo(int networkType) { 435 enforceAccessPermission(); 436 if (ConnectivityManager.isNetworkTypeValid(networkType)) { 437 NetworkStateTracker t = mNetTrackers[networkType]; 438 if (t != null) 439 return t.getNetworkInfo(); 440 } 441 return null; 442 } 443 444 public NetworkInfo[] getAllNetworkInfo() { 445 enforceAccessPermission(); 446 NetworkInfo[] result = new NetworkInfo[mNetworksDefined]; 447 int i = 0; 448 for (NetworkStateTracker t : mNetTrackers) { 449 if(t != null) result[i++] = t.getNetworkInfo(); 450 } 451 return result; 452 } 453 454 public boolean setRadios(boolean turnOn) { 455 boolean result = true; 456 enforceChangePermission(); 457 for (NetworkStateTracker t : mNetTrackers) { 458 if (t != null) result = t.setRadio(turnOn) && result; 459 } 460 return result; 461 } 462 463 public boolean setRadio(int netType, boolean turnOn) { 464 enforceChangePermission(); 465 if (!ConnectivityManager.isNetworkTypeValid(netType)) { 466 return false; 467 } 468 NetworkStateTracker tracker = mNetTrackers[netType]; 469 return tracker != null && tracker.setRadio(turnOn); 470 } 471 472 /** 473 * Used to notice when the calling process dies so we can self-expire 474 * 475 * Also used to know if the process has cleaned up after itself when 476 * our auto-expire timer goes off. The timer has a link to an object. 477 * 478 */ 479 private class FeatureUser implements IBinder.DeathRecipient { 480 int mNetworkType; 481 String mFeature; 482 IBinder mBinder; 483 int mPid; 484 int mUid; 485 long mCreateTime; 486 487 FeatureUser(int type, String feature, IBinder binder) { 488 super(); 489 mNetworkType = type; 490 mFeature = feature; 491 mBinder = binder; 492 mPid = getCallingPid(); 493 mUid = getCallingUid(); 494 mCreateTime = System.currentTimeMillis(); 495 496 try { 497 mBinder.linkToDeath(this, 0); 498 } catch (RemoteException e) { 499 binderDied(); 500 } 501 } 502 503 void unlinkDeathRecipient() { 504 mBinder.unlinkToDeath(this, 0); 505 } 506 507 public void binderDied() { 508 Slog.d(TAG, "ConnectivityService FeatureUser binderDied(" + 509 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " + 510 (System.currentTimeMillis() - mCreateTime) + " mSec ago"); 511 stopUsingNetworkFeature(this, false); 512 } 513 514 public void expire() { 515 Slog.d(TAG, "ConnectivityService FeatureUser expire(" + 516 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " + 517 (System.currentTimeMillis() - mCreateTime) + " mSec ago"); 518 stopUsingNetworkFeature(this, false); 519 } 520 521 public String toString() { 522 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " + 523 (System.currentTimeMillis() - mCreateTime) + " mSec ago"; 524 } 525 } 526 527 // javadoc from interface 528 public int startUsingNetworkFeature(int networkType, String feature, 529 IBinder binder) { 530 if (DBG) { 531 Slog.d(TAG, "startUsingNetworkFeature for net " + networkType + 532 ": " + feature); 533 } 534 enforceChangePermission(); 535 if (!ConnectivityManager.isNetworkTypeValid(networkType) || 536 mNetAttributes[networkType] == null) { 537 return Phone.APN_REQUEST_FAILED; 538 } 539 540 FeatureUser f = new FeatureUser(networkType, feature, binder); 541 542 // TODO - move this into the MobileDataStateTracker 543 int usedNetworkType = networkType; 544 if(networkType == ConnectivityManager.TYPE_MOBILE) { 545 if (!getMobileDataEnabled()) { 546 if (DBG) Slog.d(TAG, "requested special network with data disabled - rejected"); 547 return Phone.APN_TYPE_NOT_AVAILABLE; 548 } 549 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) { 550 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS; 551 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) { 552 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL; 553 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN)) { 554 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN; 555 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) { 556 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI; 557 } 558 } 559 NetworkStateTracker network = mNetTrackers[usedNetworkType]; 560 if (network != null) { 561 if (usedNetworkType != networkType) { 562 Integer currentPid = new Integer(getCallingPid()); 563 564 NetworkStateTracker radio = mNetTrackers[networkType]; 565 NetworkInfo ni = network.getNetworkInfo(); 566 567 if (ni.isAvailable() == false) { 568 if (DBG) Slog.d(TAG, "special network not available"); 569 return Phone.APN_TYPE_NOT_AVAILABLE; 570 } 571 572 synchronized(this) { 573 mFeatureUsers.add(f); 574 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) { 575 // this gets used for per-pid dns when connected 576 mNetRequestersPids[usedNetworkType].add(currentPid); 577 } 578 } 579 mHandler.sendMessageDelayed(mHandler.obtainMessage( 580 NetworkStateTracker.EVENT_RESTORE_DEFAULT_NETWORK, 581 f), getRestoreDefaultNetworkDelay()); 582 583 584 if ((ni.isConnectedOrConnecting() == true) && 585 !network.isTeardownRequested()) { 586 if (ni.isConnected() == true) { 587 // add the pid-specific dns 588 handleDnsConfigurationChange(); 589 if (DBG) Slog.d(TAG, "special network already active"); 590 return Phone.APN_ALREADY_ACTIVE; 591 } 592 if (DBG) Slog.d(TAG, "special network already connecting"); 593 return Phone.APN_REQUEST_STARTED; 594 } 595 596 // check if the radio in play can make another contact 597 // assume if cannot for now 598 599 if (DBG) Slog.d(TAG, "reconnecting to special network"); 600 network.reconnect(); 601 return Phone.APN_REQUEST_STARTED; 602 } else { 603 synchronized(this) { 604 mFeatureUsers.add(f); 605 } 606 mHandler.sendMessageDelayed(mHandler.obtainMessage( 607 NetworkStateTracker.EVENT_RESTORE_DEFAULT_NETWORK, 608 f), getRestoreDefaultNetworkDelay()); 609 610 return network.startUsingNetworkFeature(feature, 611 getCallingPid(), getCallingUid()); 612 } 613 } 614 return Phone.APN_TYPE_NOT_AVAILABLE; 615 } 616 617 // javadoc from interface 618 public int stopUsingNetworkFeature(int networkType, String feature) { 619 enforceChangePermission(); 620 621 int pid = getCallingPid(); 622 int uid = getCallingUid(); 623 624 FeatureUser u = null; 625 boolean found = false; 626 627 synchronized(this) { 628 for (int i = 0; i < mFeatureUsers.size() ; i++) { 629 u = (FeatureUser)mFeatureUsers.get(i); 630 if (uid == u.mUid && pid == u.mPid && 631 networkType == u.mNetworkType && 632 TextUtils.equals(feature, u.mFeature)) { 633 found = true; 634 break; 635 } 636 } 637 } 638 if (found && u != null) { 639 // stop regardless of how many other time this proc had called start 640 return stopUsingNetworkFeature(u, true); 641 } else { 642 // none found! 643 if (DBG) Slog.d(TAG, "ignoring stopUsingNetworkFeature - not a live request"); 644 return 1; 645 } 646 } 647 648 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) { 649 int networkType = u.mNetworkType; 650 String feature = u.mFeature; 651 int pid = u.mPid; 652 int uid = u.mUid; 653 654 NetworkStateTracker tracker = null; 655 boolean callTeardown = false; // used to carry our decision outside of sync block 656 657 if (DBG) { 658 Slog.d(TAG, "stopUsingNetworkFeature for net " + networkType + 659 ": " + feature); 660 } 661 662 if (!ConnectivityManager.isNetworkTypeValid(networkType)) { 663 return -1; 664 } 665 666 // need to link the mFeatureUsers list with the mNetRequestersPids state in this 667 // sync block 668 synchronized(this) { 669 // check if this process still has an outstanding start request 670 if (!mFeatureUsers.contains(u)) { 671 return 1; 672 } 673 u.unlinkDeathRecipient(); 674 mFeatureUsers.remove(mFeatureUsers.indexOf(u)); 675 // If we care about duplicate requests, check for that here. 676 // 677 // This is done to support the extension of a request - the app 678 // can request we start the network feature again and renew the 679 // auto-shutoff delay. Normal "stop" calls from the app though 680 // do not pay attention to duplicate requests - in effect the 681 // API does not refcount and a single stop will counter multiple starts. 682 if (ignoreDups == false) { 683 for (int i = 0; i < mFeatureUsers.size() ; i++) { 684 FeatureUser x = (FeatureUser)mFeatureUsers.get(i); 685 if (x.mUid == u.mUid && x.mPid == u.mPid && 686 x.mNetworkType == u.mNetworkType && 687 TextUtils.equals(x.mFeature, u.mFeature)) { 688 if (DBG) Slog.d(TAG, "ignoring stopUsingNetworkFeature as dup is found"); 689 return 1; 690 } 691 } 692 } 693 694 // TODO - move to MobileDataStateTracker 695 int usedNetworkType = networkType; 696 if (networkType == ConnectivityManager.TYPE_MOBILE) { 697 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) { 698 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS; 699 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) { 700 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL; 701 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN)) { 702 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN; 703 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) { 704 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI; 705 } 706 } 707 tracker = mNetTrackers[usedNetworkType]; 708 if (tracker == null) { 709 return -1; 710 } 711 if (usedNetworkType != networkType) { 712 Integer currentPid = new Integer(pid); 713 mNetRequestersPids[usedNetworkType].remove(currentPid); 714 reassessPidDns(pid, true); 715 if (mNetRequestersPids[usedNetworkType].size() != 0) { 716 if (DBG) Slog.d(TAG, "not tearing down special network - " + 717 "others still using it"); 718 return 1; 719 } 720 callTeardown = true; 721 } 722 } 723 724 if (callTeardown) { 725 tracker.teardown(); 726 return 1; 727 } else { 728 // do it the old fashioned way 729 return tracker.stopUsingNetworkFeature(feature, pid, uid); 730 } 731 } 732 733 /** 734 * Ensure that a network route exists to deliver traffic to the specified 735 * host via the specified network interface. 736 * @param networkType the type of the network over which traffic to the 737 * specified host is to be routed 738 * @param hostAddress the IP address of the host to which the route is 739 * desired 740 * @return {@code true} on success, {@code false} on failure 741 */ 742 public boolean requestRouteToHost(int networkType, int hostAddress) { 743 enforceChangePermission(); 744 if (!ConnectivityManager.isNetworkTypeValid(networkType)) { 745 return false; 746 } 747 NetworkStateTracker tracker = mNetTrackers[networkType]; 748 749 if (tracker == null || !tracker.getNetworkInfo().isConnected() || 750 tracker.isTeardownRequested()) { 751 if (DBG) { 752 Slog.d(TAG, "requestRouteToHost on down network (" + networkType + ") - dropped"); 753 } 754 return false; 755 } 756 return tracker.requestRouteToHost(hostAddress); 757 } 758 759 /** 760 * @see ConnectivityManager#getBackgroundDataSetting() 761 */ 762 public boolean getBackgroundDataSetting() { 763 return Settings.Secure.getInt(mContext.getContentResolver(), 764 Settings.Secure.BACKGROUND_DATA, 1) == 1; 765 } 766 767 /** 768 * @see ConnectivityManager#setBackgroundDataSetting(boolean) 769 */ 770 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) { 771 mContext.enforceCallingOrSelfPermission( 772 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING, 773 "ConnectivityService"); 774 775 if (getBackgroundDataSetting() == allowBackgroundDataUsage) return; 776 777 Settings.Secure.putInt(mContext.getContentResolver(), 778 Settings.Secure.BACKGROUND_DATA, 779 allowBackgroundDataUsage ? 1 : 0); 780 781 Intent broadcast = new Intent( 782 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED); 783 mContext.sendBroadcast(broadcast); 784 } 785 786 /** 787 * @see ConnectivityManager#getMobileDataEnabled() 788 */ 789 public boolean getMobileDataEnabled() { 790 enforceAccessPermission(); 791 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(), 792 Settings.Secure.MOBILE_DATA, 1) == 1; 793 if (DBG) Slog.d(TAG, "getMobileDataEnabled returning " + retVal); 794 return retVal; 795 } 796 797 /** 798 * @see ConnectivityManager#setMobileDataEnabled(boolean) 799 */ 800 public synchronized void setMobileDataEnabled(boolean enabled) { 801 enforceChangePermission(); 802 if (DBG) Slog.d(TAG, "setMobileDataEnabled(" + enabled + ")"); 803 804 if (getMobileDataEnabled() == enabled) return; 805 806 Settings.Secure.putInt(mContext.getContentResolver(), 807 Settings.Secure.MOBILE_DATA, enabled ? 1 : 0); 808 809 if (enabled) { 810 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) { 811 if (DBG) Slog.d(TAG, "starting up " + mNetTrackers[ConnectivityManager.TYPE_MOBILE]); 812 mNetTrackers[ConnectivityManager.TYPE_MOBILE].reconnect(); 813 } 814 } else { 815 for (NetworkStateTracker nt : mNetTrackers) { 816 if (nt == null) continue; 817 int netType = nt.getNetworkInfo().getType(); 818 if (mNetAttributes[netType].mRadio == ConnectivityManager.TYPE_MOBILE) { 819 if (DBG) Slog.d(TAG, "tearing down " + nt); 820 nt.teardown(); 821 } 822 } 823 } 824 } 825 826 private int getNumConnectedNetworks() { 827 int numConnectedNets = 0; 828 829 for (NetworkStateTracker nt : mNetTrackers) { 830 if (nt != null && nt.getNetworkInfo().isConnected() && 831 !nt.isTeardownRequested()) { 832 ++numConnectedNets; 833 } 834 } 835 return numConnectedNets; 836 } 837 838 private void enforceAccessPermission() { 839 mContext.enforceCallingOrSelfPermission( 840 android.Manifest.permission.ACCESS_NETWORK_STATE, 841 "ConnectivityService"); 842 } 843 844 private void enforceChangePermission() { 845 mContext.enforceCallingOrSelfPermission( 846 android.Manifest.permission.CHANGE_NETWORK_STATE, 847 "ConnectivityService"); 848 } 849 850 // TODO Make this a special check when it goes public 851 private void enforceTetherChangePermission() { 852 mContext.enforceCallingOrSelfPermission( 853 android.Manifest.permission.CHANGE_NETWORK_STATE, 854 "ConnectivityService"); 855 } 856 857 private void enforceTetherAccessPermission() { 858 mContext.enforceCallingOrSelfPermission( 859 android.Manifest.permission.ACCESS_NETWORK_STATE, 860 "ConnectivityService"); 861 } 862 863 /** 864 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active 865 * network, we ignore it. If it is for the active network, we send out a 866 * broadcast. But first, we check whether it might be possible to connect 867 * to a different network. 868 * @param info the {@code NetworkInfo} for the network 869 */ 870 private void handleDisconnect(NetworkInfo info) { 871 872 int prevNetType = info.getType(); 873 874 mNetTrackers[prevNetType].setTeardownRequested(false); 875 /* 876 * If the disconnected network is not the active one, then don't report 877 * this as a loss of connectivity. What probably happened is that we're 878 * getting the disconnect for a network that we explicitly disabled 879 * in accordance with network preference policies. 880 */ 881 if (!mNetAttributes[prevNetType].isDefault()) { 882 List pids = mNetRequestersPids[prevNetType]; 883 for (int i = 0; i<pids.size(); i++) { 884 Integer pid = (Integer)pids.get(i); 885 // will remove them because the net's no longer connected 886 // need to do this now as only now do we know the pids and 887 // can properly null things that are no longer referenced. 888 reassessPidDns(pid.intValue(), false); 889 } 890 } 891 892 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 893 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); 894 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 895 if (info.isFailover()) { 896 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 897 info.setFailover(false); 898 } 899 if (info.getReason() != null) { 900 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 901 } 902 if (info.getExtraInfo() != null) { 903 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, 904 info.getExtraInfo()); 905 } 906 907 NetworkStateTracker newNet = null; 908 if (mNetAttributes[prevNetType].isDefault()) { 909 newNet = tryFailover(prevNetType); 910 if (newNet != null) { 911 NetworkInfo switchTo = newNet.getNetworkInfo(); 912 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo); 913 } else { 914 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 915 } 916 } 917 // do this before we broadcast the change 918 handleConnectivityChange(); 919 920 sendStickyBroadcast(intent); 921 /* 922 * If the failover network is already connected, then immediately send 923 * out a followup broadcast indicating successful failover 924 */ 925 if (newNet != null && newNet.getNetworkInfo().isConnected()) { 926 sendConnectedBroadcast(newNet.getNetworkInfo()); 927 } 928 } 929 930 // returns null if no failover available 931 private NetworkStateTracker tryFailover(int prevNetType) { 932 /* 933 * If this is a default network, check if other defaults are available 934 * or active 935 */ 936 NetworkStateTracker newNet = null; 937 if (mNetAttributes[prevNetType].isDefault()) { 938 if (mActiveDefaultNetwork == prevNetType) { 939 mActiveDefaultNetwork = -1; 940 } 941 942 int newType = -1; 943 int newPriority = -1; 944 boolean noMobileData = !getMobileDataEnabled(); 945 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) { 946 if (checkType == prevNetType) continue; 947 if (mNetAttributes[checkType] == null) continue; 948 if (mNetAttributes[checkType].mRadio == ConnectivityManager.TYPE_MOBILE && 949 noMobileData) { 950 if (DBG) { 951 Slog.d(TAG, "not failing over to mobile type " + checkType + 952 " because Mobile Data Disabled"); 953 } 954 continue; 955 } 956 if (mNetAttributes[checkType].isDefault()) { 957 /* TODO - if we have multiple nets we could use 958 * we may want to put more thought into which we choose 959 */ 960 if (checkType == mNetworkPreference) { 961 newType = checkType; 962 break; 963 } 964 if (mNetAttributes[checkType].mPriority > newPriority) { 965 newType = checkType; 966 newPriority = mNetAttributes[newType].mPriority; 967 } 968 } 969 } 970 971 if (newType != -1) { 972 newNet = mNetTrackers[newType]; 973 /** 974 * See if the other network is available to fail over to. 975 * If is not available, we enable it anyway, so that it 976 * will be able to connect when it does become available, 977 * but we report a total loss of connectivity rather than 978 * report that we are attempting to fail over. 979 */ 980 if (newNet.isAvailable()) { 981 NetworkInfo switchTo = newNet.getNetworkInfo(); 982 switchTo.setFailover(true); 983 if (!switchTo.isConnectedOrConnecting() || 984 newNet.isTeardownRequested()) { 985 newNet.reconnect(); 986 } 987 if (DBG) { 988 if (switchTo.isConnected()) { 989 Slog.v(TAG, "Switching to already connected " + 990 switchTo.getTypeName()); 991 } else { 992 Slog.v(TAG, "Attempting to switch to " + 993 switchTo.getTypeName()); 994 } 995 } 996 } else { 997 newNet.reconnect(); 998 } 999 } 1000 } 1001 1002 return newNet; 1003 } 1004 1005 private void sendConnectedBroadcast(NetworkInfo info) { 1006 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 1007 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); 1008 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 1009 if (info.isFailover()) { 1010 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 1011 info.setFailover(false); 1012 } 1013 if (info.getReason() != null) { 1014 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 1015 } 1016 if (info.getExtraInfo() != null) { 1017 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, 1018 info.getExtraInfo()); 1019 } 1020 sendStickyBroadcast(intent); 1021 } 1022 1023 /** 1024 * Called when an attempt to fail over to another network has failed. 1025 * @param info the {@link NetworkInfo} for the failed network 1026 */ 1027 private void handleConnectionFailure(NetworkInfo info) { 1028 mNetTrackers[info.getType()].setTeardownRequested(false); 1029 1030 String reason = info.getReason(); 1031 String extraInfo = info.getExtraInfo(); 1032 1033 if (DBG) { 1034 String reasonText; 1035 if (reason == null) { 1036 reasonText = "."; 1037 } else { 1038 reasonText = " (" + reason + ")."; 1039 } 1040 Slog.v(TAG, "Attempt to connect to " + info.getTypeName() + 1041 " failed" + reasonText); 1042 } 1043 1044 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 1045 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); 1046 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 1047 if (getActiveNetworkInfo() == null) { 1048 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 1049 } 1050 if (reason != null) { 1051 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason); 1052 } 1053 if (extraInfo != null) { 1054 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo); 1055 } 1056 if (info.isFailover()) { 1057 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 1058 info.setFailover(false); 1059 } 1060 1061 NetworkStateTracker newNet = null; 1062 if (mNetAttributes[info.getType()].isDefault()) { 1063 newNet = tryFailover(info.getType()); 1064 if (newNet != null) { 1065 NetworkInfo switchTo = newNet.getNetworkInfo(); 1066 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo); 1067 } else { 1068 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 1069 } 1070 } 1071 1072 // do this before we broadcast the change 1073 handleConnectivityChange(); 1074 1075 sendStickyBroadcast(intent); 1076 /* 1077 * If the failover network is already connected, then immediately send 1078 * out a followup broadcast indicating successful failover 1079 */ 1080 if (newNet != null && newNet.getNetworkInfo().isConnected()) { 1081 sendConnectedBroadcast(newNet.getNetworkInfo()); 1082 } 1083 } 1084 1085 private void sendStickyBroadcast(Intent intent) { 1086 synchronized(this) { 1087 if (!mSystemReady) { 1088 mInitialBroadcast = new Intent(intent); 1089 } 1090 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1091 mContext.sendStickyBroadcast(intent); 1092 } 1093 } 1094 1095 void systemReady() { 1096 synchronized(this) { 1097 mSystemReady = true; 1098 if (mInitialBroadcast != null) { 1099 mContext.sendStickyBroadcast(mInitialBroadcast); 1100 mInitialBroadcast = null; 1101 } 1102 } 1103 } 1104 1105 private void handleConnect(NetworkInfo info) { 1106 int type = info.getType(); 1107 1108 // snapshot isFailover, because sendConnectedBroadcast() resets it 1109 boolean isFailover = info.isFailover(); 1110 NetworkStateTracker thisNet = mNetTrackers[type]; 1111 1112 // if this is a default net and other default is running 1113 // kill the one not preferred 1114 if (mNetAttributes[type].isDefault()) { 1115 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) { 1116 if ((type != mNetworkPreference && 1117 mNetAttributes[mActiveDefaultNetwork].mPriority > 1118 mNetAttributes[type].mPriority) || 1119 mNetworkPreference == mActiveDefaultNetwork) { 1120 // don't accept this one 1121 if (DBG) Slog.v(TAG, "Not broadcasting CONNECT_ACTION " + 1122 "to torn down network " + info.getTypeName()); 1123 teardown(thisNet); 1124 return; 1125 } else { 1126 // tear down the other 1127 NetworkStateTracker otherNet = 1128 mNetTrackers[mActiveDefaultNetwork]; 1129 if (DBG) Slog.v(TAG, "Policy requires " + 1130 otherNet.getNetworkInfo().getTypeName() + 1131 " teardown"); 1132 if (!teardown(otherNet)) { 1133 Slog.e(TAG, "Network declined teardown request"); 1134 return; 1135 } 1136 if (isFailover) { 1137 otherNet.releaseWakeLock(); 1138 } 1139 } 1140 } 1141 mActiveDefaultNetwork = type; 1142 } 1143 thisNet.setTeardownRequested(false); 1144 thisNet.updateNetworkSettings(); 1145 handleConnectivityChange(); 1146 sendConnectedBroadcast(info); 1147 } 1148 1149 private void handleScanResultsAvailable(NetworkInfo info) { 1150 int networkType = info.getType(); 1151 if (networkType != ConnectivityManager.TYPE_WIFI) { 1152 if (DBG) Slog.v(TAG, "Got ScanResultsAvailable for " + 1153 info.getTypeName() + " network. Don't know how to handle."); 1154 } 1155 1156 mNetTrackers[networkType].interpretScanResultsAvailable(); 1157 } 1158 1159 private void handleNotificationChange(boolean visible, int id, 1160 Notification notification) { 1161 NotificationManager notificationManager = (NotificationManager) mContext 1162 .getSystemService(Context.NOTIFICATION_SERVICE); 1163 1164 if (visible) { 1165 notificationManager.notify(id, notification); 1166 } else { 1167 notificationManager.cancel(id); 1168 } 1169 } 1170 1171 /** 1172 * After any kind of change in the connectivity state of any network, 1173 * make sure that anything that depends on the connectivity state of 1174 * more than one network is set up correctly. We're mainly concerned 1175 * with making sure that the list of DNS servers is set up according 1176 * to which networks are connected, and ensuring that the right routing 1177 * table entries exist. 1178 */ 1179 private void handleConnectivityChange() { 1180 /* 1181 * If a non-default network is enabled, add the host routes that 1182 * will allow it's DNS servers to be accessed. Only 1183 * If both mobile and wifi are enabled, add the host routes that 1184 * will allow MMS traffic to pass on the mobile network. But 1185 * remove the default route for the mobile network, so that there 1186 * will be only one default route, to ensure that all traffic 1187 * except MMS will travel via Wi-Fi. 1188 */ 1189 handleDnsConfigurationChange(); 1190 1191 for (int netType : mPriorityList) { 1192 if (mNetTrackers[netType].getNetworkInfo().isConnected()) { 1193 if (mNetAttributes[netType].isDefault()) { 1194 mNetTrackers[netType].addDefaultRoute(); 1195 } else { 1196 mNetTrackers[netType].addPrivateDnsRoutes(); 1197 } 1198 } else { 1199 if (mNetAttributes[netType].isDefault()) { 1200 mNetTrackers[netType].removeDefaultRoute(); 1201 } else { 1202 mNetTrackers[netType].removePrivateDnsRoutes(); 1203 } 1204 } 1205 } 1206 } 1207 1208 /** 1209 * Adjust the per-process dns entries (net.dns<x>.<pid>) based 1210 * on the highest priority active net which this process requested. 1211 * If there aren't any, clear it out 1212 */ 1213 private void reassessPidDns(int myPid, boolean doBump) 1214 { 1215 if (DBG) Slog.d(TAG, "reassessPidDns for pid " + myPid); 1216 for(int i : mPriorityList) { 1217 if (mNetAttributes[i].isDefault()) { 1218 continue; 1219 } 1220 NetworkStateTracker nt = mNetTrackers[i]; 1221 if (nt.getNetworkInfo().isConnected() && 1222 !nt.isTeardownRequested()) { 1223 List pids = mNetRequestersPids[i]; 1224 for (int j=0; j<pids.size(); j++) { 1225 Integer pid = (Integer)pids.get(j); 1226 if (pid.intValue() == myPid) { 1227 String[] dnsList = nt.getNameServers(); 1228 writePidDns(dnsList, myPid); 1229 if (doBump) { 1230 bumpDns(); 1231 } 1232 return; 1233 } 1234 } 1235 } 1236 } 1237 // nothing found - delete 1238 for (int i = 1; ; i++) { 1239 String prop = "net.dns" + i + "." + myPid; 1240 if (SystemProperties.get(prop).length() == 0) { 1241 if (doBump) { 1242 bumpDns(); 1243 } 1244 return; 1245 } 1246 SystemProperties.set(prop, ""); 1247 } 1248 } 1249 1250 private void writePidDns(String[] dnsList, int pid) { 1251 int j = 1; 1252 for (String dns : dnsList) { 1253 if (dns != null && !TextUtils.equals(dns, "0.0.0.0")) { 1254 SystemProperties.set("net.dns" + j++ + "." + pid, dns); 1255 } 1256 } 1257 } 1258 1259 private void bumpDns() { 1260 /* 1261 * Bump the property that tells the name resolver library to reread 1262 * the DNS server list from the properties. 1263 */ 1264 String propVal = SystemProperties.get("net.dnschange"); 1265 int n = 0; 1266 if (propVal.length() != 0) { 1267 try { 1268 n = Integer.parseInt(propVal); 1269 } catch (NumberFormatException e) {} 1270 } 1271 SystemProperties.set("net.dnschange", "" + (n+1)); 1272 } 1273 1274 private void handleDnsConfigurationChange() { 1275 // add default net's dns entries 1276 for (int x = mPriorityList.length-1; x>= 0; x--) { 1277 int netType = mPriorityList[x]; 1278 NetworkStateTracker nt = mNetTrackers[netType]; 1279 if (nt != null && nt.getNetworkInfo().isConnected() && 1280 !nt.isTeardownRequested()) { 1281 String[] dnsList = nt.getNameServers(); 1282 if (mNetAttributes[netType].isDefault()) { 1283 int j = 1; 1284 for (String dns : dnsList) { 1285 if (dns != null && !TextUtils.equals(dns, "0.0.0.0")) { 1286 if (DBG) { 1287 Slog.d(TAG, "adding dns " + dns + " for " + 1288 nt.getNetworkInfo().getTypeName()); 1289 } 1290 SystemProperties.set("net.dns" + j++, dns); 1291 } 1292 } 1293 for (int k=j ; k<mNumDnsEntries; k++) { 1294 if (DBG) Slog.d(TAG, "erasing net.dns" + k); 1295 SystemProperties.set("net.dns" + k, ""); 1296 } 1297 mNumDnsEntries = j; 1298 } else { 1299 // set per-pid dns for attached secondary nets 1300 List pids = mNetRequestersPids[netType]; 1301 for (int y=0; y< pids.size(); y++) { 1302 Integer pid = (Integer)pids.get(y); 1303 writePidDns(dnsList, pid.intValue()); 1304 } 1305 } 1306 } 1307 } 1308 1309 bumpDns(); 1310 } 1311 1312 private int getRestoreDefaultNetworkDelay() { 1313 String restoreDefaultNetworkDelayStr = SystemProperties.get( 1314 NETWORK_RESTORE_DELAY_PROP_NAME); 1315 if(restoreDefaultNetworkDelayStr != null && 1316 restoreDefaultNetworkDelayStr.length() != 0) { 1317 try { 1318 return Integer.valueOf(restoreDefaultNetworkDelayStr); 1319 } catch (NumberFormatException e) { 1320 } 1321 } 1322 return RESTORE_DEFAULT_NETWORK_DELAY; 1323 } 1324 1325 @Override 1326 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1327 if (mContext.checkCallingOrSelfPermission( 1328 android.Manifest.permission.DUMP) 1329 != PackageManager.PERMISSION_GRANTED) { 1330 pw.println("Permission Denial: can't dump ConnectivityService " + 1331 "from from pid=" + Binder.getCallingPid() + ", uid=" + 1332 Binder.getCallingUid()); 1333 return; 1334 } 1335 pw.println(); 1336 for (NetworkStateTracker nst : mNetTrackers) { 1337 if (nst != null) { 1338 if (nst.getNetworkInfo().isConnected()) { 1339 pw.println("Active network: " + nst.getNetworkInfo(). 1340 getTypeName()); 1341 } 1342 pw.println(nst.getNetworkInfo()); 1343 pw.println(nst); 1344 pw.println(); 1345 } 1346 } 1347 1348 pw.println("Network Requester Pids:"); 1349 for (int net : mPriorityList) { 1350 String pidString = net + ": "; 1351 for (Object pid : mNetRequestersPids[net]) { 1352 pidString = pidString + pid.toString() + ", "; 1353 } 1354 pw.println(pidString); 1355 } 1356 pw.println(); 1357 1358 pw.println("FeatureUsers:"); 1359 for (Object requester : mFeatureUsers) { 1360 pw.println(requester.toString()); 1361 } 1362 pw.println(); 1363 1364 mTethering.dump(fd, pw, args); 1365 } 1366 1367 // must be stateless - things change under us. 1368 private class MyHandler extends Handler { 1369 @Override 1370 public void handleMessage(Message msg) { 1371 NetworkInfo info; 1372 switch (msg.what) { 1373 case NetworkStateTracker.EVENT_STATE_CHANGED: 1374 info = (NetworkInfo) msg.obj; 1375 int type = info.getType(); 1376 NetworkInfo.State state = info.getState(); 1377 // only do this optimization for wifi. It going into scan mode for location 1378 // services generates alot of noise. Meanwhile the mms apn won't send out 1379 // subsequent notifications when on default cellular because it never 1380 // disconnects.. so only do this to wifi notifications. Fixed better when the 1381 // APN notifications are standardized. 1382 if (mNetAttributes[type].mLastState == state && 1383 mNetAttributes[type].mRadio == ConnectivityManager.TYPE_WIFI) { 1384 if (DBG) { 1385 // TODO - remove this after we validate the dropping doesn't break 1386 // anything 1387 Slog.d(TAG, "Dropping ConnectivityChange for " + 1388 info.getTypeName() + ": " + 1389 state + "/" + info.getDetailedState()); 1390 } 1391 return; 1392 } 1393 mNetAttributes[type].mLastState = state; 1394 1395 if (DBG) Slog.d(TAG, "ConnectivityChange for " + 1396 info.getTypeName() + ": " + 1397 state + "/" + info.getDetailedState()); 1398 1399 // Connectivity state changed: 1400 // [31-13] Reserved for future use 1401 // [12-9] Network subtype (for mobile network, as defined 1402 // by TelephonyManager) 1403 // [8-3] Detailed state ordinal (as defined by 1404 // NetworkInfo.DetailedState) 1405 // [2-0] Network type (as defined by ConnectivityManager) 1406 int eventLogParam = (info.getType() & 0x7) | 1407 ((info.getDetailedState().ordinal() & 0x3f) << 3) | 1408 (info.getSubtype() << 9); 1409 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED, 1410 eventLogParam); 1411 1412 if (info.getDetailedState() == 1413 NetworkInfo.DetailedState.FAILED) { 1414 handleConnectionFailure(info); 1415 } else if (state == NetworkInfo.State.DISCONNECTED) { 1416 handleDisconnect(info); 1417 } else if (state == NetworkInfo.State.SUSPENDED) { 1418 // TODO: need to think this over. 1419 // the logic here is, handle SUSPENDED the same as 1420 // DISCONNECTED. The only difference being we are 1421 // broadcasting an intent with NetworkInfo that's 1422 // suspended. This allows the applications an 1423 // opportunity to handle DISCONNECTED and SUSPENDED 1424 // differently, or not. 1425 handleDisconnect(info); 1426 } else if (state == NetworkInfo.State.CONNECTED) { 1427 handleConnect(info); 1428 } 1429 break; 1430 1431 case NetworkStateTracker.EVENT_SCAN_RESULTS_AVAILABLE: 1432 info = (NetworkInfo) msg.obj; 1433 handleScanResultsAvailable(info); 1434 break; 1435 1436 case NetworkStateTracker.EVENT_NOTIFICATION_CHANGED: 1437 handleNotificationChange(msg.arg1 == 1, msg.arg2, 1438 (Notification) msg.obj); 1439 1440 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: 1441 handleDnsConfigurationChange(); 1442 break; 1443 1444 case NetworkStateTracker.EVENT_ROAMING_CHANGED: 1445 // fill me in 1446 break; 1447 1448 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: 1449 // fill me in 1450 break; 1451 case NetworkStateTracker.EVENT_RESTORE_DEFAULT_NETWORK: 1452 FeatureUser u = (FeatureUser)msg.obj; 1453 u.expire(); 1454 break; 1455 } 1456 } 1457 } 1458 1459 // javadoc from interface 1460 public boolean tether(String iface) { 1461 enforceTetherChangePermission(); 1462 return isTetheringSupported() && mTethering.tether(iface); 1463 } 1464 1465 // javadoc from interface 1466 public boolean untether(String iface) { 1467 enforceTetherChangePermission(); 1468 return isTetheringSupported() && mTethering.untether(iface); 1469 } 1470 1471 // TODO - proper iface API for selection by property, inspection, etc 1472 public String[] getTetherableUsbRegexs() { 1473 enforceTetherAccessPermission(); 1474 if (isTetheringSupported()) { 1475 return mTethering.getTetherableUsbRegexs(); 1476 } else { 1477 return new String[0]; 1478 } 1479 } 1480 1481 public String[] getTetherableWifiRegexs() { 1482 enforceTetherAccessPermission(); 1483 if (isTetheringSupported()) { 1484 return mTethering.getTetherableWifiRegexs(); 1485 } else { 1486 return new String[0]; 1487 } 1488 } 1489 1490 // TODO - move iface listing, queries, etc to new module 1491 // javadoc from interface 1492 public String[] getTetherableIfaces() { 1493 enforceTetherAccessPermission(); 1494 return mTethering.getTetherableIfaces(); 1495 } 1496 1497 public String[] getTetheredIfaces() { 1498 enforceTetherAccessPermission(); 1499 return mTethering.getTetheredIfaces(); 1500 } 1501 1502 // if ro.tether.denied = true we default to no tethering 1503 // gservices could set the secure setting to 1 though to enable it on a build where it 1504 // had previously been turned off. 1505 public boolean isTetheringSupported() { 1506 enforceTetherAccessPermission(); 1507 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1); 1508 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(), 1509 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0); 1510 return tetherEnabledInSettings && mTetheringConfigValid; 1511 } 1512} 1513