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 = ((mTethering.getTetherableUsbRegexs().length != 0 ||
435 mTethering.getTetherableWifiRegexs().length != 0 ||
436 mTethering.getTetherableBluetoothRegexs().length != 0) &&
437 mTethering.getUpstreamIfaceTypes().length != 0);
440 mInetLog = new ArrayList();
443 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
444 mSettingsObserver.observe(mContext);
448 VpnManager.startVpnService(context);
453 * Sets the preferred network.
454 * @param preference the new preference
456 public void setNetworkPreference(int preference) {
457 enforceChangePermission();
459 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
462 public int getNetworkPreference() {
463 enforceAccessPermission();
466 preference = mNetworkPreference;
471 private void handleSetNetworkPreference(int preference) {
472 if (ConnectivityManager.isNetworkTypeValid(preference) &&
473 mNetConfigs[preference] != null &&
474 mNetConfigs[preference].isDefault()) {
475 if (mNetworkPreference != preference) {
476 final ContentResolver cr = mContext.getContentResolver();
477 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
479 mNetworkPreference = preference;
486 private int getPersistedNetworkPreference() {
487 final ContentResolver cr = mContext.getContentResolver();
489 final int networkPrefSetting = Settings.Secure
490 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
491 if (networkPrefSetting != -1) {
492 return networkPrefSetting;
495 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
499 * Make the state of network connectivity conform to the preference settings
500 * In this method, we only tear down a non-preferred network. Establishing
501 * a connection to the preferred network is taken care of when we handle
502 * the disconnect event from the non-preferred network
503 * (see {@link #handleDisconnect(NetworkInfo)}).
505 private void enforcePreference() {
506 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
509 if (!mNetTrackers[mNetworkPreference].isAvailable())
512 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
513 if (t != mNetworkPreference && mNetTrackers[t] != null &&
514 mNetTrackers[t].getNetworkInfo().isConnected()) {
516 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
517 " in enforcePreference");
519 teardown(mNetTrackers[t]);
524 private boolean teardown(NetworkStateTracker netTracker) {
525 if (netTracker.teardown()) {
526 netTracker.setTeardownRequested(true);
534 * Return NetworkInfo for the active (i.e., connected) network interface.
535 * It is assumed that at most one network is active at a time. If more
536 * than one is active, it is indeterminate which will be returned.
537 * @return the info for the active network, or {@code null} if none is
540 public NetworkInfo getActiveNetworkInfo() {
541 return getNetworkInfo(mActiveDefaultNetwork);
544 public NetworkInfo getNetworkInfo(int networkType) {
545 enforceAccessPermission();
546 if (ConnectivityManager.isNetworkTypeValid(networkType)) {
547 NetworkStateTracker t = mNetTrackers[networkType];
549 return t.getNetworkInfo();
554 public NetworkInfo[] getAllNetworkInfo() {
555 enforceAccessPermission();
556 NetworkInfo[] result = new NetworkInfo[mNetworksDefined];
558 for (NetworkStateTracker t : mNetTrackers) {
559 if(t != null) result[i++] = t.getNetworkInfo();
565 * Return LinkProperties for the active (i.e., connected) default
566 * network interface. It is assumed that at most one default network
567 * is active at a time. If more than one is active, it is indeterminate
568 * which will be returned.
569 * @return the ip properties for the active network, or {@code null} if
572 public LinkProperties getActiveLinkProperties() {
573 return getLinkProperties(mActiveDefaultNetwork);
576 public LinkProperties getLinkProperties(int networkType) {
577 enforceAccessPermission();
578 if (ConnectivityManager.isNetworkTypeValid(networkType)) {
579 NetworkStateTracker t = mNetTrackers[networkType];
580 if (t != null) return t.getLinkProperties();
585 public boolean setRadios(boolean turnOn) {
586 boolean result = true;
587 enforceChangePermission();
588 for (NetworkStateTracker t : mNetTrackers) {
589 if (t != null) result = t.setRadio(turnOn) && result;
594 public boolean setRadio(int netType, boolean turnOn) {
595 enforceChangePermission();
596 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
599 NetworkStateTracker tracker = mNetTrackers[netType];
600 return tracker != null && tracker.setRadio(turnOn);
604 * Used to notice when the calling process dies so we can self-expire
606 * Also used to know if the process has cleaned up after itself when
607 * our auto-expire timer goes off. The timer has a link to an object.
610 private class FeatureUser implements IBinder.DeathRecipient {
618 FeatureUser(int type, String feature, IBinder binder) {
623 mPid = getCallingPid();
624 mUid = getCallingUid();
625 mCreateTime = System.currentTimeMillis();
628 mBinder.linkToDeath(this, 0);
629 } catch (RemoteException e) {
634 void unlinkDeathRecipient() {
635 mBinder.unlinkToDeath(this, 0);
638 public void binderDied() {
639 log("ConnectivityService FeatureUser binderDied(" +
640 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
641 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
642 stopUsingNetworkFeature(this, false);
645 public void expire() {
646 log("ConnectivityService FeatureUser expire(" +
647 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
648 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
649 stopUsingNetworkFeature(this, false);
652 public String toString() {
653 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
654 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
658 // javadoc from interface
659 public int startUsingNetworkFeature(int networkType, String feature,
662 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
664 enforceChangePermission();
665 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
666 mNetConfigs[networkType] == null) {
667 return Phone.APN_REQUEST_FAILED;
670 FeatureUser f = new FeatureUser(networkType, feature, binder);
672 // TODO - move this into the MobileDataStateTracker
673 int usedNetworkType = networkType;
674 if(networkType == ConnectivityManager.TYPE_MOBILE) {
675 usedNetworkType = convertFeatureToNetworkType(feature);
676 if (usedNetworkType < 0) {
677 Slog.e(TAG, "Can't match any netTracker!");
678 usedNetworkType = networkType;
681 NetworkStateTracker network = mNetTrackers[usedNetworkType];
682 if (network != null) {
683 Integer currentPid = new Integer(getCallingPid());
684 if (usedNetworkType != networkType) {
685 NetworkStateTracker radio = mNetTrackers[networkType];
686 NetworkInfo ni = network.getNetworkInfo();
688 if (ni.isAvailable() == false) {
689 if (DBG) log("special network not available");
690 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
691 return Phone.APN_TYPE_NOT_AVAILABLE;
693 // else make the attempt anyway - probably giving REQUEST_STARTED below
698 mFeatureUsers.add(f);
699 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
700 // this gets used for per-pid dns when connected
701 mNetRequestersPids[usedNetworkType].add(currentPid);
705 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
707 if (restoreTimer >= 0) {
708 mHandler.sendMessageDelayed(
709 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
712 if ((ni.isConnectedOrConnecting() == true) &&
713 !network.isTeardownRequested()) {
714 if (ni.isConnected() == true) {
715 // add the pid-specific dns
716 handleDnsConfigurationChange(networkType);
717 if (DBG) log("special network already active");
718 return Phone.APN_ALREADY_ACTIVE;
720 if (DBG) log("special network already connecting");
721 return Phone.APN_REQUEST_STARTED;
724 // check if the radio in play can make another contact
725 // assume if cannot for now
727 if (DBG) log("reconnecting to special network");
729 return Phone.APN_REQUEST_STARTED;
731 // need to remember this unsupported request so we respond appropriately on stop
733 mFeatureUsers.add(f);
734 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
735 // this gets used for per-pid dns when connected
736 mNetRequestersPids[usedNetworkType].add(currentPid);
742 return Phone.APN_TYPE_NOT_AVAILABLE;
745 // javadoc from interface
746 public int stopUsingNetworkFeature(int networkType, String feature) {
747 enforceChangePermission();
749 int pid = getCallingPid();
750 int uid = getCallingUid();
752 FeatureUser u = null;
753 boolean found = false;
756 for (int i = 0; i < mFeatureUsers.size() ; i++) {
757 u = (FeatureUser)mFeatureUsers.get(i);
758 if (uid == u.mUid && pid == u.mPid &&
759 networkType == u.mNetworkType &&
760 TextUtils.equals(feature, u.mFeature)) {
766 if (found && u != null) {
767 // stop regardless of how many other time this proc had called start
768 return stopUsingNetworkFeature(u, true);
771 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
776 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
777 int networkType = u.mNetworkType;
778 String feature = u.mFeature;
782 NetworkStateTracker tracker = null;
783 boolean callTeardown = false; // used to carry our decision outside of sync block
786 log("stopUsingNetworkFeature for net " + networkType +
790 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
794 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
797 // check if this process still has an outstanding start request
798 if (!mFeatureUsers.contains(u)) {
799 if (DBG) log("ignoring - this process has no outstanding requests");
802 u.unlinkDeathRecipient();
803 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
804 // If we care about duplicate requests, check for that here.
806 // This is done to support the extension of a request - the app
807 // can request we start the network feature again and renew the
808 // auto-shutoff delay. Normal "stop" calls from the app though
809 // do not pay attention to duplicate requests - in effect the
810 // API does not refcount and a single stop will counter multiple starts.
811 if (ignoreDups == false) {
812 for (int i = 0; i < mFeatureUsers.size() ; i++) {
813 FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
814 if (x.mUid == u.mUid && x.mPid == u.mPid &&
815 x.mNetworkType == u.mNetworkType &&
816 TextUtils.equals(x.mFeature, u.mFeature)) {
817 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
823 // TODO - move to MobileDataStateTracker
824 int usedNetworkType = networkType;
825 if (networkType == ConnectivityManager.TYPE_MOBILE) {
826 usedNetworkType = convertFeatureToNetworkType(feature);
827 if (usedNetworkType < 0) {
828 usedNetworkType = networkType;
831 tracker = mNetTrackers[usedNetworkType];
832 if (tracker == null) {
833 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
836 if (usedNetworkType != networkType) {
837 Integer currentPid = new Integer(pid);
838 mNetRequestersPids[usedNetworkType].remove(currentPid);
839 reassessPidDns(pid, true);
840 if (mNetRequestersPids[usedNetworkType].size() != 0) {
841 if (DBG) log("not tearing down special network - " +
842 "others still using it");
847 if (DBG) log("not a known feature - dropping");
850 if (DBG) log("Doing network teardown");
860 * @deprecated use requestRouteToHostAddress instead
862 * Ensure that a network route exists to deliver traffic to the specified
863 * host via the specified network interface.
864 * @param networkType the type of the network over which traffic to the
865 * specified host is to be routed
866 * @param hostAddress the IP address of the host to which the route is
868 * @return {@code true} on success, {@code false} on failure
870 public boolean requestRouteToHost(int networkType, int hostAddress) {
871 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
873 if (inetAddress == null) {
877 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
881 * Ensure that a network route exists to deliver traffic to the specified
882 * host via the specified network interface.
883 * @param networkType the type of the network over which traffic to the
884 * specified host is to be routed
885 * @param hostAddress the IP address of the host to which the route is
887 * @return {@code true} on success, {@code false} on failure
889 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
890 enforceChangePermission();
891 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
894 NetworkStateTracker tracker = mNetTrackers[networkType];
896 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
897 tracker.isTeardownRequested()) {
899 log("requestRouteToHostAddress on down network " +
900 "(" + networkType + ") - dropped");
905 InetAddress addr = InetAddress.getByAddress(hostAddress);
906 return addHostRoute(tracker, addr, 0);
907 } catch (UnknownHostException e) {}
912 * Ensure that a network route exists to deliver traffic to the specified
913 * host via the mobile data network.
914 * @param hostAddress the IP address of the host to which the route is desired,
915 * in network byte order.
917 * @return {@code true} on success, {@code false} on failure
919 private boolean addHostRoute(NetworkStateTracker nt, InetAddress hostAddress, int cycleCount) {
920 LinkProperties lp = nt.getLinkProperties();
921 if ((lp == null) || (hostAddress == null)) return false;
923 String interfaceName = lp.getInterfaceName();
925 log("Requested host route to " + hostAddress + "(" + interfaceName + "), cycleCount=" +
928 if (interfaceName == null) {
929 if (DBG) loge("addHostRoute failed due to null interface name");
933 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), hostAddress);
934 InetAddress gatewayAddress = null;
935 if (bestRoute != null) {
936 gatewayAddress = bestRoute.getGateway();
937 // if the best route is ourself, don't relf-reference, just add the host route
938 if (hostAddress.equals(gatewayAddress)) gatewayAddress = null;
940 if (gatewayAddress != null) {
941 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
942 loge("Error adding hostroute - too much recursion");
945 if (!addHostRoute(nt, gatewayAddress, cycleCount+1)) return false;
948 RouteInfo route = RouteInfo.makeHostRoute(hostAddress, gatewayAddress);
951 mNetd.addRoute(interfaceName, route);
953 } catch (Exception ex) {
958 // TODO support the removal of single host routes. Keep a ref count of them so we
959 // aren't over-zealous
960 private boolean removeHostRoute(NetworkStateTracker nt, InetAddress hostAddress) {
965 * @see ConnectivityManager#getBackgroundDataSetting()
967 public boolean getBackgroundDataSetting() {
968 return mBackgroundDataEnabled.get();
972 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
974 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
975 mContext.enforceCallingOrSelfPermission(
976 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
977 "ConnectivityService");
979 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
981 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
982 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
985 private void handleSetBackgroundData(boolean enabled) {
986 Settings.Secure.putInt(mContext.getContentResolver(),
987 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
988 Intent broadcast = new Intent(
989 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
990 mContext.sendBroadcast(broadcast);
994 * @see ConnectivityManager#getMobileDataEnabled()
996 public boolean getMobileDataEnabled() {
997 // TODO: This detail should probably be in DataConnectionTracker's
998 // which is where we store the value and maybe make this
1000 enforceAccessPermission();
1001 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1002 Settings.Secure.MOBILE_DATA, 1) == 1;
1003 if (DBG) log("getMobileDataEnabled returning " + retVal);
1007 public void setDataDependency(int networkType, boolean met) {
1008 enforceChangePermission();
1010 log("setDataDependency(" + networkType + ", " + met + ")");
1012 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1013 (met ? ENABLED : DISABLED), networkType));
1016 private void handleSetDependencyMet(int networkType, boolean met) {
1017 if (mNetTrackers[networkType] != null) {
1019 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1021 mNetTrackers[networkType].setDependencyMet(met);
1026 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1028 public void setMobileDataEnabled(boolean enabled) {
1029 enforceChangePermission();
1030 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
1032 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
1033 (enabled ? ENABLED : DISABLED), 0));
1036 private void handleSetMobileData(boolean enabled) {
1037 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1039 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
1041 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
1045 private void enforceAccessPermission() {
1046 mContext.enforceCallingOrSelfPermission(
1047 android.Manifest.permission.ACCESS_NETWORK_STATE,
1048 "ConnectivityService");
1051 private void enforceChangePermission() {
1052 mContext.enforceCallingOrSelfPermission(
1053 android.Manifest.permission.CHANGE_NETWORK_STATE,
1054 "ConnectivityService");
1057 // TODO Make this a special check when it goes public
1058 private void enforceTetherChangePermission() {
1059 mContext.enforceCallingOrSelfPermission(
1060 android.Manifest.permission.CHANGE_NETWORK_STATE,
1061 "ConnectivityService");
1064 private void enforceTetherAccessPermission() {
1065 mContext.enforceCallingOrSelfPermission(
1066 android.Manifest.permission.ACCESS_NETWORK_STATE,
1067 "ConnectivityService");
1070 private void enforceConnectivityInternalPermission() {
1071 mContext.enforceCallingOrSelfPermission(
1072 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1073 "ConnectivityService");
1077 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1078 * network, we ignore it. If it is for the active network, we send out a
1079 * broadcast. But first, we check whether it might be possible to connect
1080 * to a different network.
1081 * @param info the {@code NetworkInfo} for the network
1083 private void handleDisconnect(NetworkInfo info) {
1085 int prevNetType = info.getType();
1087 mNetTrackers[prevNetType].setTeardownRequested(false);
1089 * If the disconnected network is not the active one, then don't report
1090 * this as a loss of connectivity. What probably happened is that we're
1091 * getting the disconnect for a network that we explicitly disabled
1092 * in accordance with network preference policies.
1094 if (!mNetConfigs[prevNetType].isDefault()) {
1095 List pids = mNetRequestersPids[prevNetType];
1096 for (int i = 0; i<pids.size(); i++) {
1097 Integer pid = (Integer)pids.get(i);
1098 // will remove them because the net's no longer connected
1099 // need to do this now as only now do we know the pids and
1100 // can properly null things that are no longer referenced.
1101 reassessPidDns(pid.intValue(), false);
1105 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1106 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1107 if (info.isFailover()) {
1108 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1109 info.setFailover(false);
1111 if (info.getReason() != null) {
1112 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1114 if (info.getExtraInfo() != null) {
1115 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1116 info.getExtraInfo());
1119 if (mNetConfigs[prevNetType].isDefault()) {
1120 tryFailover(prevNetType);
1121 if (mActiveDefaultNetwork != -1) {
1122 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1123 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1125 mDefaultInetConditionPublished = 0; // we're not connected anymore
1126 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1129 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1131 // Reset interface if no other connections are using the same interface
1132 boolean doReset = true;
1133 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1134 if (linkProperties != null) {
1135 String oldIface = linkProperties.getInterfaceName();
1136 if (TextUtils.isEmpty(oldIface) == false) {
1137 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1138 if (networkStateTracker == null) continue;
1139 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1140 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1141 LinkProperties l = networkStateTracker.getLinkProperties();
1142 if (l == null) continue;
1143 if (oldIface.equals(l.getInterfaceName())) {
1152 // do this before we broadcast the change
1153 handleConnectivityChange(prevNetType, doReset);
1155 sendStickyBroadcast(intent);
1157 * If the failover network is already connected, then immediately send
1158 * out a followup broadcast indicating successful failover
1160 if (mActiveDefaultNetwork != -1) {
1161 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
1165 private void tryFailover(int prevNetType) {
1167 * If this is a default network, check if other defaults are available.
1168 * Try to reconnect on all available and let them hash it out when
1169 * more than one connects.
1171 if (mNetConfigs[prevNetType].isDefault()) {
1172 if (mActiveDefaultNetwork == prevNetType) {
1173 mActiveDefaultNetwork = -1;
1176 // don't signal a reconnect for anything lower or equal priority than our
1177 // current connected default
1178 // TODO - don't filter by priority now - nice optimization but risky
1179 // int currentPriority = -1;
1180 // if (mActiveDefaultNetwork != -1) {
1181 // currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
1183 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
1184 if (checkType == prevNetType) continue;
1185 if (mNetConfigs[checkType] == null) continue;
1186 if (!mNetConfigs[checkType].isDefault()) continue;
1188 // Enabling the isAvailable() optimization caused mobile to not get
1189 // selected if it was in the middle of error handling. Specifically
1190 // a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1191 // would not be available and we wouldn't get connected to anything.
1192 // So removing the isAvailable() optimization below for now. TODO: This
1193 // optimization should work and we need to investigate why it doesn't work.
1194 // This could be related to how DEACTIVATE_DATA_CALL is reporting its
1195 // complete before it is really complete.
1196 // if (!mNetTrackers[checkType].isAvailable()) continue;
1198 // if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
1200 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1201 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1202 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1203 checkInfo.setFailover(true);
1204 checkTracker.reconnect();
1206 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
1211 private void sendConnectedBroadcast(NetworkInfo info) {
1212 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1215 private void sendInetConditionBroadcast(NetworkInfo info) {
1216 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1219 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1220 Intent intent = new Intent(bcastType);
1221 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1222 if (info.isFailover()) {
1223 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1224 info.setFailover(false);
1226 if (info.getReason() != null) {
1227 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1229 if (info.getExtraInfo() != null) {
1230 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1231 info.getExtraInfo());
1233 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1234 sendStickyBroadcast(intent);
1238 * Called when an attempt to fail over to another network has failed.
1239 * @param info the {@link NetworkInfo} for the failed network
1241 private void handleConnectionFailure(NetworkInfo info) {
1242 mNetTrackers[info.getType()].setTeardownRequested(false);
1244 String reason = info.getReason();
1245 String extraInfo = info.getExtraInfo();
1248 if (reason == null) {
1251 reasonText = " (" + reason + ").";
1253 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
1255 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1256 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1257 if (getActiveNetworkInfo() == null) {
1258 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1260 if (reason != null) {
1261 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1263 if (extraInfo != null) {
1264 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1266 if (info.isFailover()) {
1267 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1268 info.setFailover(false);
1271 if (mNetConfigs[info.getType()].isDefault()) {
1272 tryFailover(info.getType());
1273 if (mActiveDefaultNetwork != -1) {
1274 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1275 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1277 mDefaultInetConditionPublished = 0;
1278 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1282 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1283 sendStickyBroadcast(intent);
1285 * If the failover network is already connected, then immediately send
1286 * out a followup broadcast indicating successful failover
1288 if (mActiveDefaultNetwork != -1) {
1289 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
1293 private void sendStickyBroadcast(Intent intent) {
1294 synchronized(this) {
1295 if (!mSystemReady) {
1296 mInitialBroadcast = new Intent(intent);
1298 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1299 mContext.sendStickyBroadcast(intent);
1303 void systemReady() {
1304 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
1305 mNetd = INetworkManagementService.Stub.asInterface(b);
1307 synchronized(this) {
1308 mSystemReady = true;
1309 if (mInitialBroadcast != null) {
1310 mContext.sendStickyBroadcast(mInitialBroadcast);
1311 mInitialBroadcast = null;
1314 // load the global proxy at startup
1315 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
1318 private void handleConnect(NetworkInfo info) {
1319 int type = info.getType();
1321 // snapshot isFailover, because sendConnectedBroadcast() resets it
1322 boolean isFailover = info.isFailover();
1323 NetworkStateTracker thisNet = mNetTrackers[type];
1325 // if this is a default net and other default is running
1326 // kill the one not preferred
1327 if (mNetConfigs[type].isDefault()) {
1328 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1329 if ((type != mNetworkPreference &&
1330 mNetConfigs[mActiveDefaultNetwork].priority >
1331 mNetConfigs[type].priority) ||
1332 mNetworkPreference == mActiveDefaultNetwork) {
1333 // don't accept this one
1335 log("Not broadcasting CONNECT_ACTION " +
1336 "to torn down network " + info.getTypeName());
1341 // tear down the other
1342 NetworkStateTracker otherNet =
1343 mNetTrackers[mActiveDefaultNetwork];
1345 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
1348 if (!teardown(otherNet)) {
1349 loge("Network declined teardown request");
1354 synchronized (ConnectivityService.this) {
1355 // have a new default network, release the transition wakelock in a second
1356 // if it's held. The second pause is to allow apps to reconnect over the
1358 if (mNetTransitionWakeLock.isHeld()) {
1359 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1360 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
1361 mNetTransitionWakeLockSerialNumber, 0),
1365 mActiveDefaultNetwork = type;
1366 // this will cause us to come up initially as unconnected and switching
1367 // to connected after our normal pause unless somebody reports us as reall
1369 mDefaultInetConditionPublished = 0;
1370 mDefaultConnectionSequence++;
1371 mInetConditionChangeInFlight = false;
1372 // Don't do this - if we never sign in stay, grey
1373 //reportNetworkCondition(mActiveDefaultNetwork, 100);
1375 thisNet.setTeardownRequested(false);
1376 updateNetworkSettings(thisNet);
1377 handleConnectivityChange(type, false);
1378 sendConnectedBroadcast(info);
1382 * After a change in the connectivity state of a network. We're mainly
1383 * concerned with making sure that the list of DNS servers is set up
1384 * according to which networks are connected, and ensuring that the
1385 * right routing table entries exist.
1387 private void handleConnectivityChange(int netType, boolean doReset) {
1389 * If a non-default network is enabled, add the host routes that
1390 * will allow it's DNS servers to be accessed.
1392 handleDnsConfigurationChange(netType);
1394 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
1395 if (mNetConfigs[netType].isDefault()) {
1396 handleApplyDefaultProxy(netType);
1397 addDefaultRoute(mNetTrackers[netType]);
1399 addPrivateDnsRoutes(mNetTrackers[netType]);
1402 if (mNetConfigs[netType].isDefault()) {
1403 removeDefaultRoute(mNetTrackers[netType]);
1405 removePrivateDnsRoutes(mNetTrackers[netType]);
1410 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1411 if (linkProperties != null) {
1412 String iface = linkProperties.getInterfaceName();
1413 if (TextUtils.isEmpty(iface) == false) {
1414 if (DBG) log("resetConnections(" + iface + ")");
1415 NetworkUtils.resetConnections(iface);
1421 private void addPrivateDnsRoutes(NetworkStateTracker nt) {
1422 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1423 LinkProperties p = nt.getLinkProperties();
1424 if (p == null) return;
1425 String interfaceName = p.getInterfaceName();
1428 log("addPrivateDnsRoutes for " + nt +
1429 "(" + interfaceName + ") - mPrivateDnsRouteSet = " + privateDnsRouteSet);
1431 if (interfaceName != null && !privateDnsRouteSet) {
1432 Collection<InetAddress> dnsList = p.getDnses();
1433 for (InetAddress dns : dnsList) {
1434 addHostRoute(nt, dns, 0);
1436 nt.privateDnsRouteSet(true);
1440 private void removePrivateDnsRoutes(NetworkStateTracker nt) {
1441 LinkProperties p = nt.getLinkProperties();
1442 if (p == null) return;
1443 String interfaceName = p.getInterfaceName();
1444 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1445 if (interfaceName != null && privateDnsRouteSet) {
1447 log("removePrivateDnsRoutes for " + nt.getNetworkInfo().getTypeName() +
1448 " (" + interfaceName + ")");
1451 Collection<InetAddress> dnsList = p.getDnses();
1452 for (InetAddress dns : dnsList) {
1453 if (DBG) log(" removing " + dns);
1454 RouteInfo route = RouteInfo.makeHostRoute(dns);
1456 mNetd.removeRoute(interfaceName, route);
1457 } catch (Exception ex) {
1458 loge("error (" + ex + ") removing dns route " + route);
1461 nt.privateDnsRouteSet(false);
1466 private void addDefaultRoute(NetworkStateTracker nt) {
1467 LinkProperties p = nt.getLinkProperties();
1468 if (p == null) return;
1469 String interfaceName = p.getInterfaceName();
1470 if (TextUtils.isEmpty(interfaceName)) return;
1472 for (RouteInfo route : p.getRoutes()) {
1473 //TODO - handle non-default routes
1474 if (route.isDefaultRoute()) {
1475 if (DBG) log("adding default route " + route);
1476 InetAddress gateway = route.getGateway();
1477 if (addHostRoute(nt, gateway, 0)) {
1479 mNetd.addRoute(interfaceName, route);
1480 } catch (Exception e) {
1481 loge("error adding default route " + route);
1485 NetworkInfo networkInfo = nt.getNetworkInfo();
1486 log("addDefaultRoute for " + networkInfo.getTypeName() +
1487 " (" + interfaceName + "), GatewayAddr=" +
1488 gateway.getHostAddress());
1491 loge("error adding host route for default route " + route);
1498 public void removeDefaultRoute(NetworkStateTracker nt) {
1499 LinkProperties p = nt.getLinkProperties();
1500 if (p == null) return;
1501 String interfaceName = p.getInterfaceName();
1503 if (interfaceName == null) return;
1505 for (RouteInfo route : p.getRoutes()) {
1506 //TODO - handle non-default routes
1507 if (route.isDefaultRoute()) {
1509 mNetd.removeRoute(interfaceName, route);
1510 } catch (Exception ex) {
1511 loge("error (" + ex + ") removing default route " + route);
1515 NetworkInfo networkInfo = nt.getNetworkInfo();
1516 log("removeDefaultRoute for " + networkInfo.getTypeName() + " (" +
1517 interfaceName + ")");
1524 * Reads the network specific TCP buffer sizes from SystemProperties
1525 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1528 public void updateNetworkSettings(NetworkStateTracker nt) {
1529 String key = nt.getTcpBufferSizesPropName();
1530 String bufferSizes = SystemProperties.get(key);
1532 if (bufferSizes.length() == 0) {
1533 loge(key + " not found in system properties. Using defaults");
1535 // Setting to default values so we won't be stuck to previous values
1536 key = "net.tcp.buffersize.default";
1537 bufferSizes = SystemProperties.get(key);
1540 // Set values in kernel
1541 if (bufferSizes.length() != 0) {
1543 log("Setting TCP values: [" + bufferSizes
1544 + "] which comes from [" + key + "]");
1546 setBufferSize(bufferSizes);
1551 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1552 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1554 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1555 * writeMin, writeInitial, writeMax"
1557 private void setBufferSize(String bufferSizes) {
1559 String[] values = bufferSizes.split(",");
1561 if (values.length == 6) {
1562 final String prefix = "/sys/kernel/ipv4/tcp_";
1563 stringToFile(prefix + "rmem_min", values[0]);
1564 stringToFile(prefix + "rmem_def", values[1]);
1565 stringToFile(prefix + "rmem_max", values[2]);
1566 stringToFile(prefix + "wmem_min", values[3]);
1567 stringToFile(prefix + "wmem_def", values[4]);
1568 stringToFile(prefix + "wmem_max", values[5]);
1570 loge("Invalid buffersize string: " + bufferSizes);
1572 } catch (IOException e) {
1573 loge("Can't set tcp buffer sizes:" + e);
1578 * Writes string to file. Basically same as "echo -n $string > $filename"
1582 * @throws IOException
1584 private void stringToFile(String filename, String string) throws IOException {
1585 FileWriter out = new FileWriter(filename);
1595 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1596 * on the highest priority active net which this process requested.
1597 * If there aren't any, clear it out
1599 private void reassessPidDns(int myPid, boolean doBump)
1601 if (DBG) log("reassessPidDns for pid " + myPid);
1602 for(int i : mPriorityList) {
1603 if (mNetConfigs[i].isDefault()) {
1606 NetworkStateTracker nt = mNetTrackers[i];
1607 if (nt.getNetworkInfo().isConnected() &&
1608 !nt.isTeardownRequested()) {
1609 LinkProperties p = nt.getLinkProperties();
1610 if (p == null) continue;
1611 List pids = mNetRequestersPids[i];
1612 for (int j=0; j<pids.size(); j++) {
1613 Integer pid = (Integer)pids.get(j);
1614 if (pid.intValue() == myPid) {
1615 Collection<InetAddress> dnses = p.getDnses();
1616 writePidDns(dnses, myPid);
1625 // nothing found - delete
1626 for (int i = 1; ; i++) {
1627 String prop = "net.dns" + i + "." + myPid;
1628 if (SystemProperties.get(prop).length() == 0) {
1634 SystemProperties.set(prop, "");
1638 // return true if results in a change
1639 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
1641 boolean changed = false;
1642 for (InetAddress dns : dnses) {
1643 String dnsString = dns.getHostAddress();
1644 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1646 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1652 private void bumpDns() {
1654 * Bump the property that tells the name resolver library to reread
1655 * the DNS server list from the properties.
1657 String propVal = SystemProperties.get("net.dnschange");
1659 if (propVal.length() != 0) {
1661 n = Integer.parseInt(propVal);
1662 } catch (NumberFormatException e) {}
1664 SystemProperties.set("net.dnschange", "" + (n+1));
1666 * Tell the VMs to toss their DNS caches
1668 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1669 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1671 * Connectivity events can happen before boot has completed ...
1673 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1674 mContext.sendBroadcast(intent);
1677 private void handleDnsConfigurationChange(int netType) {
1678 // add default net's dns entries
1679 NetworkStateTracker nt = mNetTrackers[netType];
1680 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
1681 LinkProperties p = nt.getLinkProperties();
1682 if (p == null) return;
1683 Collection<InetAddress> dnses = p.getDnses();
1684 boolean changed = false;
1685 if (mNetConfigs[netType].isDefault()) {
1687 if (dnses.size() == 0 && mDefaultDns != null) {
1688 String dnsString = mDefaultDns.getHostAddress();
1689 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1691 log("no dns provided - using " + dnsString);
1694 SystemProperties.set("net.dns1", dnsString);
1698 for (InetAddress dns : dnses) {
1699 String dnsString = dns.getHostAddress();
1700 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1705 log("adding dns " + dns + " for " +
1706 nt.getNetworkInfo().getTypeName());
1709 SystemProperties.set("net.dns" + j++, dnsString);
1712 for (int k=j ; k<mNumDnsEntries; k++) {
1713 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1714 if (DBG) log("erasing net.dns" + k);
1716 SystemProperties.set("net.dns" + k, "");
1721 // set per-pid dns for attached secondary nets
1722 List pids = mNetRequestersPids[netType];
1723 for (int y=0; y< pids.size(); y++) {
1724 Integer pid = (Integer)pids.get(y);
1725 changed = writePidDns(dnses, pid.intValue());
1728 if (changed) bumpDns();
1732 private int getRestoreDefaultNetworkDelay(int networkType) {
1733 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1734 NETWORK_RESTORE_DELAY_PROP_NAME);
1735 if(restoreDefaultNetworkDelayStr != null &&
1736 restoreDefaultNetworkDelayStr.length() != 0) {
1738 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1739 } catch (NumberFormatException e) {
1742 // if the system property isn't set, use the value for the apn type
1743 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1745 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1746 (mNetConfigs[networkType] != null)) {
1747 ret = mNetConfigs[networkType].restoreTime;
1753 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1754 if (mContext.checkCallingOrSelfPermission(
1755 android.Manifest.permission.DUMP)
1756 != PackageManager.PERMISSION_GRANTED) {
1757 pw.println("Permission Denial: can't dump ConnectivityService " +
1758 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1759 Binder.getCallingUid());
1763 for (NetworkStateTracker nst : mNetTrackers) {
1765 if (nst.getNetworkInfo().isConnected()) {
1766 pw.println("Active network: " + nst.getNetworkInfo().
1769 pw.println(nst.getNetworkInfo());
1775 pw.println("Network Requester Pids:");
1776 for (int net : mPriorityList) {
1777 String pidString = net + ": ";
1778 for (Object pid : mNetRequestersPids[net]) {
1779 pidString = pidString + pid.toString() + ", ";
1781 pw.println(pidString);
1785 pw.println("FeatureUsers:");
1786 for (Object requester : mFeatureUsers) {
1787 pw.println(requester.toString());
1791 synchronized (this) {
1792 pw.println("NetworkTranstionWakeLock is currently " +
1793 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1794 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1798 mTethering.dump(fd, pw, args);
1800 if (mInetLog != null) {
1802 pw.println("Inet condition reports:");
1803 for(int i = 0; i < mInetLog.size(); i++) {
1804 pw.println(mInetLog.get(i));
1809 // must be stateless - things change under us.
1810 private class MyHandler extends Handler {
1811 public MyHandler(Looper looper) {
1816 public void handleMessage(Message msg) {
1819 case NetworkStateTracker.EVENT_STATE_CHANGED:
1820 info = (NetworkInfo) msg.obj;
1821 int type = info.getType();
1822 NetworkInfo.State state = info.getState();
1824 if (DBG) log("ConnectivityChange for " +
1825 info.getTypeName() + ": " +
1826 state + "/" + info.getDetailedState());
1828 // Connectivity state changed:
1829 // [31-13] Reserved for future use
1830 // [12-9] Network subtype (for mobile network, as defined
1831 // by TelephonyManager)
1832 // [8-3] Detailed state ordinal (as defined by
1833 // NetworkInfo.DetailedState)
1834 // [2-0] Network type (as defined by ConnectivityManager)
1835 int eventLogParam = (info.getType() & 0x7) |
1836 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
1837 (info.getSubtype() << 9);
1838 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
1841 if (info.getDetailedState() ==
1842 NetworkInfo.DetailedState.FAILED) {
1843 handleConnectionFailure(info);
1844 } else if (state == NetworkInfo.State.DISCONNECTED) {
1845 handleDisconnect(info);
1846 } else if (state == NetworkInfo.State.SUSPENDED) {
1847 // TODO: need to think this over.
1848 // the logic here is, handle SUSPENDED the same as
1849 // DISCONNECTED. The only difference being we are
1850 // broadcasting an intent with NetworkInfo that's
1851 // suspended. This allows the applications an
1852 // opportunity to handle DISCONNECTED and SUSPENDED
1853 // differently, or not.
1854 handleDisconnect(info);
1855 } else if (state == NetworkInfo.State.CONNECTED) {
1856 handleConnect(info);
1859 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
1860 info = (NetworkInfo) msg.obj;
1861 handleConnectivityChange(info.getType(), true);
1863 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
1864 String causedBy = null;
1865 synchronized (ConnectivityService.this) {
1866 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
1867 mNetTransitionWakeLock.isHeld()) {
1868 mNetTransitionWakeLock.release();
1869 causedBy = mNetTransitionWakeLockCausedBy;
1872 if (causedBy != null) {
1873 log("NetTransition Wakelock for " + causedBy + " released by timeout");
1876 case EVENT_RESTORE_DEFAULT_NETWORK:
1877 FeatureUser u = (FeatureUser)msg.obj;
1880 case EVENT_INET_CONDITION_CHANGE:
1882 int netType = msg.arg1;
1883 int condition = msg.arg2;
1884 handleInetConditionChange(netType, condition);
1887 case EVENT_INET_CONDITION_HOLD_END:
1889 int netType = msg.arg1;
1890 int sequence = msg.arg2;
1891 handleInetConditionHoldEnd(netType, sequence);
1894 case EVENT_SET_NETWORK_PREFERENCE:
1896 int preference = msg.arg1;
1897 handleSetNetworkPreference(preference);
1900 case EVENT_SET_BACKGROUND_DATA:
1902 boolean enabled = (msg.arg1 == ENABLED);
1903 handleSetBackgroundData(enabled);
1906 case EVENT_SET_MOBILE_DATA:
1908 boolean enabled = (msg.arg1 == ENABLED);
1909 handleSetMobileData(enabled);
1912 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
1914 handleDeprecatedGlobalHttpProxy();
1917 case EVENT_SET_DEPENDENCY_MET:
1919 boolean met = (msg.arg1 == ENABLED);
1920 handleSetDependencyMet(msg.arg2, met);
1927 // javadoc from interface
1928 public int tether(String iface) {
1929 enforceTetherChangePermission();
1931 if (isTetheringSupported()) {
1932 return mTethering.tether(iface);
1934 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1938 // javadoc from interface
1939 public int untether(String iface) {
1940 enforceTetherChangePermission();
1942 if (isTetheringSupported()) {
1943 return mTethering.untether(iface);
1945 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1949 // javadoc from interface
1950 public int getLastTetherError(String iface) {
1951 enforceTetherAccessPermission();
1953 if (isTetheringSupported()) {
1954 return mTethering.getLastTetherError(iface);
1956 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1960 // TODO - proper iface API for selection by property, inspection, etc
1961 public String[] getTetherableUsbRegexs() {
1962 enforceTetherAccessPermission();
1963 if (isTetheringSupported()) {
1964 return mTethering.getTetherableUsbRegexs();
1966 return new String[0];
1970 public String[] getTetherableWifiRegexs() {
1971 enforceTetherAccessPermission();
1972 if (isTetheringSupported()) {
1973 return mTethering.getTetherableWifiRegexs();
1975 return new String[0];
1979 public String[] getTetherableBluetoothRegexs() {
1980 enforceTetherAccessPermission();
1981 if (isTetheringSupported()) {
1982 return mTethering.getTetherableBluetoothRegexs();
1984 return new String[0];
1988 // TODO - move iface listing, queries, etc to new module
1989 // javadoc from interface
1990 public String[] getTetherableIfaces() {
1991 enforceTetherAccessPermission();
1992 return mTethering.getTetherableIfaces();
1995 public String[] getTetheredIfaces() {
1996 enforceTetherAccessPermission();
1997 return mTethering.getTetheredIfaces();
2000 public String[] getTetheringErroredIfaces() {
2001 enforceTetherAccessPermission();
2002 return mTethering.getErroredIfaces();
2005 // if ro.tether.denied = true we default to no tethering
2006 // gservices could set the secure setting to 1 though to enable it on a build where it
2007 // had previously been turned off.
2008 public boolean isTetheringSupported() {
2009 enforceTetherAccessPermission();
2010 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2011 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2012 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2013 return tetherEnabledInSettings && mTetheringConfigValid;
2016 // An API NetworkStateTrackers can call when they lose their network.
2017 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2018 // whichever happens first. The timer is started by the first caller and not
2019 // restarted by subsequent callers.
2020 public void requestNetworkTransitionWakelock(String forWhom) {
2021 enforceConnectivityInternalPermission();
2022 synchronized (this) {
2023 if (mNetTransitionWakeLock.isHeld()) return;
2024 mNetTransitionWakeLockSerialNumber++;
2025 mNetTransitionWakeLock.acquire();
2026 mNetTransitionWakeLockCausedBy = forWhom;
2028 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2029 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2030 mNetTransitionWakeLockSerialNumber, 0),
2031 mNetTransitionWakeLockTimeout);
2035 // 100 percent is full good, 0 is full bad.
2036 public void reportInetCondition(int networkType, int percentage) {
2037 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
2038 mContext.enforceCallingOrSelfPermission(
2039 android.Manifest.permission.STATUS_BAR,
2040 "ConnectivityService");
2043 int pid = getCallingPid();
2044 int uid = getCallingUid();
2045 String s = pid + "(" + uid + ") reports inet is " +
2046 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2047 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2049 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2053 mHandler.sendMessage(mHandler.obtainMessage(
2054 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2057 private void handleInetConditionChange(int netType, int condition) {
2059 log("Inet connectivity change, net=" +
2060 netType + ", condition=" + condition +
2061 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2063 if (mActiveDefaultNetwork == -1) {
2064 if (DBG) log("no active default network - aborting");
2067 if (mActiveDefaultNetwork != netType) {
2068 if (DBG) log("given net not default - aborting");
2071 mDefaultInetCondition = condition;
2073 if (mInetConditionChangeInFlight == false) {
2074 if (DBG) log("starting a change hold");
2075 // setup a new hold to debounce this
2076 if (mDefaultInetCondition > 50) {
2077 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2078 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2080 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2081 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2083 mInetConditionChangeInFlight = true;
2084 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2085 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2087 // we've set the new condition, when this hold ends that will get
2089 if (DBG) log("currently in hold - not setting new end evt");
2093 private void handleInetConditionHoldEnd(int netType, int sequence) {
2095 log("Inet hold end, net=" + netType +
2096 ", condition =" + mDefaultInetCondition +
2097 ", published condition =" + mDefaultInetConditionPublished);
2099 mInetConditionChangeInFlight = false;
2101 if (mActiveDefaultNetwork == -1) {
2102 if (DBG) log("no active default network - aborting");
2105 if (mDefaultConnectionSequence != sequence) {
2106 if (DBG) log("event hold for obsolete network - aborting");
2109 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2110 if (DBG) log("no change in condition - aborting");
2113 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2114 if (networkInfo.isConnected() == false) {
2115 if (DBG) log("default network not connected - aborting");
2118 mDefaultInetConditionPublished = mDefaultInetCondition;
2119 sendInetConditionBroadcast(networkInfo);
2123 public synchronized ProxyProperties getProxy() {
2124 if (mGlobalProxy != null) return mGlobalProxy;
2125 if (mDefaultProxy != null) return mDefaultProxy;
2129 public void setGlobalProxy(ProxyProperties proxyProperties) {
2130 enforceChangePermission();
2131 synchronized (mGlobalProxyLock) {
2132 if (proxyProperties == mGlobalProxy) return;
2133 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2134 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2138 String exclList = "";
2139 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2140 mGlobalProxy = new ProxyProperties(proxyProperties);
2141 host = mGlobalProxy.getHost();
2142 port = mGlobalProxy.getPort();
2143 exclList = mGlobalProxy.getExclusionList();
2145 mGlobalProxy = null;
2147 ContentResolver res = mContext.getContentResolver();
2148 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2149 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
2150 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2154 if (mGlobalProxy == null) {
2155 proxyProperties = mDefaultProxy;
2157 sendProxyBroadcast(proxyProperties);
2160 private void loadGlobalProxy() {
2161 ContentResolver res = mContext.getContentResolver();
2162 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2163 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2164 String exclList = Settings.Secure.getString(res,
2165 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2166 if (!TextUtils.isEmpty(host)) {
2167 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2168 synchronized (mGlobalProxyLock) {
2169 mGlobalProxy = proxyProperties;
2174 public ProxyProperties getGlobalProxy() {
2175 synchronized (mGlobalProxyLock) {
2176 return mGlobalProxy;
2180 private void handleApplyDefaultProxy(int type) {
2181 // check if new default - push it out to all VM if so
2182 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2183 synchronized (this) {
2184 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2185 if (mDefaultProxy == proxy) return;
2186 if (!TextUtils.isEmpty(proxy.getHost())) {
2187 mDefaultProxy = proxy;
2189 mDefaultProxy = null;
2192 if (DBG) log("changing default proxy to " + proxy);
2193 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2194 if (mGlobalProxy != null) return;
2195 sendProxyBroadcast(proxy);
2198 private void handleDeprecatedGlobalHttpProxy() {
2199 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2200 Settings.Secure.HTTP_PROXY);
2201 if (!TextUtils.isEmpty(proxy)) {
2202 String data[] = proxy.split(":");
2203 String proxyHost = data[0];
2204 int proxyPort = 8080;
2205 if (data.length > 1) {
2207 proxyPort = Integer.parseInt(data[1]);
2208 } catch (NumberFormatException e) {
2212 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2217 private void sendProxyBroadcast(ProxyProperties proxy) {
2218 if (proxy == null) proxy = new ProxyProperties("", 0, "");
2219 log("sending Proxy Broadcast for " + proxy);
2220 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
2221 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2222 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2223 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
2224 mContext.sendStickyBroadcast(intent);
2227 private static class SettingsObserver extends ContentObserver {
2229 private Handler mHandler;
2230 SettingsObserver(Handler handler, int what) {
2236 void observe(Context context) {
2237 ContentResolver resolver = context.getContentResolver();
2238 resolver.registerContentObserver(Settings.Secure.getUriFor(
2239 Settings.Secure.HTTP_PROXY), false, this);
2243 public void onChange(boolean selfChange) {
2244 mHandler.obtainMessage(mWhat).sendToTarget();
2248 private void log(String s) {
2252 private void loge(String s) {
2255 int convertFeatureToNetworkType(String feature){
2256 int networkType = -1;
2257 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2258 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2259 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2260 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2261 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2262 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2263 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2264 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2265 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2266 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2267 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2268 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2269 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2270 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2271 networkType = ConnectivityManager.TYPE_MOBILE_CBS;