2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server;
19 import android.bluetooth.BluetoothTetheringDataTracker;
20 import android.content.ContentResolver;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.content.pm.PackageManager;
24 import android.database.ContentObserver;
25 import android.net.ConnectivityManager;
26 import android.net.DummyDataStateTracker;
27 import android.net.EthernetDataTracker;
28 import android.net.IConnectivityManager;
29 import android.net.LinkAddress;
30 import android.net.LinkProperties;
31 import android.net.MobileDataStateTracker;
32 import android.net.NetworkConfig;
33 import android.net.NetworkInfo;
34 import android.net.NetworkStateTracker;
35 import android.net.NetworkUtils;
36 import android.net.Proxy;
37 import android.net.ProxyProperties;
38 import android.net.RouteInfo;
39 import android.net.vpn.VpnManager;
40 import android.net.wifi.WifiStateTracker;
41 import android.os.Binder;
42 import android.os.Handler;
43 import android.os.HandlerThread;
44 import android.os.IBinder;
45 import android.os.INetworkManagementService;
46 import android.os.Looper;
47 import android.os.Message;
48 import android.os.PowerManager;
49 import android.os.RemoteException;
50 import android.os.ServiceManager;
51 import android.os.SystemProperties;
52 import android.provider.Settings;
53 import android.text.TextUtils;
54 import android.util.EventLog;
55 import android.util.Slog;
57 import com.android.internal.telephony.Phone;
58 import com.android.server.connectivity.Tethering;
60 import java.io.FileDescriptor;
61 import java.io.FileWriter;
62 import java.io.IOException;
63 import java.io.PrintWriter;
64 import java.net.InetAddress;
65 import java.net.Inet4Address;
66 import java.net.UnknownHostException;
67 import java.util.ArrayList;
68 import java.util.Collection;
69 import java.util.concurrent.atomic.AtomicBoolean;
70 import java.util.GregorianCalendar;
71 import java.util.List;
76 public class ConnectivityService extends IConnectivityManager.Stub {
78 private static final boolean DBG = true;
79 private static final String TAG = "ConnectivityService";
81 // how long to wait before switching back to a radio's default network
82 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
83 // system property that can override the above value
84 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
85 "android.telephony.apn-restore";
87 // used in recursive route setting to add gateways for the host for which
88 // a host route was requested.
89 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
91 private Tethering mTethering;
92 private boolean mTetheringConfigValid = false;
95 * Sometimes we want to refer to the individual network state
96 * trackers separately, and sometimes we just want to treat them
99 private NetworkStateTracker mNetTrackers[];
102 * A per Net list of the PID's that requested access to the net
103 * used both as a refcount and for per-PID DNS selection
105 private List mNetRequestersPids[];
107 private WifiWatchdogService mWifiWatchdogService;
109 // priority order of the nettrackers
110 // (excluding dynamically set mNetworkPreference)
111 // TODO - move mNetworkTypePreference into this
112 private int[] mPriorityList;
114 private Context mContext;
115 private int mNetworkPreference;
116 private int mActiveDefaultNetwork = -1;
117 // 0 is full bad, 100 is full good
118 private int mDefaultInetCondition = 0;
119 private int mDefaultInetConditionPublished = 0;
120 private boolean mInetConditionChangeInFlight = false;
121 private int mDefaultConnectionSequence = 0;
123 private int mNumDnsEntries;
125 private boolean mTestMode;
126 private static ConnectivityService sServiceInstance;
128 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
130 private INetworkManagementService mNetd;
132 private static final int ENABLED = 1;
133 private static final int DISABLED = 0;
135 // Share the event space with NetworkStateTracker (which can't see this
136 // internal class but sends us events). If you change these, change
137 // NetworkStateTracker.java too.
138 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
139 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
142 * used internally as a delayed event to make us switch back to the
145 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
146 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
149 * used internally to change our mobile data enabled flag
151 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
152 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
155 * used internally to change our network preference setting
156 * arg1 = networkType to prefer
158 private static final int EVENT_SET_NETWORK_PREFERENCE =
159 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
162 * used internally to synchronize inet condition reports
164 * arg2 = condition (0 bad, 100 good)
166 private static final int EVENT_INET_CONDITION_CHANGE =
167 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
170 * used internally to mark the end of inet condition hold periods
173 private static final int EVENT_INET_CONDITION_HOLD_END =
174 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
177 * used internally to set the background data preference
178 * arg1 = TRUE for enabled, FALSE for disabled
180 private static final int EVENT_SET_BACKGROUND_DATA =
181 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
184 * used internally to set enable/disable cellular data
185 * arg1 = ENBALED or DISABLED
187 private static final int EVENT_SET_MOBILE_DATA =
188 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
191 * used internally to clear a wakelock when transitioning
192 * from one net to another
194 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
195 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
198 * used internally to reload global proxy settings
200 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
201 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
204 * used internally to set external dependency met/unmet
205 * arg1 = ENABLED (met) or DISABLED (unmet)
208 private static final int EVENT_SET_DEPENDENCY_MET =
209 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
211 private Handler mHandler;
213 // list of DeathRecipients used to make sure features are turned off when
215 private List mFeatureUsers;
217 private boolean mSystemReady;
218 private Intent mInitialBroadcast;
220 private PowerManager.WakeLock mNetTransitionWakeLock;
221 private String mNetTransitionWakeLockCausedBy = "";
222 private int mNetTransitionWakeLockSerialNumber;
223 private int mNetTransitionWakeLockTimeout;
225 private InetAddress mDefaultDns;
227 // used in DBG mode to track inet condition reports
228 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
229 private ArrayList mInetLog;
231 // track the current default http proxy - tell the world if we get a new one (real change)
232 private ProxyProperties mDefaultProxy = null;
233 // track the global proxy.
234 private ProxyProperties mGlobalProxy = null;
235 private final Object mGlobalProxyLock = new Object();
237 private SettingsObserver mSettingsObserver;
239 NetworkConfig[] mNetConfigs;
240 int mNetworksDefined;
242 private static class RadioAttributes {
243 public int mSimultaneity;
245 public RadioAttributes(String init) {
246 String fragments[] = init.split(",");
247 mType = Integer.parseInt(fragments[0]);
248 mSimultaneity = Integer.parseInt(fragments[1]);
251 RadioAttributes[] mRadioAttributes;
253 // the set of network types that can only be enabled by system/sig apps
254 List mProtectedNetworks;
256 public static synchronized ConnectivityService getInstance(Context context) {
257 if (sServiceInstance == null) {
258 sServiceInstance = new ConnectivityService(context);
260 return sServiceInstance;
263 private ConnectivityService(Context context) {
264 if (DBG) log("ConnectivityService starting up");
266 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
267 handlerThread.start();
268 mHandler = new MyHandler(handlerThread.getLooper());
270 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
271 Settings.Secure.BACKGROUND_DATA, 1) == 1);
273 // setup our unique device name
274 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
275 String id = Settings.Secure.getString(context.getContentResolver(),
276 Settings.Secure.ANDROID_ID);
277 if (id != null && id.length() > 0) {
278 String name = new String("android_").concat(id);
279 SystemProperties.set("net.hostname", name);
283 // read our default dns server ip
284 String dns = Settings.Secure.getString(context.getContentResolver(),
285 Settings.Secure.DEFAULT_DNS_SERVER);
286 if (dns == null || dns.length() == 0) {
287 dns = context.getResources().getString(
288 com.android.internal.R.string.config_default_dns_server);
291 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
292 } catch (IllegalArgumentException e) {
293 loge("Error setting defaultDns using " + dns);
298 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
299 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
300 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
301 com.android.internal.R.integer.config_networkTransitionTimeout);
303 mNetTrackers = new NetworkStateTracker[
304 ConnectivityManager.MAX_NETWORK_TYPE+1];
306 mNetworkPreference = getPersistedNetworkPreference();
308 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
309 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
311 // Load device network attributes from resources
312 String[] raStrings = context.getResources().getStringArray(
313 com.android.internal.R.array.radioAttributes);
314 for (String raString : raStrings) {
315 RadioAttributes r = new RadioAttributes(raString);
316 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
317 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
320 if (mRadioAttributes[r.mType] != null) {
321 loge("Error in radioAttributes - ignoring attempt to redefine type " +
325 mRadioAttributes[r.mType] = r;
328 String[] naStrings = context.getResources().getStringArray(
329 com.android.internal.R.array.networkAttributes);
330 for (String naString : naStrings) {
332 NetworkConfig n = new NetworkConfig(naString);
333 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
334 loge("Error in networkAttributes - ignoring attempt to define type " +
338 if (mNetConfigs[n.type] != null) {
339 loge("Error in networkAttributes - ignoring attempt to redefine type " +
343 if (mRadioAttributes[n.radio] == null) {
344 loge("Error in networkAttributes - ignoring attempt to use undefined " +
345 "radio " + n.radio + " in network type " + n.type);
348 mNetConfigs[n.type] = n;
350 } catch(Exception e) {
351 // ignore it - leave the entry null
355 mProtectedNetworks = new ArrayList<Integer>();
356 int[] protectedNetworks = context.getResources().getIntArray(
357 com.android.internal.R.array.config_protectedNetworks);
358 for (int p : protectedNetworks) {
359 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
360 mProtectedNetworks.add(p);
362 if (DBG) loge("Ignoring protectedNetwork " + p);
366 // high priority first
367 mPriorityList = new int[mNetworksDefined];
369 int insertionPoint = mNetworksDefined-1;
370 int currentLowest = 0;
372 while (insertionPoint > -1) {
373 for (NetworkConfig na : mNetConfigs) {
374 if (na == null) continue;
375 if (na.priority < currentLowest) continue;
376 if (na.priority > currentLowest) {
377 if (na.priority < nextLowest || nextLowest == 0) {
378 nextLowest = na.priority;
382 mPriorityList[insertionPoint--] = na.type;
384 currentLowest = nextLowest;
389 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
390 for (int i : mPriorityList) {
391 mNetRequestersPids[i] = new ArrayList();
394 mFeatureUsers = new ArrayList();
398 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
399 && SystemProperties.get("ro.build.type").equals("eng");
401 * Create the network state trackers for Wi-Fi and mobile
402 * data. Maybe this could be done with a factory class,
403 * but it's not clear that it's worth it, given that
404 * the number of different network types is not going
405 * to change very often.
407 for (int netType : mPriorityList) {
408 switch (mNetConfigs[netType].radio) {
409 case ConnectivityManager.TYPE_WIFI:
410 if (DBG) log("Starting Wifi Service.");
411 WifiStateTracker wst = new WifiStateTracker();
412 WifiService wifiService = new WifiService(context);
413 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
414 wifiService.checkAndStartWifi();
415 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
416 wst.startMonitoring(context, mHandler);
418 //TODO: as part of WWS refactor, create only when needed
419 mWifiWatchdogService = new WifiWatchdogService(context);
422 case ConnectivityManager.TYPE_MOBILE:
423 mNetTrackers[netType] = new MobileDataStateTracker(netType,
424 mNetConfigs[netType].name);
425 mNetTrackers[netType].startMonitoring(context, mHandler);
427 case ConnectivityManager.TYPE_DUMMY:
428 mNetTrackers[netType] = new DummyDataStateTracker(netType,
429 mNetConfigs[netType].name);
430 mNetTrackers[netType].startMonitoring(context, mHandler);
432 case ConnectivityManager.TYPE_BLUETOOTH:
433 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
434 mNetTrackers[netType].startMonitoring(context, mHandler);
436 case ConnectivityManager.TYPE_ETHERNET:
437 mNetTrackers[netType] = EthernetDataTracker.getInstance();
438 mNetTrackers[netType].startMonitoring(context, mHandler);
441 loge("Trying to create a DataStateTracker for an unknown radio type " +
442 mNetConfigs[netType].radio);
447 mTethering = new Tethering(mContext, mHandler.getLooper());
448 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
449 mTethering.getTetherableWifiRegexs().length != 0 ||
450 mTethering.getTetherableBluetoothRegexs().length != 0) &&
451 mTethering.getUpstreamIfaceTypes().length != 0);
454 mInetLog = new ArrayList();
457 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
458 mSettingsObserver.observe(mContext);
462 VpnManager.startVpnService(context);
467 * Sets the preferred network.
468 * @param preference the new preference
470 public void setNetworkPreference(int preference) {
471 enforceChangePermission();
473 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
476 public int getNetworkPreference() {
477 enforceAccessPermission();
480 preference = mNetworkPreference;
485 private void handleSetNetworkPreference(int preference) {
486 if (ConnectivityManager.isNetworkTypeValid(preference) &&
487 mNetConfigs[preference] != null &&
488 mNetConfigs[preference].isDefault()) {
489 if (mNetworkPreference != preference) {
490 final ContentResolver cr = mContext.getContentResolver();
491 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
493 mNetworkPreference = preference;
500 private int getPersistedNetworkPreference() {
501 final ContentResolver cr = mContext.getContentResolver();
503 final int networkPrefSetting = Settings.Secure
504 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
505 if (networkPrefSetting != -1) {
506 return networkPrefSetting;
509 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
513 * Make the state of network connectivity conform to the preference settings
514 * In this method, we only tear down a non-preferred network. Establishing
515 * a connection to the preferred network is taken care of when we handle
516 * the disconnect event from the non-preferred network
517 * (see {@link #handleDisconnect(NetworkInfo)}).
519 private void enforcePreference() {
520 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
523 if (!mNetTrackers[mNetworkPreference].isAvailable())
526 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
527 if (t != mNetworkPreference && mNetTrackers[t] != null &&
528 mNetTrackers[t].getNetworkInfo().isConnected()) {
530 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
531 " in enforcePreference");
533 teardown(mNetTrackers[t]);
538 private boolean teardown(NetworkStateTracker netTracker) {
539 if (netTracker.teardown()) {
540 netTracker.setTeardownRequested(true);
548 * Return NetworkInfo for the active (i.e., connected) network interface.
549 * It is assumed that at most one network is active at a time. If more
550 * than one is active, it is indeterminate which will be returned.
551 * @return the info for the active network, or {@code null} if none is
554 public NetworkInfo getActiveNetworkInfo() {
555 return getNetworkInfo(mActiveDefaultNetwork);
558 public NetworkInfo getNetworkInfo(int networkType) {
559 enforceAccessPermission();
560 if (ConnectivityManager.isNetworkTypeValid(networkType)) {
561 NetworkStateTracker t = mNetTrackers[networkType];
563 return t.getNetworkInfo();
568 public NetworkInfo[] getAllNetworkInfo() {
569 enforceAccessPermission();
570 NetworkInfo[] result = new NetworkInfo[mNetworksDefined];
572 for (NetworkStateTracker t : mNetTrackers) {
573 if(t != null) result[i++] = t.getNetworkInfo();
579 * Return LinkProperties for the active (i.e., connected) default
580 * network interface. It is assumed that at most one default network
581 * is active at a time. If more than one is active, it is indeterminate
582 * which will be returned.
583 * @return the ip properties for the active network, or {@code null} if
586 public LinkProperties getActiveLinkProperties() {
587 return getLinkProperties(mActiveDefaultNetwork);
590 public LinkProperties getLinkProperties(int networkType) {
591 enforceAccessPermission();
592 if (ConnectivityManager.isNetworkTypeValid(networkType)) {
593 NetworkStateTracker t = mNetTrackers[networkType];
594 if (t != null) return t.getLinkProperties();
599 public boolean setRadios(boolean turnOn) {
600 boolean result = true;
601 enforceChangePermission();
602 for (NetworkStateTracker t : mNetTrackers) {
603 if (t != null) result = t.setRadio(turnOn) && result;
608 public boolean setRadio(int netType, boolean turnOn) {
609 enforceChangePermission();
610 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
613 NetworkStateTracker tracker = mNetTrackers[netType];
614 return tracker != null && tracker.setRadio(turnOn);
618 * Used to notice when the calling process dies so we can self-expire
620 * Also used to know if the process has cleaned up after itself when
621 * our auto-expire timer goes off. The timer has a link to an object.
624 private class FeatureUser implements IBinder.DeathRecipient {
632 FeatureUser(int type, String feature, IBinder binder) {
637 mPid = getCallingPid();
638 mUid = getCallingUid();
639 mCreateTime = System.currentTimeMillis();
642 mBinder.linkToDeath(this, 0);
643 } catch (RemoteException e) {
648 void unlinkDeathRecipient() {
649 mBinder.unlinkToDeath(this, 0);
652 public void binderDied() {
653 log("ConnectivityService FeatureUser binderDied(" +
654 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
655 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
656 stopUsingNetworkFeature(this, false);
659 public void expire() {
660 log("ConnectivityService FeatureUser expire(" +
661 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
662 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
663 stopUsingNetworkFeature(this, false);
666 public String toString() {
667 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
668 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
672 // javadoc from interface
673 public int startUsingNetworkFeature(int networkType, String feature,
676 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
678 enforceChangePermission();
679 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
680 mNetConfigs[networkType] == null) {
681 return Phone.APN_REQUEST_FAILED;
684 FeatureUser f = new FeatureUser(networkType, feature, binder);
686 // TODO - move this into the MobileDataStateTracker
687 int usedNetworkType = networkType;
688 if(networkType == ConnectivityManager.TYPE_MOBILE) {
689 usedNetworkType = convertFeatureToNetworkType(feature);
690 if (usedNetworkType < 0) {
691 Slog.e(TAG, "Can't match any netTracker!");
692 usedNetworkType = networkType;
696 if (mProtectedNetworks.contains(usedNetworkType)) {
697 enforceConnectivityInternalPermission();
700 NetworkStateTracker network = mNetTrackers[usedNetworkType];
701 if (network != null) {
702 Integer currentPid = new Integer(getCallingPid());
703 if (usedNetworkType != networkType) {
704 NetworkStateTracker radio = mNetTrackers[networkType];
705 NetworkInfo ni = network.getNetworkInfo();
707 if (ni.isAvailable() == false) {
708 if (DBG) log("special network not available");
709 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
710 return Phone.APN_TYPE_NOT_AVAILABLE;
712 // else make the attempt anyway - probably giving REQUEST_STARTED below
717 mFeatureUsers.add(f);
718 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
719 // this gets used for per-pid dns when connected
720 mNetRequestersPids[usedNetworkType].add(currentPid);
724 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
726 if (restoreTimer >= 0) {
727 mHandler.sendMessageDelayed(
728 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
731 if ((ni.isConnectedOrConnecting() == true) &&
732 !network.isTeardownRequested()) {
733 if (ni.isConnected() == true) {
734 // add the pid-specific dns
735 handleDnsConfigurationChange(networkType);
736 if (DBG) log("special network already active");
737 return Phone.APN_ALREADY_ACTIVE;
739 if (DBG) log("special network already connecting");
740 return Phone.APN_REQUEST_STARTED;
743 // check if the radio in play can make another contact
744 // assume if cannot for now
746 if (DBG) log("reconnecting to special network");
748 return Phone.APN_REQUEST_STARTED;
750 // need to remember this unsupported request so we respond appropriately on stop
752 mFeatureUsers.add(f);
753 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
754 // this gets used for per-pid dns when connected
755 mNetRequestersPids[usedNetworkType].add(currentPid);
761 return Phone.APN_TYPE_NOT_AVAILABLE;
764 // javadoc from interface
765 public int stopUsingNetworkFeature(int networkType, String feature) {
766 enforceChangePermission();
768 int pid = getCallingPid();
769 int uid = getCallingUid();
771 FeatureUser u = null;
772 boolean found = false;
775 for (int i = 0; i < mFeatureUsers.size() ; i++) {
776 u = (FeatureUser)mFeatureUsers.get(i);
777 if (uid == u.mUid && pid == u.mPid &&
778 networkType == u.mNetworkType &&
779 TextUtils.equals(feature, u.mFeature)) {
785 if (found && u != null) {
786 // stop regardless of how many other time this proc had called start
787 return stopUsingNetworkFeature(u, true);
790 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
795 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
796 int networkType = u.mNetworkType;
797 String feature = u.mFeature;
801 NetworkStateTracker tracker = null;
802 boolean callTeardown = false; // used to carry our decision outside of sync block
805 log("stopUsingNetworkFeature for net " + networkType +
809 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
813 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
816 // check if this process still has an outstanding start request
817 if (!mFeatureUsers.contains(u)) {
818 if (DBG) log("ignoring - this process has no outstanding requests");
821 u.unlinkDeathRecipient();
822 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
823 // If we care about duplicate requests, check for that here.
825 // This is done to support the extension of a request - the app
826 // can request we start the network feature again and renew the
827 // auto-shutoff delay. Normal "stop" calls from the app though
828 // do not pay attention to duplicate requests - in effect the
829 // API does not refcount and a single stop will counter multiple starts.
830 if (ignoreDups == false) {
831 for (int i = 0; i < mFeatureUsers.size() ; i++) {
832 FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
833 if (x.mUid == u.mUid && x.mPid == u.mPid &&
834 x.mNetworkType == u.mNetworkType &&
835 TextUtils.equals(x.mFeature, u.mFeature)) {
836 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
842 // TODO - move to MobileDataStateTracker
843 int usedNetworkType = networkType;
844 if (networkType == ConnectivityManager.TYPE_MOBILE) {
845 usedNetworkType = convertFeatureToNetworkType(feature);
846 if (usedNetworkType < 0) {
847 usedNetworkType = networkType;
850 tracker = mNetTrackers[usedNetworkType];
851 if (tracker == null) {
852 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
855 if (usedNetworkType != networkType) {
856 Integer currentPid = new Integer(pid);
857 mNetRequestersPids[usedNetworkType].remove(currentPid);
858 reassessPidDns(pid, true);
859 if (mNetRequestersPids[usedNetworkType].size() != 0) {
860 if (DBG) log("not tearing down special network - " +
861 "others still using it");
866 if (DBG) log("not a known feature - dropping");
869 if (DBG) log("Doing network teardown");
879 * @deprecated use requestRouteToHostAddress instead
881 * Ensure that a network route exists to deliver traffic to the specified
882 * host via the specified network interface.
883 * @param networkType the type of the network over which traffic to the
884 * specified host is to be routed
885 * @param hostAddress the IP address of the host to which the route is
887 * @return {@code true} on success, {@code false} on failure
889 public boolean requestRouteToHost(int networkType, int hostAddress) {
890 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
892 if (inetAddress == null) {
896 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
900 * Ensure that a network route exists to deliver traffic to the specified
901 * host via the specified network interface.
902 * @param networkType the type of the network over which traffic to the
903 * specified host is to be routed
904 * @param hostAddress the IP address of the host to which the route is
906 * @return {@code true} on success, {@code false} on failure
908 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
909 enforceChangePermission();
910 if (mProtectedNetworks.contains(networkType)) {
911 enforceConnectivityInternalPermission();
914 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
917 NetworkStateTracker tracker = mNetTrackers[networkType];
919 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
920 tracker.isTeardownRequested()) {
922 log("requestRouteToHostAddress on down network " +
923 "(" + networkType + ") - dropped");
928 InetAddress addr = InetAddress.getByAddress(hostAddress);
929 return addHostRoute(tracker, addr, 0);
930 } catch (UnknownHostException e) {}
935 * Ensure that a network route exists to deliver traffic to the specified
936 * host via the mobile data network.
937 * @param hostAddress the IP address of the host to which the route is desired,
938 * in network byte order.
940 * @return {@code true} on success, {@code false} on failure
942 private boolean addHostRoute(NetworkStateTracker nt, InetAddress hostAddress, int cycleCount) {
943 LinkProperties lp = nt.getLinkProperties();
944 if ((lp == null) || (hostAddress == null)) return false;
946 String interfaceName = lp.getInterfaceName();
948 log("Requested host route to " + hostAddress + "(" + interfaceName + "), cycleCount=" +
951 if (interfaceName == null) {
952 if (DBG) loge("addHostRoute failed due to null interface name");
956 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), hostAddress);
957 InetAddress gatewayAddress = null;
958 if (bestRoute != null) {
959 gatewayAddress = bestRoute.getGateway();
960 // if the best route is ourself, don't relf-reference, just add the host route
961 if (hostAddress.equals(gatewayAddress)) gatewayAddress = null;
963 if (gatewayAddress != null) {
964 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
965 loge("Error adding hostroute - too much recursion");
968 if (!addHostRoute(nt, gatewayAddress, cycleCount+1)) return false;
971 RouteInfo route = RouteInfo.makeHostRoute(hostAddress, gatewayAddress);
974 mNetd.addRoute(interfaceName, route);
976 } catch (Exception ex) {
981 // TODO support the removal of single host routes. Keep a ref count of them so we
982 // aren't over-zealous
983 private boolean removeHostRoute(NetworkStateTracker nt, InetAddress hostAddress) {
988 * @see ConnectivityManager#getBackgroundDataSetting()
990 public boolean getBackgroundDataSetting() {
991 return mBackgroundDataEnabled.get();
995 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
997 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
998 mContext.enforceCallingOrSelfPermission(
999 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1000 "ConnectivityService");
1002 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1004 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1005 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1008 private void handleSetBackgroundData(boolean enabled) {
1009 Settings.Secure.putInt(mContext.getContentResolver(),
1010 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1011 Intent broadcast = new Intent(
1012 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1013 mContext.sendBroadcast(broadcast);
1017 * @see ConnectivityManager#getMobileDataEnabled()
1019 public boolean getMobileDataEnabled() {
1020 // TODO: This detail should probably be in DataConnectionTracker's
1021 // which is where we store the value and maybe make this
1023 enforceAccessPermission();
1024 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1025 Settings.Secure.MOBILE_DATA, 1) == 1;
1026 if (DBG) log("getMobileDataEnabled returning " + retVal);
1030 public void setDataDependency(int networkType, boolean met) {
1031 enforceConnectivityInternalPermission();
1034 log("setDataDependency(" + networkType + ", " + met + ")");
1036 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1037 (met ? ENABLED : DISABLED), networkType));
1040 private void handleSetDependencyMet(int networkType, boolean met) {
1041 if (mNetTrackers[networkType] != null) {
1043 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1045 mNetTrackers[networkType].setDependencyMet(met);
1050 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1052 public void setMobileDataEnabled(boolean enabled) {
1053 enforceChangePermission();
1054 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
1056 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
1057 (enabled ? ENABLED : DISABLED), 0));
1060 private void handleSetMobileData(boolean enabled) {
1061 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1063 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
1065 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
1069 private void enforceAccessPermission() {
1070 mContext.enforceCallingOrSelfPermission(
1071 android.Manifest.permission.ACCESS_NETWORK_STATE,
1072 "ConnectivityService");
1075 private void enforceChangePermission() {
1076 mContext.enforceCallingOrSelfPermission(
1077 android.Manifest.permission.CHANGE_NETWORK_STATE,
1078 "ConnectivityService");
1081 // TODO Make this a special check when it goes public
1082 private void enforceTetherChangePermission() {
1083 mContext.enforceCallingOrSelfPermission(
1084 android.Manifest.permission.CHANGE_NETWORK_STATE,
1085 "ConnectivityService");
1088 private void enforceTetherAccessPermission() {
1089 mContext.enforceCallingOrSelfPermission(
1090 android.Manifest.permission.ACCESS_NETWORK_STATE,
1091 "ConnectivityService");
1094 private void enforceConnectivityInternalPermission() {
1095 mContext.enforceCallingOrSelfPermission(
1096 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1097 "ConnectivityService");
1101 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1102 * network, we ignore it. If it is for the active network, we send out a
1103 * broadcast. But first, we check whether it might be possible to connect
1104 * to a different network.
1105 * @param info the {@code NetworkInfo} for the network
1107 private void handleDisconnect(NetworkInfo info) {
1109 int prevNetType = info.getType();
1111 mNetTrackers[prevNetType].setTeardownRequested(false);
1113 * If the disconnected network is not the active one, then don't report
1114 * this as a loss of connectivity. What probably happened is that we're
1115 * getting the disconnect for a network that we explicitly disabled
1116 * in accordance with network preference policies.
1118 if (!mNetConfigs[prevNetType].isDefault()) {
1119 List pids = mNetRequestersPids[prevNetType];
1120 for (int i = 0; i<pids.size(); i++) {
1121 Integer pid = (Integer)pids.get(i);
1122 // will remove them because the net's no longer connected
1123 // need to do this now as only now do we know the pids and
1124 // can properly null things that are no longer referenced.
1125 reassessPidDns(pid.intValue(), false);
1129 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1130 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1131 if (info.isFailover()) {
1132 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1133 info.setFailover(false);
1135 if (info.getReason() != null) {
1136 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1138 if (info.getExtraInfo() != null) {
1139 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1140 info.getExtraInfo());
1143 if (mNetConfigs[prevNetType].isDefault()) {
1144 tryFailover(prevNetType);
1145 if (mActiveDefaultNetwork != -1) {
1146 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1147 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1149 mDefaultInetConditionPublished = 0; // we're not connected anymore
1150 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1153 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1155 // Reset interface if no other connections are using the same interface
1156 boolean doReset = true;
1157 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1158 if (linkProperties != null) {
1159 String oldIface = linkProperties.getInterfaceName();
1160 if (TextUtils.isEmpty(oldIface) == false) {
1161 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1162 if (networkStateTracker == null) continue;
1163 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1164 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1165 LinkProperties l = networkStateTracker.getLinkProperties();
1166 if (l == null) continue;
1167 if (oldIface.equals(l.getInterfaceName())) {
1176 // do this before we broadcast the change
1177 handleConnectivityChange(prevNetType, doReset);
1179 sendStickyBroadcast(intent);
1181 * If the failover network is already connected, then immediately send
1182 * out a followup broadcast indicating successful failover
1184 if (mActiveDefaultNetwork != -1) {
1185 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
1189 private void tryFailover(int prevNetType) {
1191 * If this is a default network, check if other defaults are available.
1192 * Try to reconnect on all available and let them hash it out when
1193 * more than one connects.
1195 if (mNetConfigs[prevNetType].isDefault()) {
1196 if (mActiveDefaultNetwork == prevNetType) {
1197 mActiveDefaultNetwork = -1;
1200 // don't signal a reconnect for anything lower or equal priority than our
1201 // current connected default
1202 // TODO - don't filter by priority now - nice optimization but risky
1203 // int currentPriority = -1;
1204 // if (mActiveDefaultNetwork != -1) {
1205 // currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
1207 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
1208 if (checkType == prevNetType) continue;
1209 if (mNetConfigs[checkType] == null) continue;
1210 if (!mNetConfigs[checkType].isDefault()) continue;
1212 // Enabling the isAvailable() optimization caused mobile to not get
1213 // selected if it was in the middle of error handling. Specifically
1214 // a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1215 // would not be available and we wouldn't get connected to anything.
1216 // So removing the isAvailable() optimization below for now. TODO: This
1217 // optimization should work and we need to investigate why it doesn't work.
1218 // This could be related to how DEACTIVATE_DATA_CALL is reporting its
1219 // complete before it is really complete.
1220 // if (!mNetTrackers[checkType].isAvailable()) continue;
1222 // if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
1224 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1225 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1226 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1227 checkInfo.setFailover(true);
1228 checkTracker.reconnect();
1230 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
1235 private void sendConnectedBroadcast(NetworkInfo info) {
1236 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1239 private void sendInetConditionBroadcast(NetworkInfo info) {
1240 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1243 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1244 Intent intent = new Intent(bcastType);
1245 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1246 if (info.isFailover()) {
1247 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1248 info.setFailover(false);
1250 if (info.getReason() != null) {
1251 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1253 if (info.getExtraInfo() != null) {
1254 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1255 info.getExtraInfo());
1257 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1258 sendStickyBroadcast(intent);
1262 * Called when an attempt to fail over to another network has failed.
1263 * @param info the {@link NetworkInfo} for the failed network
1265 private void handleConnectionFailure(NetworkInfo info) {
1266 mNetTrackers[info.getType()].setTeardownRequested(false);
1268 String reason = info.getReason();
1269 String extraInfo = info.getExtraInfo();
1272 if (reason == null) {
1275 reasonText = " (" + reason + ").";
1277 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
1279 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1280 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1281 if (getActiveNetworkInfo() == null) {
1282 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1284 if (reason != null) {
1285 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1287 if (extraInfo != null) {
1288 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1290 if (info.isFailover()) {
1291 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1292 info.setFailover(false);
1295 if (mNetConfigs[info.getType()].isDefault()) {
1296 tryFailover(info.getType());
1297 if (mActiveDefaultNetwork != -1) {
1298 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1299 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1301 mDefaultInetConditionPublished = 0;
1302 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1306 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1307 sendStickyBroadcast(intent);
1309 * If the failover network is already connected, then immediately send
1310 * out a followup broadcast indicating successful failover
1312 if (mActiveDefaultNetwork != -1) {
1313 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
1317 private void sendStickyBroadcast(Intent intent) {
1318 synchronized(this) {
1319 if (!mSystemReady) {
1320 mInitialBroadcast = new Intent(intent);
1322 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1323 mContext.sendStickyBroadcast(intent);
1327 void systemReady() {
1328 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
1329 mNetd = INetworkManagementService.Stub.asInterface(b);
1331 synchronized(this) {
1332 mSystemReady = true;
1333 if (mInitialBroadcast != null) {
1334 mContext.sendStickyBroadcast(mInitialBroadcast);
1335 mInitialBroadcast = null;
1338 // load the global proxy at startup
1339 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
1342 private void handleConnect(NetworkInfo info) {
1343 int type = info.getType();
1345 // snapshot isFailover, because sendConnectedBroadcast() resets it
1346 boolean isFailover = info.isFailover();
1347 NetworkStateTracker thisNet = mNetTrackers[type];
1349 // if this is a default net and other default is running
1350 // kill the one not preferred
1351 if (mNetConfigs[type].isDefault()) {
1352 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1353 if ((type != mNetworkPreference &&
1354 mNetConfigs[mActiveDefaultNetwork].priority >
1355 mNetConfigs[type].priority) ||
1356 mNetworkPreference == mActiveDefaultNetwork) {
1357 // don't accept this one
1359 log("Not broadcasting CONNECT_ACTION " +
1360 "to torn down network " + info.getTypeName());
1365 // tear down the other
1366 NetworkStateTracker otherNet =
1367 mNetTrackers[mActiveDefaultNetwork];
1369 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
1372 if (!teardown(otherNet)) {
1373 loge("Network declined teardown request");
1378 synchronized (ConnectivityService.this) {
1379 // have a new default network, release the transition wakelock in a second
1380 // if it's held. The second pause is to allow apps to reconnect over the
1382 if (mNetTransitionWakeLock.isHeld()) {
1383 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1384 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
1385 mNetTransitionWakeLockSerialNumber, 0),
1389 mActiveDefaultNetwork = type;
1390 // this will cause us to come up initially as unconnected and switching
1391 // to connected after our normal pause unless somebody reports us as reall
1393 mDefaultInetConditionPublished = 0;
1394 mDefaultConnectionSequence++;
1395 mInetConditionChangeInFlight = false;
1396 // Don't do this - if we never sign in stay, grey
1397 //reportNetworkCondition(mActiveDefaultNetwork, 100);
1399 thisNet.setTeardownRequested(false);
1400 updateNetworkSettings(thisNet);
1401 handleConnectivityChange(type, false);
1402 sendConnectedBroadcast(info);
1406 * After a change in the connectivity state of a network. We're mainly
1407 * concerned with making sure that the list of DNS servers is set up
1408 * according to which networks are connected, and ensuring that the
1409 * right routing table entries exist.
1411 private void handleConnectivityChange(int netType, boolean doReset) {
1413 * If a non-default network is enabled, add the host routes that
1414 * will allow it's DNS servers to be accessed.
1416 handleDnsConfigurationChange(netType);
1418 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
1419 if (mNetConfigs[netType].isDefault()) {
1420 handleApplyDefaultProxy(netType);
1421 addDefaultRoute(mNetTrackers[netType]);
1423 addPrivateDnsRoutes(mNetTrackers[netType]);
1426 if (mNetConfigs[netType].isDefault()) {
1427 removeDefaultRoute(mNetTrackers[netType]);
1429 removePrivateDnsRoutes(mNetTrackers[netType]);
1434 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1435 if (linkProperties != null) {
1436 String iface = linkProperties.getInterfaceName();
1437 if (TextUtils.isEmpty(iface) == false) {
1438 if (DBG) log("resetConnections(" + iface + ")");
1439 NetworkUtils.resetConnections(iface);
1444 // TODO: Temporary notifying upstread change to Tethering.
1446 /** Notify TetheringService if interface name has been changed. */
1447 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1448 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1449 if (isTetheringSupported()) {
1450 mTethering.handleTetherIfaceChange();
1455 private void addPrivateDnsRoutes(NetworkStateTracker nt) {
1456 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1457 LinkProperties p = nt.getLinkProperties();
1458 if (p == null) return;
1459 String interfaceName = p.getInterfaceName();
1462 log("addPrivateDnsRoutes for " + nt +
1463 "(" + interfaceName + ") - mPrivateDnsRouteSet = " + privateDnsRouteSet);
1465 if (interfaceName != null && !privateDnsRouteSet) {
1466 Collection<InetAddress> dnsList = p.getDnses();
1467 for (InetAddress dns : dnsList) {
1468 addHostRoute(nt, dns, 0);
1470 nt.privateDnsRouteSet(true);
1474 private void removePrivateDnsRoutes(NetworkStateTracker nt) {
1475 LinkProperties p = nt.getLinkProperties();
1476 if (p == null) return;
1477 String interfaceName = p.getInterfaceName();
1478 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1479 if (interfaceName != null && privateDnsRouteSet) {
1481 log("removePrivateDnsRoutes for " + nt.getNetworkInfo().getTypeName() +
1482 " (" + interfaceName + ")");
1485 Collection<InetAddress> dnsList = p.getDnses();
1486 for (InetAddress dns : dnsList) {
1487 if (DBG) log(" removing " + dns);
1488 RouteInfo route = RouteInfo.makeHostRoute(dns);
1490 mNetd.removeRoute(interfaceName, route);
1491 } catch (Exception ex) {
1492 loge("error (" + ex + ") removing dns route " + route);
1495 nt.privateDnsRouteSet(false);
1500 private void addDefaultRoute(NetworkStateTracker nt) {
1501 LinkProperties p = nt.getLinkProperties();
1502 if (p == null) return;
1503 String interfaceName = p.getInterfaceName();
1504 if (TextUtils.isEmpty(interfaceName)) return;
1506 for (RouteInfo route : p.getRoutes()) {
1507 //TODO - handle non-default routes
1508 if (route.isDefaultRoute()) {
1509 if (DBG) log("adding default route " + route);
1510 InetAddress gateway = route.getGateway();
1511 if (addHostRoute(nt, gateway, 0)) {
1513 mNetd.addRoute(interfaceName, route);
1514 } catch (Exception e) {
1515 loge("error adding default route " + route);
1519 NetworkInfo networkInfo = nt.getNetworkInfo();
1520 log("addDefaultRoute for " + networkInfo.getTypeName() +
1521 " (" + interfaceName + "), GatewayAddr=" +
1522 gateway.getHostAddress());
1525 loge("error adding host route for default route " + route);
1532 public void removeDefaultRoute(NetworkStateTracker nt) {
1533 LinkProperties p = nt.getLinkProperties();
1534 if (p == null) return;
1535 String interfaceName = p.getInterfaceName();
1537 if (interfaceName == null) return;
1539 for (RouteInfo route : p.getRoutes()) {
1540 //TODO - handle non-default routes
1541 if (route.isDefaultRoute()) {
1543 mNetd.removeRoute(interfaceName, route);
1544 } catch (Exception ex) {
1545 loge("error (" + ex + ") removing default route " + route);
1549 NetworkInfo networkInfo = nt.getNetworkInfo();
1550 log("removeDefaultRoute for " + networkInfo.getTypeName() + " (" +
1551 interfaceName + ")");
1558 * Reads the network specific TCP buffer sizes from SystemProperties
1559 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1562 public void updateNetworkSettings(NetworkStateTracker nt) {
1563 String key = nt.getTcpBufferSizesPropName();
1564 String bufferSizes = SystemProperties.get(key);
1566 if (bufferSizes.length() == 0) {
1567 loge(key + " not found in system properties. Using defaults");
1569 // Setting to default values so we won't be stuck to previous values
1570 key = "net.tcp.buffersize.default";
1571 bufferSizes = SystemProperties.get(key);
1574 // Set values in kernel
1575 if (bufferSizes.length() != 0) {
1577 log("Setting TCP values: [" + bufferSizes
1578 + "] which comes from [" + key + "]");
1580 setBufferSize(bufferSizes);
1585 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1586 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1588 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1589 * writeMin, writeInitial, writeMax"
1591 private void setBufferSize(String bufferSizes) {
1593 String[] values = bufferSizes.split(",");
1595 if (values.length == 6) {
1596 final String prefix = "/sys/kernel/ipv4/tcp_";
1597 stringToFile(prefix + "rmem_min", values[0]);
1598 stringToFile(prefix + "rmem_def", values[1]);
1599 stringToFile(prefix + "rmem_max", values[2]);
1600 stringToFile(prefix + "wmem_min", values[3]);
1601 stringToFile(prefix + "wmem_def", values[4]);
1602 stringToFile(prefix + "wmem_max", values[5]);
1604 loge("Invalid buffersize string: " + bufferSizes);
1606 } catch (IOException e) {
1607 loge("Can't set tcp buffer sizes:" + e);
1612 * Writes string to file. Basically same as "echo -n $string > $filename"
1616 * @throws IOException
1618 private void stringToFile(String filename, String string) throws IOException {
1619 FileWriter out = new FileWriter(filename);
1629 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1630 * on the highest priority active net which this process requested.
1631 * If there aren't any, clear it out
1633 private void reassessPidDns(int myPid, boolean doBump)
1635 if (DBG) log("reassessPidDns for pid " + myPid);
1636 for(int i : mPriorityList) {
1637 if (mNetConfigs[i].isDefault()) {
1640 NetworkStateTracker nt = mNetTrackers[i];
1641 if (nt.getNetworkInfo().isConnected() &&
1642 !nt.isTeardownRequested()) {
1643 LinkProperties p = nt.getLinkProperties();
1644 if (p == null) continue;
1645 List pids = mNetRequestersPids[i];
1646 for (int j=0; j<pids.size(); j++) {
1647 Integer pid = (Integer)pids.get(j);
1648 if (pid.intValue() == myPid) {
1649 Collection<InetAddress> dnses = p.getDnses();
1650 writePidDns(dnses, myPid);
1659 // nothing found - delete
1660 for (int i = 1; ; i++) {
1661 String prop = "net.dns" + i + "." + myPid;
1662 if (SystemProperties.get(prop).length() == 0) {
1668 SystemProperties.set(prop, "");
1672 // return true if results in a change
1673 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
1675 boolean changed = false;
1676 for (InetAddress dns : dnses) {
1677 String dnsString = dns.getHostAddress();
1678 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1680 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1686 private void bumpDns() {
1688 * Bump the property that tells the name resolver library to reread
1689 * the DNS server list from the properties.
1691 String propVal = SystemProperties.get("net.dnschange");
1693 if (propVal.length() != 0) {
1695 n = Integer.parseInt(propVal);
1696 } catch (NumberFormatException e) {}
1698 SystemProperties.set("net.dnschange", "" + (n+1));
1700 * Tell the VMs to toss their DNS caches
1702 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1703 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1705 * Connectivity events can happen before boot has completed ...
1707 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1708 mContext.sendBroadcast(intent);
1711 private void handleDnsConfigurationChange(int netType) {
1712 // add default net's dns entries
1713 NetworkStateTracker nt = mNetTrackers[netType];
1714 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
1715 LinkProperties p = nt.getLinkProperties();
1716 if (p == null) return;
1717 Collection<InetAddress> dnses = p.getDnses();
1718 boolean changed = false;
1719 if (mNetConfigs[netType].isDefault()) {
1721 if (dnses.size() == 0 && mDefaultDns != null) {
1722 String dnsString = mDefaultDns.getHostAddress();
1723 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1725 log("no dns provided - using " + dnsString);
1728 SystemProperties.set("net.dns1", dnsString);
1732 for (InetAddress dns : dnses) {
1733 String dnsString = dns.getHostAddress();
1734 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1739 log("adding dns " + dns + " for " +
1740 nt.getNetworkInfo().getTypeName());
1743 SystemProperties.set("net.dns" + j++, dnsString);
1746 for (int k=j ; k<mNumDnsEntries; k++) {
1747 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1748 if (DBG) log("erasing net.dns" + k);
1750 SystemProperties.set("net.dns" + k, "");
1755 // set per-pid dns for attached secondary nets
1756 List pids = mNetRequestersPids[netType];
1757 for (int y=0; y< pids.size(); y++) {
1758 Integer pid = (Integer)pids.get(y);
1759 changed = writePidDns(dnses, pid.intValue());
1762 if (changed) bumpDns();
1766 private int getRestoreDefaultNetworkDelay(int networkType) {
1767 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1768 NETWORK_RESTORE_DELAY_PROP_NAME);
1769 if(restoreDefaultNetworkDelayStr != null &&
1770 restoreDefaultNetworkDelayStr.length() != 0) {
1772 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1773 } catch (NumberFormatException e) {
1776 // if the system property isn't set, use the value for the apn type
1777 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1779 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1780 (mNetConfigs[networkType] != null)) {
1781 ret = mNetConfigs[networkType].restoreTime;
1787 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1788 if (mContext.checkCallingOrSelfPermission(
1789 android.Manifest.permission.DUMP)
1790 != PackageManager.PERMISSION_GRANTED) {
1791 pw.println("Permission Denial: can't dump ConnectivityService " +
1792 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1793 Binder.getCallingUid());
1797 for (NetworkStateTracker nst : mNetTrackers) {
1799 if (nst.getNetworkInfo().isConnected()) {
1800 pw.println("Active network: " + nst.getNetworkInfo().
1803 pw.println(nst.getNetworkInfo());
1809 pw.println("Network Requester Pids:");
1810 for (int net : mPriorityList) {
1811 String pidString = net + ": ";
1812 for (Object pid : mNetRequestersPids[net]) {
1813 pidString = pidString + pid.toString() + ", ";
1815 pw.println(pidString);
1819 pw.println("FeatureUsers:");
1820 for (Object requester : mFeatureUsers) {
1821 pw.println(requester.toString());
1825 synchronized (this) {
1826 pw.println("NetworkTranstionWakeLock is currently " +
1827 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1828 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1832 mTethering.dump(fd, pw, args);
1834 if (mInetLog != null) {
1836 pw.println("Inet condition reports:");
1837 for(int i = 0; i < mInetLog.size(); i++) {
1838 pw.println(mInetLog.get(i));
1843 // must be stateless - things change under us.
1844 private class MyHandler extends Handler {
1845 public MyHandler(Looper looper) {
1850 public void handleMessage(Message msg) {
1853 case NetworkStateTracker.EVENT_STATE_CHANGED:
1854 info = (NetworkInfo) msg.obj;
1855 int type = info.getType();
1856 NetworkInfo.State state = info.getState();
1858 if (DBG) log("ConnectivityChange for " +
1859 info.getTypeName() + ": " +
1860 state + "/" + info.getDetailedState());
1862 // Connectivity state changed:
1863 // [31-13] Reserved for future use
1864 // [12-9] Network subtype (for mobile network, as defined
1865 // by TelephonyManager)
1866 // [8-3] Detailed state ordinal (as defined by
1867 // NetworkInfo.DetailedState)
1868 // [2-0] Network type (as defined by ConnectivityManager)
1869 int eventLogParam = (info.getType() & 0x7) |
1870 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
1871 (info.getSubtype() << 9);
1872 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
1875 if (info.getDetailedState() ==
1876 NetworkInfo.DetailedState.FAILED) {
1877 handleConnectionFailure(info);
1878 } else if (state == NetworkInfo.State.DISCONNECTED) {
1879 handleDisconnect(info);
1880 } else if (state == NetworkInfo.State.SUSPENDED) {
1881 // TODO: need to think this over.
1882 // the logic here is, handle SUSPENDED the same as
1883 // DISCONNECTED. The only difference being we are
1884 // broadcasting an intent with NetworkInfo that's
1885 // suspended. This allows the applications an
1886 // opportunity to handle DISCONNECTED and SUSPENDED
1887 // differently, or not.
1888 handleDisconnect(info);
1889 } else if (state == NetworkInfo.State.CONNECTED) {
1890 handleConnect(info);
1893 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
1894 info = (NetworkInfo) msg.obj;
1895 // TODO: Temporary allowing network configuration
1896 // change not resetting sockets.
1898 handleConnectivityChange(info.getType(), false);
1900 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
1901 String causedBy = null;
1902 synchronized (ConnectivityService.this) {
1903 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
1904 mNetTransitionWakeLock.isHeld()) {
1905 mNetTransitionWakeLock.release();
1906 causedBy = mNetTransitionWakeLockCausedBy;
1909 if (causedBy != null) {
1910 log("NetTransition Wakelock for " + causedBy + " released by timeout");
1913 case EVENT_RESTORE_DEFAULT_NETWORK:
1914 FeatureUser u = (FeatureUser)msg.obj;
1917 case EVENT_INET_CONDITION_CHANGE:
1919 int netType = msg.arg1;
1920 int condition = msg.arg2;
1921 handleInetConditionChange(netType, condition);
1924 case EVENT_INET_CONDITION_HOLD_END:
1926 int netType = msg.arg1;
1927 int sequence = msg.arg2;
1928 handleInetConditionHoldEnd(netType, sequence);
1931 case EVENT_SET_NETWORK_PREFERENCE:
1933 int preference = msg.arg1;
1934 handleSetNetworkPreference(preference);
1937 case EVENT_SET_BACKGROUND_DATA:
1939 boolean enabled = (msg.arg1 == ENABLED);
1940 handleSetBackgroundData(enabled);
1943 case EVENT_SET_MOBILE_DATA:
1945 boolean enabled = (msg.arg1 == ENABLED);
1946 handleSetMobileData(enabled);
1949 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
1951 handleDeprecatedGlobalHttpProxy();
1954 case EVENT_SET_DEPENDENCY_MET:
1956 boolean met = (msg.arg1 == ENABLED);
1957 handleSetDependencyMet(msg.arg2, met);
1964 // javadoc from interface
1965 public int tether(String iface) {
1966 enforceTetherChangePermission();
1968 if (isTetheringSupported()) {
1969 return mTethering.tether(iface);
1971 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1975 // javadoc from interface
1976 public int untether(String iface) {
1977 enforceTetherChangePermission();
1979 if (isTetheringSupported()) {
1980 return mTethering.untether(iface);
1982 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1986 // javadoc from interface
1987 public int getLastTetherError(String iface) {
1988 enforceTetherAccessPermission();
1990 if (isTetheringSupported()) {
1991 return mTethering.getLastTetherError(iface);
1993 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1997 // TODO - proper iface API for selection by property, inspection, etc
1998 public String[] getTetherableUsbRegexs() {
1999 enforceTetherAccessPermission();
2000 if (isTetheringSupported()) {
2001 return mTethering.getTetherableUsbRegexs();
2003 return new String[0];
2007 public String[] getTetherableWifiRegexs() {
2008 enforceTetherAccessPermission();
2009 if (isTetheringSupported()) {
2010 return mTethering.getTetherableWifiRegexs();
2012 return new String[0];
2016 public String[] getTetherableBluetoothRegexs() {
2017 enforceTetherAccessPermission();
2018 if (isTetheringSupported()) {
2019 return mTethering.getTetherableBluetoothRegexs();
2021 return new String[0];
2025 // TODO - move iface listing, queries, etc to new module
2026 // javadoc from interface
2027 public String[] getTetherableIfaces() {
2028 enforceTetherAccessPermission();
2029 return mTethering.getTetherableIfaces();
2032 public String[] getTetheredIfaces() {
2033 enforceTetherAccessPermission();
2034 return mTethering.getTetheredIfaces();
2037 public String[] getTetheringErroredIfaces() {
2038 enforceTetherAccessPermission();
2039 return mTethering.getErroredIfaces();
2042 // if ro.tether.denied = true we default to no tethering
2043 // gservices could set the secure setting to 1 though to enable it on a build where it
2044 // had previously been turned off.
2045 public boolean isTetheringSupported() {
2046 enforceTetherAccessPermission();
2047 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2048 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2049 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2050 return tetherEnabledInSettings && mTetheringConfigValid;
2053 // An API NetworkStateTrackers can call when they lose their network.
2054 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2055 // whichever happens first. The timer is started by the first caller and not
2056 // restarted by subsequent callers.
2057 public void requestNetworkTransitionWakelock(String forWhom) {
2058 enforceConnectivityInternalPermission();
2059 synchronized (this) {
2060 if (mNetTransitionWakeLock.isHeld()) return;
2061 mNetTransitionWakeLockSerialNumber++;
2062 mNetTransitionWakeLock.acquire();
2063 mNetTransitionWakeLockCausedBy = forWhom;
2065 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2066 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2067 mNetTransitionWakeLockSerialNumber, 0),
2068 mNetTransitionWakeLockTimeout);
2072 // 100 percent is full good, 0 is full bad.
2073 public void reportInetCondition(int networkType, int percentage) {
2074 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
2075 mContext.enforceCallingOrSelfPermission(
2076 android.Manifest.permission.STATUS_BAR,
2077 "ConnectivityService");
2080 int pid = getCallingPid();
2081 int uid = getCallingUid();
2082 String s = pid + "(" + uid + ") reports inet is " +
2083 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2084 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2086 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2090 mHandler.sendMessage(mHandler.obtainMessage(
2091 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2094 private void handleInetConditionChange(int netType, int condition) {
2096 log("Inet connectivity change, net=" +
2097 netType + ", condition=" + condition +
2098 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2100 if (mActiveDefaultNetwork == -1) {
2101 if (DBG) log("no active default network - aborting");
2104 if (mActiveDefaultNetwork != netType) {
2105 if (DBG) log("given net not default - aborting");
2108 mDefaultInetCondition = condition;
2110 if (mInetConditionChangeInFlight == false) {
2111 if (DBG) log("starting a change hold");
2112 // setup a new hold to debounce this
2113 if (mDefaultInetCondition > 50) {
2114 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2115 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2117 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2118 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2120 mInetConditionChangeInFlight = true;
2121 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2122 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2124 // we've set the new condition, when this hold ends that will get
2126 if (DBG) log("currently in hold - not setting new end evt");
2130 private void handleInetConditionHoldEnd(int netType, int sequence) {
2132 log("Inet hold end, net=" + netType +
2133 ", condition =" + mDefaultInetCondition +
2134 ", published condition =" + mDefaultInetConditionPublished);
2136 mInetConditionChangeInFlight = false;
2138 if (mActiveDefaultNetwork == -1) {
2139 if (DBG) log("no active default network - aborting");
2142 if (mDefaultConnectionSequence != sequence) {
2143 if (DBG) log("event hold for obsolete network - aborting");
2146 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2147 if (DBG) log("no change in condition - aborting");
2150 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2151 if (networkInfo.isConnected() == false) {
2152 if (DBG) log("default network not connected - aborting");
2155 mDefaultInetConditionPublished = mDefaultInetCondition;
2156 sendInetConditionBroadcast(networkInfo);
2160 public synchronized ProxyProperties getProxy() {
2161 if (mGlobalProxy != null) return mGlobalProxy;
2162 if (mDefaultProxy != null) return mDefaultProxy;
2166 public void setGlobalProxy(ProxyProperties proxyProperties) {
2167 enforceChangePermission();
2168 synchronized (mGlobalProxyLock) {
2169 if (proxyProperties == mGlobalProxy) return;
2170 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2171 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2175 String exclList = "";
2176 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2177 mGlobalProxy = new ProxyProperties(proxyProperties);
2178 host = mGlobalProxy.getHost();
2179 port = mGlobalProxy.getPort();
2180 exclList = mGlobalProxy.getExclusionList();
2182 mGlobalProxy = null;
2184 ContentResolver res = mContext.getContentResolver();
2185 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2186 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
2187 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2191 if (mGlobalProxy == null) {
2192 proxyProperties = mDefaultProxy;
2194 sendProxyBroadcast(proxyProperties);
2197 private void loadGlobalProxy() {
2198 ContentResolver res = mContext.getContentResolver();
2199 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2200 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2201 String exclList = Settings.Secure.getString(res,
2202 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2203 if (!TextUtils.isEmpty(host)) {
2204 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2205 synchronized (mGlobalProxyLock) {
2206 mGlobalProxy = proxyProperties;
2211 public ProxyProperties getGlobalProxy() {
2212 synchronized (mGlobalProxyLock) {
2213 return mGlobalProxy;
2217 private void handleApplyDefaultProxy(int type) {
2218 // check if new default - push it out to all VM if so
2219 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2220 synchronized (this) {
2221 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2222 if (mDefaultProxy == proxy) return;
2223 if (!TextUtils.isEmpty(proxy.getHost())) {
2224 mDefaultProxy = proxy;
2226 mDefaultProxy = null;
2229 if (DBG) log("changing default proxy to " + proxy);
2230 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2231 if (mGlobalProxy != null) return;
2232 sendProxyBroadcast(proxy);
2235 private void handleDeprecatedGlobalHttpProxy() {
2236 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2237 Settings.Secure.HTTP_PROXY);
2238 if (!TextUtils.isEmpty(proxy)) {
2239 String data[] = proxy.split(":");
2240 String proxyHost = data[0];
2241 int proxyPort = 8080;
2242 if (data.length > 1) {
2244 proxyPort = Integer.parseInt(data[1]);
2245 } catch (NumberFormatException e) {
2249 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2254 private void sendProxyBroadcast(ProxyProperties proxy) {
2255 if (proxy == null) proxy = new ProxyProperties("", 0, "");
2256 log("sending Proxy Broadcast for " + proxy);
2257 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
2258 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2259 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2260 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
2261 mContext.sendStickyBroadcast(intent);
2264 private static class SettingsObserver extends ContentObserver {
2266 private Handler mHandler;
2267 SettingsObserver(Handler handler, int what) {
2273 void observe(Context context) {
2274 ContentResolver resolver = context.getContentResolver();
2275 resolver.registerContentObserver(Settings.Secure.getUriFor(
2276 Settings.Secure.HTTP_PROXY), false, this);
2280 public void onChange(boolean selfChange) {
2281 mHandler.obtainMessage(mWhat).sendToTarget();
2285 private void log(String s) {
2289 private void loge(String s) {
2292 int convertFeatureToNetworkType(String feature){
2293 int networkType = -1;
2294 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2295 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2296 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2297 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2298 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2299 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2300 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2301 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2302 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2303 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2304 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2305 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2306 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2307 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2308 networkType = ConnectivityManager.TYPE_MOBILE_CBS;