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.LinkProperties.CompareAddressesResult;
32 import android.net.MobileDataStateTracker;
33 import android.net.NetworkConfig;
34 import android.net.NetworkInfo;
35 import android.net.NetworkStateTracker;
36 import android.net.NetworkUtils;
37 import android.net.Proxy;
38 import android.net.ProxyProperties;
39 import android.net.RouteInfo;
40 import android.net.vpn.VpnManager;
41 import android.net.wifi.WifiStateTracker;
42 import android.os.Binder;
43 import android.os.Handler;
44 import android.os.HandlerThread;
45 import android.os.IBinder;
46 import android.os.INetworkManagementService;
47 import android.os.Looper;
48 import android.os.Message;
49 import android.os.PowerManager;
50 import android.os.RemoteException;
51 import android.os.ServiceManager;
52 import android.os.SystemProperties;
53 import android.provider.Settings;
54 import android.text.TextUtils;
55 import android.util.EventLog;
56 import android.util.Slog;
58 import com.android.internal.telephony.Phone;
59 import com.android.server.connectivity.Tethering;
61 import java.io.FileDescriptor;
62 import java.io.FileWriter;
63 import java.io.IOException;
64 import java.io.PrintWriter;
65 import java.net.Inet6Address;
66 import java.net.InetAddress;
67 import java.net.Inet4Address;
68 import java.net.UnknownHostException;
69 import java.util.ArrayList;
70 import java.util.Collection;
71 import java.util.concurrent.atomic.AtomicBoolean;
72 import java.util.GregorianCalendar;
73 import java.util.List;
78 public class ConnectivityService extends IConnectivityManager.Stub {
80 private static final boolean DBG = true;
81 private static final boolean VDBG = true;
82 private static final String TAG = "ConnectivityService";
84 // how long to wait before switching back to a radio's default network
85 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
86 // system property that can override the above value
87 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
88 "android.telephony.apn-restore";
90 // used in recursive route setting to add gateways for the host for which
91 // a host route was requested.
92 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
94 private Tethering mTethering;
95 private boolean mTetheringConfigValid = false;
98 * Sometimes we want to refer to the individual network state
99 * trackers separately, and sometimes we just want to treat them
102 private NetworkStateTracker mNetTrackers[];
105 * The link properties that define the current links
107 private LinkProperties mCurrentLinkProperties[];
110 * A per Net list of the PID's that requested access to the net
111 * used both as a refcount and for per-PID DNS selection
113 private List mNetRequestersPids[];
115 private WifiWatchdogService mWifiWatchdogService;
117 // priority order of the nettrackers
118 // (excluding dynamically set mNetworkPreference)
119 // TODO - move mNetworkTypePreference into this
120 private int[] mPriorityList;
122 private Context mContext;
123 private int mNetworkPreference;
124 private int mActiveDefaultNetwork = -1;
125 // 0 is full bad, 100 is full good
126 private int mDefaultInetCondition = 0;
127 private int mDefaultInetConditionPublished = 0;
128 private boolean mInetConditionChangeInFlight = false;
129 private int mDefaultConnectionSequence = 0;
131 private int mNumDnsEntries;
133 private boolean mTestMode;
134 private static ConnectivityService sServiceInstance;
136 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
138 private INetworkManagementService mNetd;
140 private static final int ENABLED = 1;
141 private static final int DISABLED = 0;
143 // Share the event space with NetworkStateTracker (which can't see this
144 // internal class but sends us events). If you change these, change
145 // NetworkStateTracker.java too.
146 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
147 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
150 * used internally as a delayed event to make us switch back to the
153 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
154 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
157 * used internally to change our mobile data enabled flag
159 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
160 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
163 * used internally to change our network preference setting
164 * arg1 = networkType to prefer
166 private static final int EVENT_SET_NETWORK_PREFERENCE =
167 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
170 * used internally to synchronize inet condition reports
172 * arg2 = condition (0 bad, 100 good)
174 private static final int EVENT_INET_CONDITION_CHANGE =
175 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
178 * used internally to mark the end of inet condition hold periods
181 private static final int EVENT_INET_CONDITION_HOLD_END =
182 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
185 * used internally to set the background data preference
186 * arg1 = TRUE for enabled, FALSE for disabled
188 private static final int EVENT_SET_BACKGROUND_DATA =
189 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
192 * used internally to set enable/disable cellular data
193 * arg1 = ENBALED or DISABLED
195 private static final int EVENT_SET_MOBILE_DATA =
196 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
199 * used internally to clear a wakelock when transitioning
200 * from one net to another
202 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
203 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
206 * used internally to reload global proxy settings
208 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
209 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
212 * used internally to set external dependency met/unmet
213 * arg1 = ENABLED (met) or DISABLED (unmet)
216 private static final int EVENT_SET_DEPENDENCY_MET =
217 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
219 private Handler mHandler;
221 // list of DeathRecipients used to make sure features are turned off when
223 private List mFeatureUsers;
225 private boolean mSystemReady;
226 private Intent mInitialBroadcast;
228 private PowerManager.WakeLock mNetTransitionWakeLock;
229 private String mNetTransitionWakeLockCausedBy = "";
230 private int mNetTransitionWakeLockSerialNumber;
231 private int mNetTransitionWakeLockTimeout;
233 private InetAddress mDefaultDns;
235 // used in DBG mode to track inet condition reports
236 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
237 private ArrayList mInetLog;
239 // track the current default http proxy - tell the world if we get a new one (real change)
240 private ProxyProperties mDefaultProxy = null;
241 // track the global proxy.
242 private ProxyProperties mGlobalProxy = null;
243 private final Object mGlobalProxyLock = new Object();
245 private SettingsObserver mSettingsObserver;
247 NetworkConfig[] mNetConfigs;
248 int mNetworksDefined;
250 private static class RadioAttributes {
251 public int mSimultaneity;
253 public RadioAttributes(String init) {
254 String fragments[] = init.split(",");
255 mType = Integer.parseInt(fragments[0]);
256 mSimultaneity = Integer.parseInt(fragments[1]);
259 RadioAttributes[] mRadioAttributes;
261 // the set of network types that can only be enabled by system/sig apps
262 List mProtectedNetworks;
264 public static synchronized ConnectivityService getInstance(Context context) {
265 if (sServiceInstance == null) {
266 sServiceInstance = new ConnectivityService(context);
268 return sServiceInstance;
271 private ConnectivityService(Context context) {
272 if (DBG) log("ConnectivityService starting up");
274 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
275 handlerThread.start();
276 mHandler = new MyHandler(handlerThread.getLooper());
278 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
279 Settings.Secure.BACKGROUND_DATA, 1) == 1);
281 // setup our unique device name
282 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
283 String id = Settings.Secure.getString(context.getContentResolver(),
284 Settings.Secure.ANDROID_ID);
285 if (id != null && id.length() > 0) {
286 String name = new String("android_").concat(id);
287 SystemProperties.set("net.hostname", name);
291 // read our default dns server ip
292 String dns = Settings.Secure.getString(context.getContentResolver(),
293 Settings.Secure.DEFAULT_DNS_SERVER);
294 if (dns == null || dns.length() == 0) {
295 dns = context.getResources().getString(
296 com.android.internal.R.string.config_default_dns_server);
299 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
300 } catch (IllegalArgumentException e) {
301 loge("Error setting defaultDns using " + dns);
306 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
307 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
308 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
309 com.android.internal.R.integer.config_networkTransitionTimeout);
311 mNetTrackers = new NetworkStateTracker[
312 ConnectivityManager.MAX_NETWORK_TYPE+1];
313 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
315 mNetworkPreference = getPersistedNetworkPreference();
317 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
318 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
320 // Load device network attributes from resources
321 String[] raStrings = context.getResources().getStringArray(
322 com.android.internal.R.array.radioAttributes);
323 for (String raString : raStrings) {
324 RadioAttributes r = new RadioAttributes(raString);
325 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
326 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
329 if (mRadioAttributes[r.mType] != null) {
330 loge("Error in radioAttributes - ignoring attempt to redefine type " +
334 mRadioAttributes[r.mType] = r;
337 String[] naStrings = context.getResources().getStringArray(
338 com.android.internal.R.array.networkAttributes);
339 for (String naString : naStrings) {
341 NetworkConfig n = new NetworkConfig(naString);
342 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
343 loge("Error in networkAttributes - ignoring attempt to define type " +
347 if (mNetConfigs[n.type] != null) {
348 loge("Error in networkAttributes - ignoring attempt to redefine type " +
352 if (mRadioAttributes[n.radio] == null) {
353 loge("Error in networkAttributes - ignoring attempt to use undefined " +
354 "radio " + n.radio + " in network type " + n.type);
357 mNetConfigs[n.type] = n;
359 } catch(Exception e) {
360 // ignore it - leave the entry null
364 mProtectedNetworks = new ArrayList<Integer>();
365 int[] protectedNetworks = context.getResources().getIntArray(
366 com.android.internal.R.array.config_protectedNetworks);
367 for (int p : protectedNetworks) {
368 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
369 mProtectedNetworks.add(p);
371 if (DBG) loge("Ignoring protectedNetwork " + p);
375 // high priority first
376 mPriorityList = new int[mNetworksDefined];
378 int insertionPoint = mNetworksDefined-1;
379 int currentLowest = 0;
381 while (insertionPoint > -1) {
382 for (NetworkConfig na : mNetConfigs) {
383 if (na == null) continue;
384 if (na.priority < currentLowest) continue;
385 if (na.priority > currentLowest) {
386 if (na.priority < nextLowest || nextLowest == 0) {
387 nextLowest = na.priority;
391 mPriorityList[insertionPoint--] = na.type;
393 currentLowest = nextLowest;
398 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
399 for (int i : mPriorityList) {
400 mNetRequestersPids[i] = new ArrayList();
403 mFeatureUsers = new ArrayList();
407 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
408 && SystemProperties.get("ro.build.type").equals("eng");
410 * Create the network state trackers for Wi-Fi and mobile
411 * data. Maybe this could be done with a factory class,
412 * but it's not clear that it's worth it, given that
413 * the number of different network types is not going
414 * to change very often.
416 for (int netType : mPriorityList) {
417 switch (mNetConfigs[netType].radio) {
418 case ConnectivityManager.TYPE_WIFI:
419 if (DBG) log("Starting Wifi Service.");
420 WifiStateTracker wst = new WifiStateTracker();
421 WifiService wifiService = new WifiService(context);
422 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
423 wifiService.checkAndStartWifi();
424 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
425 wst.startMonitoring(context, mHandler);
427 //TODO: as part of WWS refactor, create only when needed
428 mWifiWatchdogService = new WifiWatchdogService(context);
431 case ConnectivityManager.TYPE_MOBILE:
432 mNetTrackers[netType] = new MobileDataStateTracker(netType,
433 mNetConfigs[netType].name);
434 mNetTrackers[netType].startMonitoring(context, mHandler);
436 case ConnectivityManager.TYPE_DUMMY:
437 mNetTrackers[netType] = new DummyDataStateTracker(netType,
438 mNetConfigs[netType].name);
439 mNetTrackers[netType].startMonitoring(context, mHandler);
441 case ConnectivityManager.TYPE_BLUETOOTH:
442 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
443 mNetTrackers[netType].startMonitoring(context, mHandler);
445 case ConnectivityManager.TYPE_ETHERNET:
446 mNetTrackers[netType] = EthernetDataTracker.getInstance();
447 mNetTrackers[netType].startMonitoring(context, mHandler);
450 loge("Trying to create a DataStateTracker for an unknown radio type " +
451 mNetConfigs[netType].radio);
454 mCurrentLinkProperties[netType] = mNetTrackers[netType].getLinkProperties();
457 mTethering = new Tethering(mContext, mHandler.getLooper());
458 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
459 mTethering.getTetherableWifiRegexs().length != 0 ||
460 mTethering.getTetherableBluetoothRegexs().length != 0) &&
461 mTethering.getUpstreamIfaceTypes().length != 0);
464 mInetLog = new ArrayList();
467 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
468 mSettingsObserver.observe(mContext);
472 VpnManager.startVpnService(context);
477 * Sets the preferred network.
478 * @param preference the new preference
480 public void setNetworkPreference(int preference) {
481 enforceChangePermission();
483 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
486 public int getNetworkPreference() {
487 enforceAccessPermission();
490 preference = mNetworkPreference;
495 private void handleSetNetworkPreference(int preference) {
496 if (ConnectivityManager.isNetworkTypeValid(preference) &&
497 mNetConfigs[preference] != null &&
498 mNetConfigs[preference].isDefault()) {
499 if (mNetworkPreference != preference) {
500 final ContentResolver cr = mContext.getContentResolver();
501 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
503 mNetworkPreference = preference;
510 private int getPersistedNetworkPreference() {
511 final ContentResolver cr = mContext.getContentResolver();
513 final int networkPrefSetting = Settings.Secure
514 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
515 if (networkPrefSetting != -1) {
516 return networkPrefSetting;
519 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
523 * Make the state of network connectivity conform to the preference settings
524 * In this method, we only tear down a non-preferred network. Establishing
525 * a connection to the preferred network is taken care of when we handle
526 * the disconnect event from the non-preferred network
527 * (see {@link #handleDisconnect(NetworkInfo)}).
529 private void enforcePreference() {
530 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
533 if (!mNetTrackers[mNetworkPreference].isAvailable())
536 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
537 if (t != mNetworkPreference && mNetTrackers[t] != null &&
538 mNetTrackers[t].getNetworkInfo().isConnected()) {
540 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
541 " in enforcePreference");
543 teardown(mNetTrackers[t]);
548 private boolean teardown(NetworkStateTracker netTracker) {
549 if (netTracker.teardown()) {
550 netTracker.setTeardownRequested(true);
558 * Return NetworkInfo for the active (i.e., connected) network interface.
559 * It is assumed that at most one network is active at a time. If more
560 * than one is active, it is indeterminate which will be returned.
561 * @return the info for the active network, or {@code null} if none is
564 public NetworkInfo getActiveNetworkInfo() {
565 return getNetworkInfo(mActiveDefaultNetwork);
568 public NetworkInfo getNetworkInfo(int networkType) {
569 enforceAccessPermission();
570 if (ConnectivityManager.isNetworkTypeValid(networkType)) {
571 NetworkStateTracker t = mNetTrackers[networkType];
573 return t.getNetworkInfo();
578 public NetworkInfo[] getAllNetworkInfo() {
579 enforceAccessPermission();
580 NetworkInfo[] result = new NetworkInfo[mNetworksDefined];
582 for (NetworkStateTracker t : mNetTrackers) {
583 if(t != null) result[i++] = t.getNetworkInfo();
589 * Return LinkProperties for the active (i.e., connected) default
590 * network interface. It is assumed that at most one default network
591 * is active at a time. If more than one is active, it is indeterminate
592 * which will be returned.
593 * @return the ip properties for the active network, or {@code null} if
596 public LinkProperties getActiveLinkProperties() {
597 return getLinkProperties(mActiveDefaultNetwork);
600 public LinkProperties getLinkProperties(int networkType) {
601 enforceAccessPermission();
602 if (ConnectivityManager.isNetworkTypeValid(networkType)) {
603 NetworkStateTracker t = mNetTrackers[networkType];
604 if (t != null) return t.getLinkProperties();
609 public boolean setRadios(boolean turnOn) {
610 boolean result = true;
611 enforceChangePermission();
612 for (NetworkStateTracker t : mNetTrackers) {
613 if (t != null) result = t.setRadio(turnOn) && result;
618 public boolean setRadio(int netType, boolean turnOn) {
619 enforceChangePermission();
620 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
623 NetworkStateTracker tracker = mNetTrackers[netType];
624 return tracker != null && tracker.setRadio(turnOn);
628 * Used to notice when the calling process dies so we can self-expire
630 * Also used to know if the process has cleaned up after itself when
631 * our auto-expire timer goes off. The timer has a link to an object.
634 private class FeatureUser implements IBinder.DeathRecipient {
642 FeatureUser(int type, String feature, IBinder binder) {
647 mPid = getCallingPid();
648 mUid = getCallingUid();
649 mCreateTime = System.currentTimeMillis();
652 mBinder.linkToDeath(this, 0);
653 } catch (RemoteException e) {
658 void unlinkDeathRecipient() {
659 mBinder.unlinkToDeath(this, 0);
662 public void binderDied() {
663 log("ConnectivityService FeatureUser binderDied(" +
664 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
665 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
666 stopUsingNetworkFeature(this, false);
669 public void expire() {
670 log("ConnectivityService FeatureUser expire(" +
671 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
672 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
673 stopUsingNetworkFeature(this, false);
676 public String toString() {
677 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
678 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
682 // javadoc from interface
683 public int startUsingNetworkFeature(int networkType, String feature,
686 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
688 enforceChangePermission();
689 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
690 mNetConfigs[networkType] == null) {
691 return Phone.APN_REQUEST_FAILED;
694 FeatureUser f = new FeatureUser(networkType, feature, binder);
696 // TODO - move this into the MobileDataStateTracker
697 int usedNetworkType = networkType;
698 if(networkType == ConnectivityManager.TYPE_MOBILE) {
699 usedNetworkType = convertFeatureToNetworkType(feature);
700 if (usedNetworkType < 0) {
701 Slog.e(TAG, "Can't match any netTracker!");
702 usedNetworkType = networkType;
706 if (mProtectedNetworks.contains(usedNetworkType)) {
707 enforceConnectivityInternalPermission();
710 NetworkStateTracker network = mNetTrackers[usedNetworkType];
711 if (network != null) {
712 Integer currentPid = new Integer(getCallingPid());
713 if (usedNetworkType != networkType) {
714 NetworkStateTracker radio = mNetTrackers[networkType];
715 NetworkInfo ni = network.getNetworkInfo();
717 if (ni.isAvailable() == false) {
718 if (DBG) log("special network not available");
719 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
720 return Phone.APN_TYPE_NOT_AVAILABLE;
722 // else make the attempt anyway - probably giving REQUEST_STARTED below
727 mFeatureUsers.add(f);
728 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
729 // this gets used for per-pid dns when connected
730 mNetRequestersPids[usedNetworkType].add(currentPid);
734 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
736 if (restoreTimer >= 0) {
737 mHandler.sendMessageDelayed(
738 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
741 if ((ni.isConnectedOrConnecting() == true) &&
742 !network.isTeardownRequested()) {
743 if (ni.isConnected() == true) {
744 // add the pid-specific dns
745 handleDnsConfigurationChange(networkType);
746 if (DBG) log("special network already active");
747 return Phone.APN_ALREADY_ACTIVE;
749 if (DBG) log("special network already connecting");
750 return Phone.APN_REQUEST_STARTED;
753 // check if the radio in play can make another contact
754 // assume if cannot for now
756 if (DBG) log("reconnecting to special network");
758 return Phone.APN_REQUEST_STARTED;
760 // need to remember this unsupported request so we respond appropriately on stop
762 mFeatureUsers.add(f);
763 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
764 // this gets used for per-pid dns when connected
765 mNetRequestersPids[usedNetworkType].add(currentPid);
771 return Phone.APN_TYPE_NOT_AVAILABLE;
774 // javadoc from interface
775 public int stopUsingNetworkFeature(int networkType, String feature) {
776 enforceChangePermission();
778 int pid = getCallingPid();
779 int uid = getCallingUid();
781 FeatureUser u = null;
782 boolean found = false;
785 for (int i = 0; i < mFeatureUsers.size() ; i++) {
786 u = (FeatureUser)mFeatureUsers.get(i);
787 if (uid == u.mUid && pid == u.mPid &&
788 networkType == u.mNetworkType &&
789 TextUtils.equals(feature, u.mFeature)) {
795 if (found && u != null) {
796 // stop regardless of how many other time this proc had called start
797 return stopUsingNetworkFeature(u, true);
800 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
805 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
806 int networkType = u.mNetworkType;
807 String feature = u.mFeature;
811 NetworkStateTracker tracker = null;
812 boolean callTeardown = false; // used to carry our decision outside of sync block
815 log("stopUsingNetworkFeature for net " + networkType +
819 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
823 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
826 // check if this process still has an outstanding start request
827 if (!mFeatureUsers.contains(u)) {
828 if (DBG) log("ignoring - this process has no outstanding requests");
831 u.unlinkDeathRecipient();
832 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
833 // If we care about duplicate requests, check for that here.
835 // This is done to support the extension of a request - the app
836 // can request we start the network feature again and renew the
837 // auto-shutoff delay. Normal "stop" calls from the app though
838 // do not pay attention to duplicate requests - in effect the
839 // API does not refcount and a single stop will counter multiple starts.
840 if (ignoreDups == false) {
841 for (int i = 0; i < mFeatureUsers.size() ; i++) {
842 FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
843 if (x.mUid == u.mUid && x.mPid == u.mPid &&
844 x.mNetworkType == u.mNetworkType &&
845 TextUtils.equals(x.mFeature, u.mFeature)) {
846 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
852 // TODO - move to MobileDataStateTracker
853 int usedNetworkType = networkType;
854 if (networkType == ConnectivityManager.TYPE_MOBILE) {
855 usedNetworkType = convertFeatureToNetworkType(feature);
856 if (usedNetworkType < 0) {
857 usedNetworkType = networkType;
860 tracker = mNetTrackers[usedNetworkType];
861 if (tracker == null) {
862 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
865 if (usedNetworkType != networkType) {
866 Integer currentPid = new Integer(pid);
867 mNetRequestersPids[usedNetworkType].remove(currentPid);
868 reassessPidDns(pid, true);
869 if (mNetRequestersPids[usedNetworkType].size() != 0) {
870 if (DBG) log("not tearing down special network - " +
871 "others still using it");
876 if (DBG) log("not a known feature - dropping");
879 if (DBG) log("Doing network teardown");
889 * @deprecated use requestRouteToHostAddress instead
891 * Ensure that a network route exists to deliver traffic to the specified
892 * host via the specified network interface.
893 * @param networkType the type of the network over which traffic to the
894 * specified host is to be routed
895 * @param hostAddress the IP address of the host to which the route is
897 * @return {@code true} on success, {@code false} on failure
899 public boolean requestRouteToHost(int networkType, int hostAddress) {
900 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
902 if (inetAddress == null) {
906 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
910 * Ensure that a network route exists to deliver traffic to the specified
911 * host via the specified network interface.
912 * @param networkType the type of the network over which traffic to the
913 * specified host is to be routed
914 * @param hostAddress the IP address of the host to which the route is
916 * @return {@code true} on success, {@code false} on failure
918 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
919 enforceChangePermission();
920 if (mProtectedNetworks.contains(networkType)) {
921 enforceConnectivityInternalPermission();
924 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
927 NetworkStateTracker tracker = mNetTrackers[networkType];
929 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
930 tracker.isTeardownRequested()) {
932 log("requestRouteToHostAddress on down network " +
933 "(" + networkType + ") - dropped");
938 InetAddress addr = InetAddress.getByAddress(hostAddress);
939 return addHostRoute(tracker, addr, 0);
940 } catch (UnknownHostException e) {}
945 * Ensure that a network route exists to deliver traffic to the specified
946 * host via the mobile data network.
947 * @param hostAddress the IP address of the host to which the route is desired,
948 * in network byte order.
950 * @return {@code true} on success, {@code false} on failure
952 private boolean addHostRoute(NetworkStateTracker nt, InetAddress hostAddress, int cycleCount) {
953 LinkProperties lp = nt.getLinkProperties();
954 if ((lp == null) || (hostAddress == null)) return false;
956 String interfaceName = lp.getInterfaceName();
958 log("Requested host route to " + hostAddress + "(" + interfaceName + "), cycleCount=" +
961 if (interfaceName == null) {
962 if (DBG) loge("addHostRoute failed due to null interface name");
966 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), hostAddress);
967 InetAddress gatewayAddress = null;
968 if (bestRoute != null) {
969 gatewayAddress = bestRoute.getGateway();
970 // if the best route is ourself, don't relf-reference, just add the host route
971 if (hostAddress.equals(gatewayAddress)) gatewayAddress = null;
973 if (gatewayAddress != null) {
974 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
975 loge("Error adding hostroute - too much recursion");
978 if (!addHostRoute(nt, gatewayAddress, cycleCount+1)) return false;
981 RouteInfo route = RouteInfo.makeHostRoute(hostAddress, gatewayAddress);
984 mNetd.addRoute(interfaceName, route);
986 } catch (Exception ex) {
991 // TODO support the removal of single host routes. Keep a ref count of them so we
992 // aren't over-zealous
993 private boolean removeHostRoute(NetworkStateTracker nt, InetAddress hostAddress) {
998 * @see ConnectivityManager#getBackgroundDataSetting()
1000 public boolean getBackgroundDataSetting() {
1001 return mBackgroundDataEnabled.get();
1005 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1007 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1008 mContext.enforceCallingOrSelfPermission(
1009 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1010 "ConnectivityService");
1012 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1014 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1015 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1018 private void handleSetBackgroundData(boolean enabled) {
1019 Settings.Secure.putInt(mContext.getContentResolver(),
1020 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1021 Intent broadcast = new Intent(
1022 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1023 mContext.sendBroadcast(broadcast);
1027 * @see ConnectivityManager#getMobileDataEnabled()
1029 public boolean getMobileDataEnabled() {
1030 // TODO: This detail should probably be in DataConnectionTracker's
1031 // which is where we store the value and maybe make this
1033 enforceAccessPermission();
1034 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1035 Settings.Secure.MOBILE_DATA, 1) == 1;
1036 if (DBG) log("getMobileDataEnabled returning " + retVal);
1040 public void setDataDependency(int networkType, boolean met) {
1041 enforceConnectivityInternalPermission();
1044 log("setDataDependency(" + networkType + ", " + met + ")");
1046 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1047 (met ? ENABLED : DISABLED), networkType));
1050 private void handleSetDependencyMet(int networkType, boolean met) {
1051 if (mNetTrackers[networkType] != null) {
1053 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1055 mNetTrackers[networkType].setDependencyMet(met);
1060 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1062 public void setMobileDataEnabled(boolean enabled) {
1063 enforceChangePermission();
1064 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
1066 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
1067 (enabled ? ENABLED : DISABLED), 0));
1070 private void handleSetMobileData(boolean enabled) {
1071 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1073 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
1075 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
1079 private void enforceAccessPermission() {
1080 mContext.enforceCallingOrSelfPermission(
1081 android.Manifest.permission.ACCESS_NETWORK_STATE,
1082 "ConnectivityService");
1085 private void enforceChangePermission() {
1086 mContext.enforceCallingOrSelfPermission(
1087 android.Manifest.permission.CHANGE_NETWORK_STATE,
1088 "ConnectivityService");
1091 // TODO Make this a special check when it goes public
1092 private void enforceTetherChangePermission() {
1093 mContext.enforceCallingOrSelfPermission(
1094 android.Manifest.permission.CHANGE_NETWORK_STATE,
1095 "ConnectivityService");
1098 private void enforceTetherAccessPermission() {
1099 mContext.enforceCallingOrSelfPermission(
1100 android.Manifest.permission.ACCESS_NETWORK_STATE,
1101 "ConnectivityService");
1104 private void enforceConnectivityInternalPermission() {
1105 mContext.enforceCallingOrSelfPermission(
1106 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1107 "ConnectivityService");
1111 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1112 * network, we ignore it. If it is for the active network, we send out a
1113 * broadcast. But first, we check whether it might be possible to connect
1114 * to a different network.
1115 * @param info the {@code NetworkInfo} for the network
1117 private void handleDisconnect(NetworkInfo info) {
1119 int prevNetType = info.getType();
1121 mNetTrackers[prevNetType].setTeardownRequested(false);
1123 * If the disconnected network is not the active one, then don't report
1124 * this as a loss of connectivity. What probably happened is that we're
1125 * getting the disconnect for a network that we explicitly disabled
1126 * in accordance with network preference policies.
1128 if (!mNetConfigs[prevNetType].isDefault()) {
1129 List pids = mNetRequestersPids[prevNetType];
1130 for (int i = 0; i<pids.size(); i++) {
1131 Integer pid = (Integer)pids.get(i);
1132 // will remove them because the net's no longer connected
1133 // need to do this now as only now do we know the pids and
1134 // can properly null things that are no longer referenced.
1135 reassessPidDns(pid.intValue(), false);
1139 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1140 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1141 if (info.isFailover()) {
1142 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1143 info.setFailover(false);
1145 if (info.getReason() != null) {
1146 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1148 if (info.getExtraInfo() != null) {
1149 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1150 info.getExtraInfo());
1153 if (mNetConfigs[prevNetType].isDefault()) {
1154 tryFailover(prevNetType);
1155 if (mActiveDefaultNetwork != -1) {
1156 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1157 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1159 mDefaultInetConditionPublished = 0; // we're not connected anymore
1160 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1163 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1165 // Reset interface if no other connections are using the same interface
1166 boolean doReset = true;
1167 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1168 if (linkProperties != null) {
1169 String oldIface = linkProperties.getInterfaceName();
1170 if (TextUtils.isEmpty(oldIface) == false) {
1171 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1172 if (networkStateTracker == null) continue;
1173 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1174 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1175 LinkProperties l = networkStateTracker.getLinkProperties();
1176 if (l == null) continue;
1177 if (oldIface.equals(l.getInterfaceName())) {
1186 // do this before we broadcast the change
1187 handleConnectivityChange(prevNetType, doReset);
1189 sendStickyBroadcast(intent);
1191 * If the failover network is already connected, then immediately send
1192 * out a followup broadcast indicating successful failover
1194 if (mActiveDefaultNetwork != -1) {
1195 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
1199 private void tryFailover(int prevNetType) {
1201 * If this is a default network, check if other defaults are available.
1202 * Try to reconnect on all available and let them hash it out when
1203 * more than one connects.
1205 if (mNetConfigs[prevNetType].isDefault()) {
1206 if (mActiveDefaultNetwork == prevNetType) {
1207 mActiveDefaultNetwork = -1;
1210 // don't signal a reconnect for anything lower or equal priority than our
1211 // current connected default
1212 // TODO - don't filter by priority now - nice optimization but risky
1213 // int currentPriority = -1;
1214 // if (mActiveDefaultNetwork != -1) {
1215 // currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
1217 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
1218 if (checkType == prevNetType) continue;
1219 if (mNetConfigs[checkType] == null) continue;
1220 if (!mNetConfigs[checkType].isDefault()) continue;
1222 // Enabling the isAvailable() optimization caused mobile to not get
1223 // selected if it was in the middle of error handling. Specifically
1224 // a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1225 // would not be available and we wouldn't get connected to anything.
1226 // So removing the isAvailable() optimization below for now. TODO: This
1227 // optimization should work and we need to investigate why it doesn't work.
1228 // This could be related to how DEACTIVATE_DATA_CALL is reporting its
1229 // complete before it is really complete.
1230 // if (!mNetTrackers[checkType].isAvailable()) continue;
1232 // if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
1234 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1235 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1236 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1237 checkInfo.setFailover(true);
1238 checkTracker.reconnect();
1240 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
1245 private void sendConnectedBroadcast(NetworkInfo info) {
1246 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1249 private void sendInetConditionBroadcast(NetworkInfo info) {
1250 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1253 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1254 Intent intent = new Intent(bcastType);
1255 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1256 if (info.isFailover()) {
1257 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1258 info.setFailover(false);
1260 if (info.getReason() != null) {
1261 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1263 if (info.getExtraInfo() != null) {
1264 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1265 info.getExtraInfo());
1267 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1268 sendStickyBroadcast(intent);
1272 * Called when an attempt to fail over to another network has failed.
1273 * @param info the {@link NetworkInfo} for the failed network
1275 private void handleConnectionFailure(NetworkInfo info) {
1276 mNetTrackers[info.getType()].setTeardownRequested(false);
1278 String reason = info.getReason();
1279 String extraInfo = info.getExtraInfo();
1282 if (reason == null) {
1285 reasonText = " (" + reason + ").";
1287 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
1289 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1290 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1291 if (getActiveNetworkInfo() == null) {
1292 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1294 if (reason != null) {
1295 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1297 if (extraInfo != null) {
1298 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1300 if (info.isFailover()) {
1301 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1302 info.setFailover(false);
1305 if (mNetConfigs[info.getType()].isDefault()) {
1306 tryFailover(info.getType());
1307 if (mActiveDefaultNetwork != -1) {
1308 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1309 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1311 mDefaultInetConditionPublished = 0;
1312 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1316 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1317 sendStickyBroadcast(intent);
1319 * If the failover network is already connected, then immediately send
1320 * out a followup broadcast indicating successful failover
1322 if (mActiveDefaultNetwork != -1) {
1323 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
1327 private void sendStickyBroadcast(Intent intent) {
1328 synchronized(this) {
1329 if (!mSystemReady) {
1330 mInitialBroadcast = new Intent(intent);
1332 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1333 mContext.sendStickyBroadcast(intent);
1337 void systemReady() {
1338 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
1339 mNetd = INetworkManagementService.Stub.asInterface(b);
1341 synchronized(this) {
1342 mSystemReady = true;
1343 if (mInitialBroadcast != null) {
1344 mContext.sendStickyBroadcast(mInitialBroadcast);
1345 mInitialBroadcast = null;
1348 // load the global proxy at startup
1349 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
1352 private void handleConnect(NetworkInfo info) {
1353 int type = info.getType();
1355 // snapshot isFailover, because sendConnectedBroadcast() resets it
1356 boolean isFailover = info.isFailover();
1357 NetworkStateTracker thisNet = mNetTrackers[type];
1359 // if this is a default net and other default is running
1360 // kill the one not preferred
1361 if (mNetConfigs[type].isDefault()) {
1362 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1363 if ((type != mNetworkPreference &&
1364 mNetConfigs[mActiveDefaultNetwork].priority >
1365 mNetConfigs[type].priority) ||
1366 mNetworkPreference == mActiveDefaultNetwork) {
1367 // don't accept this one
1369 log("Not broadcasting CONNECT_ACTION " +
1370 "to torn down network " + info.getTypeName());
1375 // tear down the other
1376 NetworkStateTracker otherNet =
1377 mNetTrackers[mActiveDefaultNetwork];
1379 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
1382 if (!teardown(otherNet)) {
1383 loge("Network declined teardown request");
1388 synchronized (ConnectivityService.this) {
1389 // have a new default network, release the transition wakelock in a second
1390 // if it's held. The second pause is to allow apps to reconnect over the
1392 if (mNetTransitionWakeLock.isHeld()) {
1393 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1394 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
1395 mNetTransitionWakeLockSerialNumber, 0),
1399 mActiveDefaultNetwork = type;
1400 // this will cause us to come up initially as unconnected and switching
1401 // to connected after our normal pause unless somebody reports us as reall
1403 mDefaultInetConditionPublished = 0;
1404 mDefaultConnectionSequence++;
1405 mInetConditionChangeInFlight = false;
1406 // Don't do this - if we never sign in stay, grey
1407 //reportNetworkCondition(mActiveDefaultNetwork, 100);
1409 thisNet.setTeardownRequested(false);
1410 updateNetworkSettings(thisNet);
1411 handleConnectivityChange(type, false);
1412 sendConnectedBroadcast(info);
1416 * After a change in the connectivity state of a network. We're mainly
1417 * concerned with making sure that the list of DNS servers is set up
1418 * according to which networks are connected, and ensuring that the
1419 * right routing table entries exist.
1421 private void handleConnectivityChange(int netType, boolean doReset) {
1422 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1425 * If a non-default network is enabled, add the host routes that
1426 * will allow it's DNS servers to be accessed.
1428 handleDnsConfigurationChange(netType);
1430 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
1431 LinkProperties newLp = mNetTrackers[netType].getLinkProperties();
1432 LinkProperties curLp = mCurrentLinkProperties[netType];
1433 mCurrentLinkProperties[netType] = newLp;
1435 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1436 " doReset=" + doReset + " resetMask=" + resetMask +
1437 "\n curLp=" + curLp +
1438 "\n newLp=" + newLp);
1441 if (curLp.isIdenticalInterfaceName(newLp)) {
1442 CompareAddressesResult car = curLp.compareAddresses(newLp);
1443 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1444 for (LinkAddress linkAddr : car.removed) {
1445 if (linkAddr.getAddress() instanceof Inet4Address) {
1446 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1448 if (linkAddr.getAddress() instanceof Inet6Address) {
1449 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1453 log("handleConnectivityChange: addresses changed" +
1454 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1459 log("handleConnectivityChange: address are the same reset per doReset" +
1460 " linkProperty[" + netType + "]:" +
1461 " resetMask=" + resetMask);
1465 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
1466 log("handleConnectivityChange: interface not not equivalent reset both" +
1467 " linkProperty[" + netType + "]:" +
1468 " resetMask=" + resetMask);
1470 if (mNetConfigs[netType].isDefault()) {
1471 handleApplyDefaultProxy(netType);
1472 addDefaultRoute(mNetTrackers[netType]);
1474 addPrivateDnsRoutes(mNetTrackers[netType]);
1477 if (mNetConfigs[netType].isDefault()) {
1478 removeDefaultRoute(mNetTrackers[netType]);
1480 removePrivateDnsRoutes(mNetTrackers[netType]);
1484 if (doReset || resetMask != 0) {
1485 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1486 if (linkProperties != null) {
1487 String iface = linkProperties.getInterfaceName();
1488 if (TextUtils.isEmpty(iface) == false) {
1489 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1490 NetworkUtils.resetConnections(iface, resetMask);
1495 // TODO: Temporary notifying upstread change to Tethering.
1497 /** Notify TetheringService if interface name has been changed. */
1498 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1499 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1500 if (isTetheringSupported()) {
1501 mTethering.handleTetherIfaceChange();
1506 private void addPrivateDnsRoutes(NetworkStateTracker nt) {
1507 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1508 LinkProperties p = nt.getLinkProperties();
1509 if (p == null) return;
1510 String interfaceName = p.getInterfaceName();
1513 log("addPrivateDnsRoutes for " + nt +
1514 "(" + interfaceName + ") - mPrivateDnsRouteSet = " + privateDnsRouteSet);
1516 if (interfaceName != null && !privateDnsRouteSet) {
1517 Collection<InetAddress> dnsList = p.getDnses();
1518 for (InetAddress dns : dnsList) {
1519 addHostRoute(nt, dns, 0);
1521 nt.privateDnsRouteSet(true);
1525 private void removePrivateDnsRoutes(NetworkStateTracker nt) {
1526 LinkProperties p = nt.getLinkProperties();
1527 if (p == null) return;
1528 String interfaceName = p.getInterfaceName();
1529 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1530 if (interfaceName != null && privateDnsRouteSet) {
1532 log("removePrivateDnsRoutes for " + nt.getNetworkInfo().getTypeName() +
1533 " (" + interfaceName + ")");
1536 Collection<InetAddress> dnsList = p.getDnses();
1537 for (InetAddress dns : dnsList) {
1538 if (DBG) log(" removing " + dns);
1539 RouteInfo route = RouteInfo.makeHostRoute(dns);
1541 mNetd.removeRoute(interfaceName, route);
1542 } catch (Exception ex) {
1543 loge("error (" + ex + ") removing dns route " + route);
1546 nt.privateDnsRouteSet(false);
1551 private void addDefaultRoute(NetworkStateTracker nt) {
1552 LinkProperties p = nt.getLinkProperties();
1553 if (p == null) return;
1554 String interfaceName = p.getInterfaceName();
1555 if (TextUtils.isEmpty(interfaceName)) return;
1557 for (RouteInfo route : p.getRoutes()) {
1558 //TODO - handle non-default routes
1559 if (route.isDefaultRoute()) {
1560 if (DBG) log("adding default route " + route);
1561 InetAddress gateway = route.getGateway();
1562 if (addHostRoute(nt, gateway, 0)) {
1564 mNetd.addRoute(interfaceName, route);
1565 } catch (Exception e) {
1566 loge("error adding default route " + route);
1570 NetworkInfo networkInfo = nt.getNetworkInfo();
1571 log("addDefaultRoute for " + networkInfo.getTypeName() +
1572 " (" + interfaceName + "), GatewayAddr=" +
1573 gateway.getHostAddress());
1576 loge("error adding host route for default route " + route);
1583 public void removeDefaultRoute(NetworkStateTracker nt) {
1584 LinkProperties p = nt.getLinkProperties();
1585 if (p == null) return;
1586 String interfaceName = p.getInterfaceName();
1588 if (interfaceName == null) return;
1590 for (RouteInfo route : p.getRoutes()) {
1591 //TODO - handle non-default routes
1592 if (route.isDefaultRoute()) {
1594 mNetd.removeRoute(interfaceName, route);
1595 } catch (Exception ex) {
1596 loge("error (" + ex + ") removing default route " + route);
1600 NetworkInfo networkInfo = nt.getNetworkInfo();
1601 log("removeDefaultRoute for " + networkInfo.getTypeName() + " (" +
1602 interfaceName + ")");
1609 * Reads the network specific TCP buffer sizes from SystemProperties
1610 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1613 public void updateNetworkSettings(NetworkStateTracker nt) {
1614 String key = nt.getTcpBufferSizesPropName();
1615 String bufferSizes = SystemProperties.get(key);
1617 if (bufferSizes.length() == 0) {
1618 loge(key + " not found in system properties. Using defaults");
1620 // Setting to default values so we won't be stuck to previous values
1621 key = "net.tcp.buffersize.default";
1622 bufferSizes = SystemProperties.get(key);
1625 // Set values in kernel
1626 if (bufferSizes.length() != 0) {
1628 log("Setting TCP values: [" + bufferSizes
1629 + "] which comes from [" + key + "]");
1631 setBufferSize(bufferSizes);
1636 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1637 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1639 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1640 * writeMin, writeInitial, writeMax"
1642 private void setBufferSize(String bufferSizes) {
1644 String[] values = bufferSizes.split(",");
1646 if (values.length == 6) {
1647 final String prefix = "/sys/kernel/ipv4/tcp_";
1648 stringToFile(prefix + "rmem_min", values[0]);
1649 stringToFile(prefix + "rmem_def", values[1]);
1650 stringToFile(prefix + "rmem_max", values[2]);
1651 stringToFile(prefix + "wmem_min", values[3]);
1652 stringToFile(prefix + "wmem_def", values[4]);
1653 stringToFile(prefix + "wmem_max", values[5]);
1655 loge("Invalid buffersize string: " + bufferSizes);
1657 } catch (IOException e) {
1658 loge("Can't set tcp buffer sizes:" + e);
1663 * Writes string to file. Basically same as "echo -n $string > $filename"
1667 * @throws IOException
1669 private void stringToFile(String filename, String string) throws IOException {
1670 FileWriter out = new FileWriter(filename);
1680 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1681 * on the highest priority active net which this process requested.
1682 * If there aren't any, clear it out
1684 private void reassessPidDns(int myPid, boolean doBump)
1686 if (DBG) log("reassessPidDns for pid " + myPid);
1687 for(int i : mPriorityList) {
1688 if (mNetConfigs[i].isDefault()) {
1691 NetworkStateTracker nt = mNetTrackers[i];
1692 if (nt.getNetworkInfo().isConnected() &&
1693 !nt.isTeardownRequested()) {
1694 LinkProperties p = nt.getLinkProperties();
1695 if (p == null) continue;
1696 List pids = mNetRequestersPids[i];
1697 for (int j=0; j<pids.size(); j++) {
1698 Integer pid = (Integer)pids.get(j);
1699 if (pid.intValue() == myPid) {
1700 Collection<InetAddress> dnses = p.getDnses();
1701 writePidDns(dnses, myPid);
1710 // nothing found - delete
1711 for (int i = 1; ; i++) {
1712 String prop = "net.dns" + i + "." + myPid;
1713 if (SystemProperties.get(prop).length() == 0) {
1719 SystemProperties.set(prop, "");
1723 // return true if results in a change
1724 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
1726 boolean changed = false;
1727 for (InetAddress dns : dnses) {
1728 String dnsString = dns.getHostAddress();
1729 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1731 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1737 private void bumpDns() {
1739 * Bump the property that tells the name resolver library to reread
1740 * the DNS server list from the properties.
1742 String propVal = SystemProperties.get("net.dnschange");
1744 if (propVal.length() != 0) {
1746 n = Integer.parseInt(propVal);
1747 } catch (NumberFormatException e) {}
1749 SystemProperties.set("net.dnschange", "" + (n+1));
1751 * Tell the VMs to toss their DNS caches
1753 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1754 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1756 * Connectivity events can happen before boot has completed ...
1758 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1759 mContext.sendBroadcast(intent);
1762 private void handleDnsConfigurationChange(int netType) {
1763 // add default net's dns entries
1764 NetworkStateTracker nt = mNetTrackers[netType];
1765 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
1766 LinkProperties p = nt.getLinkProperties();
1767 if (p == null) return;
1768 Collection<InetAddress> dnses = p.getDnses();
1769 boolean changed = false;
1770 if (mNetConfigs[netType].isDefault()) {
1772 if (dnses.size() == 0 && mDefaultDns != null) {
1773 String dnsString = mDefaultDns.getHostAddress();
1774 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1776 log("no dns provided - using " + dnsString);
1779 SystemProperties.set("net.dns1", dnsString);
1783 for (InetAddress dns : dnses) {
1784 String dnsString = dns.getHostAddress();
1785 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1790 log("adding dns " + dns + " for " +
1791 nt.getNetworkInfo().getTypeName());
1794 SystemProperties.set("net.dns" + j++, dnsString);
1797 for (int k=j ; k<mNumDnsEntries; k++) {
1798 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1799 if (DBG) log("erasing net.dns" + k);
1801 SystemProperties.set("net.dns" + k, "");
1806 // set per-pid dns for attached secondary nets
1807 List pids = mNetRequestersPids[netType];
1808 for (int y=0; y< pids.size(); y++) {
1809 Integer pid = (Integer)pids.get(y);
1810 changed = writePidDns(dnses, pid.intValue());
1813 if (changed) bumpDns();
1817 private int getRestoreDefaultNetworkDelay(int networkType) {
1818 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1819 NETWORK_RESTORE_DELAY_PROP_NAME);
1820 if(restoreDefaultNetworkDelayStr != null &&
1821 restoreDefaultNetworkDelayStr.length() != 0) {
1823 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1824 } catch (NumberFormatException e) {
1827 // if the system property isn't set, use the value for the apn type
1828 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1830 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1831 (mNetConfigs[networkType] != null)) {
1832 ret = mNetConfigs[networkType].restoreTime;
1838 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1839 if (mContext.checkCallingOrSelfPermission(
1840 android.Manifest.permission.DUMP)
1841 != PackageManager.PERMISSION_GRANTED) {
1842 pw.println("Permission Denial: can't dump ConnectivityService " +
1843 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1844 Binder.getCallingUid());
1848 for (NetworkStateTracker nst : mNetTrackers) {
1850 if (nst.getNetworkInfo().isConnected()) {
1851 pw.println("Active network: " + nst.getNetworkInfo().
1854 pw.println(nst.getNetworkInfo());
1860 pw.println("Network Requester Pids:");
1861 for (int net : mPriorityList) {
1862 String pidString = net + ": ";
1863 for (Object pid : mNetRequestersPids[net]) {
1864 pidString = pidString + pid.toString() + ", ";
1866 pw.println(pidString);
1870 pw.println("FeatureUsers:");
1871 for (Object requester : mFeatureUsers) {
1872 pw.println(requester.toString());
1876 synchronized (this) {
1877 pw.println("NetworkTranstionWakeLock is currently " +
1878 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1879 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1883 mTethering.dump(fd, pw, args);
1885 if (mInetLog != null) {
1887 pw.println("Inet condition reports:");
1888 for(int i = 0; i < mInetLog.size(); i++) {
1889 pw.println(mInetLog.get(i));
1894 // must be stateless - things change under us.
1895 private class MyHandler extends Handler {
1896 public MyHandler(Looper looper) {
1901 public void handleMessage(Message msg) {
1904 case NetworkStateTracker.EVENT_STATE_CHANGED:
1905 info = (NetworkInfo) msg.obj;
1906 int type = info.getType();
1907 NetworkInfo.State state = info.getState();
1909 if (DBG) log("ConnectivityChange for " +
1910 info.getTypeName() + ": " +
1911 state + "/" + info.getDetailedState());
1913 // Connectivity state changed:
1914 // [31-13] Reserved for future use
1915 // [12-9] Network subtype (for mobile network, as defined
1916 // by TelephonyManager)
1917 // [8-3] Detailed state ordinal (as defined by
1918 // NetworkInfo.DetailedState)
1919 // [2-0] Network type (as defined by ConnectivityManager)
1920 int eventLogParam = (info.getType() & 0x7) |
1921 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
1922 (info.getSubtype() << 9);
1923 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
1926 if (info.getDetailedState() ==
1927 NetworkInfo.DetailedState.FAILED) {
1928 handleConnectionFailure(info);
1929 } else if (state == NetworkInfo.State.DISCONNECTED) {
1930 handleDisconnect(info);
1931 } else if (state == NetworkInfo.State.SUSPENDED) {
1932 // TODO: need to think this over.
1933 // the logic here is, handle SUSPENDED the same as
1934 // DISCONNECTED. The only difference being we are
1935 // broadcasting an intent with NetworkInfo that's
1936 // suspended. This allows the applications an
1937 // opportunity to handle DISCONNECTED and SUSPENDED
1938 // differently, or not.
1939 handleDisconnect(info);
1940 } else if (state == NetworkInfo.State.CONNECTED) {
1941 handleConnect(info);
1944 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
1945 info = (NetworkInfo) msg.obj;
1946 // TODO: Temporary allowing network configuration
1947 // change not resetting sockets.
1949 handleConnectivityChange(info.getType(), false);
1951 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
1952 String causedBy = null;
1953 synchronized (ConnectivityService.this) {
1954 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
1955 mNetTransitionWakeLock.isHeld()) {
1956 mNetTransitionWakeLock.release();
1957 causedBy = mNetTransitionWakeLockCausedBy;
1960 if (causedBy != null) {
1961 log("NetTransition Wakelock for " + causedBy + " released by timeout");
1964 case EVENT_RESTORE_DEFAULT_NETWORK:
1965 FeatureUser u = (FeatureUser)msg.obj;
1968 case EVENT_INET_CONDITION_CHANGE:
1970 int netType = msg.arg1;
1971 int condition = msg.arg2;
1972 handleInetConditionChange(netType, condition);
1975 case EVENT_INET_CONDITION_HOLD_END:
1977 int netType = msg.arg1;
1978 int sequence = msg.arg2;
1979 handleInetConditionHoldEnd(netType, sequence);
1982 case EVENT_SET_NETWORK_PREFERENCE:
1984 int preference = msg.arg1;
1985 handleSetNetworkPreference(preference);
1988 case EVENT_SET_BACKGROUND_DATA:
1990 boolean enabled = (msg.arg1 == ENABLED);
1991 handleSetBackgroundData(enabled);
1994 case EVENT_SET_MOBILE_DATA:
1996 boolean enabled = (msg.arg1 == ENABLED);
1997 handleSetMobileData(enabled);
2000 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2002 handleDeprecatedGlobalHttpProxy();
2005 case EVENT_SET_DEPENDENCY_MET:
2007 boolean met = (msg.arg1 == ENABLED);
2008 handleSetDependencyMet(msg.arg2, met);
2015 // javadoc from interface
2016 public int tether(String iface) {
2017 enforceTetherChangePermission();
2019 if (isTetheringSupported()) {
2020 return mTethering.tether(iface);
2022 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2026 // javadoc from interface
2027 public int untether(String iface) {
2028 enforceTetherChangePermission();
2030 if (isTetheringSupported()) {
2031 return mTethering.untether(iface);
2033 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2037 // javadoc from interface
2038 public int getLastTetherError(String iface) {
2039 enforceTetherAccessPermission();
2041 if (isTetheringSupported()) {
2042 return mTethering.getLastTetherError(iface);
2044 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2048 // TODO - proper iface API for selection by property, inspection, etc
2049 public String[] getTetherableUsbRegexs() {
2050 enforceTetherAccessPermission();
2051 if (isTetheringSupported()) {
2052 return mTethering.getTetherableUsbRegexs();
2054 return new String[0];
2058 public String[] getTetherableWifiRegexs() {
2059 enforceTetherAccessPermission();
2060 if (isTetheringSupported()) {
2061 return mTethering.getTetherableWifiRegexs();
2063 return new String[0];
2067 public String[] getTetherableBluetoothRegexs() {
2068 enforceTetherAccessPermission();
2069 if (isTetheringSupported()) {
2070 return mTethering.getTetherableBluetoothRegexs();
2072 return new String[0];
2076 // TODO - move iface listing, queries, etc to new module
2077 // javadoc from interface
2078 public String[] getTetherableIfaces() {
2079 enforceTetherAccessPermission();
2080 return mTethering.getTetherableIfaces();
2083 public String[] getTetheredIfaces() {
2084 enforceTetherAccessPermission();
2085 return mTethering.getTetheredIfaces();
2088 public String[] getTetheringErroredIfaces() {
2089 enforceTetherAccessPermission();
2090 return mTethering.getErroredIfaces();
2093 // if ro.tether.denied = true we default to no tethering
2094 // gservices could set the secure setting to 1 though to enable it on a build where it
2095 // had previously been turned off.
2096 public boolean isTetheringSupported() {
2097 enforceTetherAccessPermission();
2098 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2099 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2100 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2101 return tetherEnabledInSettings && mTetheringConfigValid;
2104 // An API NetworkStateTrackers can call when they lose their network.
2105 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2106 // whichever happens first. The timer is started by the first caller and not
2107 // restarted by subsequent callers.
2108 public void requestNetworkTransitionWakelock(String forWhom) {
2109 enforceConnectivityInternalPermission();
2110 synchronized (this) {
2111 if (mNetTransitionWakeLock.isHeld()) return;
2112 mNetTransitionWakeLockSerialNumber++;
2113 mNetTransitionWakeLock.acquire();
2114 mNetTransitionWakeLockCausedBy = forWhom;
2116 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2117 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2118 mNetTransitionWakeLockSerialNumber, 0),
2119 mNetTransitionWakeLockTimeout);
2123 // 100 percent is full good, 0 is full bad.
2124 public void reportInetCondition(int networkType, int percentage) {
2125 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
2126 mContext.enforceCallingOrSelfPermission(
2127 android.Manifest.permission.STATUS_BAR,
2128 "ConnectivityService");
2131 int pid = getCallingPid();
2132 int uid = getCallingUid();
2133 String s = pid + "(" + uid + ") reports inet is " +
2134 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2135 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2137 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2141 mHandler.sendMessage(mHandler.obtainMessage(
2142 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2145 private void handleInetConditionChange(int netType, int condition) {
2147 log("Inet connectivity change, net=" +
2148 netType + ", condition=" + condition +
2149 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2151 if (mActiveDefaultNetwork == -1) {
2152 if (DBG) log("no active default network - aborting");
2155 if (mActiveDefaultNetwork != netType) {
2156 if (DBG) log("given net not default - aborting");
2159 mDefaultInetCondition = condition;
2161 if (mInetConditionChangeInFlight == false) {
2162 if (DBG) log("starting a change hold");
2163 // setup a new hold to debounce this
2164 if (mDefaultInetCondition > 50) {
2165 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2166 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2168 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2169 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2171 mInetConditionChangeInFlight = true;
2172 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2173 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2175 // we've set the new condition, when this hold ends that will get
2177 if (DBG) log("currently in hold - not setting new end evt");
2181 private void handleInetConditionHoldEnd(int netType, int sequence) {
2183 log("Inet hold end, net=" + netType +
2184 ", condition =" + mDefaultInetCondition +
2185 ", published condition =" + mDefaultInetConditionPublished);
2187 mInetConditionChangeInFlight = false;
2189 if (mActiveDefaultNetwork == -1) {
2190 if (DBG) log("no active default network - aborting");
2193 if (mDefaultConnectionSequence != sequence) {
2194 if (DBG) log("event hold for obsolete network - aborting");
2197 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2198 if (DBG) log("no change in condition - aborting");
2201 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2202 if (networkInfo.isConnected() == false) {
2203 if (DBG) log("default network not connected - aborting");
2206 mDefaultInetConditionPublished = mDefaultInetCondition;
2207 sendInetConditionBroadcast(networkInfo);
2211 public synchronized ProxyProperties getProxy() {
2212 if (mGlobalProxy != null) return mGlobalProxy;
2213 if (mDefaultProxy != null) return mDefaultProxy;
2217 public void setGlobalProxy(ProxyProperties proxyProperties) {
2218 enforceChangePermission();
2219 synchronized (mGlobalProxyLock) {
2220 if (proxyProperties == mGlobalProxy) return;
2221 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2222 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2226 String exclList = "";
2227 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2228 mGlobalProxy = new ProxyProperties(proxyProperties);
2229 host = mGlobalProxy.getHost();
2230 port = mGlobalProxy.getPort();
2231 exclList = mGlobalProxy.getExclusionList();
2233 mGlobalProxy = null;
2235 ContentResolver res = mContext.getContentResolver();
2236 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2237 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
2238 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2242 if (mGlobalProxy == null) {
2243 proxyProperties = mDefaultProxy;
2245 sendProxyBroadcast(proxyProperties);
2248 private void loadGlobalProxy() {
2249 ContentResolver res = mContext.getContentResolver();
2250 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2251 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2252 String exclList = Settings.Secure.getString(res,
2253 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2254 if (!TextUtils.isEmpty(host)) {
2255 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2256 synchronized (mGlobalProxyLock) {
2257 mGlobalProxy = proxyProperties;
2262 public ProxyProperties getGlobalProxy() {
2263 synchronized (mGlobalProxyLock) {
2264 return mGlobalProxy;
2268 private void handleApplyDefaultProxy(int type) {
2269 // check if new default - push it out to all VM if so
2270 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2271 synchronized (this) {
2272 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2273 if (mDefaultProxy == proxy) return;
2274 if (!TextUtils.isEmpty(proxy.getHost())) {
2275 mDefaultProxy = proxy;
2277 mDefaultProxy = null;
2280 if (DBG) log("changing default proxy to " + proxy);
2281 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2282 if (mGlobalProxy != null) return;
2283 sendProxyBroadcast(proxy);
2286 private void handleDeprecatedGlobalHttpProxy() {
2287 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2288 Settings.Secure.HTTP_PROXY);
2289 if (!TextUtils.isEmpty(proxy)) {
2290 String data[] = proxy.split(":");
2291 String proxyHost = data[0];
2292 int proxyPort = 8080;
2293 if (data.length > 1) {
2295 proxyPort = Integer.parseInt(data[1]);
2296 } catch (NumberFormatException e) {
2300 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2305 private void sendProxyBroadcast(ProxyProperties proxy) {
2306 if (proxy == null) proxy = new ProxyProperties("", 0, "");
2307 log("sending Proxy Broadcast for " + proxy);
2308 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
2309 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2310 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2311 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
2312 mContext.sendStickyBroadcast(intent);
2315 private static class SettingsObserver extends ContentObserver {
2317 private Handler mHandler;
2318 SettingsObserver(Handler handler, int what) {
2324 void observe(Context context) {
2325 ContentResolver resolver = context.getContentResolver();
2326 resolver.registerContentObserver(Settings.Secure.getUriFor(
2327 Settings.Secure.HTTP_PROXY), false, this);
2331 public void onChange(boolean selfChange) {
2332 mHandler.obtainMessage(mWhat).sendToTarget();
2336 private void log(String s) {
2340 private void loge(String s) {
2343 int convertFeatureToNetworkType(String feature){
2344 int networkType = -1;
2345 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2346 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2347 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2348 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2349 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2350 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2351 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2352 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2353 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2354 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2355 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2356 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2357 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2358 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2359 networkType = ConnectivityManager.TYPE_MOBILE_CBS;