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 public static synchronized ConnectivityService getInstance(Context context) {
254 if (sServiceInstance == null) {
255 sServiceInstance = new ConnectivityService(context);
257 return sServiceInstance;
260 private ConnectivityService(Context context) {
261 if (DBG) log("ConnectivityService starting up");
263 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
264 handlerThread.start();
265 mHandler = new MyHandler(handlerThread.getLooper());
267 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
268 Settings.Secure.BACKGROUND_DATA, 1) == 1);
270 // setup our unique device name
271 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
272 String id = Settings.Secure.getString(context.getContentResolver(),
273 Settings.Secure.ANDROID_ID);
274 if (id != null && id.length() > 0) {
275 String name = new String("android_").concat(id);
276 SystemProperties.set("net.hostname", name);
280 // read our default dns server ip
281 String dns = Settings.Secure.getString(context.getContentResolver(),
282 Settings.Secure.DEFAULT_DNS_SERVER);
283 if (dns == null || dns.length() == 0) {
284 dns = context.getResources().getString(
285 com.android.internal.R.string.config_default_dns_server);
288 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
289 } catch (IllegalArgumentException e) {
290 loge("Error setting defaultDns using " + dns);
295 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
296 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
297 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
298 com.android.internal.R.integer.config_networkTransitionTimeout);
300 mNetTrackers = new NetworkStateTracker[
301 ConnectivityManager.MAX_NETWORK_TYPE+1];
303 mNetworkPreference = getPersistedNetworkPreference();
305 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
306 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
308 // Load device network attributes from resources
309 String[] raStrings = context.getResources().getStringArray(
310 com.android.internal.R.array.radioAttributes);
311 for (String raString : raStrings) {
312 RadioAttributes r = new RadioAttributes(raString);
313 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
314 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
317 if (mRadioAttributes[r.mType] != null) {
318 loge("Error in radioAttributes - ignoring attempt to redefine type " +
322 mRadioAttributes[r.mType] = r;
325 String[] naStrings = context.getResources().getStringArray(
326 com.android.internal.R.array.networkAttributes);
327 for (String naString : naStrings) {
329 NetworkConfig n = new NetworkConfig(naString);
330 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
331 loge("Error in networkAttributes - ignoring attempt to define type " +
335 if (mNetConfigs[n.type] != null) {
336 loge("Error in networkAttributes - ignoring attempt to redefine type " +
340 if (mRadioAttributes[n.radio] == null) {
341 loge("Error in networkAttributes - ignoring attempt to use undefined " +
342 "radio " + n.radio + " in network type " + n.type);
345 mNetConfigs[n.type] = n;
347 } catch(Exception e) {
348 // ignore it - leave the entry null
352 // high priority first
353 mPriorityList = new int[mNetworksDefined];
355 int insertionPoint = mNetworksDefined-1;
356 int currentLowest = 0;
358 while (insertionPoint > -1) {
359 for (NetworkConfig na : mNetConfigs) {
360 if (na == null) continue;
361 if (na.priority < currentLowest) continue;
362 if (na.priority > currentLowest) {
363 if (na.priority < nextLowest || nextLowest == 0) {
364 nextLowest = na.priority;
368 mPriorityList[insertionPoint--] = na.type;
370 currentLowest = nextLowest;
375 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
376 for (int i : mPriorityList) {
377 mNetRequestersPids[i] = new ArrayList();
380 mFeatureUsers = new ArrayList();
384 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
385 && SystemProperties.get("ro.build.type").equals("eng");
387 * Create the network state trackers for Wi-Fi and mobile
388 * data. Maybe this could be done with a factory class,
389 * but it's not clear that it's worth it, given that
390 * the number of different network types is not going
391 * to change very often.
393 for (int netType : mPriorityList) {
394 switch (mNetConfigs[netType].radio) {
395 case ConnectivityManager.TYPE_WIFI:
396 if (DBG) log("Starting Wifi Service.");
397 WifiStateTracker wst = new WifiStateTracker();
398 WifiService wifiService = new WifiService(context);
399 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
400 wifiService.checkAndStartWifi();
401 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
402 wst.startMonitoring(context, mHandler);
404 //TODO: as part of WWS refactor, create only when needed
405 mWifiWatchdogService = new WifiWatchdogService(context);
408 case ConnectivityManager.TYPE_MOBILE:
409 mNetTrackers[netType] = new MobileDataStateTracker(netType,
410 mNetConfigs[netType].name);
411 mNetTrackers[netType].startMonitoring(context, mHandler);
413 case ConnectivityManager.TYPE_DUMMY:
414 mNetTrackers[netType] = new DummyDataStateTracker(netType,
415 mNetConfigs[netType].name);
416 mNetTrackers[netType].startMonitoring(context, mHandler);
418 case ConnectivityManager.TYPE_BLUETOOTH:
419 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
420 mNetTrackers[netType].startMonitoring(context, mHandler);
422 case ConnectivityManager.TYPE_ETHERNET:
423 mNetTrackers[netType] = EthernetDataTracker.getInstance();
424 mNetTrackers[netType].startMonitoring(context, mHandler);
427 loge("Trying to create a DataStateTracker for an unknown radio type " +
428 mNetConfigs[netType].radio);
433 mTethering = new Tethering(mContext, mHandler.getLooper());
434 mTetheringConfigValid = (((mNetTrackers[ConnectivityManager.TYPE_MOBILE_DUN] != null) ||
435 !mTethering.isDunRequired()) &&
436 (mTethering.getTetherableUsbRegexs().length != 0 ||
437 mTethering.getTetherableWifiRegexs().length != 0 ||
438 mTethering.getTetherableBluetoothRegexs().length != 0) &&
439 mTethering.getUpstreamIfaceRegexs().length != 0);
442 mInetLog = new ArrayList();
445 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
446 mSettingsObserver.observe(mContext);
450 VpnManager.startVpnService(context);
455 * Sets the preferred network.
456 * @param preference the new preference
458 public void setNetworkPreference(int preference) {
459 enforceChangePermission();
461 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
464 public int getNetworkPreference() {
465 enforceAccessPermission();
468 preference = mNetworkPreference;
473 private void handleSetNetworkPreference(int preference) {
474 if (ConnectivityManager.isNetworkTypeValid(preference) &&
475 mNetConfigs[preference] != null &&
476 mNetConfigs[preference].isDefault()) {
477 if (mNetworkPreference != preference) {
478 final ContentResolver cr = mContext.getContentResolver();
479 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
481 mNetworkPreference = preference;
488 private int getPersistedNetworkPreference() {
489 final ContentResolver cr = mContext.getContentResolver();
491 final int networkPrefSetting = Settings.Secure
492 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
493 if (networkPrefSetting != -1) {
494 return networkPrefSetting;
497 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
501 * Make the state of network connectivity conform to the preference settings
502 * In this method, we only tear down a non-preferred network. Establishing
503 * a connection to the preferred network is taken care of when we handle
504 * the disconnect event from the non-preferred network
505 * (see {@link #handleDisconnect(NetworkInfo)}).
507 private void enforcePreference() {
508 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
511 if (!mNetTrackers[mNetworkPreference].isAvailable())
514 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
515 if (t != mNetworkPreference && mNetTrackers[t] != null &&
516 mNetTrackers[t].getNetworkInfo().isConnected()) {
518 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
519 " in enforcePreference");
521 teardown(mNetTrackers[t]);
526 private boolean teardown(NetworkStateTracker netTracker) {
527 if (netTracker.teardown()) {
528 netTracker.setTeardownRequested(true);
536 * Return NetworkInfo for the active (i.e., connected) network interface.
537 * It is assumed that at most one network is active at a time. If more
538 * than one is active, it is indeterminate which will be returned.
539 * @return the info for the active network, or {@code null} if none is
542 public NetworkInfo getActiveNetworkInfo() {
543 return getNetworkInfo(mActiveDefaultNetwork);
546 public NetworkInfo getNetworkInfo(int networkType) {
547 enforceAccessPermission();
548 if (ConnectivityManager.isNetworkTypeValid(networkType)) {
549 NetworkStateTracker t = mNetTrackers[networkType];
551 return t.getNetworkInfo();
556 public NetworkInfo[] getAllNetworkInfo() {
557 enforceAccessPermission();
558 NetworkInfo[] result = new NetworkInfo[mNetworksDefined];
560 for (NetworkStateTracker t : mNetTrackers) {
561 if(t != null) result[i++] = t.getNetworkInfo();
567 * Return LinkProperties for the active (i.e., connected) default
568 * network interface. It is assumed that at most one default network
569 * is active at a time. If more than one is active, it is indeterminate
570 * which will be returned.
571 * @return the ip properties for the active network, or {@code null} if
574 public LinkProperties getActiveLinkProperties() {
575 return getLinkProperties(mActiveDefaultNetwork);
578 public LinkProperties getLinkProperties(int networkType) {
579 enforceAccessPermission();
580 if (ConnectivityManager.isNetworkTypeValid(networkType)) {
581 NetworkStateTracker t = mNetTrackers[networkType];
582 if (t != null) return t.getLinkProperties();
587 public boolean setRadios(boolean turnOn) {
588 boolean result = true;
589 enforceChangePermission();
590 for (NetworkStateTracker t : mNetTrackers) {
591 if (t != null) result = t.setRadio(turnOn) && result;
596 public boolean setRadio(int netType, boolean turnOn) {
597 enforceChangePermission();
598 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
601 NetworkStateTracker tracker = mNetTrackers[netType];
602 return tracker != null && tracker.setRadio(turnOn);
606 * Used to notice when the calling process dies so we can self-expire
608 * Also used to know if the process has cleaned up after itself when
609 * our auto-expire timer goes off. The timer has a link to an object.
612 private class FeatureUser implements IBinder.DeathRecipient {
620 FeatureUser(int type, String feature, IBinder binder) {
625 mPid = getCallingPid();
626 mUid = getCallingUid();
627 mCreateTime = System.currentTimeMillis();
630 mBinder.linkToDeath(this, 0);
631 } catch (RemoteException e) {
636 void unlinkDeathRecipient() {
637 mBinder.unlinkToDeath(this, 0);
640 public void binderDied() {
641 log("ConnectivityService FeatureUser binderDied(" +
642 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
643 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
644 stopUsingNetworkFeature(this, false);
647 public void expire() {
648 log("ConnectivityService FeatureUser expire(" +
649 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
650 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
651 stopUsingNetworkFeature(this, false);
654 public String toString() {
655 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
656 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
660 // javadoc from interface
661 public int startUsingNetworkFeature(int networkType, String feature,
664 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
666 enforceChangePermission();
667 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
668 mNetConfigs[networkType] == null) {
669 return Phone.APN_REQUEST_FAILED;
672 FeatureUser f = new FeatureUser(networkType, feature, binder);
674 // TODO - move this into the MobileDataStateTracker
675 int usedNetworkType = networkType;
676 if(networkType == ConnectivityManager.TYPE_MOBILE) {
677 usedNetworkType = convertFeatureToNetworkType(feature);
678 if (usedNetworkType < 0) {
679 Slog.e(TAG, "Can't match any netTracker!");
680 usedNetworkType = networkType;
683 NetworkStateTracker network = mNetTrackers[usedNetworkType];
684 if (network != null) {
685 Integer currentPid = new Integer(getCallingPid());
686 if (usedNetworkType != networkType) {
687 NetworkStateTracker radio = mNetTrackers[networkType];
688 NetworkInfo ni = network.getNetworkInfo();
690 if (ni.isAvailable() == false) {
691 if (DBG) log("special network not available");
692 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
693 return Phone.APN_TYPE_NOT_AVAILABLE;
695 // else make the attempt anyway - probably giving REQUEST_STARTED below
700 mFeatureUsers.add(f);
701 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
702 // this gets used for per-pid dns when connected
703 mNetRequestersPids[usedNetworkType].add(currentPid);
707 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
709 if (restoreTimer >= 0) {
710 mHandler.sendMessageDelayed(
711 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
714 if ((ni.isConnectedOrConnecting() == true) &&
715 !network.isTeardownRequested()) {
716 if (ni.isConnected() == true) {
717 // add the pid-specific dns
718 handleDnsConfigurationChange(networkType);
719 if (DBG) log("special network already active");
720 return Phone.APN_ALREADY_ACTIVE;
722 if (DBG) log("special network already connecting");
723 return Phone.APN_REQUEST_STARTED;
726 // check if the radio in play can make another contact
727 // assume if cannot for now
729 if (DBG) log("reconnecting to special network");
731 return Phone.APN_REQUEST_STARTED;
733 // need to remember this unsupported request so we respond appropriately on stop
735 mFeatureUsers.add(f);
736 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
737 // this gets used for per-pid dns when connected
738 mNetRequestersPids[usedNetworkType].add(currentPid);
744 return Phone.APN_TYPE_NOT_AVAILABLE;
747 // javadoc from interface
748 public int stopUsingNetworkFeature(int networkType, String feature) {
749 enforceChangePermission();
751 int pid = getCallingPid();
752 int uid = getCallingUid();
754 FeatureUser u = null;
755 boolean found = false;
758 for (int i = 0; i < mFeatureUsers.size() ; i++) {
759 u = (FeatureUser)mFeatureUsers.get(i);
760 if (uid == u.mUid && pid == u.mPid &&
761 networkType == u.mNetworkType &&
762 TextUtils.equals(feature, u.mFeature)) {
768 if (found && u != null) {
769 // stop regardless of how many other time this proc had called start
770 return stopUsingNetworkFeature(u, true);
773 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
778 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
779 int networkType = u.mNetworkType;
780 String feature = u.mFeature;
784 NetworkStateTracker tracker = null;
785 boolean callTeardown = false; // used to carry our decision outside of sync block
788 log("stopUsingNetworkFeature for net " + networkType +
792 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
796 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
799 // check if this process still has an outstanding start request
800 if (!mFeatureUsers.contains(u)) {
801 if (DBG) log("ignoring - this process has no outstanding requests");
804 u.unlinkDeathRecipient();
805 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
806 // If we care about duplicate requests, check for that here.
808 // This is done to support the extension of a request - the app
809 // can request we start the network feature again and renew the
810 // auto-shutoff delay. Normal "stop" calls from the app though
811 // do not pay attention to duplicate requests - in effect the
812 // API does not refcount and a single stop will counter multiple starts.
813 if (ignoreDups == false) {
814 for (int i = 0; i < mFeatureUsers.size() ; i++) {
815 FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
816 if (x.mUid == u.mUid && x.mPid == u.mPid &&
817 x.mNetworkType == u.mNetworkType &&
818 TextUtils.equals(x.mFeature, u.mFeature)) {
819 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
825 // TODO - move to MobileDataStateTracker
826 int usedNetworkType = networkType;
827 if (networkType == ConnectivityManager.TYPE_MOBILE) {
828 usedNetworkType = convertFeatureToNetworkType(feature);
829 if (usedNetworkType < 0) {
830 usedNetworkType = networkType;
833 tracker = mNetTrackers[usedNetworkType];
834 if (tracker == null) {
835 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
838 if (usedNetworkType != networkType) {
839 Integer currentPid = new Integer(pid);
840 mNetRequestersPids[usedNetworkType].remove(currentPid);
841 reassessPidDns(pid, true);
842 if (mNetRequestersPids[usedNetworkType].size() != 0) {
843 if (DBG) log("not tearing down special network - " +
844 "others still using it");
849 if (DBG) log("not a known feature - dropping");
852 if (DBG) log("Doing network teardown");
862 * @deprecated use requestRouteToHostAddress instead
864 * Ensure that a network route exists to deliver traffic to the specified
865 * host via the specified network interface.
866 * @param networkType the type of the network over which traffic to the
867 * specified host is to be routed
868 * @param hostAddress the IP address of the host to which the route is
870 * @return {@code true} on success, {@code false} on failure
872 public boolean requestRouteToHost(int networkType, int hostAddress) {
873 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
875 if (inetAddress == null) {
879 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
883 * Ensure that a network route exists to deliver traffic to the specified
884 * host via the specified network interface.
885 * @param networkType the type of the network over which traffic to the
886 * specified host is to be routed
887 * @param hostAddress the IP address of the host to which the route is
889 * @return {@code true} on success, {@code false} on failure
891 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
892 enforceChangePermission();
893 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
896 NetworkStateTracker tracker = mNetTrackers[networkType];
898 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
899 tracker.isTeardownRequested()) {
901 log("requestRouteToHostAddress on down network " +
902 "(" + networkType + ") - dropped");
907 InetAddress addr = InetAddress.getByAddress(hostAddress);
908 return addHostRoute(tracker, addr, 0);
909 } catch (UnknownHostException e) {}
914 * Ensure that a network route exists to deliver traffic to the specified
915 * host via the mobile data network.
916 * @param hostAddress the IP address of the host to which the route is desired,
917 * in network byte order.
919 * @return {@code true} on success, {@code false} on failure
921 private boolean addHostRoute(NetworkStateTracker nt, InetAddress hostAddress, int cycleCount) {
922 LinkProperties lp = nt.getLinkProperties();
923 if ((lp == null) || (hostAddress == null)) return false;
925 String interfaceName = lp.getInterfaceName();
927 log("Requested host route to " + hostAddress + "(" + interfaceName + "), cycleCount=" +
930 if (interfaceName == null) {
931 if (DBG) loge("addHostRoute failed due to null interface name");
935 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), hostAddress);
936 InetAddress gatewayAddress = null;
937 if (bestRoute != null) {
938 gatewayAddress = bestRoute.getGateway();
939 // if the best route is ourself, don't relf-reference, just add the host route
940 if (hostAddress.equals(gatewayAddress)) gatewayAddress = null;
942 if (gatewayAddress != null) {
943 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
944 loge("Error adding hostroute - too much recursion");
947 if (!addHostRoute(nt, gatewayAddress, cycleCount+1)) return false;
950 RouteInfo route = RouteInfo.makeHostRoute(hostAddress, gatewayAddress);
953 mNetd.addRoute(interfaceName, route);
955 } catch (Exception ex) {
960 // TODO support the removal of single host routes. Keep a ref count of them so we
961 // aren't over-zealous
962 private boolean removeHostRoute(NetworkStateTracker nt, InetAddress hostAddress) {
967 * @see ConnectivityManager#getBackgroundDataSetting()
969 public boolean getBackgroundDataSetting() {
970 return mBackgroundDataEnabled.get();
974 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
976 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
977 mContext.enforceCallingOrSelfPermission(
978 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
979 "ConnectivityService");
981 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
983 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
984 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
987 private void handleSetBackgroundData(boolean enabled) {
988 Settings.Secure.putInt(mContext.getContentResolver(),
989 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
990 Intent broadcast = new Intent(
991 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
992 mContext.sendBroadcast(broadcast);
996 * @see ConnectivityManager#getMobileDataEnabled()
998 public boolean getMobileDataEnabled() {
999 // TODO: This detail should probably be in DataConnectionTracker's
1000 // which is where we store the value and maybe make this
1002 enforceAccessPermission();
1003 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1004 Settings.Secure.MOBILE_DATA, 1) == 1;
1005 if (DBG) log("getMobileDataEnabled returning " + retVal);
1009 public void setDataDependency(int networkType, boolean met) {
1010 enforceChangePermission();
1012 log("setDataDependency(" + networkType + ", " + met + ")");
1014 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1015 (met ? ENABLED : DISABLED), networkType));
1018 private void handleSetDependencyMet(int networkType, boolean met) {
1019 if (mNetTrackers[networkType] != null) {
1021 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1023 mNetTrackers[networkType].setDependencyMet(met);
1028 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1030 public void setMobileDataEnabled(boolean enabled) {
1031 enforceChangePermission();
1032 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
1034 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
1035 (enabled ? ENABLED : DISABLED), 0));
1038 private void handleSetMobileData(boolean enabled) {
1039 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1041 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
1043 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
1047 private void enforceAccessPermission() {
1048 mContext.enforceCallingOrSelfPermission(
1049 android.Manifest.permission.ACCESS_NETWORK_STATE,
1050 "ConnectivityService");
1053 private void enforceChangePermission() {
1054 mContext.enforceCallingOrSelfPermission(
1055 android.Manifest.permission.CHANGE_NETWORK_STATE,
1056 "ConnectivityService");
1059 // TODO Make this a special check when it goes public
1060 private void enforceTetherChangePermission() {
1061 mContext.enforceCallingOrSelfPermission(
1062 android.Manifest.permission.CHANGE_NETWORK_STATE,
1063 "ConnectivityService");
1066 private void enforceTetherAccessPermission() {
1067 mContext.enforceCallingOrSelfPermission(
1068 android.Manifest.permission.ACCESS_NETWORK_STATE,
1069 "ConnectivityService");
1072 private void enforceConnectivityInternalPermission() {
1073 mContext.enforceCallingOrSelfPermission(
1074 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1075 "ConnectivityService");
1079 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1080 * network, we ignore it. If it is for the active network, we send out a
1081 * broadcast. But first, we check whether it might be possible to connect
1082 * to a different network.
1083 * @param info the {@code NetworkInfo} for the network
1085 private void handleDisconnect(NetworkInfo info) {
1087 int prevNetType = info.getType();
1089 mNetTrackers[prevNetType].setTeardownRequested(false);
1091 * If the disconnected network is not the active one, then don't report
1092 * this as a loss of connectivity. What probably happened is that we're
1093 * getting the disconnect for a network that we explicitly disabled
1094 * in accordance with network preference policies.
1096 if (!mNetConfigs[prevNetType].isDefault()) {
1097 List pids = mNetRequestersPids[prevNetType];
1098 for (int i = 0; i<pids.size(); i++) {
1099 Integer pid = (Integer)pids.get(i);
1100 // will remove them because the net's no longer connected
1101 // need to do this now as only now do we know the pids and
1102 // can properly null things that are no longer referenced.
1103 reassessPidDns(pid.intValue(), false);
1107 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1108 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1109 if (info.isFailover()) {
1110 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1111 info.setFailover(false);
1113 if (info.getReason() != null) {
1114 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1116 if (info.getExtraInfo() != null) {
1117 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1118 info.getExtraInfo());
1121 if (mNetConfigs[prevNetType].isDefault()) {
1122 tryFailover(prevNetType);
1123 if (mActiveDefaultNetwork != -1) {
1124 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1125 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1127 mDefaultInetConditionPublished = 0; // we're not connected anymore
1128 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1131 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1133 // Reset interface if no other connections are using the same interface
1134 boolean doReset = true;
1135 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1136 if (linkProperties != null) {
1137 String oldIface = linkProperties.getInterfaceName();
1138 if (TextUtils.isEmpty(oldIface) == false) {
1139 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1140 if (networkStateTracker == null) continue;
1141 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1142 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1143 LinkProperties l = networkStateTracker.getLinkProperties();
1144 if (l == null) continue;
1145 if (oldIface.equals(l.getInterfaceName())) {
1154 // do this before we broadcast the change
1155 handleConnectivityChange(prevNetType, doReset);
1157 sendStickyBroadcast(intent);
1159 * If the failover network is already connected, then immediately send
1160 * out a followup broadcast indicating successful failover
1162 if (mActiveDefaultNetwork != -1) {
1163 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
1167 private void tryFailover(int prevNetType) {
1169 * If this is a default network, check if other defaults are available.
1170 * Try to reconnect on all available and let them hash it out when
1171 * more than one connects.
1173 if (mNetConfigs[prevNetType].isDefault()) {
1174 if (mActiveDefaultNetwork == prevNetType) {
1175 mActiveDefaultNetwork = -1;
1178 // don't signal a reconnect for anything lower or equal priority than our
1179 // current connected default
1180 // TODO - don't filter by priority now - nice optimization but risky
1181 // int currentPriority = -1;
1182 // if (mActiveDefaultNetwork != -1) {
1183 // currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
1185 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
1186 if (checkType == prevNetType) continue;
1187 if (mNetConfigs[checkType] == null) continue;
1188 if (!mNetConfigs[checkType].isDefault()) continue;
1190 // Enabling the isAvailable() optimization caused mobile to not get
1191 // selected if it was in the middle of error handling. Specifically
1192 // a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1193 // would not be available and we wouldn't get connected to anything.
1194 // So removing the isAvailable() optimization below for now. TODO: This
1195 // optimization should work and we need to investigate why it doesn't work.
1196 // This could be related to how DEACTIVATE_DATA_CALL is reporting its
1197 // complete before it is really complete.
1198 // if (!mNetTrackers[checkType].isAvailable()) continue;
1200 // if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
1202 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1203 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1204 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1205 checkInfo.setFailover(true);
1206 checkTracker.reconnect();
1208 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
1213 private void sendConnectedBroadcast(NetworkInfo info) {
1214 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1217 private void sendInetConditionBroadcast(NetworkInfo info) {
1218 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1221 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1222 Intent intent = new Intent(bcastType);
1223 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1224 if (info.isFailover()) {
1225 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1226 info.setFailover(false);
1228 if (info.getReason() != null) {
1229 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1231 if (info.getExtraInfo() != null) {
1232 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1233 info.getExtraInfo());
1235 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1236 sendStickyBroadcast(intent);
1240 * Called when an attempt to fail over to another network has failed.
1241 * @param info the {@link NetworkInfo} for the failed network
1243 private void handleConnectionFailure(NetworkInfo info) {
1244 mNetTrackers[info.getType()].setTeardownRequested(false);
1246 String reason = info.getReason();
1247 String extraInfo = info.getExtraInfo();
1250 if (reason == null) {
1253 reasonText = " (" + reason + ").";
1255 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
1257 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1258 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1259 if (getActiveNetworkInfo() == null) {
1260 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1262 if (reason != null) {
1263 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1265 if (extraInfo != null) {
1266 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1268 if (info.isFailover()) {
1269 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1270 info.setFailover(false);
1273 if (mNetConfigs[info.getType()].isDefault()) {
1274 tryFailover(info.getType());
1275 if (mActiveDefaultNetwork != -1) {
1276 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1277 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1279 mDefaultInetConditionPublished = 0;
1280 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1284 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1285 sendStickyBroadcast(intent);
1287 * If the failover network is already connected, then immediately send
1288 * out a followup broadcast indicating successful failover
1290 if (mActiveDefaultNetwork != -1) {
1291 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
1295 private void sendStickyBroadcast(Intent intent) {
1296 synchronized(this) {
1297 if (!mSystemReady) {
1298 mInitialBroadcast = new Intent(intent);
1300 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1301 mContext.sendStickyBroadcast(intent);
1305 void systemReady() {
1306 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
1307 mNetd = INetworkManagementService.Stub.asInterface(b);
1309 synchronized(this) {
1310 mSystemReady = true;
1311 if (mInitialBroadcast != null) {
1312 mContext.sendStickyBroadcast(mInitialBroadcast);
1313 mInitialBroadcast = null;
1316 // load the global proxy at startup
1317 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
1320 private void handleConnect(NetworkInfo info) {
1321 int type = info.getType();
1323 // snapshot isFailover, because sendConnectedBroadcast() resets it
1324 boolean isFailover = info.isFailover();
1325 NetworkStateTracker thisNet = mNetTrackers[type];
1327 // if this is a default net and other default is running
1328 // kill the one not preferred
1329 if (mNetConfigs[type].isDefault()) {
1330 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1331 if ((type != mNetworkPreference &&
1332 mNetConfigs[mActiveDefaultNetwork].priority >
1333 mNetConfigs[type].priority) ||
1334 mNetworkPreference == mActiveDefaultNetwork) {
1335 // don't accept this one
1337 log("Not broadcasting CONNECT_ACTION " +
1338 "to torn down network " + info.getTypeName());
1343 // tear down the other
1344 NetworkStateTracker otherNet =
1345 mNetTrackers[mActiveDefaultNetwork];
1347 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
1350 if (!teardown(otherNet)) {
1351 loge("Network declined teardown request");
1356 synchronized (ConnectivityService.this) {
1357 // have a new default network, release the transition wakelock in a second
1358 // if it's held. The second pause is to allow apps to reconnect over the
1360 if (mNetTransitionWakeLock.isHeld()) {
1361 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1362 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
1363 mNetTransitionWakeLockSerialNumber, 0),
1367 mActiveDefaultNetwork = type;
1368 // this will cause us to come up initially as unconnected and switching
1369 // to connected after our normal pause unless somebody reports us as reall
1371 mDefaultInetConditionPublished = 0;
1372 mDefaultConnectionSequence++;
1373 mInetConditionChangeInFlight = false;
1374 // Don't do this - if we never sign in stay, grey
1375 //reportNetworkCondition(mActiveDefaultNetwork, 100);
1377 thisNet.setTeardownRequested(false);
1378 updateNetworkSettings(thisNet);
1379 handleConnectivityChange(type, false);
1380 sendConnectedBroadcast(info);
1384 * After a change in the connectivity state of a network. We're mainly
1385 * concerned with making sure that the list of DNS servers is set up
1386 * according to which networks are connected, and ensuring that the
1387 * right routing table entries exist.
1389 private void handleConnectivityChange(int netType, boolean doReset) {
1391 * If a non-default network is enabled, add the host routes that
1392 * will allow it's DNS servers to be accessed.
1394 handleDnsConfigurationChange(netType);
1396 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
1397 if (mNetConfigs[netType].isDefault()) {
1398 handleApplyDefaultProxy(netType);
1399 addDefaultRoute(mNetTrackers[netType]);
1401 addPrivateDnsRoutes(mNetTrackers[netType]);
1404 /** Notify TetheringService if interface name has been changed. */
1405 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1406 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1407 handleTetherIfaceChange(netType);
1410 if (mNetConfigs[netType].isDefault()) {
1411 removeDefaultRoute(mNetTrackers[netType]);
1413 removePrivateDnsRoutes(mNetTrackers[netType]);
1418 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1419 if (linkProperties != null) {
1420 String iface = linkProperties.getInterfaceName();
1421 if (TextUtils.isEmpty(iface) == false) {
1422 if (DBG) log("resetConnections(" + iface + ")");
1423 NetworkUtils.resetConnections(iface);
1429 private void addPrivateDnsRoutes(NetworkStateTracker nt) {
1430 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1431 LinkProperties p = nt.getLinkProperties();
1432 if (p == null) return;
1433 String interfaceName = p.getInterfaceName();
1436 log("addPrivateDnsRoutes for " + nt +
1437 "(" + interfaceName + ") - mPrivateDnsRouteSet = " + privateDnsRouteSet);
1439 if (interfaceName != null && !privateDnsRouteSet) {
1440 Collection<InetAddress> dnsList = p.getDnses();
1441 for (InetAddress dns : dnsList) {
1442 addHostRoute(nt, dns, 0);
1444 nt.privateDnsRouteSet(true);
1448 private void removePrivateDnsRoutes(NetworkStateTracker nt) {
1449 LinkProperties p = nt.getLinkProperties();
1450 if (p == null) return;
1451 String interfaceName = p.getInterfaceName();
1452 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1453 if (interfaceName != null && privateDnsRouteSet) {
1455 log("removePrivateDnsRoutes for " + nt.getNetworkInfo().getTypeName() +
1456 " (" + interfaceName + ")");
1459 Collection<InetAddress> dnsList = p.getDnses();
1460 for (InetAddress dns : dnsList) {
1461 if (DBG) log(" removing " + dns);
1462 RouteInfo route = RouteInfo.makeHostRoute(dns);
1464 mNetd.removeRoute(interfaceName, route);
1465 } catch (Exception ex) {
1466 loge("error (" + ex + ") removing dns route " + route);
1469 nt.privateDnsRouteSet(false);
1474 private void addDefaultRoute(NetworkStateTracker nt) {
1475 LinkProperties p = nt.getLinkProperties();
1476 if (p == null) return;
1477 String interfaceName = p.getInterfaceName();
1478 if (TextUtils.isEmpty(interfaceName)) return;
1480 for (RouteInfo route : p.getRoutes()) {
1481 //TODO - handle non-default routes
1482 if (route.isDefaultRoute()) {
1483 if (DBG) log("adding default route " + route);
1484 InetAddress gateway = route.getGateway();
1485 if (addHostRoute(nt, gateway, 0)) {
1487 mNetd.addRoute(interfaceName, route);
1488 } catch (Exception e) {
1489 loge("error adding default route " + route);
1493 NetworkInfo networkInfo = nt.getNetworkInfo();
1494 log("addDefaultRoute for " + networkInfo.getTypeName() +
1495 " (" + interfaceName + "), GatewayAddr=" +
1496 gateway.getHostAddress());
1499 loge("error adding host route for default route " + route);
1506 public void removeDefaultRoute(NetworkStateTracker nt) {
1507 LinkProperties p = nt.getLinkProperties();
1508 if (p == null) return;
1509 String interfaceName = p.getInterfaceName();
1511 if (interfaceName == null) return;
1513 for (RouteInfo route : p.getRoutes()) {
1514 //TODO - handle non-default routes
1515 if (route.isDefaultRoute()) {
1517 mNetd.removeRoute(interfaceName, route);
1518 } catch (Exception ex) {
1519 loge("error (" + ex + ") removing default route " + route);
1523 NetworkInfo networkInfo = nt.getNetworkInfo();
1524 log("removeDefaultRoute for " + networkInfo.getTypeName() + " (" +
1525 interfaceName + ")");
1532 * Reads the network specific TCP buffer sizes from SystemProperties
1533 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1536 public void updateNetworkSettings(NetworkStateTracker nt) {
1537 String key = nt.getTcpBufferSizesPropName();
1538 String bufferSizes = SystemProperties.get(key);
1540 if (bufferSizes.length() == 0) {
1541 loge(key + " not found in system properties. Using defaults");
1543 // Setting to default values so we won't be stuck to previous values
1544 key = "net.tcp.buffersize.default";
1545 bufferSizes = SystemProperties.get(key);
1548 // Set values in kernel
1549 if (bufferSizes.length() != 0) {
1551 log("Setting TCP values: [" + bufferSizes
1552 + "] which comes from [" + key + "]");
1554 setBufferSize(bufferSizes);
1559 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1560 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1562 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1563 * writeMin, writeInitial, writeMax"
1565 private void setBufferSize(String bufferSizes) {
1567 String[] values = bufferSizes.split(",");
1569 if (values.length == 6) {
1570 final String prefix = "/sys/kernel/ipv4/tcp_";
1571 stringToFile(prefix + "rmem_min", values[0]);
1572 stringToFile(prefix + "rmem_def", values[1]);
1573 stringToFile(prefix + "rmem_max", values[2]);
1574 stringToFile(prefix + "wmem_min", values[3]);
1575 stringToFile(prefix + "wmem_def", values[4]);
1576 stringToFile(prefix + "wmem_max", values[5]);
1578 loge("Invalid buffersize string: " + bufferSizes);
1580 } catch (IOException e) {
1581 loge("Can't set tcp buffer sizes:" + e);
1586 * Writes string to file. Basically same as "echo -n $string > $filename"
1590 * @throws IOException
1592 private void stringToFile(String filename, String string) throws IOException {
1593 FileWriter out = new FileWriter(filename);
1603 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1604 * on the highest priority active net which this process requested.
1605 * If there aren't any, clear it out
1607 private void reassessPidDns(int myPid, boolean doBump)
1609 if (DBG) log("reassessPidDns for pid " + myPid);
1610 for(int i : mPriorityList) {
1611 if (mNetConfigs[i].isDefault()) {
1614 NetworkStateTracker nt = mNetTrackers[i];
1615 if (nt.getNetworkInfo().isConnected() &&
1616 !nt.isTeardownRequested()) {
1617 LinkProperties p = nt.getLinkProperties();
1618 if (p == null) continue;
1619 List pids = mNetRequestersPids[i];
1620 for (int j=0; j<pids.size(); j++) {
1621 Integer pid = (Integer)pids.get(j);
1622 if (pid.intValue() == myPid) {
1623 Collection<InetAddress> dnses = p.getDnses();
1624 writePidDns(dnses, myPid);
1633 // nothing found - delete
1634 for (int i = 1; ; i++) {
1635 String prop = "net.dns" + i + "." + myPid;
1636 if (SystemProperties.get(prop).length() == 0) {
1642 SystemProperties.set(prop, "");
1646 // return true if results in a change
1647 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
1649 boolean changed = false;
1650 for (InetAddress dns : dnses) {
1651 String dnsString = dns.getHostAddress();
1652 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1654 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1660 private void bumpDns() {
1662 * Bump the property that tells the name resolver library to reread
1663 * the DNS server list from the properties.
1665 String propVal = SystemProperties.get("net.dnschange");
1667 if (propVal.length() != 0) {
1669 n = Integer.parseInt(propVal);
1670 } catch (NumberFormatException e) {}
1672 SystemProperties.set("net.dnschange", "" + (n+1));
1674 * Tell the VMs to toss their DNS caches
1676 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1677 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1679 * Connectivity events can happen before boot has completed ...
1681 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1682 mContext.sendBroadcast(intent);
1685 private void handleDnsConfigurationChange(int netType) {
1686 // add default net's dns entries
1687 NetworkStateTracker nt = mNetTrackers[netType];
1688 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
1689 LinkProperties p = nt.getLinkProperties();
1690 if (p == null) return;
1691 Collection<InetAddress> dnses = p.getDnses();
1692 boolean changed = false;
1693 if (mNetConfigs[netType].isDefault()) {
1695 if (dnses.size() == 0 && mDefaultDns != null) {
1696 String dnsString = mDefaultDns.getHostAddress();
1697 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1699 log("no dns provided - using " + dnsString);
1702 SystemProperties.set("net.dns1", dnsString);
1706 for (InetAddress dns : dnses) {
1707 String dnsString = dns.getHostAddress();
1708 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1713 log("adding dns " + dns + " for " +
1714 nt.getNetworkInfo().getTypeName());
1717 SystemProperties.set("net.dns" + j++, dnsString);
1720 for (int k=j ; k<mNumDnsEntries; k++) {
1721 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1722 if (DBG) log("erasing net.dns" + k);
1724 SystemProperties.set("net.dns" + k, "");
1729 // set per-pid dns for attached secondary nets
1730 List pids = mNetRequestersPids[netType];
1731 for (int y=0; y< pids.size(); y++) {
1732 Integer pid = (Integer)pids.get(y);
1733 changed = writePidDns(dnses, pid.intValue());
1736 if (changed) bumpDns();
1740 private int getRestoreDefaultNetworkDelay(int networkType) {
1741 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1742 NETWORK_RESTORE_DELAY_PROP_NAME);
1743 if(restoreDefaultNetworkDelayStr != null &&
1744 restoreDefaultNetworkDelayStr.length() != 0) {
1746 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1747 } catch (NumberFormatException e) {
1750 // if the system property isn't set, use the value for the apn type
1751 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1753 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1754 (mNetConfigs[networkType] != null)) {
1755 ret = mNetConfigs[networkType].restoreTime;
1761 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1762 if (mContext.checkCallingOrSelfPermission(
1763 android.Manifest.permission.DUMP)
1764 != PackageManager.PERMISSION_GRANTED) {
1765 pw.println("Permission Denial: can't dump ConnectivityService " +
1766 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1767 Binder.getCallingUid());
1771 for (NetworkStateTracker nst : mNetTrackers) {
1773 if (nst.getNetworkInfo().isConnected()) {
1774 pw.println("Active network: " + nst.getNetworkInfo().
1777 pw.println(nst.getNetworkInfo());
1783 pw.println("Network Requester Pids:");
1784 for (int net : mPriorityList) {
1785 String pidString = net + ": ";
1786 for (Object pid : mNetRequestersPids[net]) {
1787 pidString = pidString + pid.toString() + ", ";
1789 pw.println(pidString);
1793 pw.println("FeatureUsers:");
1794 for (Object requester : mFeatureUsers) {
1795 pw.println(requester.toString());
1799 synchronized (this) {
1800 pw.println("NetworkTranstionWakeLock is currently " +
1801 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1802 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1806 mTethering.dump(fd, pw, args);
1808 if (mInetLog != null) {
1810 pw.println("Inet condition reports:");
1811 for(int i = 0; i < mInetLog.size(); i++) {
1812 pw.println(mInetLog.get(i));
1817 // must be stateless - things change under us.
1818 private class MyHandler extends Handler {
1819 public MyHandler(Looper looper) {
1824 public void handleMessage(Message msg) {
1827 case NetworkStateTracker.EVENT_STATE_CHANGED:
1828 info = (NetworkInfo) msg.obj;
1829 int type = info.getType();
1830 NetworkInfo.State state = info.getState();
1832 if (DBG) log("ConnectivityChange for " +
1833 info.getTypeName() + ": " +
1834 state + "/" + info.getDetailedState());
1836 // Connectivity state changed:
1837 // [31-13] Reserved for future use
1838 // [12-9] Network subtype (for mobile network, as defined
1839 // by TelephonyManager)
1840 // [8-3] Detailed state ordinal (as defined by
1841 // NetworkInfo.DetailedState)
1842 // [2-0] Network type (as defined by ConnectivityManager)
1843 int eventLogParam = (info.getType() & 0x7) |
1844 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
1845 (info.getSubtype() << 9);
1846 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
1849 if (info.getDetailedState() ==
1850 NetworkInfo.DetailedState.FAILED) {
1851 handleConnectionFailure(info);
1852 } else if (state == NetworkInfo.State.DISCONNECTED) {
1853 handleDisconnect(info);
1854 } else if (state == NetworkInfo.State.SUSPENDED) {
1855 // TODO: need to think this over.
1856 // the logic here is, handle SUSPENDED the same as
1857 // DISCONNECTED. The only difference being we are
1858 // broadcasting an intent with NetworkInfo that's
1859 // suspended. This allows the applications an
1860 // opportunity to handle DISCONNECTED and SUSPENDED
1861 // differently, or not.
1862 handleDisconnect(info);
1863 } else if (state == NetworkInfo.State.CONNECTED) {
1864 handleConnect(info);
1867 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
1868 info = (NetworkInfo) msg.obj;
1869 handleConnectivityChange(info.getType(), true);
1871 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
1872 String causedBy = null;
1873 synchronized (ConnectivityService.this) {
1874 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
1875 mNetTransitionWakeLock.isHeld()) {
1876 mNetTransitionWakeLock.release();
1877 causedBy = mNetTransitionWakeLockCausedBy;
1880 if (causedBy != null) {
1881 log("NetTransition Wakelock for " + causedBy + " released by timeout");
1884 case EVENT_RESTORE_DEFAULT_NETWORK:
1885 FeatureUser u = (FeatureUser)msg.obj;
1888 case EVENT_INET_CONDITION_CHANGE:
1890 int netType = msg.arg1;
1891 int condition = msg.arg2;
1892 handleInetConditionChange(netType, condition);
1895 case EVENT_INET_CONDITION_HOLD_END:
1897 int netType = msg.arg1;
1898 int sequence = msg.arg2;
1899 handleInetConditionHoldEnd(netType, sequence);
1902 case EVENT_SET_NETWORK_PREFERENCE:
1904 int preference = msg.arg1;
1905 handleSetNetworkPreference(preference);
1908 case EVENT_SET_BACKGROUND_DATA:
1910 boolean enabled = (msg.arg1 == ENABLED);
1911 handleSetBackgroundData(enabled);
1914 case EVENT_SET_MOBILE_DATA:
1916 boolean enabled = (msg.arg1 == ENABLED);
1917 handleSetMobileData(enabled);
1920 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
1922 handleDeprecatedGlobalHttpProxy();
1925 case EVENT_SET_DEPENDENCY_MET:
1927 boolean met = (msg.arg1 == ENABLED);
1928 handleSetDependencyMet(msg.arg2, met);
1935 // javadoc from interface
1936 public int tether(String iface) {
1937 enforceTetherChangePermission();
1939 if (isTetheringSupported()) {
1940 return mTethering.tether(iface);
1942 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1946 // javadoc from interface
1947 public int untether(String iface) {
1948 enforceTetherChangePermission();
1950 if (isTetheringSupported()) {
1951 return mTethering.untether(iface);
1953 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1957 // javadoc from interface
1958 public int getLastTetherError(String iface) {
1959 enforceTetherAccessPermission();
1961 if (isTetheringSupported()) {
1962 return mTethering.getLastTetherError(iface);
1964 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1968 // TODO - proper iface API for selection by property, inspection, etc
1969 public String[] getTetherableUsbRegexs() {
1970 enforceTetherAccessPermission();
1971 if (isTetheringSupported()) {
1972 return mTethering.getTetherableUsbRegexs();
1974 return new String[0];
1978 public String[] getTetherableWifiRegexs() {
1979 enforceTetherAccessPermission();
1980 if (isTetheringSupported()) {
1981 return mTethering.getTetherableWifiRegexs();
1983 return new String[0];
1987 public String[] getTetherableBluetoothRegexs() {
1988 enforceTetherAccessPermission();
1989 if (isTetheringSupported()) {
1990 return mTethering.getTetherableBluetoothRegexs();
1992 return new String[0];
1996 // TODO - move iface listing, queries, etc to new module
1997 // javadoc from interface
1998 public String[] getTetherableIfaces() {
1999 enforceTetherAccessPermission();
2000 return mTethering.getTetherableIfaces();
2003 public String[] getTetheredIfaces() {
2004 enforceTetherAccessPermission();
2005 return mTethering.getTetheredIfaces();
2008 public String[] getTetheringErroredIfaces() {
2009 enforceTetherAccessPermission();
2010 return mTethering.getErroredIfaces();
2013 // if ro.tether.denied = true we default to no tethering
2014 // gservices could set the secure setting to 1 though to enable it on a build where it
2015 // had previously been turned off.
2016 public boolean isTetheringSupported() {
2017 enforceTetherAccessPermission();
2018 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2019 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2020 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2021 return tetherEnabledInSettings && mTetheringConfigValid;
2024 // An API NetworkStateTrackers can call when they lose their network.
2025 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2026 // whichever happens first. The timer is started by the first caller and not
2027 // restarted by subsequent callers.
2028 public void requestNetworkTransitionWakelock(String forWhom) {
2029 enforceConnectivityInternalPermission();
2030 synchronized (this) {
2031 if (mNetTransitionWakeLock.isHeld()) return;
2032 mNetTransitionWakeLockSerialNumber++;
2033 mNetTransitionWakeLock.acquire();
2034 mNetTransitionWakeLockCausedBy = forWhom;
2036 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2037 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2038 mNetTransitionWakeLockSerialNumber, 0),
2039 mNetTransitionWakeLockTimeout);
2043 // 100 percent is full good, 0 is full bad.
2044 public void reportInetCondition(int networkType, int percentage) {
2045 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
2046 mContext.enforceCallingOrSelfPermission(
2047 android.Manifest.permission.STATUS_BAR,
2048 "ConnectivityService");
2051 int pid = getCallingPid();
2052 int uid = getCallingUid();
2053 String s = pid + "(" + uid + ") reports inet is " +
2054 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2055 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2057 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2061 mHandler.sendMessage(mHandler.obtainMessage(
2062 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2065 private void handleInetConditionChange(int netType, int condition) {
2067 log("Inet connectivity change, net=" +
2068 netType + ", condition=" + condition +
2069 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2071 if (mActiveDefaultNetwork == -1) {
2072 if (DBG) log("no active default network - aborting");
2075 if (mActiveDefaultNetwork != netType) {
2076 if (DBG) log("given net not default - aborting");
2079 mDefaultInetCondition = condition;
2081 if (mInetConditionChangeInFlight == false) {
2082 if (DBG) log("starting a change hold");
2083 // setup a new hold to debounce this
2084 if (mDefaultInetCondition > 50) {
2085 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2086 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2088 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2089 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2091 mInetConditionChangeInFlight = true;
2092 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2093 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2095 // we've set the new condition, when this hold ends that will get
2097 if (DBG) log("currently in hold - not setting new end evt");
2101 private void handleInetConditionHoldEnd(int netType, int sequence) {
2103 log("Inet hold end, net=" + netType +
2104 ", condition =" + mDefaultInetCondition +
2105 ", published condition =" + mDefaultInetConditionPublished);
2107 mInetConditionChangeInFlight = false;
2109 if (mActiveDefaultNetwork == -1) {
2110 if (DBG) log("no active default network - aborting");
2113 if (mDefaultConnectionSequence != sequence) {
2114 if (DBG) log("event hold for obsolete network - aborting");
2117 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2118 if (DBG) log("no change in condition - aborting");
2121 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2122 if (networkInfo.isConnected() == false) {
2123 if (DBG) log("default network not connected - aborting");
2126 mDefaultInetConditionPublished = mDefaultInetCondition;
2127 sendInetConditionBroadcast(networkInfo);
2131 public synchronized ProxyProperties getProxy() {
2132 if (mGlobalProxy != null) return mGlobalProxy;
2133 if (mDefaultProxy != null) return mDefaultProxy;
2137 public void setGlobalProxy(ProxyProperties proxyProperties) {
2138 enforceChangePermission();
2139 synchronized (mGlobalProxyLock) {
2140 if (proxyProperties == mGlobalProxy) return;
2141 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2142 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2146 String exclList = "";
2147 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2148 mGlobalProxy = new ProxyProperties(proxyProperties);
2149 host = mGlobalProxy.getHost();
2150 port = mGlobalProxy.getPort();
2151 exclList = mGlobalProxy.getExclusionList();
2153 mGlobalProxy = null;
2155 ContentResolver res = mContext.getContentResolver();
2156 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2157 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
2158 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2162 if (mGlobalProxy == null) {
2163 proxyProperties = mDefaultProxy;
2165 sendProxyBroadcast(proxyProperties);
2168 private void loadGlobalProxy() {
2169 ContentResolver res = mContext.getContentResolver();
2170 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2171 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2172 String exclList = Settings.Secure.getString(res,
2173 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2174 if (!TextUtils.isEmpty(host)) {
2175 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2176 synchronized (mGlobalProxyLock) {
2177 mGlobalProxy = proxyProperties;
2182 public ProxyProperties getGlobalProxy() {
2183 synchronized (mGlobalProxyLock) {
2184 return mGlobalProxy;
2188 private void handleApplyDefaultProxy(int type) {
2189 // check if new default - push it out to all VM if so
2190 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2191 synchronized (this) {
2192 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2193 if (mDefaultProxy == proxy) return;
2194 if (!TextUtils.isEmpty(proxy.getHost())) {
2195 mDefaultProxy = proxy;
2197 mDefaultProxy = null;
2200 if (DBG) log("changing default proxy to " + proxy);
2201 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2202 if (mGlobalProxy != null) return;
2203 sendProxyBroadcast(proxy);
2206 private void handleDeprecatedGlobalHttpProxy() {
2207 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2208 Settings.Secure.HTTP_PROXY);
2209 if (!TextUtils.isEmpty(proxy)) {
2210 String data[] = proxy.split(":");
2211 String proxyHost = data[0];
2212 int proxyPort = 8080;
2213 if (data.length > 1) {
2215 proxyPort = Integer.parseInt(data[1]);
2216 } catch (NumberFormatException e) {
2220 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2225 private void sendProxyBroadcast(ProxyProperties proxy) {
2226 if (proxy == null) proxy = new ProxyProperties("", 0, "");
2227 log("sending Proxy Broadcast for " + proxy);
2228 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
2229 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2230 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2231 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
2232 mContext.sendStickyBroadcast(intent);
2235 private static class SettingsObserver extends ContentObserver {
2237 private Handler mHandler;
2238 SettingsObserver(Handler handler, int what) {
2244 void observe(Context context) {
2245 ContentResolver resolver = context.getContentResolver();
2246 resolver.registerContentObserver(Settings.Secure.getUriFor(
2247 Settings.Secure.HTTP_PROXY), false, this);
2251 public void onChange(boolean selfChange) {
2252 mHandler.obtainMessage(mWhat).sendToTarget();
2256 private void handleTetherIfaceChange(int type) {
2257 String iface = mNetTrackers[type].getLinkProperties().getInterfaceName();
2259 if (isTetheringSupported()) {
2260 mTethering.handleTetherIfaceChange(iface);
2264 private void log(String s) {
2268 private void loge(String s) {
2271 int convertFeatureToNetworkType(String feature){
2272 int networkType = -1;
2273 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2274 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2275 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2276 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2277 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2278 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2279 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2280 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2281 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2282 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2283 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2284 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2285 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2286 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2287 networkType = ConnectivityManager.TYPE_MOBILE_CBS;