blob: 5dd3a6a3a11f0de5a1a41b7f5b17975ad6ea0a82 [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
Chia-chi Yehcc844502011-07-14 18:01:57 -0700158 private Object mDnsLock = new Object();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800159 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700160 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800161
162 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700163 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800164
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800165 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
166
Robert Greenwalt355205c2011-05-10 15:05:02 -0700167 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700168 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700169
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700170 private static final int ENABLED = 1;
171 private static final int DISABLED = 0;
172
173 // Share the event space with NetworkStateTracker (which can't see this
174 // internal class but sends us events). If you change these, change
175 // NetworkStateTracker.java too.
176 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
177 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
178
179 /**
180 * used internally as a delayed event to make us switch back to the
181 * default network
182 */
183 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
184 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
185
186 /**
187 * used internally to change our mobile data enabled flag
188 */
189 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
190 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
191
192 /**
193 * used internally to change our network preference setting
194 * arg1 = networkType to prefer
195 */
196 private static final int EVENT_SET_NETWORK_PREFERENCE =
197 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
198
199 /**
200 * used internally to synchronize inet condition reports
201 * arg1 = networkType
202 * arg2 = condition (0 bad, 100 good)
203 */
204 private static final int EVENT_INET_CONDITION_CHANGE =
205 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
206
207 /**
208 * used internally to mark the end of inet condition hold periods
209 * arg1 = networkType
210 */
211 private static final int EVENT_INET_CONDITION_HOLD_END =
212 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
213
214 /**
215 * used internally to set the background data preference
216 * arg1 = TRUE for enabled, FALSE for disabled
217 */
218 private static final int EVENT_SET_BACKGROUND_DATA =
219 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
220
221 /**
222 * used internally to set enable/disable cellular data
223 * arg1 = ENBALED or DISABLED
224 */
225 private static final int EVENT_SET_MOBILE_DATA =
226 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
227
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700228 /**
229 * used internally to clear a wakelock when transitioning
230 * from one net to another
231 */
232 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
233 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
234
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700235 /**
236 * used internally to reload global proxy settings
237 */
238 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
239 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
240
Robert Greenwalt34848c02011-03-25 13:09:25 -0700241 /**
242 * used internally to set external dependency met/unmet
243 * arg1 = ENABLED (met) or DISABLED (unmet)
244 * arg2 = NetworkType
245 */
246 private static final int EVENT_SET_DEPENDENCY_MET =
247 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
248
Chia-chi Yehcc844502011-07-14 18:01:57 -0700249 /**
250 * used internally to restore DNS properties back to the
251 * default network
252 */
253 private static final int EVENT_RESTORE_DNS =
254 MAX_NETWORK_STATE_TRACKER_EVENT + 11;
255
Robert Greenwalt2034b912009-08-12 16:08:25 -0700256 private Handler mHandler;
257
258 // list of DeathRecipients used to make sure features are turned off when
259 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500260 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700261
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400262 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800263 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400264
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700265 private PowerManager.WakeLock mNetTransitionWakeLock;
266 private String mNetTransitionWakeLockCausedBy = "";
267 private int mNetTransitionWakeLockSerialNumber;
268 private int mNetTransitionWakeLockTimeout;
269
Robert Greenwalt94daa182010-09-01 11:34:05 -0700270 private InetAddress mDefaultDns;
271
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700272 // this collection is used to refcount the added routes - if there are none left
273 // it's time to remove the route from the route table
274 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
275
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700276 // used in DBG mode to track inet condition reports
277 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
278 private ArrayList mInetLog;
279
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700280 // track the current default http proxy - tell the world if we get a new one (real change)
281 private ProxyProperties mDefaultProxy = null;
282 // track the global proxy.
283 private ProxyProperties mGlobalProxy = null;
284 private final Object mGlobalProxyLock = new Object();
285
286 private SettingsObserver mSettingsObserver;
287
Robert Greenwalt34848c02011-03-25 13:09:25 -0700288 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700289 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700290
Robert Greenwalt12c44552009-12-07 11:33:18 -0800291 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700292 public int mSimultaneity;
293 public int mType;
294 public RadioAttributes(String init) {
295 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700296 mType = Integer.parseInt(fragments[0]);
297 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700298 }
299 }
300 RadioAttributes[] mRadioAttributes;
301
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700302 // the set of network types that can only be enabled by system/sig apps
303 List mProtectedNetworks;
304
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700305 public ConnectivityService(
306 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800307 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800308
Wink Saville775aad62010-09-02 19:23:52 -0700309 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
310 handlerThread.start();
311 mHandler = new MyHandler(handlerThread.getLooper());
312
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800313 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
314 Settings.Secure.BACKGROUND_DATA, 1) == 1);
315
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800316 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800317 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
318 String id = Settings.Secure.getString(context.getContentResolver(),
319 Settings.Secure.ANDROID_ID);
320 if (id != null && id.length() > 0) {
321 String name = new String("android_").concat(id);
322 SystemProperties.set("net.hostname", name);
323 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800324 }
325
Robert Greenwalt94daa182010-09-01 11:34:05 -0700326 // read our default dns server ip
327 String dns = Settings.Secure.getString(context.getContentResolver(),
328 Settings.Secure.DEFAULT_DNS_SERVER);
329 if (dns == null || dns.length() == 0) {
330 dns = context.getResources().getString(
331 com.android.internal.R.string.config_default_dns_server);
332 }
333 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800334 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
335 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800336 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700337 }
338
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700339 mContext = checkNotNull(context, "missing Context");
340 mNetd = checkNotNull(netd, "missing INetworkManagementService");
341 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700342
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700343 try {
344 mPolicyManager.registerListener(mPolicyListener);
345 } catch (RemoteException e) {
346 // ouch, no rules updates means some processes may never get network
347 Slog.e(TAG, "unable to register INetworkPolicyListener", e);
348 }
349
350 final PowerManager powerManager = (PowerManager) context.getSystemService(
351 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700352 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
353 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
354 com.android.internal.R.integer.config_networkTransitionTimeout);
355
Robert Greenwalt2034b912009-08-12 16:08:25 -0700356 mNetTrackers = new NetworkStateTracker[
357 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700358 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700359
The Android Open Source Project28527d22009-03-03 19:31:44 -0800360 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700361
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700362 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700363 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700364
Robert Greenwalt2034b912009-08-12 16:08:25 -0700365 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700366 String[] raStrings = context.getResources().getStringArray(
367 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700368 for (String raString : raStrings) {
369 RadioAttributes r = new RadioAttributes(raString);
370 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800371 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700372 continue;
373 }
374 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800375 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700376 r.mType);
377 continue;
378 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700379 mRadioAttributes[r.mType] = r;
380 }
381
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700382 String[] naStrings = context.getResources().getStringArray(
383 com.android.internal.R.array.networkAttributes);
384 for (String naString : naStrings) {
385 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700386 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700387 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800388 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700389 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700390 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700391 }
Wink Savillef2a62832011-04-07 14:23:45 -0700392 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800393 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700394 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700395 continue;
396 }
Wink Savillef2a62832011-04-07 14:23:45 -0700397 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800398 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700399 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700400 continue;
401 }
Wink Savillef2a62832011-04-07 14:23:45 -0700402 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700403 mNetworksDefined++;
404 } catch(Exception e) {
405 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700406 }
407 }
408
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700409 mProtectedNetworks = new ArrayList<Integer>();
410 int[] protectedNetworks = context.getResources().getIntArray(
411 com.android.internal.R.array.config_protectedNetworks);
412 for (int p : protectedNetworks) {
413 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
414 mProtectedNetworks.add(p);
415 } else {
416 if (DBG) loge("Ignoring protectedNetwork " + p);
417 }
418 }
419
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700420 // high priority first
421 mPriorityList = new int[mNetworksDefined];
422 {
423 int insertionPoint = mNetworksDefined-1;
424 int currentLowest = 0;
425 int nextLowest = 0;
426 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700427 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700428 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700429 if (na.priority < currentLowest) continue;
430 if (na.priority > currentLowest) {
431 if (na.priority < nextLowest || nextLowest == 0) {
432 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700433 }
434 continue;
435 }
Wink Savillef2a62832011-04-07 14:23:45 -0700436 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700437 }
438 currentLowest = nextLowest;
439 nextLowest = 0;
440 }
441 }
442
443 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
444 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700445 mNetRequestersPids[i] = new ArrayList();
446 }
447
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500448 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700449
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700450 mNumDnsEntries = 0;
451
452 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
453 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800454 /*
455 * Create the network state trackers for Wi-Fi and mobile
456 * data. Maybe this could be done with a factory class,
457 * but it's not clear that it's worth it, given that
458 * the number of different network types is not going
459 * to change very often.
460 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700461 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700462 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700463 case ConnectivityManager.TYPE_WIFI:
Wink Savillee70c6f52010-12-03 12:01:38 -0800464 if (DBG) log("Starting Wifi Service.");
Wink Saville7fabfa22010-08-13 16:11:42 -0700465 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff25be0762010-07-28 09:35:20 -0700466 WifiService wifiService = new WifiService(context);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700467 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff25be0762010-07-28 09:35:20 -0700468 wifiService.checkAndStartWifi();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700469 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Saville7fabfa22010-08-13 16:11:42 -0700470 wst.startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700471 break;
472 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700473 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700474 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700475 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700476 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800477 case ConnectivityManager.TYPE_DUMMY:
478 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700479 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800480 mNetTrackers[netType].startMonitoring(context, mHandler);
481 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800482 case ConnectivityManager.TYPE_BLUETOOTH:
483 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
484 mNetTrackers[netType].startMonitoring(context, mHandler);
485 break;
Benoit Goby211b5692010-12-22 14:29:40 -0800486 case ConnectivityManager.TYPE_ETHERNET:
487 mNetTrackers[netType] = EthernetDataTracker.getInstance();
488 mNetTrackers[netType].startMonitoring(context, mHandler);
489 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700490 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800491 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700492 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700493 continue;
494 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700495 mCurrentLinkProperties[netType] = null;
Robert Greenwalt497ff5e72011-07-15 11:16:45 -0700496 if (mNetConfigs[netType].isDefault()) mNetTrackers[netType].reconnect();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700497 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800498
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700499 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
500 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
501
502 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700503 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700504 mTethering.getTetherableWifiRegexs().length != 0 ||
505 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700506 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800507
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700508 mVpn = new Vpn(mContext, new VpnCallback());
509
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700510 try {
511 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700512 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700513 } catch (RemoteException e) {
514 loge("Error registering observer :" + e);
515 }
516
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700517 if (DBG) {
518 mInetLog = new ArrayList();
519 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700520
521 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
522 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800523
524 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800525 }
526
527 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700528 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800529 * @param preference the new preference
530 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700531 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800532 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700533
534 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800535 }
536
537 public int getNetworkPreference() {
538 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700539 int preference;
540 synchronized(this) {
541 preference = mNetworkPreference;
542 }
543 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800544 }
545
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700546 private void handleSetNetworkPreference(int preference) {
547 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700548 mNetConfigs[preference] != null &&
549 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700550 if (mNetworkPreference != preference) {
551 final ContentResolver cr = mContext.getContentResolver();
552 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
553 synchronized(this) {
554 mNetworkPreference = preference;
555 }
556 enforcePreference();
557 }
558 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800559 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700560
The Android Open Source Project28527d22009-03-03 19:31:44 -0800561 private int getPersistedNetworkPreference() {
562 final ContentResolver cr = mContext.getContentResolver();
563
564 final int networkPrefSetting = Settings.Secure
565 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
566 if (networkPrefSetting != -1) {
567 return networkPrefSetting;
568 }
569
570 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
571 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700572
The Android Open Source Project28527d22009-03-03 19:31:44 -0800573 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700574 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800575 * In this method, we only tear down a non-preferred network. Establishing
576 * a connection to the preferred network is taken care of when we handle
577 * the disconnect event from the non-preferred network
578 * (see {@link #handleDisconnect(NetworkInfo)}).
579 */
580 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700581 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800582 return;
583
Robert Greenwalt2034b912009-08-12 16:08:25 -0700584 if (!mNetTrackers[mNetworkPreference].isAvailable())
585 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800586
Robert Greenwalt2034b912009-08-12 16:08:25 -0700587 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700588 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700589 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700590 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800591 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700592 " in enforcePreference");
593 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700594 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800595 }
596 }
597 }
598
599 private boolean teardown(NetworkStateTracker netTracker) {
600 if (netTracker.teardown()) {
601 netTracker.setTeardownRequested(true);
602 return true;
603 } else {
604 return false;
605 }
606 }
607
608 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700609 * Check if UID should be blocked from using the network represented by the
610 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700611 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700612 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
613 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700614
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700615 final boolean networkCostly;
616 final int uidRules;
617 synchronized (mRulesLock) {
618 networkCostly = mMeteredIfaces.contains(iface);
619 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700620 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700621
622 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
623 return true;
624 }
625
626 // no restrictive rules; network is visible
627 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700628 }
629
630 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700631 * Return a filtered {@link NetworkInfo}, potentially marked
632 * {@link DetailedState#BLOCKED} based on
633 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700634 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700635 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
636 NetworkInfo info = tracker.getNetworkInfo();
637 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700638 // network is blocked; clone and override state
639 info = new NetworkInfo(info);
640 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700641 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700642 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700643 }
644
645 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800646 * Return NetworkInfo for the active (i.e., connected) network interface.
647 * It is assumed that at most one network is active at a time. If more
648 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700649 * @return the info for the active network, or {@code null} if none is
650 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800651 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700652 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800653 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700654 enforceAccessPermission();
655 final int uid = Binder.getCallingUid();
656 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800657 }
658
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700659 @Override
660 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
661 enforceConnectivityInternalPermission();
662 return getNetworkInfo(mActiveDefaultNetwork, uid);
663 }
664
665 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800666 public NetworkInfo getNetworkInfo(int networkType) {
667 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700668 final int uid = Binder.getCallingUid();
669 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800670 }
671
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700672 private NetworkInfo getNetworkInfo(int networkType, int uid) {
673 NetworkInfo info = null;
674 if (isNetworkTypeValid(networkType)) {
675 final NetworkStateTracker tracker = mNetTrackers[networkType];
676 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700677 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700678 }
679 }
680 return info;
681 }
682
683 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800684 public NetworkInfo[] getAllNetworkInfo() {
685 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700686 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700687 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700688 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700689 for (NetworkStateTracker tracker : mNetTrackers) {
690 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700691 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700692 }
693 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800694 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700695 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800696 }
697
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700698 /**
699 * Return LinkProperties for the active (i.e., connected) default
700 * network interface. It is assumed that at most one default network
701 * is active at a time. If more than one is active, it is indeterminate
702 * which will be returned.
703 * @return the ip properties for the active network, or {@code null} if
704 * none is active
705 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700706 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700707 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700708 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700709 }
710
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700711 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700712 public LinkProperties getLinkProperties(int networkType) {
713 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700714 if (isNetworkTypeValid(networkType)) {
715 final NetworkStateTracker tracker = mNetTrackers[networkType];
716 if (tracker != null) {
717 return tracker.getLinkProperties();
718 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700719 }
720 return null;
721 }
722
Jeff Sharkey21062e72011-05-28 20:56:34 -0700723 @Override
724 public NetworkState[] getAllNetworkState() {
725 enforceAccessPermission();
726 final int uid = Binder.getCallingUid();
727 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700728 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700729 for (NetworkStateTracker tracker : mNetTrackers) {
730 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700731 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700732 result.add(new NetworkState(
733 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
734 }
735 }
736 }
737 return result.toArray(new NetworkState[result.size()]);
738 }
739
The Android Open Source Project28527d22009-03-03 19:31:44 -0800740 public boolean setRadios(boolean turnOn) {
741 boolean result = true;
742 enforceChangePermission();
743 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700744 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800745 }
746 return result;
747 }
748
749 public boolean setRadio(int netType, boolean turnOn) {
750 enforceChangePermission();
751 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
752 return false;
753 }
754 NetworkStateTracker tracker = mNetTrackers[netType];
755 return tracker != null && tracker.setRadio(turnOn);
756 }
757
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700758 /**
759 * Used to notice when the calling process dies so we can self-expire
760 *
761 * Also used to know if the process has cleaned up after itself when
762 * our auto-expire timer goes off. The timer has a link to an object.
763 *
764 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700765 private class FeatureUser implements IBinder.DeathRecipient {
766 int mNetworkType;
767 String mFeature;
768 IBinder mBinder;
769 int mPid;
770 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800771 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700772
773 FeatureUser(int type, String feature, IBinder binder) {
774 super();
775 mNetworkType = type;
776 mFeature = feature;
777 mBinder = binder;
778 mPid = getCallingPid();
779 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800780 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700781
Robert Greenwalt2034b912009-08-12 16:08:25 -0700782 try {
783 mBinder.linkToDeath(this, 0);
784 } catch (RemoteException e) {
785 binderDied();
786 }
787 }
788
789 void unlinkDeathRecipient() {
790 mBinder.unlinkToDeath(this, 0);
791 }
792
793 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800794 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800795 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
796 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700797 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700798 }
799
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700800 public void expire() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800801 log("ConnectivityService FeatureUser expire(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800802 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
803 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700804 stopUsingNetworkFeature(this, false);
805 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800806
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500807 public boolean isSameUser(FeatureUser u) {
808 if (u == null) return false;
809
810 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
811 }
812
813 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
814 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
815 TextUtils.equals(mFeature, feature)) {
816 return true;
817 }
818 return false;
819 }
820
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800821 public String toString() {
822 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
823 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
824 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700825 }
826
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700827 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700828 public int startUsingNetworkFeature(int networkType, String feature,
829 IBinder binder) {
830 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800831 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700832 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800833 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700834 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700835 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700836 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800837 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700838
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700839 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700840
841 // TODO - move this into the MobileDataStateTracker
842 int usedNetworkType = networkType;
843 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800844 usedNetworkType = convertFeatureToNetworkType(feature);
845 if (usedNetworkType < 0) {
846 Slog.e(TAG, "Can't match any netTracker!");
847 usedNetworkType = networkType;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700848 }
849 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700850
851 if (mProtectedNetworks.contains(usedNetworkType)) {
852 enforceConnectivityInternalPermission();
853 }
854
Robert Greenwalt2034b912009-08-12 16:08:25 -0700855 NetworkStateTracker network = mNetTrackers[usedNetworkType];
856 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800857 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700858 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700859 NetworkStateTracker radio = mNetTrackers[networkType];
860 NetworkInfo ni = network.getNetworkInfo();
861
862 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800863 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800864 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
865 return Phone.APN_TYPE_NOT_AVAILABLE;
866 } else {
867 // else make the attempt anyway - probably giving REQUEST_STARTED below
868 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700869 }
870
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500871 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
872
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700873 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500874 boolean addToList = true;
875 if (restoreTimer < 0) {
876 // In case there is no timer is specified for the feature,
877 // make sure we don't add duplicate entry with the same request.
878 for (FeatureUser u : mFeatureUsers) {
879 if (u.isSameUser(f)) {
880 // Duplicate user is found. Do not add.
881 addToList = false;
882 break;
883 }
884 }
885 }
886
887 if (addToList) mFeatureUsers.add(f);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700888 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
889 // this gets used for per-pid dns when connected
890 mNetRequestersPids[usedNetworkType].add(currentPid);
891 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700892 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700893
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700894 if (restoreTimer >= 0) {
895 mHandler.sendMessageDelayed(
896 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
897 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700898
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700899 if ((ni.isConnectedOrConnecting() == true) &&
900 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700901 if (ni.isConnected() == true) {
902 // add the pid-specific dns
Robert Greenwalt3afbead2010-07-23 15:46:26 -0700903 handleDnsConfigurationChange(networkType);
Wink Savillee70c6f52010-12-03 12:01:38 -0800904 if (DBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700905 return Phone.APN_ALREADY_ACTIVE;
906 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800907 if (DBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700908 return Phone.APN_REQUEST_STARTED;
909 }
910
911 // check if the radio in play can make another contact
912 // assume if cannot for now
913
Wink Savillee70c6f52010-12-03 12:01:38 -0800914 if (DBG) log("reconnecting to special network");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700915 network.reconnect();
916 return Phone.APN_REQUEST_STARTED;
917 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800918 // need to remember this unsupported request so we respond appropriately on stop
919 synchronized(this) {
920 mFeatureUsers.add(f);
921 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
922 // this gets used for per-pid dns when connected
923 mNetRequestersPids[usedNetworkType].add(currentPid);
924 }
925 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700926 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700927 }
928 }
929 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800930 }
931
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700932 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800933 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700934 enforceChangePermission();
935
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700936 int pid = getCallingPid();
937 int uid = getCallingUid();
938
939 FeatureUser u = null;
940 boolean found = false;
941
942 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500943 for (FeatureUser x : mFeatureUsers) {
944 if (x.isSameUser(pid, uid, networkType, feature)) {
945 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700946 found = true;
947 break;
948 }
949 }
950 }
951 if (found && u != null) {
952 // stop regardless of how many other time this proc had called start
953 return stopUsingNetworkFeature(u, true);
954 } else {
955 // none found!
Wink Savillee70c6f52010-12-03 12:01:38 -0800956 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700957 return 1;
958 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700959 }
960
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700961 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
962 int networkType = u.mNetworkType;
963 String feature = u.mFeature;
964 int pid = u.mPid;
965 int uid = u.mUid;
966
967 NetworkStateTracker tracker = null;
968 boolean callTeardown = false; // used to carry our decision outside of sync block
969
Robert Greenwalt2034b912009-08-12 16:08:25 -0700970 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800971 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -0700972 ": " + feature);
973 }
Robert Greenwalt28f43012009-10-06 17:52:40 -0700974
The Android Open Source Project28527d22009-03-03 19:31:44 -0800975 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
976 return -1;
977 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700978
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700979 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
980 // sync block
981 synchronized(this) {
982 // check if this process still has an outstanding start request
983 if (!mFeatureUsers.contains(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800984 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700985 return 1;
986 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700987 u.unlinkDeathRecipient();
988 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
989 // If we care about duplicate requests, check for that here.
990 //
991 // This is done to support the extension of a request - the app
992 // can request we start the network feature again and renew the
993 // auto-shutoff delay. Normal "stop" calls from the app though
994 // do not pay attention to duplicate requests - in effect the
995 // API does not refcount and a single stop will counter multiple starts.
996 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500997 for (FeatureUser x : mFeatureUsers) {
998 if (x.isSameUser(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800999 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001000 return 1;
1001 }
1002 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001003 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001004
1005 // TODO - move to MobileDataStateTracker
1006 int usedNetworkType = networkType;
1007 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -08001008 usedNetworkType = convertFeatureToNetworkType(feature);
1009 if (usedNetworkType < 0) {
1010 usedNetworkType = networkType;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001011 }
1012 }
1013 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001014 if (tracker == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001015 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001016 return -1;
1017 }
1018 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001019 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001020 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001021 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001022 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001023 if (DBG) log("not tearing down special network - " +
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001024 "others still using it");
1025 return 1;
1026 }
1027 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001028 } else {
1029 if (DBG) log("not a known feature - dropping");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001030 }
1031 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001032 if (DBG) log("Doing network teardown");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001033 if (callTeardown) {
1034 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001035 return 1;
1036 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001037 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001038 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001039 }
1040
1041 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001042 * @deprecated use requestRouteToHostAddress instead
1043 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001044 * Ensure that a network route exists to deliver traffic to the specified
1045 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001046 * @param networkType the type of the network over which traffic to the
1047 * specified host is to be routed
1048 * @param hostAddress the IP address of the host to which the route is
1049 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001050 * @return {@code true} on success, {@code false} on failure
1051 */
1052 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001053 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1054
1055 if (inetAddress == null) {
1056 return false;
1057 }
1058
1059 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1060 }
1061
1062 /**
1063 * Ensure that a network route exists to deliver traffic to the specified
1064 * host via the specified network interface.
1065 * @param networkType the type of the network over which traffic to the
1066 * specified host is to be routed
1067 * @param hostAddress the IP address of the host to which the route is
1068 * desired
1069 * @return {@code true} on success, {@code false} on failure
1070 */
1071 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001072 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001073 if (mProtectedNetworks.contains(networkType)) {
1074 enforceConnectivityInternalPermission();
1075 }
1076
The Android Open Source Project28527d22009-03-03 19:31:44 -08001077 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1078 return false;
1079 }
1080 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001081
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001082 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1083 tracker.isTeardownRequested()) {
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001084 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001085 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001086 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001087 }
1088 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001089 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001090 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001091 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001092 LinkProperties lp = tracker.getLinkProperties();
1093 return addRoute(lp, RouteInfo.makeHostRoute(addr));
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001094 } catch (UnknownHostException e) {}
1095 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001096 }
1097
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001098 private boolean addRoute(LinkProperties p, RouteInfo r) {
1099 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001100 }
1101
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001102 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1103 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1104 }
1105
1106 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1107 boolean doAdd) {
1108 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1109
1110 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1111 loge("Error adding route - too much recursion");
1112 return false;
1113 }
1114
1115 if (r.isHostRoute() == false) {
1116 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1117 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001118 if (bestRoute.getGateway().equals(r.getGateway())) {
1119 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001120 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001121 } else {
1122 // if we will connect to our gateway through another route, add a direct
1123 // route to it's gateway
1124 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001125 }
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001126 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001127 }
1128 }
1129 if (doAdd) {
1130 if (DBG) log("Adding " + r + " for interface " + ifaceName);
1131 mAddedRoutes.add(r);
1132 try {
1133 mNetd.addRoute(ifaceName, r);
1134 } catch (Exception e) {
1135 // never crash - catch them all
1136 loge("Exception trying to add a route: " + e);
1137 return false;
1138 }
1139 } else {
1140 // if we remove this one and there are no more like it, then refcount==0 and
1141 // we can remove it from the table
1142 mAddedRoutes.remove(r);
1143 if (mAddedRoutes.contains(r) == false) {
1144 if (DBG) log("Removing " + r + " for interface " + ifaceName);
1145 try {
1146 mNetd.removeRoute(ifaceName, r);
1147 } catch (Exception e) {
1148 // never crash - catch them all
1149 loge("Exception trying to remove a route: " + e);
1150 return false;
1151 }
1152 } else {
1153 if (DBG) log("not removing " + r + " as it's still in use");
1154 }
1155 }
1156 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001157 }
1158
1159 /**
1160 * @see ConnectivityManager#getBackgroundDataSetting()
1161 */
1162 public boolean getBackgroundDataSetting() {
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001163 return mBackgroundDataEnabled.get();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001164 }
Robert Greenwalt0659da32009-07-16 17:21:39 -07001165
The Android Open Source Project28527d22009-03-03 19:31:44 -08001166 /**
1167 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1168 */
1169 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1170 mContext.enforceCallingOrSelfPermission(
1171 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1172 "ConnectivityService");
Robert Greenwalt0659da32009-07-16 17:21:39 -07001173
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001174 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1175
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001176 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1177 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1178 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001179
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001180 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwalt0ffdef12011-02-25 13:44:09 -08001181 Settings.Secure.putInt(mContext.getContentResolver(),
1182 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1183 Intent broadcast = new Intent(
1184 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1185 mContext.sendBroadcast(broadcast);
Robert Greenwalt0659da32009-07-16 17:21:39 -07001186 }
1187
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001188 /**
1189 * @see ConnectivityManager#getMobileDataEnabled()
1190 */
1191 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001192 // TODO: This detail should probably be in DataConnectionTracker's
1193 // which is where we store the value and maybe make this
1194 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001195 enforceAccessPermission();
1196 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1197 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savillee70c6f52010-12-03 12:01:38 -08001198 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001199 return retVal;
1200 }
1201
Robert Greenwalt34848c02011-03-25 13:09:25 -07001202 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001203 enforceConnectivityInternalPermission();
1204
Robert Greenwalt34848c02011-03-25 13:09:25 -07001205 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1206 (met ? ENABLED : DISABLED), networkType));
1207 }
1208
1209 private void handleSetDependencyMet(int networkType, boolean met) {
1210 if (mNetTrackers[networkType] != null) {
1211 if (DBG) {
1212 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1213 }
1214 mNetTrackers[networkType].setDependencyMet(met);
1215 }
1216 }
1217
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001218 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1219 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001220 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001221 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001222 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001223
1224 if (LOGD_RULES) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001225 Slog.d(TAG, "onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001226 }
1227
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001228 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001229 // skip update when we've already applied rules
1230 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1231 if (oldRules == uidRules) return;
1232
1233 mUidRules.put(uid, uidRules);
1234 }
1235
1236 // TODO: dispatch into NMS to push rules towards kernel module
1237 // TODO: notify UID when it has requested targeted updates
1238 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001239
1240 @Override
1241 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1242 // only someone like NPMS should only be calling us
1243 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1244
1245 if (LOGD_RULES) {
1246 Slog.d(TAG,
1247 "onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1248 }
1249
1250 synchronized (mRulesLock) {
1251 mMeteredIfaces.clear();
1252 for (String iface : meteredIfaces) {
1253 mMeteredIfaces.add(iface);
1254 }
1255 }
1256 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001257 };
1258
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001259 /**
1260 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1261 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001262 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001263 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001264 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001265
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001266 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001267 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001268 }
1269
1270 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001271 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1272 if (DBG) {
1273 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001274 }
Wink Savilleb9024c62010-12-07 10:31:02 -08001275 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001276 }
1277 }
1278
The Android Open Source Project28527d22009-03-03 19:31:44 -08001279 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001280 mContext.enforceCallingOrSelfPermission(
1281 android.Manifest.permission.ACCESS_NETWORK_STATE,
1282 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001283 }
1284
1285 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001286 mContext.enforceCallingOrSelfPermission(
1287 android.Manifest.permission.CHANGE_NETWORK_STATE,
1288 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001289 }
1290
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001291 // TODO Make this a special check when it goes public
1292 private void enforceTetherChangePermission() {
1293 mContext.enforceCallingOrSelfPermission(
1294 android.Manifest.permission.CHANGE_NETWORK_STATE,
1295 "ConnectivityService");
1296 }
1297
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001298 private void enforceTetherAccessPermission() {
1299 mContext.enforceCallingOrSelfPermission(
1300 android.Manifest.permission.ACCESS_NETWORK_STATE,
1301 "ConnectivityService");
1302 }
1303
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001304 private void enforceConnectivityInternalPermission() {
1305 mContext.enforceCallingOrSelfPermission(
1306 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1307 "ConnectivityService");
1308 }
1309
The Android Open Source Project28527d22009-03-03 19:31:44 -08001310 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001311 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1312 * network, we ignore it. If it is for the active network, we send out a
1313 * broadcast. But first, we check whether it might be possible to connect
1314 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001315 * @param info the {@code NetworkInfo} for the network
1316 */
1317 private void handleDisconnect(NetworkInfo info) {
1318
Robert Greenwalt2034b912009-08-12 16:08:25 -07001319 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001320
Robert Greenwalt2034b912009-08-12 16:08:25 -07001321 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001322 /*
1323 * If the disconnected network is not the active one, then don't report
1324 * this as a loss of connectivity. What probably happened is that we're
1325 * getting the disconnect for a network that we explicitly disabled
1326 * in accordance with network preference policies.
1327 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001328 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001329 List pids = mNetRequestersPids[prevNetType];
1330 for (int i = 0; i<pids.size(); i++) {
1331 Integer pid = (Integer)pids.get(i);
1332 // will remove them because the net's no longer connected
1333 // need to do this now as only now do we know the pids and
1334 // can properly null things that are no longer referenced.
1335 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001336 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001337 }
1338
The Android Open Source Project28527d22009-03-03 19:31:44 -08001339 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1340 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1341 if (info.isFailover()) {
1342 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1343 info.setFailover(false);
1344 }
1345 if (info.getReason() != null) {
1346 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1347 }
1348 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001349 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1350 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001351 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001352
Robert Greenwalt34848c02011-03-25 13:09:25 -07001353 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001354 tryFailover(prevNetType);
1355 if (mActiveDefaultNetwork != -1) {
1356 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001357 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1358 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001359 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001360 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1361 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001362 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001363 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001364
1365 // Reset interface if no other connections are using the same interface
1366 boolean doReset = true;
1367 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1368 if (linkProperties != null) {
1369 String oldIface = linkProperties.getInterfaceName();
1370 if (TextUtils.isEmpty(oldIface) == false) {
1371 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1372 if (networkStateTracker == null) continue;
1373 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1374 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1375 LinkProperties l = networkStateTracker.getLinkProperties();
1376 if (l == null) continue;
1377 if (oldIface.equals(l.getInterfaceName())) {
1378 doReset = false;
1379 break;
1380 }
1381 }
1382 }
1383 }
1384 }
1385
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001386 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001387 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001388
1389 sendStickyBroadcast(intent);
1390 /*
1391 * If the failover network is already connected, then immediately send
1392 * out a followup broadcast indicating successful failover
1393 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001394 if (mActiveDefaultNetwork != -1) {
1395 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001396 }
1397 }
1398
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001399 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001400 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001401 * If this is a default network, check if other defaults are available.
1402 * Try to reconnect on all available and let them hash it out when
1403 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001404 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001405 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001406 if (mActiveDefaultNetwork == prevNetType) {
1407 mActiveDefaultNetwork = -1;
1408 }
1409
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001410 // don't signal a reconnect for anything lower or equal priority than our
1411 // current connected default
1412 // TODO - don't filter by priority now - nice optimization but risky
1413// int currentPriority = -1;
1414// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001415// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001416// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001417 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001418 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001419 if (mNetConfigs[checkType] == null) continue;
1420 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001421
1422// Enabling the isAvailable() optimization caused mobile to not get
1423// selected if it was in the middle of error handling. Specifically
1424// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1425// would not be available and we wouldn't get connected to anything.
1426// So removing the isAvailable() optimization below for now. TODO: This
1427// optimization should work and we need to investigate why it doesn't work.
1428// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1429// complete before it is really complete.
1430// if (!mNetTrackers[checkType].isAvailable()) continue;
1431
Robert Greenwalt34848c02011-03-25 13:09:25 -07001432// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001433
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001434 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1435 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1436 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1437 checkInfo.setFailover(true);
1438 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001439 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001440 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001441 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001442 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001443 }
1444
1445 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001446 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1447 }
1448
1449 private void sendInetConditionBroadcast(NetworkInfo info) {
1450 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1451 }
1452
1453 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1454 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001455 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1456 if (info.isFailover()) {
1457 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1458 info.setFailover(false);
1459 }
1460 if (info.getReason() != null) {
1461 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1462 }
1463 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001464 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1465 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001466 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001467 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001468 sendStickyBroadcast(intent);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001469 }
1470
1471 /**
1472 * Called when an attempt to fail over to another network has failed.
1473 * @param info the {@link NetworkInfo} for the failed network
1474 */
1475 private void handleConnectionFailure(NetworkInfo info) {
1476 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001477
Robert Greenwalt2034b912009-08-12 16:08:25 -07001478 String reason = info.getReason();
1479 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001480
Robert Greenwalte981bc52010-10-08 16:35:52 -07001481 String reasonText;
1482 if (reason == null) {
1483 reasonText = ".";
1484 } else {
1485 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001486 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001487 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001488
1489 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1490 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1491 if (getActiveNetworkInfo() == null) {
1492 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1493 }
1494 if (reason != null) {
1495 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1496 }
1497 if (extraInfo != null) {
1498 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1499 }
1500 if (info.isFailover()) {
1501 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1502 info.setFailover(false);
1503 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001504
Robert Greenwalt34848c02011-03-25 13:09:25 -07001505 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001506 tryFailover(info.getType());
1507 if (mActiveDefaultNetwork != -1) {
1508 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001509 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1510 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001511 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001512 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1513 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001514 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001515
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001516 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001517 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001518 /*
1519 * If the failover network is already connected, then immediately send
1520 * out a followup broadcast indicating successful failover
1521 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001522 if (mActiveDefaultNetwork != -1) {
1523 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001524 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001525 }
1526
1527 private void sendStickyBroadcast(Intent intent) {
1528 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001529 if (!mSystemReady) {
1530 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001531 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001532 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1533 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001534 }
1535 }
1536
1537 void systemReady() {
1538 synchronized(this) {
1539 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001540 if (mInitialBroadcast != null) {
1541 mContext.sendStickyBroadcast(mInitialBroadcast);
1542 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001543 }
1544 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001545 // load the global proxy at startup
1546 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001547 }
1548
1549 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001550 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001551
1552 // snapshot isFailover, because sendConnectedBroadcast() resets it
1553 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001554 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001555
Robert Greenwalt2034b912009-08-12 16:08:25 -07001556 // if this is a default net and other default is running
1557 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001558 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001559 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1560 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001561 mNetConfigs[mActiveDefaultNetwork].priority >
1562 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001563 mNetworkPreference == mActiveDefaultNetwork) {
1564 // don't accept this one
Wink Savillee70c6f52010-12-03 12:01:38 -08001565 if (DBG) {
1566 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001567 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001568 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001569 teardown(thisNet);
1570 return;
1571 } else {
1572 // tear down the other
1573 NetworkStateTracker otherNet =
1574 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001575 if (DBG) {
1576 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001577 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001578 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001579 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001580 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001581 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001582 return;
1583 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001584 }
1585 }
1586 synchronized (ConnectivityService.this) {
1587 // have a new default network, release the transition wakelock in a second
1588 // if it's held. The second pause is to allow apps to reconnect over the
1589 // new network
1590 if (mNetTransitionWakeLock.isHeld()) {
1591 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001592 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001593 mNetTransitionWakeLockSerialNumber, 0),
1594 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001595 }
1596 }
1597 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001598 // this will cause us to come up initially as unconnected and switching
1599 // to connected after our normal pause unless somebody reports us as reall
1600 // disconnected
1601 mDefaultInetConditionPublished = 0;
1602 mDefaultConnectionSequence++;
1603 mInetConditionChangeInFlight = false;
1604 // Don't do this - if we never sign in stay, grey
1605 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001606 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001607 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001608 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001609 handleConnectivityChange(type, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001610 sendConnectedBroadcast(info);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001611 }
1612
The Android Open Source Project28527d22009-03-03 19:31:44 -08001613 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001614 * After a change in the connectivity state of a network. We're mainly
1615 * concerned with making sure that the list of DNS servers is set up
1616 * according to which networks are connected, and ensuring that the
1617 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001618 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001619 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001620 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1621
The Android Open Source Project28527d22009-03-03 19:31:44 -08001622 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001623 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001624 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001625 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001626 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001627
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001628 LinkProperties curLp = mCurrentLinkProperties[netType];
1629 LinkProperties newLp = null;
1630
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001631 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001632 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001633 if (VDBG) {
1634 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1635 " doReset=" + doReset + " resetMask=" + resetMask +
1636 "\n curLp=" + curLp +
1637 "\n newLp=" + newLp);
1638 }
1639
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001640 if (curLp != null) {
1641 if (curLp.isIdenticalInterfaceName(newLp)) {
1642 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1643 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1644 for (LinkAddress linkAddr : car.removed) {
1645 if (linkAddr.getAddress() instanceof Inet4Address) {
1646 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1647 }
1648 if (linkAddr.getAddress() instanceof Inet6Address) {
1649 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1650 }
Wink Saville051a6642011-07-13 13:44:13 -07001651 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001652 if (DBG) {
1653 log("handleConnectivityChange: addresses changed" +
1654 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1655 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001656 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001657 } else {
1658 if (DBG) {
1659 log("handleConnectivityChange: address are the same reset per doReset" +
1660 " linkProperty[" + netType + "]:" +
1661 " resetMask=" + resetMask);
1662 }
Wink Saville051a6642011-07-13 13:44:13 -07001663 }
1664 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001665 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
1666 log("handleConnectivityChange: interface not not equivalent reset both" +
1667 " linkProperty[" + netType + "]:" +
1668 " resetMask=" + resetMask);
Wink Saville051a6642011-07-13 13:44:13 -07001669 }
Wink Saville051a6642011-07-13 13:44:13 -07001670 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001671 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001672 handleApplyDefaultProxy(netType);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001673 }
1674 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001675 if (VDBG) {
1676 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1677 " doReset=" + doReset + " resetMask=" + resetMask +
1678 "\n curLp=" + curLp +
1679 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001680 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001681 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001682 mCurrentLinkProperties[netType] = newLp;
1683 updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001684
Wink Saville051a6642011-07-13 13:44:13 -07001685 if (doReset || resetMask != 0) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001686 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1687 if (linkProperties != null) {
1688 String iface = linkProperties.getInterfaceName();
1689 if (TextUtils.isEmpty(iface) == false) {
Wink Saville051a6642011-07-13 13:44:13 -07001690 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1691 NetworkUtils.resetConnections(iface, resetMask);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001692 }
1693 }
1694 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001695
1696 // TODO: Temporary notifying upstread change to Tethering.
1697 // @see bug/4455071
1698 /** Notify TetheringService if interface name has been changed. */
1699 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1700 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1701 if (isTetheringSupported()) {
1702 mTethering.handleTetherIfaceChange();
1703 }
1704 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001705 }
1706
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001707 /**
1708 * Add and remove routes using the old properties (null if not previously connected),
1709 * new properties (null if becoming disconnected). May even be double null, which
1710 * is a noop.
1711 * Uses isLinkDefault to determine if default routes should be set or conversely if
1712 * host routes should be set to the dns servers
1713 */
1714 private void updateRoutes(LinkProperties newLp, LinkProperties curLp, boolean isLinkDefault) {
1715 Collection<RouteInfo> routesToAdd = null;
1716 CompareResult<InetAddress> dnsDiff = null;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001717
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001718 if (curLp != null) {
1719 // check for the delta between the current set and the new
1720 CompareResult<RouteInfo> routeDiff = curLp.compareRoutes(newLp);
1721 dnsDiff = curLp.compareDnses(newLp);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001722
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001723 for (RouteInfo r : routeDiff.removed) {
1724 if (isLinkDefault || ! r.isDefaultRoute()) {
1725 removeRoute(curLp, r);
Robert Greenwalt355205c2011-05-10 15:05:02 -07001726 }
1727 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001728 routesToAdd = routeDiff.added;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001729 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001730
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001731 if (newLp != null) {
1732 // if we didn't get a diff from cur -> new, then just use the new
1733 if (routesToAdd == null) {
1734 routesToAdd = newLp.getRoutes();
1735 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001736
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001737 for (RouteInfo r : routesToAdd) {
1738 if (isLinkDefault || ! r.isDefaultRoute()) {
1739 addRoute(newLp, r);
1740 }
1741 }
1742 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001743
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001744 if (!isLinkDefault) {
1745 // handle DNS routes
1746 Collection<InetAddress> dnsToAdd = null;
1747 if (dnsDiff != null) {
1748 dnsToAdd = dnsDiff.added;
1749 for (InetAddress dnsAddress : dnsDiff.removed) {
1750 removeRoute(curLp, RouteInfo.makeHostRoute(dnsAddress));
1751 }
1752 }
1753 if (newLp != null) {
1754 if (dnsToAdd == null) {
1755 dnsToAdd = newLp.getDnses();
1756 }
1757 for(InetAddress dnsAddress : dnsToAdd) {
1758 addRoute(newLp, RouteInfo.makeHostRoute(dnsAddress));
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001759 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001760 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001761 }
1762 }
1763
1764
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001765 /**
1766 * Reads the network specific TCP buffer sizes from SystemProperties
1767 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1768 * wide use
1769 */
1770 public void updateNetworkSettings(NetworkStateTracker nt) {
1771 String key = nt.getTcpBufferSizesPropName();
1772 String bufferSizes = SystemProperties.get(key);
1773
1774 if (bufferSizes.length() == 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001775 loge(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001776
1777 // Setting to default values so we won't be stuck to previous values
1778 key = "net.tcp.buffersize.default";
1779 bufferSizes = SystemProperties.get(key);
1780 }
1781
1782 // Set values in kernel
1783 if (bufferSizes.length() != 0) {
1784 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001785 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001786 + "] which comes from [" + key + "]");
1787 }
1788 setBufferSize(bufferSizes);
1789 }
1790 }
1791
1792 /**
1793 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1794 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1795 *
1796 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1797 * writeMin, writeInitial, writeMax"
1798 */
1799 private void setBufferSize(String bufferSizes) {
1800 try {
1801 String[] values = bufferSizes.split(",");
1802
1803 if (values.length == 6) {
1804 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04001805 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1806 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1807 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1808 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1809 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1810 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001811 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001812 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001813 }
1814 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001815 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001816 }
1817 }
1818
Robert Greenwalt2034b912009-08-12 16:08:25 -07001819 /**
1820 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1821 * on the highest priority active net which this process requested.
1822 * If there aren't any, clear it out
1823 */
1824 private void reassessPidDns(int myPid, boolean doBump)
1825 {
Wink Savillee70c6f52010-12-03 12:01:38 -08001826 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001827 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001828 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001829 continue;
1830 }
1831 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001832 if (nt.getNetworkInfo().isConnected() &&
1833 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001834 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001835 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001836 List pids = mNetRequestersPids[i];
1837 for (int j=0; j<pids.size(); j++) {
1838 Integer pid = (Integer)pids.get(j);
1839 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001840 Collection<InetAddress> dnses = p.getDnses();
1841 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001842 if (doBump) {
1843 bumpDns();
1844 }
1845 return;
1846 }
1847 }
1848 }
1849 }
1850 // nothing found - delete
1851 for (int i = 1; ; i++) {
1852 String prop = "net.dns" + i + "." + myPid;
1853 if (SystemProperties.get(prop).length() == 0) {
1854 if (doBump) {
1855 bumpDns();
1856 }
1857 return;
1858 }
1859 SystemProperties.set(prop, "");
1860 }
1861 }
1862
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001863 // return true if results in a change
1864 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001865 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001866 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001867 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001868 String dnsString = dns.getHostAddress();
1869 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1870 changed = true;
1871 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1872 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001873 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001874 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001875 }
1876
1877 private void bumpDns() {
1878 /*
1879 * Bump the property that tells the name resolver library to reread
1880 * the DNS server list from the properties.
1881 */
1882 String propVal = SystemProperties.get("net.dnschange");
1883 int n = 0;
1884 if (propVal.length() != 0) {
1885 try {
1886 n = Integer.parseInt(propVal);
1887 } catch (NumberFormatException e) {}
1888 }
1889 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07001890 /*
1891 * Tell the VMs to toss their DNS caches
1892 */
1893 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1894 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08001895 /*
1896 * Connectivity events can happen before boot has completed ...
1897 */
1898 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07001899 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001900 }
1901
Chia-chi Yehcc844502011-07-14 18:01:57 -07001902 // Caller must grab mDnsLock.
1903 private boolean updateDns(String network, Collection<InetAddress> dnses, String domains) {
1904 boolean changed = false;
1905 int last = 0;
1906 if (dnses.size() == 0 && mDefaultDns != null) {
1907 ++last;
1908 String value = mDefaultDns.getHostAddress();
1909 if (!value.equals(SystemProperties.get("net.dns1"))) {
1910 if (DBG) {
1911 log("no dns provided for " + network + " - using " + value);
1912 }
1913 changed = true;
1914 SystemProperties.set("net.dns1", value);
1915 }
1916 } else {
1917 for (InetAddress dns : dnses) {
1918 ++last;
1919 String key = "net.dns" + last;
1920 String value = dns.getHostAddress();
1921 if (!changed && value.equals(SystemProperties.get(key))) {
1922 continue;
1923 }
1924 if (DBG) {
1925 log("adding dns " + value + " for " + network);
1926 }
1927 changed = true;
1928 SystemProperties.set(key, value);
1929 }
1930 }
1931 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
1932 String key = "net.dns" + i;
1933 if (DBG) log("erasing " + key);
1934 changed = true;
1935 SystemProperties.set(key, "");
1936 }
1937 mNumDnsEntries = last;
1938
1939 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
1940 SystemProperties.set("net.dns.search", domains);
1941 changed = true;
1942 }
1943 return changed;
1944 }
1945
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001946 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001947 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001948 NetworkStateTracker nt = mNetTrackers[netType];
1949 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001950 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001951 if (p == null) return;
1952 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001953 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001954 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07001955 String network = nt.getNetworkInfo().getTypeName();
1956 synchronized (mDnsLock) {
1957 if (!mDnsOverridden) {
1958 changed = updateDns(network, dnses, "");
Robert Greenwalt94daa182010-09-01 11:34:05 -07001959 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001960 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001961 } else {
1962 // set per-pid dns for attached secondary nets
1963 List pids = mNetRequestersPids[netType];
1964 for (int y=0; y< pids.size(); y++) {
1965 Integer pid = (Integer)pids.get(y);
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001966 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001967 }
1968 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001969 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001970 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001971 }
1972
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001973 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001974 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1975 NETWORK_RESTORE_DELAY_PROP_NAME);
1976 if(restoreDefaultNetworkDelayStr != null &&
1977 restoreDefaultNetworkDelayStr.length() != 0) {
1978 try {
1979 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1980 } catch (NumberFormatException e) {
1981 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001982 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001983 // if the system property isn't set, use the value for the apn type
1984 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1985
1986 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1987 (mNetConfigs[networkType] != null)) {
1988 ret = mNetConfigs[networkType].restoreTime;
1989 }
1990 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001991 }
1992
1993 @Override
1994 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001995 if (mContext.checkCallingOrSelfPermission(
1996 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001997 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001998 pw.println("Permission Denial: can't dump ConnectivityService " +
1999 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2000 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002001 return;
2002 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002003 pw.println();
2004 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002005 if (nst != null) {
2006 if (nst.getNetworkInfo().isConnected()) {
2007 pw.println("Active network: " + nst.getNetworkInfo().
2008 getTypeName());
2009 }
2010 pw.println(nst.getNetworkInfo());
2011 pw.println(nst);
2012 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002013 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002014 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002015
2016 pw.println("Network Requester Pids:");
2017 for (int net : mPriorityList) {
2018 String pidString = net + ": ";
2019 for (Object pid : mNetRequestersPids[net]) {
2020 pidString = pidString + pid.toString() + ", ";
2021 }
2022 pw.println(pidString);
2023 }
2024 pw.println();
2025
2026 pw.println("FeatureUsers:");
2027 for (Object requester : mFeatureUsers) {
2028 pw.println(requester.toString());
2029 }
2030 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002031
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002032 synchronized (this) {
2033 pw.println("NetworkTranstionWakeLock is currently " +
2034 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2035 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2036 }
2037 pw.println();
2038
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002039 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002040
2041 if (mInetLog != null) {
2042 pw.println();
2043 pw.println("Inet condition reports:");
2044 for(int i = 0; i < mInetLog.size(); i++) {
2045 pw.println(mInetLog.get(i));
2046 }
2047 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002048 }
2049
Robert Greenwalt2034b912009-08-12 16:08:25 -07002050 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002051 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07002052 public MyHandler(Looper looper) {
2053 super(looper);
2054 }
2055
The Android Open Source Project28527d22009-03-03 19:31:44 -08002056 @Override
2057 public void handleMessage(Message msg) {
2058 NetworkInfo info;
2059 switch (msg.what) {
2060 case NetworkStateTracker.EVENT_STATE_CHANGED:
2061 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002062 int type = info.getType();
2063 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002064
Wink Savillee70c6f52010-12-03 12:01:38 -08002065 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002066 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002067 state + "/" + info.getDetailedState());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002068
2069 // Connectivity state changed:
2070 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002071 // [12-9] Network subtype (for mobile network, as defined
2072 // by TelephonyManager)
2073 // [8-3] Detailed state ordinal (as defined by
2074 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002075 // [2-0] Network type (as defined by ConnectivityManager)
2076 int eventLogParam = (info.getType() & 0x7) |
2077 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2078 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002079 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002080 eventLogParam);
2081
2082 if (info.getDetailedState() ==
2083 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002084 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002085 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002086 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002087 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002088 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002089 // the logic here is, handle SUSPENDED the same as
2090 // DISCONNECTED. The only difference being we are
2091 // broadcasting an intent with NetworkInfo that's
2092 // suspended. This allows the applications an
2093 // opportunity to handle DISCONNECTED and SUSPENDED
2094 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002095 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002096 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002097 handleConnect(info);
2098 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002099 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002100 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002101 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002102 // TODO: Temporary allowing network configuration
2103 // change not resetting sockets.
2104 // @see bug/4455071
2105 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002106 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002107 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002108 String causedBy = null;
2109 synchronized (ConnectivityService.this) {
2110 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2111 mNetTransitionWakeLock.isHeld()) {
2112 mNetTransitionWakeLock.release();
2113 causedBy = mNetTransitionWakeLockCausedBy;
2114 }
2115 }
2116 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002117 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002118 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002119 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002120 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002121 FeatureUser u = (FeatureUser)msg.obj;
2122 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002123 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002124 case EVENT_INET_CONDITION_CHANGE:
2125 {
2126 int netType = msg.arg1;
2127 int condition = msg.arg2;
2128 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002129 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002130 }
2131 case EVENT_INET_CONDITION_HOLD_END:
2132 {
2133 int netType = msg.arg1;
2134 int sequence = msg.arg2;
2135 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002136 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002137 }
2138 case EVENT_SET_NETWORK_PREFERENCE:
2139 {
2140 int preference = msg.arg1;
2141 handleSetNetworkPreference(preference);
2142 break;
2143 }
2144 case EVENT_SET_BACKGROUND_DATA:
2145 {
2146 boolean enabled = (msg.arg1 == ENABLED);
2147 handleSetBackgroundData(enabled);
2148 break;
2149 }
2150 case EVENT_SET_MOBILE_DATA:
2151 {
2152 boolean enabled = (msg.arg1 == ENABLED);
2153 handleSetMobileData(enabled);
2154 break;
2155 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002156 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2157 {
2158 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002159 break;
2160 }
2161 case EVENT_SET_DEPENDENCY_MET:
2162 {
2163 boolean met = (msg.arg1 == ENABLED);
2164 handleSetDependencyMet(msg.arg2, met);
2165 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002166 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002167 case EVENT_RESTORE_DNS:
2168 {
2169 if (mActiveDefaultNetwork != -1) {
2170 handleDnsConfigurationChange(mActiveDefaultNetwork);
2171 }
2172 break;
2173 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002174 }
2175 }
2176 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002177
2178 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002179 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002180 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002181
2182 if (isTetheringSupported()) {
2183 return mTethering.tether(iface);
2184 } else {
2185 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2186 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002187 }
2188
2189 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002190 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002191 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002192
2193 if (isTetheringSupported()) {
2194 return mTethering.untether(iface);
2195 } else {
2196 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2197 }
2198 }
2199
2200 // javadoc from interface
2201 public int getLastTetherError(String iface) {
2202 enforceTetherAccessPermission();
2203
2204 if (isTetheringSupported()) {
2205 return mTethering.getLastTetherError(iface);
2206 } else {
2207 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2208 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002209 }
2210
2211 // TODO - proper iface API for selection by property, inspection, etc
2212 public String[] getTetherableUsbRegexs() {
2213 enforceTetherAccessPermission();
2214 if (isTetheringSupported()) {
2215 return mTethering.getTetherableUsbRegexs();
2216 } else {
2217 return new String[0];
2218 }
2219 }
2220
2221 public String[] getTetherableWifiRegexs() {
2222 enforceTetherAccessPermission();
2223 if (isTetheringSupported()) {
2224 return mTethering.getTetherableWifiRegexs();
2225 } else {
2226 return new String[0];
2227 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002228 }
2229
Danica Chang96567052010-08-11 14:54:43 -07002230 public String[] getTetherableBluetoothRegexs() {
2231 enforceTetherAccessPermission();
2232 if (isTetheringSupported()) {
2233 return mTethering.getTetherableBluetoothRegexs();
2234 } else {
2235 return new String[0];
2236 }
2237 }
2238
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002239 // TODO - move iface listing, queries, etc to new module
2240 // javadoc from interface
2241 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002242 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002243 return mTethering.getTetherableIfaces();
2244 }
2245
2246 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002247 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002248 return mTethering.getTetheredIfaces();
2249 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002250
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002251 public String[] getTetheringErroredIfaces() {
2252 enforceTetherAccessPermission();
2253 return mTethering.getErroredIfaces();
2254 }
2255
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002256 // if ro.tether.denied = true we default to no tethering
2257 // gservices could set the secure setting to 1 though to enable it on a build where it
2258 // had previously been turned off.
2259 public boolean isTetheringSupported() {
2260 enforceTetherAccessPermission();
2261 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002262 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2263 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2264 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002265 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002266
2267 // An API NetworkStateTrackers can call when they lose their network.
2268 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2269 // whichever happens first. The timer is started by the first caller and not
2270 // restarted by subsequent callers.
2271 public void requestNetworkTransitionWakelock(String forWhom) {
2272 enforceConnectivityInternalPermission();
2273 synchronized (this) {
2274 if (mNetTransitionWakeLock.isHeld()) return;
2275 mNetTransitionWakeLockSerialNumber++;
2276 mNetTransitionWakeLock.acquire();
2277 mNetTransitionWakeLockCausedBy = forWhom;
2278 }
2279 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002280 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002281 mNetTransitionWakeLockSerialNumber, 0),
2282 mNetTransitionWakeLockTimeout);
2283 return;
2284 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002285
Robert Greenwalt986c7412010-09-08 15:24:47 -07002286 // 100 percent is full good, 0 is full bad.
2287 public void reportInetCondition(int networkType, int percentage) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002288 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002289 mContext.enforceCallingOrSelfPermission(
2290 android.Manifest.permission.STATUS_BAR,
2291 "ConnectivityService");
2292
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002293 if (DBG) {
2294 int pid = getCallingPid();
2295 int uid = getCallingUid();
2296 String s = pid + "(" + uid + ") reports inet is " +
2297 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2298 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2299 mInetLog.add(s);
2300 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2301 mInetLog.remove(0);
2302 }
2303 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002304 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002305 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2306 }
2307
2308 private void handleInetConditionChange(int netType, int condition) {
2309 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002310 log("Inet connectivity change, net=" +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002311 netType + ", condition=" + condition +
2312 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2313 }
2314 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002315 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002316 return;
2317 }
2318 if (mActiveDefaultNetwork != netType) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002319 if (DBG) log("given net not default - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002320 return;
2321 }
2322 mDefaultInetCondition = condition;
2323 int delay;
2324 if (mInetConditionChangeInFlight == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002325 if (DBG) log("starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002326 // setup a new hold to debounce this
2327 if (mDefaultInetCondition > 50) {
2328 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2329 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2330 } else {
2331 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2332 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2333 }
2334 mInetConditionChangeInFlight = true;
2335 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2336 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2337 } else {
2338 // we've set the new condition, when this hold ends that will get
2339 // picked up
Wink Savillee70c6f52010-12-03 12:01:38 -08002340 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002341 }
2342 }
2343
2344 private void handleInetConditionHoldEnd(int netType, int sequence) {
2345 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002346 log("Inet hold end, net=" + netType +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002347 ", condition =" + mDefaultInetCondition +
2348 ", published condition =" + mDefaultInetConditionPublished);
2349 }
2350 mInetConditionChangeInFlight = false;
2351
2352 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002353 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002354 return;
2355 }
2356 if (mDefaultConnectionSequence != sequence) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002357 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002358 return;
2359 }
2360 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002361 if (DBG) log("no change in condition - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002362 return;
2363 }
2364 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2365 if (networkInfo.isConnected() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002366 if (DBG) log("default network not connected - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002367 return;
2368 }
2369 mDefaultInetConditionPublished = mDefaultInetCondition;
2370 sendInetConditionBroadcast(networkInfo);
2371 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002372 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002373
2374 public synchronized ProxyProperties getProxy() {
2375 if (mGlobalProxy != null) return mGlobalProxy;
2376 if (mDefaultProxy != null) return mDefaultProxy;
2377 return null;
2378 }
2379
2380 public void setGlobalProxy(ProxyProperties proxyProperties) {
2381 enforceChangePermission();
2382 synchronized (mGlobalProxyLock) {
2383 if (proxyProperties == mGlobalProxy) return;
2384 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2385 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2386
2387 String host = "";
2388 int port = 0;
2389 String exclList = "";
2390 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2391 mGlobalProxy = new ProxyProperties(proxyProperties);
2392 host = mGlobalProxy.getHost();
2393 port = mGlobalProxy.getPort();
2394 exclList = mGlobalProxy.getExclusionList();
2395 } else {
2396 mGlobalProxy = null;
2397 }
2398 ContentResolver res = mContext.getContentResolver();
2399 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2400 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002401 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002402 exclList);
2403 }
2404
2405 if (mGlobalProxy == null) {
2406 proxyProperties = mDefaultProxy;
2407 }
2408 sendProxyBroadcast(proxyProperties);
2409 }
2410
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002411 private void loadGlobalProxy() {
2412 ContentResolver res = mContext.getContentResolver();
2413 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2414 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2415 String exclList = Settings.Secure.getString(res,
2416 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2417 if (!TextUtils.isEmpty(host)) {
2418 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2419 synchronized (mGlobalProxyLock) {
2420 mGlobalProxy = proxyProperties;
2421 }
2422 }
2423 }
2424
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002425 public ProxyProperties getGlobalProxy() {
2426 synchronized (mGlobalProxyLock) {
2427 return mGlobalProxy;
2428 }
2429 }
2430
2431 private void handleApplyDefaultProxy(int type) {
2432 // check if new default - push it out to all VM if so
2433 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2434 synchronized (this) {
2435 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2436 if (mDefaultProxy == proxy) return;
2437 if (!TextUtils.isEmpty(proxy.getHost())) {
2438 mDefaultProxy = proxy;
2439 } else {
2440 mDefaultProxy = null;
2441 }
2442 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002443 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002444 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2445 if (mGlobalProxy != null) return;
2446 sendProxyBroadcast(proxy);
2447 }
2448
2449 private void handleDeprecatedGlobalHttpProxy() {
2450 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2451 Settings.Secure.HTTP_PROXY);
2452 if (!TextUtils.isEmpty(proxy)) {
2453 String data[] = proxy.split(":");
2454 String proxyHost = data[0];
2455 int proxyPort = 8080;
2456 if (data.length > 1) {
2457 try {
2458 proxyPort = Integer.parseInt(data[1]);
2459 } catch (NumberFormatException e) {
2460 return;
2461 }
2462 }
2463 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2464 setGlobalProxy(p);
2465 }
2466 }
2467
2468 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002469 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savillee70c6f52010-12-03 12:01:38 -08002470 log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002471 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002472 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2473 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002474 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002475 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002476 }
2477
2478 private static class SettingsObserver extends ContentObserver {
2479 private int mWhat;
2480 private Handler mHandler;
2481 SettingsObserver(Handler handler, int what) {
2482 super(handler);
2483 mHandler = handler;
2484 mWhat = what;
2485 }
2486
2487 void observe(Context context) {
2488 ContentResolver resolver = context.getContentResolver();
2489 resolver.registerContentObserver(Settings.Secure.getUriFor(
2490 Settings.Secure.HTTP_PROXY), false, this);
2491 }
2492
2493 @Override
2494 public void onChange(boolean selfChange) {
2495 mHandler.obtainMessage(mWhat).sendToTarget();
2496 }
2497 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002498
2499 private void log(String s) {
2500 Slog.d(TAG, s);
2501 }
2502
2503 private void loge(String s) {
2504 Slog.e(TAG, s);
2505 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002506
Wink Savillef6b76692011-02-24 17:58:51 -08002507 int convertFeatureToNetworkType(String feature){
2508 int networkType = -1;
2509 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2510 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2511 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2512 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2513 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2514 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2515 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2516 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2517 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2518 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2519 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2520 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2521 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2522 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2523 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2524 }
2525 return networkType;
2526 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002527
2528 private static <T> T checkNotNull(T value, String message) {
2529 if (value == null) {
2530 throw new NullPointerException(message);
2531 }
2532 return value;
2533 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002534
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002535 /**
2536 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002537 * VpnBuilder and not available in ConnectivityManager. Permissions
2538 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002539 * @hide
2540 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002541 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07002542 public boolean protectVpn(ParcelFileDescriptor socket) {
2543 try {
2544 int type = mActiveDefaultNetwork;
2545 if (ConnectivityManager.isNetworkTypeValid(type)) {
2546 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2547 return true;
2548 }
2549 } catch (Exception e) {
2550 // ignore
2551 } finally {
2552 try {
2553 socket.close();
2554 } catch (Exception e) {
2555 // ignore
2556 }
2557 }
2558 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002559 }
2560
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002561 /**
2562 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002563 * and not available in ConnectivityManager. Permissions are checked
2564 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002565 * @hide
2566 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002567 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07002568 public boolean prepareVpn(String oldPackage, String newPackage) {
2569 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002570 }
2571
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002572 /**
2573 * Configure a TUN interface and return its file descriptor. Parameters
2574 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002575 * and not available in ConnectivityManager. Permissions are checked in
2576 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002577 * @hide
2578 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002579 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002580 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002581 return mVpn.establish(config);
2582 }
2583
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002584 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002585 * Start legacy VPN and return an intent to VpnDialogs. This method is
2586 * used by VpnSettings and not available in ConnectivityManager.
2587 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002588 * @hide
2589 */
2590 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002591 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2592 mVpn.startLegacyVpn(config, racoon, mtpd);
2593 }
2594
2595 /**
2596 * Return the information of the ongoing legacy VPN. This method is used
2597 * by VpnSettings and not available in ConnectivityManager. Permissions
2598 * are checked in Vpn class.
2599 * @hide
2600 */
2601 @Override
2602 public LegacyVpnInfo getLegacyVpnInfo() {
2603 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002604 }
2605
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002606 /**
2607 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2608 * through NetworkStateTracker since it works differently. For example, it
2609 * needs to override DNS servers but never takes the default routes. It
2610 * relies on another data network, and it could keep existing connections
2611 * alive after reconnecting, switching between networks, or even resuming
2612 * from deep sleep. Calls from applications should be done synchronously
2613 * to avoid race conditions. As these are all hidden APIs, refactoring can
2614 * be done whenever a better abstraction is developed.
2615 */
2616 public class VpnCallback {
2617
2618 private VpnCallback() {
2619 }
2620
Chia-chi Yehcc844502011-07-14 18:01:57 -07002621 public void override(List<String> dnsServers, List<String> searchDomains) {
2622 if (dnsServers == null) {
2623 restore();
2624 return;
2625 }
2626
2627 // Convert DNS servers into addresses.
2628 List<InetAddress> addresses = new ArrayList<InetAddress>();
2629 for (String address : dnsServers) {
2630 // Double check the addresses and remove invalid ones.
2631 try {
2632 addresses.add(InetAddress.parseNumericAddress(address));
2633 } catch (Exception e) {
2634 // ignore
2635 }
2636 }
2637 if (addresses.isEmpty()) {
2638 restore();
2639 return;
2640 }
2641
2642 // Concatenate search domains into a string.
2643 StringBuilder buffer = new StringBuilder();
2644 if (searchDomains != null) {
2645 for (String domain : searchDomains) {
2646 buffer.append(domain).append(' ');
2647 }
2648 }
2649 String domains = buffer.toString().trim();
2650
2651 // Apply DNS changes.
2652 boolean changed = false;
2653 synchronized (mDnsLock) {
2654 changed = updateDns("VPN", addresses, domains);
2655 mDnsOverridden = true;
2656 }
2657 if (changed) {
2658 bumpDns();
2659 }
2660
2661 // TODO: temporarily remove http proxy?
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002662 }
2663
Chia-chi Yehcc844502011-07-14 18:01:57 -07002664 public void restore() {
2665 synchronized (mDnsLock) {
2666 if (!mDnsOverridden) {
2667 return;
2668 }
2669 mDnsOverridden = false;
2670 }
2671 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002672 }
2673 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002674}