blob: b78424b2ca105c5ff518082efa6934fb5d4ec032 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey4434b0b2011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070020import static android.net.ConnectivityManager.isNetworkTypeValid;
21import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070022import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070023
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080024import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080025import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070029import android.database.ContentObserver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080030import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080031import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080032import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080033import android.net.IConnectivityManager;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070034import android.net.INetworkPolicyListener;
35import android.net.INetworkPolicyManager;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070036import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080037import android.net.LinkProperties;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070038import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080039import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070040import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080041import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070042import android.net.NetworkInfo.DetailedState;
Jeff Sharkey21062e72011-05-28 20:56:34 -070043import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080044import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070045import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070046import android.net.Proxy;
47import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070048import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080049import android.net.wifi.WifiStateTracker;
50import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040051import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080052import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070053import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070054import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070055import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080056import android.os.Looper;
57import android.os.Message;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070058import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070059import android.os.PowerManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070060import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080061import android.os.ServiceManager;
62import android.os.SystemProperties;
63import android.provider.Settings;
Robert Greenwalt2034b912009-08-12 16:08:25 -070064import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080065import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080066import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070067import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080068
Chia-chi Yehbded3eb2011-07-04 03:23:12 -070069import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -070070import com.android.internal.net.VpnConfig;
Robert Greenwalt2034b912009-08-12 16:08:25 -070071import com.android.internal.telephony.Phone;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080072import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070073import com.android.server.connectivity.Vpn;
74
Jeff Sharkey21062e72011-05-28 20:56:34 -070075import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070076import com.google.android.collect.Sets;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080077
The Android Open Source Project28527d22009-03-03 19:31:44 -080078import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -070079import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080080import java.io.PrintWriter;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070081import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -070082import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070083import java.net.InetAddress;
84import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -070085import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070086import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070087import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -070088import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070089import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -070090import java.util.List;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070091import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project28527d22009-03-03 19:31:44 -080092
93/**
94 * @hide
95 */
96public class ConnectivityService extends IConnectivityManager.Stub {
97
Robert Greenwalt063dc7d2010-10-05 19:12:26 -070098 private static final boolean DBG = true;
Wink Saville051a6642011-07-13 13:44:13 -070099 private static final boolean VDBG = true;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800100 private static final String TAG = "ConnectivityService";
101
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700102 private static final boolean LOGD_RULES = false;
103
Robert Greenwalt2034b912009-08-12 16:08:25 -0700104 // how long to wait before switching back to a radio's default network
105 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
106 // system property that can override the above value
107 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
108 "android.telephony.apn-restore";
109
Robert Greenwaltbd492212011-05-06 17:10:53 -0700110 // used in recursive route setting to add gateways for the host for which
111 // a host route was requested.
112 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
113
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800114 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800115 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800116
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700117 private Vpn mVpn;
118
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700119 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
120 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700121 /** Currently active network rules by UID. */
122 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700123 /** Set of ifaces that are costly. */
124 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700125
The Android Open Source Project28527d22009-03-03 19:31:44 -0800126 /**
127 * Sometimes we want to refer to the individual network state
128 * trackers separately, and sometimes we just want to treat them
129 * abstractly.
130 */
131 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700132
133 /**
Wink Saville051a6642011-07-13 13:44:13 -0700134 * The link properties that define the current links
135 */
136 private LinkProperties mCurrentLinkProperties[];
137
138 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700139 * A per Net list of the PID's that requested access to the net
140 * used both as a refcount and for per-PID DNS selection
141 */
142 private List mNetRequestersPids[];
143
Robert Greenwalt2034b912009-08-12 16:08:25 -0700144 // priority order of the nettrackers
145 // (excluding dynamically set mNetworkPreference)
146 // TODO - move mNetworkTypePreference into this
147 private int[] mPriorityList;
148
The Android Open Source Project28527d22009-03-03 19:31:44 -0800149 private Context mContext;
150 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700151 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700152 // 0 is full bad, 100 is full good
153 private int mDefaultInetCondition = 0;
154 private int mDefaultInetConditionPublished = 0;
155 private boolean mInetConditionChangeInFlight = false;
156 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800157
158 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800159
160 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700161 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800162
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800163 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
164
Robert Greenwalt355205c2011-05-10 15:05:02 -0700165 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700166 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700167
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700168 private static final int ENABLED = 1;
169 private static final int DISABLED = 0;
170
171 // Share the event space with NetworkStateTracker (which can't see this
172 // internal class but sends us events). If you change these, change
173 // NetworkStateTracker.java too.
174 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
175 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
176
177 /**
178 * used internally as a delayed event to make us switch back to the
179 * default network
180 */
181 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
182 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
183
184 /**
185 * used internally to change our mobile data enabled flag
186 */
187 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
188 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
189
190 /**
191 * used internally to change our network preference setting
192 * arg1 = networkType to prefer
193 */
194 private static final int EVENT_SET_NETWORK_PREFERENCE =
195 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
196
197 /**
198 * used internally to synchronize inet condition reports
199 * arg1 = networkType
200 * arg2 = condition (0 bad, 100 good)
201 */
202 private static final int EVENT_INET_CONDITION_CHANGE =
203 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
204
205 /**
206 * used internally to mark the end of inet condition hold periods
207 * arg1 = networkType
208 */
209 private static final int EVENT_INET_CONDITION_HOLD_END =
210 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
211
212 /**
213 * used internally to set the background data preference
214 * arg1 = TRUE for enabled, FALSE for disabled
215 */
216 private static final int EVENT_SET_BACKGROUND_DATA =
217 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
218
219 /**
220 * used internally to set enable/disable cellular data
221 * arg1 = ENBALED or DISABLED
222 */
223 private static final int EVENT_SET_MOBILE_DATA =
224 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
225
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700226 /**
227 * used internally to clear a wakelock when transitioning
228 * from one net to another
229 */
230 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
231 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
232
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700233 /**
234 * used internally to reload global proxy settings
235 */
236 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
237 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
238
Robert Greenwalt34848c02011-03-25 13:09:25 -0700239 /**
240 * used internally to set external dependency met/unmet
241 * arg1 = ENABLED (met) or DISABLED (unmet)
242 * arg2 = NetworkType
243 */
244 private static final int EVENT_SET_DEPENDENCY_MET =
245 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
246
Robert Greenwalt2034b912009-08-12 16:08:25 -0700247 private Handler mHandler;
248
249 // list of DeathRecipients used to make sure features are turned off when
250 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500251 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700252
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400253 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800254 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400255
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700256 private PowerManager.WakeLock mNetTransitionWakeLock;
257 private String mNetTransitionWakeLockCausedBy = "";
258 private int mNetTransitionWakeLockSerialNumber;
259 private int mNetTransitionWakeLockTimeout;
260
Robert Greenwalt94daa182010-09-01 11:34:05 -0700261 private InetAddress mDefaultDns;
262
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700263 // this collection is used to refcount the added routes - if there are none left
264 // it's time to remove the route from the route table
265 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
266
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700267 // used in DBG mode to track inet condition reports
268 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
269 private ArrayList mInetLog;
270
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700271 // track the current default http proxy - tell the world if we get a new one (real change)
272 private ProxyProperties mDefaultProxy = null;
273 // track the global proxy.
274 private ProxyProperties mGlobalProxy = null;
275 private final Object mGlobalProxyLock = new Object();
276
277 private SettingsObserver mSettingsObserver;
278
Robert Greenwalt34848c02011-03-25 13:09:25 -0700279 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700280 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700281
Robert Greenwalt12c44552009-12-07 11:33:18 -0800282 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700283 public int mSimultaneity;
284 public int mType;
285 public RadioAttributes(String init) {
286 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700287 mType = Integer.parseInt(fragments[0]);
288 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700289 }
290 }
291 RadioAttributes[] mRadioAttributes;
292
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700293 // the set of network types that can only be enabled by system/sig apps
294 List mProtectedNetworks;
295
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700296 public ConnectivityService(
297 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800298 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800299
Wink Saville775aad62010-09-02 19:23:52 -0700300 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
301 handlerThread.start();
302 mHandler = new MyHandler(handlerThread.getLooper());
303
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800304 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
305 Settings.Secure.BACKGROUND_DATA, 1) == 1);
306
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800307 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800308 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
309 String id = Settings.Secure.getString(context.getContentResolver(),
310 Settings.Secure.ANDROID_ID);
311 if (id != null && id.length() > 0) {
312 String name = new String("android_").concat(id);
313 SystemProperties.set("net.hostname", name);
314 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800315 }
316
Robert Greenwalt94daa182010-09-01 11:34:05 -0700317 // read our default dns server ip
318 String dns = Settings.Secure.getString(context.getContentResolver(),
319 Settings.Secure.DEFAULT_DNS_SERVER);
320 if (dns == null || dns.length() == 0) {
321 dns = context.getResources().getString(
322 com.android.internal.R.string.config_default_dns_server);
323 }
324 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800325 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
326 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800327 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700328 }
329
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700330 mContext = checkNotNull(context, "missing Context");
331 mNetd = checkNotNull(netd, "missing INetworkManagementService");
332 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700333
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700334 try {
335 mPolicyManager.registerListener(mPolicyListener);
336 } catch (RemoteException e) {
337 // ouch, no rules updates means some processes may never get network
338 Slog.e(TAG, "unable to register INetworkPolicyListener", e);
339 }
340
341 final PowerManager powerManager = (PowerManager) context.getSystemService(
342 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700343 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
344 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
345 com.android.internal.R.integer.config_networkTransitionTimeout);
346
Robert Greenwalt2034b912009-08-12 16:08:25 -0700347 mNetTrackers = new NetworkStateTracker[
348 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700349 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700350
The Android Open Source Project28527d22009-03-03 19:31:44 -0800351 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700352
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700353 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700354 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700355
Robert Greenwalt2034b912009-08-12 16:08:25 -0700356 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700357 String[] raStrings = context.getResources().getStringArray(
358 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700359 for (String raString : raStrings) {
360 RadioAttributes r = new RadioAttributes(raString);
361 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800362 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700363 continue;
364 }
365 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800366 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700367 r.mType);
368 continue;
369 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700370 mRadioAttributes[r.mType] = r;
371 }
372
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700373 String[] naStrings = context.getResources().getStringArray(
374 com.android.internal.R.array.networkAttributes);
375 for (String naString : naStrings) {
376 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700377 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700378 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800379 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700380 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700381 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700382 }
Wink Savillef2a62832011-04-07 14:23:45 -0700383 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800384 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700385 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700386 continue;
387 }
Wink Savillef2a62832011-04-07 14:23:45 -0700388 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800389 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700390 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700391 continue;
392 }
Wink Savillef2a62832011-04-07 14:23:45 -0700393 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700394 mNetworksDefined++;
395 } catch(Exception e) {
396 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700397 }
398 }
399
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700400 mProtectedNetworks = new ArrayList<Integer>();
401 int[] protectedNetworks = context.getResources().getIntArray(
402 com.android.internal.R.array.config_protectedNetworks);
403 for (int p : protectedNetworks) {
404 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
405 mProtectedNetworks.add(p);
406 } else {
407 if (DBG) loge("Ignoring protectedNetwork " + p);
408 }
409 }
410
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700411 // high priority first
412 mPriorityList = new int[mNetworksDefined];
413 {
414 int insertionPoint = mNetworksDefined-1;
415 int currentLowest = 0;
416 int nextLowest = 0;
417 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700418 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700419 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700420 if (na.priority < currentLowest) continue;
421 if (na.priority > currentLowest) {
422 if (na.priority < nextLowest || nextLowest == 0) {
423 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700424 }
425 continue;
426 }
Wink Savillef2a62832011-04-07 14:23:45 -0700427 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700428 }
429 currentLowest = nextLowest;
430 nextLowest = 0;
431 }
432 }
433
434 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
435 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700436 mNetRequestersPids[i] = new ArrayList();
437 }
438
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500439 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700440
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700441 mNumDnsEntries = 0;
442
443 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
444 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800445 /*
446 * Create the network state trackers for Wi-Fi and mobile
447 * data. Maybe this could be done with a factory class,
448 * but it's not clear that it's worth it, given that
449 * the number of different network types is not going
450 * to change very often.
451 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700452 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700453 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700454 case ConnectivityManager.TYPE_WIFI:
Wink Savillee70c6f52010-12-03 12:01:38 -0800455 if (DBG) log("Starting Wifi Service.");
Wink Saville7fabfa22010-08-13 16:11:42 -0700456 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff25be0762010-07-28 09:35:20 -0700457 WifiService wifiService = new WifiService(context);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700458 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff25be0762010-07-28 09:35:20 -0700459 wifiService.checkAndStartWifi();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700460 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Saville7fabfa22010-08-13 16:11:42 -0700461 wst.startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700462 break;
463 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700464 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700465 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700466 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700467 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800468 case ConnectivityManager.TYPE_DUMMY:
469 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700470 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800471 mNetTrackers[netType].startMonitoring(context, mHandler);
472 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800473 case ConnectivityManager.TYPE_BLUETOOTH:
474 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
475 mNetTrackers[netType].startMonitoring(context, mHandler);
476 break;
Benoit Goby211b5692010-12-22 14:29:40 -0800477 case ConnectivityManager.TYPE_ETHERNET:
478 mNetTrackers[netType] = EthernetDataTracker.getInstance();
479 mNetTrackers[netType].startMonitoring(context, mHandler);
480 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700481 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800482 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700483 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700484 continue;
485 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700486 mCurrentLinkProperties[netType] = null;
Robert Greenwalt497ff5e72011-07-15 11:16:45 -0700487 if (mNetConfigs[netType].isDefault()) mNetTrackers[netType].reconnect();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700488 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800489
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700490 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
491 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
492
493 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700494 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700495 mTethering.getTetherableWifiRegexs().length != 0 ||
496 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700497 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800498
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700499 mVpn = new Vpn(mContext, new VpnCallback());
500
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700501 try {
502 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700503 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700504 } catch (RemoteException e) {
505 loge("Error registering observer :" + e);
506 }
507
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700508 if (DBG) {
509 mInetLog = new ArrayList();
510 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700511
512 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
513 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800514
515 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800516 }
517
518 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700519 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800520 * @param preference the new preference
521 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700522 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800523 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700524
525 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800526 }
527
528 public int getNetworkPreference() {
529 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700530 int preference;
531 synchronized(this) {
532 preference = mNetworkPreference;
533 }
534 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800535 }
536
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700537 private void handleSetNetworkPreference(int preference) {
538 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700539 mNetConfigs[preference] != null &&
540 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700541 if (mNetworkPreference != preference) {
542 final ContentResolver cr = mContext.getContentResolver();
543 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
544 synchronized(this) {
545 mNetworkPreference = preference;
546 }
547 enforcePreference();
548 }
549 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800550 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700551
The Android Open Source Project28527d22009-03-03 19:31:44 -0800552 private int getPersistedNetworkPreference() {
553 final ContentResolver cr = mContext.getContentResolver();
554
555 final int networkPrefSetting = Settings.Secure
556 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
557 if (networkPrefSetting != -1) {
558 return networkPrefSetting;
559 }
560
561 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
562 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700563
The Android Open Source Project28527d22009-03-03 19:31:44 -0800564 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700565 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800566 * In this method, we only tear down a non-preferred network. Establishing
567 * a connection to the preferred network is taken care of when we handle
568 * the disconnect event from the non-preferred network
569 * (see {@link #handleDisconnect(NetworkInfo)}).
570 */
571 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700572 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800573 return;
574
Robert Greenwalt2034b912009-08-12 16:08:25 -0700575 if (!mNetTrackers[mNetworkPreference].isAvailable())
576 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800577
Robert Greenwalt2034b912009-08-12 16:08:25 -0700578 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700579 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700580 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700581 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800582 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700583 " in enforcePreference");
584 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700585 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800586 }
587 }
588 }
589
590 private boolean teardown(NetworkStateTracker netTracker) {
591 if (netTracker.teardown()) {
592 netTracker.setTeardownRequested(true);
593 return true;
594 } else {
595 return false;
596 }
597 }
598
599 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700600 * Check if UID should be blocked from using the network represented by the
601 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700602 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700603 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
604 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700605
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700606 final boolean networkCostly;
607 final int uidRules;
608 synchronized (mRulesLock) {
609 networkCostly = mMeteredIfaces.contains(iface);
610 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700611 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700612
613 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
614 return true;
615 }
616
617 // no restrictive rules; network is visible
618 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700619 }
620
621 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700622 * Return a filtered {@link NetworkInfo}, potentially marked
623 * {@link DetailedState#BLOCKED} based on
624 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700625 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700626 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
627 NetworkInfo info = tracker.getNetworkInfo();
628 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700629 // network is blocked; clone and override state
630 info = new NetworkInfo(info);
631 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700632 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700633 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700634 }
635
636 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800637 * Return NetworkInfo for the active (i.e., connected) network interface.
638 * It is assumed that at most one network is active at a time. If more
639 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700640 * @return the info for the active network, or {@code null} if none is
641 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800642 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700643 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800644 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700645 enforceAccessPermission();
646 final int uid = Binder.getCallingUid();
647 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800648 }
649
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700650 @Override
651 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
652 enforceConnectivityInternalPermission();
653 return getNetworkInfo(mActiveDefaultNetwork, uid);
654 }
655
656 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800657 public NetworkInfo getNetworkInfo(int networkType) {
658 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700659 final int uid = Binder.getCallingUid();
660 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800661 }
662
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700663 private NetworkInfo getNetworkInfo(int networkType, int uid) {
664 NetworkInfo info = null;
665 if (isNetworkTypeValid(networkType)) {
666 final NetworkStateTracker tracker = mNetTrackers[networkType];
667 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700668 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700669 }
670 }
671 return info;
672 }
673
674 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800675 public NetworkInfo[] getAllNetworkInfo() {
676 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700677 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700678 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700679 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700680 for (NetworkStateTracker tracker : mNetTrackers) {
681 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700682 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700683 }
684 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800685 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700686 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800687 }
688
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700689 /**
690 * Return LinkProperties for the active (i.e., connected) default
691 * network interface. It is assumed that at most one default network
692 * is active at a time. If more than one is active, it is indeterminate
693 * which will be returned.
694 * @return the ip properties for the active network, or {@code null} if
695 * none is active
696 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700697 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700698 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700699 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700700 }
701
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700702 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700703 public LinkProperties getLinkProperties(int networkType) {
704 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700705 if (isNetworkTypeValid(networkType)) {
706 final NetworkStateTracker tracker = mNetTrackers[networkType];
707 if (tracker != null) {
708 return tracker.getLinkProperties();
709 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700710 }
711 return null;
712 }
713
Jeff Sharkey21062e72011-05-28 20:56:34 -0700714 @Override
715 public NetworkState[] getAllNetworkState() {
716 enforceAccessPermission();
717 final int uid = Binder.getCallingUid();
718 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700719 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700720 for (NetworkStateTracker tracker : mNetTrackers) {
721 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700722 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700723 result.add(new NetworkState(
724 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
725 }
726 }
727 }
728 return result.toArray(new NetworkState[result.size()]);
729 }
730
The Android Open Source Project28527d22009-03-03 19:31:44 -0800731 public boolean setRadios(boolean turnOn) {
732 boolean result = true;
733 enforceChangePermission();
734 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700735 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800736 }
737 return result;
738 }
739
740 public boolean setRadio(int netType, boolean turnOn) {
741 enforceChangePermission();
742 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
743 return false;
744 }
745 NetworkStateTracker tracker = mNetTrackers[netType];
746 return tracker != null && tracker.setRadio(turnOn);
747 }
748
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700749 /**
750 * Used to notice when the calling process dies so we can self-expire
751 *
752 * Also used to know if the process has cleaned up after itself when
753 * our auto-expire timer goes off. The timer has a link to an object.
754 *
755 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700756 private class FeatureUser implements IBinder.DeathRecipient {
757 int mNetworkType;
758 String mFeature;
759 IBinder mBinder;
760 int mPid;
761 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800762 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700763
764 FeatureUser(int type, String feature, IBinder binder) {
765 super();
766 mNetworkType = type;
767 mFeature = feature;
768 mBinder = binder;
769 mPid = getCallingPid();
770 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800771 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700772
Robert Greenwalt2034b912009-08-12 16:08:25 -0700773 try {
774 mBinder.linkToDeath(this, 0);
775 } catch (RemoteException e) {
776 binderDied();
777 }
778 }
779
780 void unlinkDeathRecipient() {
781 mBinder.unlinkToDeath(this, 0);
782 }
783
784 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800785 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800786 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
787 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700788 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700789 }
790
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700791 public void expire() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800792 log("ConnectivityService FeatureUser expire(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800793 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
794 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700795 stopUsingNetworkFeature(this, false);
796 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800797
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500798 public boolean isSameUser(FeatureUser u) {
799 if (u == null) return false;
800
801 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
802 }
803
804 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
805 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
806 TextUtils.equals(mFeature, feature)) {
807 return true;
808 }
809 return false;
810 }
811
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800812 public String toString() {
813 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
814 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
815 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700816 }
817
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700818 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700819 public int startUsingNetworkFeature(int networkType, String feature,
820 IBinder binder) {
821 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800822 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700823 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800824 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700825 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700826 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700827 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800828 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700829
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700830 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700831
832 // TODO - move this into the MobileDataStateTracker
833 int usedNetworkType = networkType;
834 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800835 usedNetworkType = convertFeatureToNetworkType(feature);
836 if (usedNetworkType < 0) {
837 Slog.e(TAG, "Can't match any netTracker!");
838 usedNetworkType = networkType;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700839 }
840 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700841
842 if (mProtectedNetworks.contains(usedNetworkType)) {
843 enforceConnectivityInternalPermission();
844 }
845
Robert Greenwalt2034b912009-08-12 16:08:25 -0700846 NetworkStateTracker network = mNetTrackers[usedNetworkType];
847 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800848 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700849 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700850 NetworkStateTracker radio = mNetTrackers[networkType];
851 NetworkInfo ni = network.getNetworkInfo();
852
853 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800854 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800855 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
856 return Phone.APN_TYPE_NOT_AVAILABLE;
857 } else {
858 // else make the attempt anyway - probably giving REQUEST_STARTED below
859 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700860 }
861
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500862 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
863
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700864 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500865 boolean addToList = true;
866 if (restoreTimer < 0) {
867 // In case there is no timer is specified for the feature,
868 // make sure we don't add duplicate entry with the same request.
869 for (FeatureUser u : mFeatureUsers) {
870 if (u.isSameUser(f)) {
871 // Duplicate user is found. Do not add.
872 addToList = false;
873 break;
874 }
875 }
876 }
877
878 if (addToList) mFeatureUsers.add(f);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700879 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
880 // this gets used for per-pid dns when connected
881 mNetRequestersPids[usedNetworkType].add(currentPid);
882 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700883 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700884
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700885 if (restoreTimer >= 0) {
886 mHandler.sendMessageDelayed(
887 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
888 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700889
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700890 if ((ni.isConnectedOrConnecting() == true) &&
891 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700892 if (ni.isConnected() == true) {
893 // add the pid-specific dns
Robert Greenwalt3afbead2010-07-23 15:46:26 -0700894 handleDnsConfigurationChange(networkType);
Wink Savillee70c6f52010-12-03 12:01:38 -0800895 if (DBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700896 return Phone.APN_ALREADY_ACTIVE;
897 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800898 if (DBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700899 return Phone.APN_REQUEST_STARTED;
900 }
901
902 // check if the radio in play can make another contact
903 // assume if cannot for now
904
Wink Savillee70c6f52010-12-03 12:01:38 -0800905 if (DBG) log("reconnecting to special network");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700906 network.reconnect();
907 return Phone.APN_REQUEST_STARTED;
908 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800909 // need to remember this unsupported request so we respond appropriately on stop
910 synchronized(this) {
911 mFeatureUsers.add(f);
912 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
913 // this gets used for per-pid dns when connected
914 mNetRequestersPids[usedNetworkType].add(currentPid);
915 }
916 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700917 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700918 }
919 }
920 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800921 }
922
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700923 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800924 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700925 enforceChangePermission();
926
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700927 int pid = getCallingPid();
928 int uid = getCallingUid();
929
930 FeatureUser u = null;
931 boolean found = false;
932
933 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500934 for (FeatureUser x : mFeatureUsers) {
935 if (x.isSameUser(pid, uid, networkType, feature)) {
936 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700937 found = true;
938 break;
939 }
940 }
941 }
942 if (found && u != null) {
943 // stop regardless of how many other time this proc had called start
944 return stopUsingNetworkFeature(u, true);
945 } else {
946 // none found!
Wink Savillee70c6f52010-12-03 12:01:38 -0800947 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700948 return 1;
949 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700950 }
951
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700952 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
953 int networkType = u.mNetworkType;
954 String feature = u.mFeature;
955 int pid = u.mPid;
956 int uid = u.mUid;
957
958 NetworkStateTracker tracker = null;
959 boolean callTeardown = false; // used to carry our decision outside of sync block
960
Robert Greenwalt2034b912009-08-12 16:08:25 -0700961 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800962 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -0700963 ": " + feature);
964 }
Robert Greenwalt28f43012009-10-06 17:52:40 -0700965
The Android Open Source Project28527d22009-03-03 19:31:44 -0800966 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
967 return -1;
968 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700969
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700970 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
971 // sync block
972 synchronized(this) {
973 // check if this process still has an outstanding start request
974 if (!mFeatureUsers.contains(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800975 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700976 return 1;
977 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700978 u.unlinkDeathRecipient();
979 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
980 // If we care about duplicate requests, check for that here.
981 //
982 // This is done to support the extension of a request - the app
983 // can request we start the network feature again and renew the
984 // auto-shutoff delay. Normal "stop" calls from the app though
985 // do not pay attention to duplicate requests - in effect the
986 // API does not refcount and a single stop will counter multiple starts.
987 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500988 for (FeatureUser x : mFeatureUsers) {
989 if (x.isSameUser(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800990 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700991 return 1;
992 }
993 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700994 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700995
996 // TODO - move to MobileDataStateTracker
997 int usedNetworkType = networkType;
998 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800999 usedNetworkType = convertFeatureToNetworkType(feature);
1000 if (usedNetworkType < 0) {
1001 usedNetworkType = networkType;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001002 }
1003 }
1004 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001005 if (tracker == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001006 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001007 return -1;
1008 }
1009 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001010 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001011 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001012 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001013 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001014 if (DBG) log("not tearing down special network - " +
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001015 "others still using it");
1016 return 1;
1017 }
1018 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001019 } else {
1020 if (DBG) log("not a known feature - dropping");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001021 }
1022 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001023 if (DBG) log("Doing network teardown");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001024 if (callTeardown) {
1025 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001026 return 1;
1027 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001028 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001029 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001030 }
1031
1032 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001033 * @deprecated use requestRouteToHostAddress instead
1034 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001035 * Ensure that a network route exists to deliver traffic to the specified
1036 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001037 * @param networkType the type of the network over which traffic to the
1038 * specified host is to be routed
1039 * @param hostAddress the IP address of the host to which the route is
1040 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001041 * @return {@code true} on success, {@code false} on failure
1042 */
1043 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001044 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1045
1046 if (inetAddress == null) {
1047 return false;
1048 }
1049
1050 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1051 }
1052
1053 /**
1054 * Ensure that a network route exists to deliver traffic to the specified
1055 * host via the specified network interface.
1056 * @param networkType the type of the network over which traffic to the
1057 * specified host is to be routed
1058 * @param hostAddress the IP address of the host to which the route is
1059 * desired
1060 * @return {@code true} on success, {@code false} on failure
1061 */
1062 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001063 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001064 if (mProtectedNetworks.contains(networkType)) {
1065 enforceConnectivityInternalPermission();
1066 }
1067
The Android Open Source Project28527d22009-03-03 19:31:44 -08001068 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1069 return false;
1070 }
1071 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001072
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001073 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1074 tracker.isTeardownRequested()) {
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001075 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001076 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001077 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001078 }
1079 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001080 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001081 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001082 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001083 LinkProperties lp = tracker.getLinkProperties();
1084 return addRoute(lp, RouteInfo.makeHostRoute(addr));
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001085 } catch (UnknownHostException e) {}
1086 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001087 }
1088
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001089 private boolean addRoute(LinkProperties p, RouteInfo r) {
1090 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001091 }
1092
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001093 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1094 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1095 }
1096
1097 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1098 boolean doAdd) {
1099 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1100
1101 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1102 loge("Error adding route - too much recursion");
1103 return false;
1104 }
1105
1106 if (r.isHostRoute() == false) {
1107 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1108 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001109 if (bestRoute.getGateway().equals(r.getGateway())) {
1110 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001111 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001112 } else {
1113 // if we will connect to our gateway through another route, add a direct
1114 // route to it's gateway
1115 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001116 }
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001117 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001118 }
1119 }
1120 if (doAdd) {
1121 if (DBG) log("Adding " + r + " for interface " + ifaceName);
1122 mAddedRoutes.add(r);
1123 try {
1124 mNetd.addRoute(ifaceName, r);
1125 } catch (Exception e) {
1126 // never crash - catch them all
1127 loge("Exception trying to add a route: " + e);
1128 return false;
1129 }
1130 } else {
1131 // if we remove this one and there are no more like it, then refcount==0 and
1132 // we can remove it from the table
1133 mAddedRoutes.remove(r);
1134 if (mAddedRoutes.contains(r) == false) {
1135 if (DBG) log("Removing " + r + " for interface " + ifaceName);
1136 try {
1137 mNetd.removeRoute(ifaceName, r);
1138 } catch (Exception e) {
1139 // never crash - catch them all
1140 loge("Exception trying to remove a route: " + e);
1141 return false;
1142 }
1143 } else {
1144 if (DBG) log("not removing " + r + " as it's still in use");
1145 }
1146 }
1147 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001148 }
1149
1150 /**
1151 * @see ConnectivityManager#getBackgroundDataSetting()
1152 */
1153 public boolean getBackgroundDataSetting() {
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001154 return mBackgroundDataEnabled.get();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001155 }
Robert Greenwalt0659da32009-07-16 17:21:39 -07001156
The Android Open Source Project28527d22009-03-03 19:31:44 -08001157 /**
1158 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1159 */
1160 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1161 mContext.enforceCallingOrSelfPermission(
1162 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1163 "ConnectivityService");
Robert Greenwalt0659da32009-07-16 17:21:39 -07001164
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001165 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1166
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001167 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1168 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1169 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001170
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001171 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwalt0ffdef12011-02-25 13:44:09 -08001172 Settings.Secure.putInt(mContext.getContentResolver(),
1173 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1174 Intent broadcast = new Intent(
1175 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1176 mContext.sendBroadcast(broadcast);
Robert Greenwalt0659da32009-07-16 17:21:39 -07001177 }
1178
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001179 /**
1180 * @see ConnectivityManager#getMobileDataEnabled()
1181 */
1182 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001183 // TODO: This detail should probably be in DataConnectionTracker's
1184 // which is where we store the value and maybe make this
1185 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001186 enforceAccessPermission();
1187 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1188 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savillee70c6f52010-12-03 12:01:38 -08001189 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001190 return retVal;
1191 }
1192
Robert Greenwalt34848c02011-03-25 13:09:25 -07001193 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001194 enforceConnectivityInternalPermission();
1195
Robert Greenwalt34848c02011-03-25 13:09:25 -07001196 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1197 (met ? ENABLED : DISABLED), networkType));
1198 }
1199
1200 private void handleSetDependencyMet(int networkType, boolean met) {
1201 if (mNetTrackers[networkType] != null) {
1202 if (DBG) {
1203 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1204 }
1205 mNetTrackers[networkType].setDependencyMet(met);
1206 }
1207 }
1208
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001209 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1210 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001211 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001212 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001213 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001214
1215 if (LOGD_RULES) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001216 Slog.d(TAG, "onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001217 }
1218
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001219 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001220 // skip update when we've already applied rules
1221 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1222 if (oldRules == uidRules) return;
1223
1224 mUidRules.put(uid, uidRules);
1225 }
1226
1227 // TODO: dispatch into NMS to push rules towards kernel module
1228 // TODO: notify UID when it has requested targeted updates
1229 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001230
1231 @Override
1232 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1233 // only someone like NPMS should only be calling us
1234 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1235
1236 if (LOGD_RULES) {
1237 Slog.d(TAG,
1238 "onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1239 }
1240
1241 synchronized (mRulesLock) {
1242 mMeteredIfaces.clear();
1243 for (String iface : meteredIfaces) {
1244 mMeteredIfaces.add(iface);
1245 }
1246 }
1247 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001248 };
1249
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001250 /**
1251 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1252 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001253 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001254 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001255 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001256
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001257 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001258 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001259 }
1260
1261 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001262 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1263 if (DBG) {
1264 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001265 }
Wink Savilleb9024c62010-12-07 10:31:02 -08001266 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001267 }
1268 }
1269
The Android Open Source Project28527d22009-03-03 19:31:44 -08001270 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001271 mContext.enforceCallingOrSelfPermission(
1272 android.Manifest.permission.ACCESS_NETWORK_STATE,
1273 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001274 }
1275
1276 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001277 mContext.enforceCallingOrSelfPermission(
1278 android.Manifest.permission.CHANGE_NETWORK_STATE,
1279 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001280 }
1281
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001282 // TODO Make this a special check when it goes public
1283 private void enforceTetherChangePermission() {
1284 mContext.enforceCallingOrSelfPermission(
1285 android.Manifest.permission.CHANGE_NETWORK_STATE,
1286 "ConnectivityService");
1287 }
1288
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001289 private void enforceTetherAccessPermission() {
1290 mContext.enforceCallingOrSelfPermission(
1291 android.Manifest.permission.ACCESS_NETWORK_STATE,
1292 "ConnectivityService");
1293 }
1294
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001295 private void enforceConnectivityInternalPermission() {
1296 mContext.enforceCallingOrSelfPermission(
1297 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1298 "ConnectivityService");
1299 }
1300
The Android Open Source Project28527d22009-03-03 19:31:44 -08001301 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001302 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1303 * network, we ignore it. If it is for the active network, we send out a
1304 * broadcast. But first, we check whether it might be possible to connect
1305 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001306 * @param info the {@code NetworkInfo} for the network
1307 */
1308 private void handleDisconnect(NetworkInfo info) {
1309
Robert Greenwalt2034b912009-08-12 16:08:25 -07001310 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001311
Robert Greenwalt2034b912009-08-12 16:08:25 -07001312 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001313 /*
1314 * If the disconnected network is not the active one, then don't report
1315 * this as a loss of connectivity. What probably happened is that we're
1316 * getting the disconnect for a network that we explicitly disabled
1317 * in accordance with network preference policies.
1318 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001319 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001320 List pids = mNetRequestersPids[prevNetType];
1321 for (int i = 0; i<pids.size(); i++) {
1322 Integer pid = (Integer)pids.get(i);
1323 // will remove them because the net's no longer connected
1324 // need to do this now as only now do we know the pids and
1325 // can properly null things that are no longer referenced.
1326 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001327 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001328 }
1329
The Android Open Source Project28527d22009-03-03 19:31:44 -08001330 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1331 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1332 if (info.isFailover()) {
1333 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1334 info.setFailover(false);
1335 }
1336 if (info.getReason() != null) {
1337 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1338 }
1339 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001340 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1341 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001342 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001343
Robert Greenwalt34848c02011-03-25 13:09:25 -07001344 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001345 tryFailover(prevNetType);
1346 if (mActiveDefaultNetwork != -1) {
1347 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001348 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1349 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001350 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001351 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1352 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001353 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001354 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001355
1356 // Reset interface if no other connections are using the same interface
1357 boolean doReset = true;
1358 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1359 if (linkProperties != null) {
1360 String oldIface = linkProperties.getInterfaceName();
1361 if (TextUtils.isEmpty(oldIface) == false) {
1362 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1363 if (networkStateTracker == null) continue;
1364 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1365 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1366 LinkProperties l = networkStateTracker.getLinkProperties();
1367 if (l == null) continue;
1368 if (oldIface.equals(l.getInterfaceName())) {
1369 doReset = false;
1370 break;
1371 }
1372 }
1373 }
1374 }
1375 }
1376
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001377 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001378 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001379
1380 sendStickyBroadcast(intent);
1381 /*
1382 * If the failover network is already connected, then immediately send
1383 * out a followup broadcast indicating successful failover
1384 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001385 if (mActiveDefaultNetwork != -1) {
1386 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001387 }
1388 }
1389
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001390 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001391 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001392 * If this is a default network, check if other defaults are available.
1393 * Try to reconnect on all available and let them hash it out when
1394 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001395 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001396 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001397 if (mActiveDefaultNetwork == prevNetType) {
1398 mActiveDefaultNetwork = -1;
1399 }
1400
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001401 // don't signal a reconnect for anything lower or equal priority than our
1402 // current connected default
1403 // TODO - don't filter by priority now - nice optimization but risky
1404// int currentPriority = -1;
1405// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001406// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001407// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001408 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001409 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001410 if (mNetConfigs[checkType] == null) continue;
1411 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001412
1413// Enabling the isAvailable() optimization caused mobile to not get
1414// selected if it was in the middle of error handling. Specifically
1415// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1416// would not be available and we wouldn't get connected to anything.
1417// So removing the isAvailable() optimization below for now. TODO: This
1418// optimization should work and we need to investigate why it doesn't work.
1419// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1420// complete before it is really complete.
1421// if (!mNetTrackers[checkType].isAvailable()) continue;
1422
Robert Greenwalt34848c02011-03-25 13:09:25 -07001423// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001424
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001425 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1426 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1427 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1428 checkInfo.setFailover(true);
1429 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001430 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001431 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001432 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001433 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001434 }
1435
1436 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001437 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1438 }
1439
1440 private void sendInetConditionBroadcast(NetworkInfo info) {
1441 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1442 }
1443
1444 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1445 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001446 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1447 if (info.isFailover()) {
1448 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1449 info.setFailover(false);
1450 }
1451 if (info.getReason() != null) {
1452 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1453 }
1454 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001455 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1456 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001457 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001458 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001459 sendStickyBroadcast(intent);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001460 }
1461
1462 /**
1463 * Called when an attempt to fail over to another network has failed.
1464 * @param info the {@link NetworkInfo} for the failed network
1465 */
1466 private void handleConnectionFailure(NetworkInfo info) {
1467 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001468
Robert Greenwalt2034b912009-08-12 16:08:25 -07001469 String reason = info.getReason();
1470 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001471
Robert Greenwalte981bc52010-10-08 16:35:52 -07001472 String reasonText;
1473 if (reason == null) {
1474 reasonText = ".";
1475 } else {
1476 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001477 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001478 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001479
1480 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1481 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1482 if (getActiveNetworkInfo() == null) {
1483 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1484 }
1485 if (reason != null) {
1486 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1487 }
1488 if (extraInfo != null) {
1489 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1490 }
1491 if (info.isFailover()) {
1492 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1493 info.setFailover(false);
1494 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001495
Robert Greenwalt34848c02011-03-25 13:09:25 -07001496 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001497 tryFailover(info.getType());
1498 if (mActiveDefaultNetwork != -1) {
1499 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001500 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1501 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001502 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001503 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1504 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001505 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001506
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001507 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001508 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001509 /*
1510 * If the failover network is already connected, then immediately send
1511 * out a followup broadcast indicating successful failover
1512 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001513 if (mActiveDefaultNetwork != -1) {
1514 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001515 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001516 }
1517
1518 private void sendStickyBroadcast(Intent intent) {
1519 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001520 if (!mSystemReady) {
1521 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001522 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001523 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1524 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001525 }
1526 }
1527
1528 void systemReady() {
1529 synchronized(this) {
1530 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001531 if (mInitialBroadcast != null) {
1532 mContext.sendStickyBroadcast(mInitialBroadcast);
1533 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001534 }
1535 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001536 // load the global proxy at startup
1537 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001538 }
1539
1540 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001541 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001542
1543 // snapshot isFailover, because sendConnectedBroadcast() resets it
1544 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001545 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001546
Robert Greenwalt2034b912009-08-12 16:08:25 -07001547 // if this is a default net and other default is running
1548 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001549 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001550 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1551 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001552 mNetConfigs[mActiveDefaultNetwork].priority >
1553 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001554 mNetworkPreference == mActiveDefaultNetwork) {
1555 // don't accept this one
Wink Savillee70c6f52010-12-03 12:01:38 -08001556 if (DBG) {
1557 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001558 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001559 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001560 teardown(thisNet);
1561 return;
1562 } else {
1563 // tear down the other
1564 NetworkStateTracker otherNet =
1565 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001566 if (DBG) {
1567 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001568 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001569 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001570 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001571 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001572 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001573 return;
1574 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001575 }
1576 }
1577 synchronized (ConnectivityService.this) {
1578 // have a new default network, release the transition wakelock in a second
1579 // if it's held. The second pause is to allow apps to reconnect over the
1580 // new network
1581 if (mNetTransitionWakeLock.isHeld()) {
1582 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001583 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001584 mNetTransitionWakeLockSerialNumber, 0),
1585 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001586 }
1587 }
1588 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001589 // this will cause us to come up initially as unconnected and switching
1590 // to connected after our normal pause unless somebody reports us as reall
1591 // disconnected
1592 mDefaultInetConditionPublished = 0;
1593 mDefaultConnectionSequence++;
1594 mInetConditionChangeInFlight = false;
1595 // Don't do this - if we never sign in stay, grey
1596 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001597 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001598 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001599 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001600 handleConnectivityChange(type, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001601 sendConnectedBroadcast(info);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001602 }
1603
The Android Open Source Project28527d22009-03-03 19:31:44 -08001604 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001605 * After a change in the connectivity state of a network. We're mainly
1606 * concerned with making sure that the list of DNS servers is set up
1607 * according to which networks are connected, and ensuring that the
1608 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001609 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001610 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001611 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1612
The Android Open Source Project28527d22009-03-03 19:31:44 -08001613 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001614 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001615 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001616 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001617 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001618
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001619 LinkProperties curLp = mCurrentLinkProperties[netType];
1620 LinkProperties newLp = null;
1621
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001622 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001623 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001624 if (VDBG) {
1625 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1626 " doReset=" + doReset + " resetMask=" + resetMask +
1627 "\n curLp=" + curLp +
1628 "\n newLp=" + newLp);
1629 }
1630
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001631 if (curLp != null) {
1632 if (curLp.isIdenticalInterfaceName(newLp)) {
1633 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1634 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1635 for (LinkAddress linkAddr : car.removed) {
1636 if (linkAddr.getAddress() instanceof Inet4Address) {
1637 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1638 }
1639 if (linkAddr.getAddress() instanceof Inet6Address) {
1640 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1641 }
Wink Saville051a6642011-07-13 13:44:13 -07001642 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001643 if (DBG) {
1644 log("handleConnectivityChange: addresses changed" +
1645 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1646 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001647 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001648 } else {
1649 if (DBG) {
1650 log("handleConnectivityChange: address are the same reset per doReset" +
1651 " linkProperty[" + netType + "]:" +
1652 " resetMask=" + resetMask);
1653 }
Wink Saville051a6642011-07-13 13:44:13 -07001654 }
1655 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001656 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
1657 log("handleConnectivityChange: interface not not equivalent reset both" +
1658 " linkProperty[" + netType + "]:" +
1659 " resetMask=" + resetMask);
Wink Saville051a6642011-07-13 13:44:13 -07001660 }
Wink Saville051a6642011-07-13 13:44:13 -07001661 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001662 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001663 handleApplyDefaultProxy(netType);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001664 }
1665 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001666 if (VDBG) {
1667 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1668 " doReset=" + doReset + " resetMask=" + resetMask +
1669 "\n curLp=" + curLp +
1670 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001671 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001672 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001673 mCurrentLinkProperties[netType] = newLp;
1674 updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001675
Wink Saville051a6642011-07-13 13:44:13 -07001676 if (doReset || resetMask != 0) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001677 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1678 if (linkProperties != null) {
1679 String iface = linkProperties.getInterfaceName();
1680 if (TextUtils.isEmpty(iface) == false) {
Wink Saville051a6642011-07-13 13:44:13 -07001681 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1682 NetworkUtils.resetConnections(iface, resetMask);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001683 }
1684 }
1685 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001686
1687 // TODO: Temporary notifying upstread change to Tethering.
1688 // @see bug/4455071
1689 /** Notify TetheringService if interface name has been changed. */
1690 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1691 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1692 if (isTetheringSupported()) {
1693 mTethering.handleTetherIfaceChange();
1694 }
1695 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001696 }
1697
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001698 /**
1699 * Add and remove routes using the old properties (null if not previously connected),
1700 * new properties (null if becoming disconnected). May even be double null, which
1701 * is a noop.
1702 * Uses isLinkDefault to determine if default routes should be set or conversely if
1703 * host routes should be set to the dns servers
1704 */
1705 private void updateRoutes(LinkProperties newLp, LinkProperties curLp, boolean isLinkDefault) {
1706 Collection<RouteInfo> routesToAdd = null;
1707 CompareResult<InetAddress> dnsDiff = null;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001708
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001709 if (curLp != null) {
1710 // check for the delta between the current set and the new
1711 CompareResult<RouteInfo> routeDiff = curLp.compareRoutes(newLp);
1712 dnsDiff = curLp.compareDnses(newLp);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001713
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001714 for (RouteInfo r : routeDiff.removed) {
1715 if (isLinkDefault || ! r.isDefaultRoute()) {
1716 removeRoute(curLp, r);
Robert Greenwalt355205c2011-05-10 15:05:02 -07001717 }
1718 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001719 routesToAdd = routeDiff.added;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001720 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001721
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001722 if (newLp != null) {
1723 // if we didn't get a diff from cur -> new, then just use the new
1724 if (routesToAdd == null) {
1725 routesToAdd = newLp.getRoutes();
1726 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001727
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001728 for (RouteInfo r : routesToAdd) {
1729 if (isLinkDefault || ! r.isDefaultRoute()) {
1730 addRoute(newLp, r);
1731 }
1732 }
1733 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001734
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001735 if (!isLinkDefault) {
1736 // handle DNS routes
1737 Collection<InetAddress> dnsToAdd = null;
1738 if (dnsDiff != null) {
1739 dnsToAdd = dnsDiff.added;
1740 for (InetAddress dnsAddress : dnsDiff.removed) {
1741 removeRoute(curLp, RouteInfo.makeHostRoute(dnsAddress));
1742 }
1743 }
1744 if (newLp != null) {
1745 if (dnsToAdd == null) {
1746 dnsToAdd = newLp.getDnses();
1747 }
1748 for(InetAddress dnsAddress : dnsToAdd) {
1749 addRoute(newLp, RouteInfo.makeHostRoute(dnsAddress));
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001750 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001751 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001752 }
1753 }
1754
1755
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001756 /**
1757 * Reads the network specific TCP buffer sizes from SystemProperties
1758 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1759 * wide use
1760 */
1761 public void updateNetworkSettings(NetworkStateTracker nt) {
1762 String key = nt.getTcpBufferSizesPropName();
1763 String bufferSizes = SystemProperties.get(key);
1764
1765 if (bufferSizes.length() == 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001766 loge(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001767
1768 // Setting to default values so we won't be stuck to previous values
1769 key = "net.tcp.buffersize.default";
1770 bufferSizes = SystemProperties.get(key);
1771 }
1772
1773 // Set values in kernel
1774 if (bufferSizes.length() != 0) {
1775 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001776 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001777 + "] which comes from [" + key + "]");
1778 }
1779 setBufferSize(bufferSizes);
1780 }
1781 }
1782
1783 /**
1784 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1785 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1786 *
1787 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1788 * writeMin, writeInitial, writeMax"
1789 */
1790 private void setBufferSize(String bufferSizes) {
1791 try {
1792 String[] values = bufferSizes.split(",");
1793
1794 if (values.length == 6) {
1795 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04001796 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1797 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1798 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1799 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1800 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1801 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001802 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001803 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001804 }
1805 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001806 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001807 }
1808 }
1809
Robert Greenwalt2034b912009-08-12 16:08:25 -07001810 /**
1811 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1812 * on the highest priority active net which this process requested.
1813 * If there aren't any, clear it out
1814 */
1815 private void reassessPidDns(int myPid, boolean doBump)
1816 {
Wink Savillee70c6f52010-12-03 12:01:38 -08001817 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001818 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001819 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001820 continue;
1821 }
1822 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001823 if (nt.getNetworkInfo().isConnected() &&
1824 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001825 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001826 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001827 List pids = mNetRequestersPids[i];
1828 for (int j=0; j<pids.size(); j++) {
1829 Integer pid = (Integer)pids.get(j);
1830 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001831 Collection<InetAddress> dnses = p.getDnses();
1832 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001833 if (doBump) {
1834 bumpDns();
1835 }
1836 return;
1837 }
1838 }
1839 }
1840 }
1841 // nothing found - delete
1842 for (int i = 1; ; i++) {
1843 String prop = "net.dns" + i + "." + myPid;
1844 if (SystemProperties.get(prop).length() == 0) {
1845 if (doBump) {
1846 bumpDns();
1847 }
1848 return;
1849 }
1850 SystemProperties.set(prop, "");
1851 }
1852 }
1853
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001854 // return true if results in a change
1855 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001856 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001857 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001858 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001859 String dnsString = dns.getHostAddress();
1860 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1861 changed = true;
1862 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1863 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001864 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001865 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001866 }
1867
1868 private void bumpDns() {
1869 /*
1870 * Bump the property that tells the name resolver library to reread
1871 * the DNS server list from the properties.
1872 */
1873 String propVal = SystemProperties.get("net.dnschange");
1874 int n = 0;
1875 if (propVal.length() != 0) {
1876 try {
1877 n = Integer.parseInt(propVal);
1878 } catch (NumberFormatException e) {}
1879 }
1880 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07001881 /*
1882 * Tell the VMs to toss their DNS caches
1883 */
1884 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1885 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08001886 /*
1887 * Connectivity events can happen before boot has completed ...
1888 */
1889 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07001890 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001891 }
1892
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001893 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001894 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001895 NetworkStateTracker nt = mNetTrackers[netType];
1896 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001897 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001898 if (p == null) return;
1899 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001900 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001901 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001902 int j = 1;
Robert Greenwalt94daa182010-09-01 11:34:05 -07001903 if (dnses.size() == 0 && mDefaultDns != null) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001904 String dnsString = mDefaultDns.getHostAddress();
1905 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1906 if (DBG) {
1907 log("no dns provided - using " + dnsString);
1908 }
1909 changed = true;
1910 SystemProperties.set("net.dns1", dnsString);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001911 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001912 j++;
1913 } else {
1914 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001915 String dnsString = dns.getHostAddress();
1916 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1917 j++;
1918 continue;
1919 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001920 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001921 log("adding dns " + dns + " for " +
Robert Greenwalt94daa182010-09-01 11:34:05 -07001922 nt.getNetworkInfo().getTypeName());
1923 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001924 changed = true;
1925 SystemProperties.set("net.dns" + j++, dnsString);
Robert Greenwalt94daa182010-09-01 11:34:05 -07001926 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001927 }
1928 for (int k=j ; k<mNumDnsEntries; k++) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001929 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1930 if (DBG) log("erasing net.dns" + k);
1931 changed = true;
1932 SystemProperties.set("net.dns" + k, "");
1933 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001934 }
1935 mNumDnsEntries = j;
1936 } else {
1937 // set per-pid dns for attached secondary nets
1938 List pids = mNetRequestersPids[netType];
1939 for (int y=0; y< pids.size(); y++) {
1940 Integer pid = (Integer)pids.get(y);
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001941 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001942 }
1943 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001944 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001945 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001946 }
1947
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001948 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001949 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1950 NETWORK_RESTORE_DELAY_PROP_NAME);
1951 if(restoreDefaultNetworkDelayStr != null &&
1952 restoreDefaultNetworkDelayStr.length() != 0) {
1953 try {
1954 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1955 } catch (NumberFormatException e) {
1956 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001957 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001958 // if the system property isn't set, use the value for the apn type
1959 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1960
1961 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1962 (mNetConfigs[networkType] != null)) {
1963 ret = mNetConfigs[networkType].restoreTime;
1964 }
1965 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001966 }
1967
1968 @Override
1969 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001970 if (mContext.checkCallingOrSelfPermission(
1971 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001972 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001973 pw.println("Permission Denial: can't dump ConnectivityService " +
1974 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1975 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001976 return;
1977 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001978 pw.println();
1979 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001980 if (nst != null) {
1981 if (nst.getNetworkInfo().isConnected()) {
1982 pw.println("Active network: " + nst.getNetworkInfo().
1983 getTypeName());
1984 }
1985 pw.println(nst.getNetworkInfo());
1986 pw.println(nst);
1987 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001988 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001989 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001990
1991 pw.println("Network Requester Pids:");
1992 for (int net : mPriorityList) {
1993 String pidString = net + ": ";
1994 for (Object pid : mNetRequestersPids[net]) {
1995 pidString = pidString + pid.toString() + ", ";
1996 }
1997 pw.println(pidString);
1998 }
1999 pw.println();
2000
2001 pw.println("FeatureUsers:");
2002 for (Object requester : mFeatureUsers) {
2003 pw.println(requester.toString());
2004 }
2005 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002006
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002007 synchronized (this) {
2008 pw.println("NetworkTranstionWakeLock is currently " +
2009 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2010 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2011 }
2012 pw.println();
2013
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002014 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002015
2016 if (mInetLog != null) {
2017 pw.println();
2018 pw.println("Inet condition reports:");
2019 for(int i = 0; i < mInetLog.size(); i++) {
2020 pw.println(mInetLog.get(i));
2021 }
2022 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002023 }
2024
Robert Greenwalt2034b912009-08-12 16:08:25 -07002025 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002026 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07002027 public MyHandler(Looper looper) {
2028 super(looper);
2029 }
2030
The Android Open Source Project28527d22009-03-03 19:31:44 -08002031 @Override
2032 public void handleMessage(Message msg) {
2033 NetworkInfo info;
2034 switch (msg.what) {
2035 case NetworkStateTracker.EVENT_STATE_CHANGED:
2036 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002037 int type = info.getType();
2038 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002039
Wink Savillee70c6f52010-12-03 12:01:38 -08002040 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002041 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002042 state + "/" + info.getDetailedState());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002043
2044 // Connectivity state changed:
2045 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002046 // [12-9] Network subtype (for mobile network, as defined
2047 // by TelephonyManager)
2048 // [8-3] Detailed state ordinal (as defined by
2049 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002050 // [2-0] Network type (as defined by ConnectivityManager)
2051 int eventLogParam = (info.getType() & 0x7) |
2052 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2053 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002054 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002055 eventLogParam);
2056
2057 if (info.getDetailedState() ==
2058 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002059 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002060 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002061 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002062 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002063 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002064 // the logic here is, handle SUSPENDED the same as
2065 // DISCONNECTED. The only difference being we are
2066 // broadcasting an intent with NetworkInfo that's
2067 // suspended. This allows the applications an
2068 // opportunity to handle DISCONNECTED and SUSPENDED
2069 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002070 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002071 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002072 handleConnect(info);
2073 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002074 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002075 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002076 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002077 // TODO: Temporary allowing network configuration
2078 // change not resetting sockets.
2079 // @see bug/4455071
2080 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002081 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002082 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002083 String causedBy = null;
2084 synchronized (ConnectivityService.this) {
2085 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2086 mNetTransitionWakeLock.isHeld()) {
2087 mNetTransitionWakeLock.release();
2088 causedBy = mNetTransitionWakeLockCausedBy;
2089 }
2090 }
2091 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002092 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002093 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002094 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002095 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002096 FeatureUser u = (FeatureUser)msg.obj;
2097 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002098 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002099 case EVENT_INET_CONDITION_CHANGE:
2100 {
2101 int netType = msg.arg1;
2102 int condition = msg.arg2;
2103 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002104 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002105 }
2106 case EVENT_INET_CONDITION_HOLD_END:
2107 {
2108 int netType = msg.arg1;
2109 int sequence = msg.arg2;
2110 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002111 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002112 }
2113 case EVENT_SET_NETWORK_PREFERENCE:
2114 {
2115 int preference = msg.arg1;
2116 handleSetNetworkPreference(preference);
2117 break;
2118 }
2119 case EVENT_SET_BACKGROUND_DATA:
2120 {
2121 boolean enabled = (msg.arg1 == ENABLED);
2122 handleSetBackgroundData(enabled);
2123 break;
2124 }
2125 case EVENT_SET_MOBILE_DATA:
2126 {
2127 boolean enabled = (msg.arg1 == ENABLED);
2128 handleSetMobileData(enabled);
2129 break;
2130 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002131 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2132 {
2133 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002134 break;
2135 }
2136 case EVENT_SET_DEPENDENCY_MET:
2137 {
2138 boolean met = (msg.arg1 == ENABLED);
2139 handleSetDependencyMet(msg.arg2, met);
2140 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002141 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002142 }
2143 }
2144 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002145
2146 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002147 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002148 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002149
2150 if (isTetheringSupported()) {
2151 return mTethering.tether(iface);
2152 } else {
2153 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2154 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002155 }
2156
2157 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002158 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002159 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002160
2161 if (isTetheringSupported()) {
2162 return mTethering.untether(iface);
2163 } else {
2164 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2165 }
2166 }
2167
2168 // javadoc from interface
2169 public int getLastTetherError(String iface) {
2170 enforceTetherAccessPermission();
2171
2172 if (isTetheringSupported()) {
2173 return mTethering.getLastTetherError(iface);
2174 } else {
2175 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2176 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002177 }
2178
2179 // TODO - proper iface API for selection by property, inspection, etc
2180 public String[] getTetherableUsbRegexs() {
2181 enforceTetherAccessPermission();
2182 if (isTetheringSupported()) {
2183 return mTethering.getTetherableUsbRegexs();
2184 } else {
2185 return new String[0];
2186 }
2187 }
2188
2189 public String[] getTetherableWifiRegexs() {
2190 enforceTetherAccessPermission();
2191 if (isTetheringSupported()) {
2192 return mTethering.getTetherableWifiRegexs();
2193 } else {
2194 return new String[0];
2195 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002196 }
2197
Danica Chang96567052010-08-11 14:54:43 -07002198 public String[] getTetherableBluetoothRegexs() {
2199 enforceTetherAccessPermission();
2200 if (isTetheringSupported()) {
2201 return mTethering.getTetherableBluetoothRegexs();
2202 } else {
2203 return new String[0];
2204 }
2205 }
2206
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002207 // TODO - move iface listing, queries, etc to new module
2208 // javadoc from interface
2209 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002210 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002211 return mTethering.getTetherableIfaces();
2212 }
2213
2214 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002215 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002216 return mTethering.getTetheredIfaces();
2217 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002218
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002219 public String[] getTetheringErroredIfaces() {
2220 enforceTetherAccessPermission();
2221 return mTethering.getErroredIfaces();
2222 }
2223
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002224 // if ro.tether.denied = true we default to no tethering
2225 // gservices could set the secure setting to 1 though to enable it on a build where it
2226 // had previously been turned off.
2227 public boolean isTetheringSupported() {
2228 enforceTetherAccessPermission();
2229 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002230 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2231 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2232 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002233 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002234
2235 // An API NetworkStateTrackers can call when they lose their network.
2236 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2237 // whichever happens first. The timer is started by the first caller and not
2238 // restarted by subsequent callers.
2239 public void requestNetworkTransitionWakelock(String forWhom) {
2240 enforceConnectivityInternalPermission();
2241 synchronized (this) {
2242 if (mNetTransitionWakeLock.isHeld()) return;
2243 mNetTransitionWakeLockSerialNumber++;
2244 mNetTransitionWakeLock.acquire();
2245 mNetTransitionWakeLockCausedBy = forWhom;
2246 }
2247 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002248 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002249 mNetTransitionWakeLockSerialNumber, 0),
2250 mNetTransitionWakeLockTimeout);
2251 return;
2252 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002253
Robert Greenwalt986c7412010-09-08 15:24:47 -07002254 // 100 percent is full good, 0 is full bad.
2255 public void reportInetCondition(int networkType, int percentage) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002256 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002257 mContext.enforceCallingOrSelfPermission(
2258 android.Manifest.permission.STATUS_BAR,
2259 "ConnectivityService");
2260
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002261 if (DBG) {
2262 int pid = getCallingPid();
2263 int uid = getCallingUid();
2264 String s = pid + "(" + uid + ") reports inet is " +
2265 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2266 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2267 mInetLog.add(s);
2268 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2269 mInetLog.remove(0);
2270 }
2271 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002272 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002273 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2274 }
2275
2276 private void handleInetConditionChange(int netType, int condition) {
2277 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002278 log("Inet connectivity change, net=" +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002279 netType + ", condition=" + condition +
2280 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2281 }
2282 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002283 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002284 return;
2285 }
2286 if (mActiveDefaultNetwork != netType) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002287 if (DBG) log("given net not default - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002288 return;
2289 }
2290 mDefaultInetCondition = condition;
2291 int delay;
2292 if (mInetConditionChangeInFlight == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002293 if (DBG) log("starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002294 // setup a new hold to debounce this
2295 if (mDefaultInetCondition > 50) {
2296 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2297 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2298 } else {
2299 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2300 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2301 }
2302 mInetConditionChangeInFlight = true;
2303 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2304 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2305 } else {
2306 // we've set the new condition, when this hold ends that will get
2307 // picked up
Wink Savillee70c6f52010-12-03 12:01:38 -08002308 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002309 }
2310 }
2311
2312 private void handleInetConditionHoldEnd(int netType, int sequence) {
2313 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002314 log("Inet hold end, net=" + netType +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002315 ", condition =" + mDefaultInetCondition +
2316 ", published condition =" + mDefaultInetConditionPublished);
2317 }
2318 mInetConditionChangeInFlight = false;
2319
2320 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002321 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002322 return;
2323 }
2324 if (mDefaultConnectionSequence != sequence) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002325 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002326 return;
2327 }
2328 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002329 if (DBG) log("no change in condition - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002330 return;
2331 }
2332 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2333 if (networkInfo.isConnected() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002334 if (DBG) log("default network not connected - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002335 return;
2336 }
2337 mDefaultInetConditionPublished = mDefaultInetCondition;
2338 sendInetConditionBroadcast(networkInfo);
2339 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002340 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002341
2342 public synchronized ProxyProperties getProxy() {
2343 if (mGlobalProxy != null) return mGlobalProxy;
2344 if (mDefaultProxy != null) return mDefaultProxy;
2345 return null;
2346 }
2347
2348 public void setGlobalProxy(ProxyProperties proxyProperties) {
2349 enforceChangePermission();
2350 synchronized (mGlobalProxyLock) {
2351 if (proxyProperties == mGlobalProxy) return;
2352 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2353 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2354
2355 String host = "";
2356 int port = 0;
2357 String exclList = "";
2358 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2359 mGlobalProxy = new ProxyProperties(proxyProperties);
2360 host = mGlobalProxy.getHost();
2361 port = mGlobalProxy.getPort();
2362 exclList = mGlobalProxy.getExclusionList();
2363 } else {
2364 mGlobalProxy = null;
2365 }
2366 ContentResolver res = mContext.getContentResolver();
2367 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2368 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002369 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002370 exclList);
2371 }
2372
2373 if (mGlobalProxy == null) {
2374 proxyProperties = mDefaultProxy;
2375 }
2376 sendProxyBroadcast(proxyProperties);
2377 }
2378
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002379 private void loadGlobalProxy() {
2380 ContentResolver res = mContext.getContentResolver();
2381 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2382 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2383 String exclList = Settings.Secure.getString(res,
2384 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2385 if (!TextUtils.isEmpty(host)) {
2386 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2387 synchronized (mGlobalProxyLock) {
2388 mGlobalProxy = proxyProperties;
2389 }
2390 }
2391 }
2392
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002393 public ProxyProperties getGlobalProxy() {
2394 synchronized (mGlobalProxyLock) {
2395 return mGlobalProxy;
2396 }
2397 }
2398
2399 private void handleApplyDefaultProxy(int type) {
2400 // check if new default - push it out to all VM if so
2401 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2402 synchronized (this) {
2403 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2404 if (mDefaultProxy == proxy) return;
2405 if (!TextUtils.isEmpty(proxy.getHost())) {
2406 mDefaultProxy = proxy;
2407 } else {
2408 mDefaultProxy = null;
2409 }
2410 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002411 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002412 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2413 if (mGlobalProxy != null) return;
2414 sendProxyBroadcast(proxy);
2415 }
2416
2417 private void handleDeprecatedGlobalHttpProxy() {
2418 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2419 Settings.Secure.HTTP_PROXY);
2420 if (!TextUtils.isEmpty(proxy)) {
2421 String data[] = proxy.split(":");
2422 String proxyHost = data[0];
2423 int proxyPort = 8080;
2424 if (data.length > 1) {
2425 try {
2426 proxyPort = Integer.parseInt(data[1]);
2427 } catch (NumberFormatException e) {
2428 return;
2429 }
2430 }
2431 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2432 setGlobalProxy(p);
2433 }
2434 }
2435
2436 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002437 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savillee70c6f52010-12-03 12:01:38 -08002438 log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002439 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002440 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2441 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002442 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002443 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002444 }
2445
2446 private static class SettingsObserver extends ContentObserver {
2447 private int mWhat;
2448 private Handler mHandler;
2449 SettingsObserver(Handler handler, int what) {
2450 super(handler);
2451 mHandler = handler;
2452 mWhat = what;
2453 }
2454
2455 void observe(Context context) {
2456 ContentResolver resolver = context.getContentResolver();
2457 resolver.registerContentObserver(Settings.Secure.getUriFor(
2458 Settings.Secure.HTTP_PROXY), false, this);
2459 }
2460
2461 @Override
2462 public void onChange(boolean selfChange) {
2463 mHandler.obtainMessage(mWhat).sendToTarget();
2464 }
2465 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002466
2467 private void log(String s) {
2468 Slog.d(TAG, s);
2469 }
2470
2471 private void loge(String s) {
2472 Slog.e(TAG, s);
2473 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002474
Wink Savillef6b76692011-02-24 17:58:51 -08002475 int convertFeatureToNetworkType(String feature){
2476 int networkType = -1;
2477 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2478 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2479 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2480 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2481 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2482 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2483 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2484 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2485 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2486 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2487 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2488 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2489 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2490 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2491 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2492 }
2493 return networkType;
2494 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002495
2496 private static <T> T checkNotNull(T value, String message) {
2497 if (value == null) {
2498 throw new NullPointerException(message);
2499 }
2500 return value;
2501 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002502
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002503 /**
2504 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002505 * VpnBuilder and not available in ConnectivityManager. Permissions
2506 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002507 * @hide
2508 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002509 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07002510 public boolean protectVpn(ParcelFileDescriptor socket) {
2511 try {
2512 int type = mActiveDefaultNetwork;
2513 if (ConnectivityManager.isNetworkTypeValid(type)) {
2514 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2515 return true;
2516 }
2517 } catch (Exception e) {
2518 // ignore
2519 } finally {
2520 try {
2521 socket.close();
2522 } catch (Exception e) {
2523 // ignore
2524 }
2525 }
2526 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002527 }
2528
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002529 /**
2530 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002531 * and not available in ConnectivityManager. Permissions are checked
2532 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002533 * @hide
2534 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002535 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07002536 public boolean prepareVpn(String oldPackage, String newPackage) {
2537 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002538 }
2539
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002540 /**
2541 * Configure a TUN interface and return its file descriptor. Parameters
2542 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002543 * and not available in ConnectivityManager. Permissions are checked in
2544 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002545 * @hide
2546 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002547 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002548 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002549 return mVpn.establish(config);
2550 }
2551
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002552 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002553 * Start legacy VPN and return an intent to VpnDialogs. This method is
2554 * used by VpnSettings and not available in ConnectivityManager.
2555 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002556 * @hide
2557 */
2558 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002559 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2560 mVpn.startLegacyVpn(config, racoon, mtpd);
2561 }
2562
2563 /**
2564 * Return the information of the ongoing legacy VPN. This method is used
2565 * by VpnSettings and not available in ConnectivityManager. Permissions
2566 * are checked in Vpn class.
2567 * @hide
2568 */
2569 @Override
2570 public LegacyVpnInfo getLegacyVpnInfo() {
2571 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002572 }
2573
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002574 /**
2575 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2576 * through NetworkStateTracker since it works differently. For example, it
2577 * needs to override DNS servers but never takes the default routes. It
2578 * relies on another data network, and it could keep existing connections
2579 * alive after reconnecting, switching between networks, or even resuming
2580 * from deep sleep. Calls from applications should be done synchronously
2581 * to avoid race conditions. As these are all hidden APIs, refactoring can
2582 * be done whenever a better abstraction is developed.
2583 */
2584 public class VpnCallback {
2585
2586 private VpnCallback() {
2587 }
2588
Chia-chi Yehd050d1c2011-07-01 01:09:42 -07002589 public synchronized void override(List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002590 // TODO: override DNS servers and http proxy.
2591 }
2592
2593 public synchronized void restore() {
2594 // TODO: restore VPN changes.
2595 }
2596 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002597}