blob: 4ea094a59f0296435c873e27d71168f44285d40b [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 Greenwaltec05b3c2009-10-30 14:17:42 -0700496 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800497
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700498 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
499 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
500
501 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700502 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700503 mTethering.getTetherableWifiRegexs().length != 0 ||
504 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700505 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800506
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700507 mVpn = new Vpn(mContext, new VpnCallback());
508
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700509 try {
510 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700511 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700512 } catch (RemoteException e) {
513 loge("Error registering observer :" + e);
514 }
515
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700516 if (DBG) {
517 mInetLog = new ArrayList();
518 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700519
520 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
521 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800522
523 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800524 }
525
526 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700527 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800528 * @param preference the new preference
529 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700530 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800531 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700532
533 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800534 }
535
536 public int getNetworkPreference() {
537 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700538 int preference;
539 synchronized(this) {
540 preference = mNetworkPreference;
541 }
542 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800543 }
544
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700545 private void handleSetNetworkPreference(int preference) {
546 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700547 mNetConfigs[preference] != null &&
548 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700549 if (mNetworkPreference != preference) {
550 final ContentResolver cr = mContext.getContentResolver();
551 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
552 synchronized(this) {
553 mNetworkPreference = preference;
554 }
555 enforcePreference();
556 }
557 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800558 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700559
The Android Open Source Project28527d22009-03-03 19:31:44 -0800560 private int getPersistedNetworkPreference() {
561 final ContentResolver cr = mContext.getContentResolver();
562
563 final int networkPrefSetting = Settings.Secure
564 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
565 if (networkPrefSetting != -1) {
566 return networkPrefSetting;
567 }
568
569 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
570 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700571
The Android Open Source Project28527d22009-03-03 19:31:44 -0800572 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700573 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800574 * In this method, we only tear down a non-preferred network. Establishing
575 * a connection to the preferred network is taken care of when we handle
576 * the disconnect event from the non-preferred network
577 * (see {@link #handleDisconnect(NetworkInfo)}).
578 */
579 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700580 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800581 return;
582
Robert Greenwalt2034b912009-08-12 16:08:25 -0700583 if (!mNetTrackers[mNetworkPreference].isAvailable())
584 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800585
Robert Greenwalt2034b912009-08-12 16:08:25 -0700586 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700587 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700588 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700589 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800590 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700591 " in enforcePreference");
592 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700593 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800594 }
595 }
596 }
597
598 private boolean teardown(NetworkStateTracker netTracker) {
599 if (netTracker.teardown()) {
600 netTracker.setTeardownRequested(true);
601 return true;
602 } else {
603 return false;
604 }
605 }
606
607 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700608 * Check if UID should be blocked from using the network represented by the
609 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700610 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700611 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
612 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700613
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700614 final boolean networkCostly;
615 final int uidRules;
616 synchronized (mRulesLock) {
617 networkCostly = mMeteredIfaces.contains(iface);
618 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700619 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700620
621 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
622 return true;
623 }
624
625 // no restrictive rules; network is visible
626 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700627 }
628
629 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700630 * Return a filtered {@link NetworkInfo}, potentially marked
631 * {@link DetailedState#BLOCKED} based on
632 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700633 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700634 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
635 NetworkInfo info = tracker.getNetworkInfo();
636 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700637 // network is blocked; clone and override state
638 info = new NetworkInfo(info);
639 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700640 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700641 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700642 }
643
644 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800645 * Return NetworkInfo for the active (i.e., connected) network interface.
646 * It is assumed that at most one network is active at a time. If more
647 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700648 * @return the info for the active network, or {@code null} if none is
649 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800650 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700651 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800652 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700653 enforceAccessPermission();
654 final int uid = Binder.getCallingUid();
655 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800656 }
657
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700658 @Override
659 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
660 enforceConnectivityInternalPermission();
661 return getNetworkInfo(mActiveDefaultNetwork, uid);
662 }
663
664 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800665 public NetworkInfo getNetworkInfo(int networkType) {
666 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700667 final int uid = Binder.getCallingUid();
668 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800669 }
670
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700671 private NetworkInfo getNetworkInfo(int networkType, int uid) {
672 NetworkInfo info = null;
673 if (isNetworkTypeValid(networkType)) {
674 final NetworkStateTracker tracker = mNetTrackers[networkType];
675 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700676 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700677 }
678 }
679 return info;
680 }
681
682 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800683 public NetworkInfo[] getAllNetworkInfo() {
684 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700685 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700686 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700687 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700688 for (NetworkStateTracker tracker : mNetTrackers) {
689 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700690 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700691 }
692 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800693 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700694 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800695 }
696
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700697 /**
698 * Return LinkProperties for the active (i.e., connected) default
699 * network interface. It is assumed that at most one default network
700 * is active at a time. If more than one is active, it is indeterminate
701 * which will be returned.
702 * @return the ip properties for the active network, or {@code null} if
703 * none is active
704 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700705 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700706 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700707 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700708 }
709
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700710 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700711 public LinkProperties getLinkProperties(int networkType) {
712 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700713 if (isNetworkTypeValid(networkType)) {
714 final NetworkStateTracker tracker = mNetTrackers[networkType];
715 if (tracker != null) {
716 return tracker.getLinkProperties();
717 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700718 }
719 return null;
720 }
721
Jeff Sharkey21062e72011-05-28 20:56:34 -0700722 @Override
723 public NetworkState[] getAllNetworkState() {
724 enforceAccessPermission();
725 final int uid = Binder.getCallingUid();
726 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700727 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700728 for (NetworkStateTracker tracker : mNetTrackers) {
729 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700730 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700731 result.add(new NetworkState(
732 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
733 }
734 }
735 }
736 return result.toArray(new NetworkState[result.size()]);
737 }
738
The Android Open Source Project28527d22009-03-03 19:31:44 -0800739 public boolean setRadios(boolean turnOn) {
740 boolean result = true;
741 enforceChangePermission();
742 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700743 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800744 }
745 return result;
746 }
747
748 public boolean setRadio(int netType, boolean turnOn) {
749 enforceChangePermission();
750 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
751 return false;
752 }
753 NetworkStateTracker tracker = mNetTrackers[netType];
754 return tracker != null && tracker.setRadio(turnOn);
755 }
756
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700757 /**
758 * Used to notice when the calling process dies so we can self-expire
759 *
760 * Also used to know if the process has cleaned up after itself when
761 * our auto-expire timer goes off. The timer has a link to an object.
762 *
763 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700764 private class FeatureUser implements IBinder.DeathRecipient {
765 int mNetworkType;
766 String mFeature;
767 IBinder mBinder;
768 int mPid;
769 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800770 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700771
772 FeatureUser(int type, String feature, IBinder binder) {
773 super();
774 mNetworkType = type;
775 mFeature = feature;
776 mBinder = binder;
777 mPid = getCallingPid();
778 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800779 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700780
Robert Greenwalt2034b912009-08-12 16:08:25 -0700781 try {
782 mBinder.linkToDeath(this, 0);
783 } catch (RemoteException e) {
784 binderDied();
785 }
786 }
787
788 void unlinkDeathRecipient() {
789 mBinder.unlinkToDeath(this, 0);
790 }
791
792 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800793 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800794 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
795 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700796 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700797 }
798
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700799 public void expire() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800800 log("ConnectivityService FeatureUser expire(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800801 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
802 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700803 stopUsingNetworkFeature(this, false);
804 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800805
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500806 public boolean isSameUser(FeatureUser u) {
807 if (u == null) return false;
808
809 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
810 }
811
812 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
813 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
814 TextUtils.equals(mFeature, feature)) {
815 return true;
816 }
817 return false;
818 }
819
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800820 public String toString() {
821 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
822 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
823 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700824 }
825
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700826 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700827 public int startUsingNetworkFeature(int networkType, String feature,
828 IBinder binder) {
829 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800830 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700831 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800832 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700833 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700834 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700835 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800836 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700837
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700838 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700839
840 // TODO - move this into the MobileDataStateTracker
841 int usedNetworkType = networkType;
842 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800843 usedNetworkType = convertFeatureToNetworkType(feature);
844 if (usedNetworkType < 0) {
845 Slog.e(TAG, "Can't match any netTracker!");
846 usedNetworkType = networkType;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700847 }
848 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700849
850 if (mProtectedNetworks.contains(usedNetworkType)) {
851 enforceConnectivityInternalPermission();
852 }
853
Robert Greenwalt2034b912009-08-12 16:08:25 -0700854 NetworkStateTracker network = mNetTrackers[usedNetworkType];
855 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800856 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700857 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700858 NetworkStateTracker radio = mNetTrackers[networkType];
859 NetworkInfo ni = network.getNetworkInfo();
860
861 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800862 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800863 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
864 return Phone.APN_TYPE_NOT_AVAILABLE;
865 } else {
866 // else make the attempt anyway - probably giving REQUEST_STARTED below
867 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700868 }
869
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500870 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
871
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700872 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500873 boolean addToList = true;
874 if (restoreTimer < 0) {
875 // In case there is no timer is specified for the feature,
876 // make sure we don't add duplicate entry with the same request.
877 for (FeatureUser u : mFeatureUsers) {
878 if (u.isSameUser(f)) {
879 // Duplicate user is found. Do not add.
880 addToList = false;
881 break;
882 }
883 }
884 }
885
886 if (addToList) mFeatureUsers.add(f);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700887 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
888 // this gets used for per-pid dns when connected
889 mNetRequestersPids[usedNetworkType].add(currentPid);
890 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700891 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700892
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700893 if (restoreTimer >= 0) {
894 mHandler.sendMessageDelayed(
895 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
896 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700897
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700898 if ((ni.isConnectedOrConnecting() == true) &&
899 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700900 if (ni.isConnected() == true) {
901 // add the pid-specific dns
Robert Greenwalt3afbead2010-07-23 15:46:26 -0700902 handleDnsConfigurationChange(networkType);
Wink Savillee70c6f52010-12-03 12:01:38 -0800903 if (DBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700904 return Phone.APN_ALREADY_ACTIVE;
905 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800906 if (DBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700907 return Phone.APN_REQUEST_STARTED;
908 }
909
910 // check if the radio in play can make another contact
911 // assume if cannot for now
912
Wink Savillee70c6f52010-12-03 12:01:38 -0800913 if (DBG) log("reconnecting to special network");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700914 network.reconnect();
915 return Phone.APN_REQUEST_STARTED;
916 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800917 // need to remember this unsupported request so we respond appropriately on stop
918 synchronized(this) {
919 mFeatureUsers.add(f);
920 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
921 // this gets used for per-pid dns when connected
922 mNetRequestersPids[usedNetworkType].add(currentPid);
923 }
924 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700925 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700926 }
927 }
928 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800929 }
930
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700931 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800932 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700933 enforceChangePermission();
934
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700935 int pid = getCallingPid();
936 int uid = getCallingUid();
937
938 FeatureUser u = null;
939 boolean found = false;
940
941 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500942 for (FeatureUser x : mFeatureUsers) {
943 if (x.isSameUser(pid, uid, networkType, feature)) {
944 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700945 found = true;
946 break;
947 }
948 }
949 }
950 if (found && u != null) {
951 // stop regardless of how many other time this proc had called start
952 return stopUsingNetworkFeature(u, true);
953 } else {
954 // none found!
Wink Savillee70c6f52010-12-03 12:01:38 -0800955 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700956 return 1;
957 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700958 }
959
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700960 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
961 int networkType = u.mNetworkType;
962 String feature = u.mFeature;
963 int pid = u.mPid;
964 int uid = u.mUid;
965
966 NetworkStateTracker tracker = null;
967 boolean callTeardown = false; // used to carry our decision outside of sync block
968
Robert Greenwalt2034b912009-08-12 16:08:25 -0700969 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800970 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -0700971 ": " + feature);
972 }
Robert Greenwalt28f43012009-10-06 17:52:40 -0700973
The Android Open Source Project28527d22009-03-03 19:31:44 -0800974 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
975 return -1;
976 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700977
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700978 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
979 // sync block
980 synchronized(this) {
981 // check if this process still has an outstanding start request
982 if (!mFeatureUsers.contains(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800983 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700984 return 1;
985 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700986 u.unlinkDeathRecipient();
987 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
988 // If we care about duplicate requests, check for that here.
989 //
990 // This is done to support the extension of a request - the app
991 // can request we start the network feature again and renew the
992 // auto-shutoff delay. Normal "stop" calls from the app though
993 // do not pay attention to duplicate requests - in effect the
994 // API does not refcount and a single stop will counter multiple starts.
995 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500996 for (FeatureUser x : mFeatureUsers) {
997 if (x.isSameUser(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800998 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700999 return 1;
1000 }
1001 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001002 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001003
1004 // TODO - move to MobileDataStateTracker
1005 int usedNetworkType = networkType;
1006 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -08001007 usedNetworkType = convertFeatureToNetworkType(feature);
1008 if (usedNetworkType < 0) {
1009 usedNetworkType = networkType;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001010 }
1011 }
1012 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001013 if (tracker == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001014 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001015 return -1;
1016 }
1017 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001018 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001019 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001020 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001021 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001022 if (DBG) log("not tearing down special network - " +
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001023 "others still using it");
1024 return 1;
1025 }
1026 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001027 } else {
1028 if (DBG) log("not a known feature - dropping");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001029 }
1030 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001031 if (DBG) log("Doing network teardown");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001032 if (callTeardown) {
1033 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001034 return 1;
1035 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001036 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001037 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001038 }
1039
1040 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001041 * @deprecated use requestRouteToHostAddress instead
1042 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001043 * Ensure that a network route exists to deliver traffic to the specified
1044 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001045 * @param networkType the type of the network over which traffic to the
1046 * specified host is to be routed
1047 * @param hostAddress the IP address of the host to which the route is
1048 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001049 * @return {@code true} on success, {@code false} on failure
1050 */
1051 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001052 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1053
1054 if (inetAddress == null) {
1055 return false;
1056 }
1057
1058 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1059 }
1060
1061 /**
1062 * Ensure that a network route exists to deliver traffic to the specified
1063 * host via the specified network interface.
1064 * @param networkType the type of the network over which traffic to the
1065 * specified host is to be routed
1066 * @param hostAddress the IP address of the host to which the route is
1067 * desired
1068 * @return {@code true} on success, {@code false} on failure
1069 */
1070 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001071 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001072 if (mProtectedNetworks.contains(networkType)) {
1073 enforceConnectivityInternalPermission();
1074 }
1075
The Android Open Source Project28527d22009-03-03 19:31:44 -08001076 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1077 return false;
1078 }
1079 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001080
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001081 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1082 tracker.isTeardownRequested()) {
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001083 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001084 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001085 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001086 }
1087 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001088 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001089 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001090 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001091 LinkProperties lp = tracker.getLinkProperties();
1092 return addRoute(lp, RouteInfo.makeHostRoute(addr));
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001093 } catch (UnknownHostException e) {}
1094 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001095 }
1096
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001097 private boolean addRoute(LinkProperties p, RouteInfo r) {
1098 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001099 }
1100
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001101 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1102 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1103 }
1104
1105 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1106 boolean doAdd) {
1107 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1108
1109 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1110 loge("Error adding route - too much recursion");
1111 return false;
1112 }
1113
1114 if (r.isHostRoute() == false) {
1115 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1116 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001117 if (bestRoute.getGateway().equals(r.getGateway())) {
1118 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001119 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001120 } else {
1121 // if we will connect to our gateway through another route, add a direct
1122 // route to it's gateway
1123 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001124 }
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001125 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001126 }
1127 }
1128 if (doAdd) {
1129 if (DBG) log("Adding " + r + " for interface " + ifaceName);
1130 mAddedRoutes.add(r);
1131 try {
1132 mNetd.addRoute(ifaceName, r);
1133 } catch (Exception e) {
1134 // never crash - catch them all
1135 loge("Exception trying to add a route: " + e);
1136 return false;
1137 }
1138 } else {
1139 // if we remove this one and there are no more like it, then refcount==0 and
1140 // we can remove it from the table
1141 mAddedRoutes.remove(r);
1142 if (mAddedRoutes.contains(r) == false) {
1143 if (DBG) log("Removing " + r + " for interface " + ifaceName);
1144 try {
1145 mNetd.removeRoute(ifaceName, r);
1146 } catch (Exception e) {
1147 // never crash - catch them all
1148 loge("Exception trying to remove a route: " + e);
1149 return false;
1150 }
1151 } else {
1152 if (DBG) log("not removing " + r + " as it's still in use");
1153 }
1154 }
1155 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001156 }
1157
1158 /**
1159 * @see ConnectivityManager#getBackgroundDataSetting()
1160 */
1161 public boolean getBackgroundDataSetting() {
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001162 return mBackgroundDataEnabled.get();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001163 }
Robert Greenwalt0659da32009-07-16 17:21:39 -07001164
The Android Open Source Project28527d22009-03-03 19:31:44 -08001165 /**
1166 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1167 */
1168 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1169 mContext.enforceCallingOrSelfPermission(
1170 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1171 "ConnectivityService");
Robert Greenwalt0659da32009-07-16 17:21:39 -07001172
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001173 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1174
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001175 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1176 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1177 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001178
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001179 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwalt0ffdef12011-02-25 13:44:09 -08001180 Settings.Secure.putInt(mContext.getContentResolver(),
1181 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1182 Intent broadcast = new Intent(
1183 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1184 mContext.sendBroadcast(broadcast);
Robert Greenwalt0659da32009-07-16 17:21:39 -07001185 }
1186
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001187 /**
1188 * @see ConnectivityManager#getMobileDataEnabled()
1189 */
1190 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001191 // TODO: This detail should probably be in DataConnectionTracker's
1192 // which is where we store the value and maybe make this
1193 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001194 enforceAccessPermission();
1195 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1196 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savillee70c6f52010-12-03 12:01:38 -08001197 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001198 return retVal;
1199 }
1200
Robert Greenwalt34848c02011-03-25 13:09:25 -07001201 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001202 enforceConnectivityInternalPermission();
1203
Robert Greenwalt34848c02011-03-25 13:09:25 -07001204 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1205 (met ? ENABLED : DISABLED), networkType));
1206 }
1207
1208 private void handleSetDependencyMet(int networkType, boolean met) {
1209 if (mNetTrackers[networkType] != null) {
1210 if (DBG) {
1211 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1212 }
1213 mNetTrackers[networkType].setDependencyMet(met);
1214 }
1215 }
1216
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001217 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1218 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001219 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001220 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001221 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001222
1223 if (LOGD_RULES) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001224 Slog.d(TAG, "onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001225 }
1226
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001227 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001228 // skip update when we've already applied rules
1229 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1230 if (oldRules == uidRules) return;
1231
1232 mUidRules.put(uid, uidRules);
1233 }
1234
1235 // TODO: dispatch into NMS to push rules towards kernel module
1236 // TODO: notify UID when it has requested targeted updates
1237 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001238
1239 @Override
1240 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1241 // only someone like NPMS should only be calling us
1242 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1243
1244 if (LOGD_RULES) {
1245 Slog.d(TAG,
1246 "onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1247 }
1248
1249 synchronized (mRulesLock) {
1250 mMeteredIfaces.clear();
1251 for (String iface : meteredIfaces) {
1252 mMeteredIfaces.add(iface);
1253 }
1254 }
1255 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001256 };
1257
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001258 /**
1259 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1260 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001261 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001262 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001263 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001264
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001265 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001266 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001267 }
1268
1269 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001270 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1271 if (DBG) {
1272 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001273 }
Wink Savilleb9024c62010-12-07 10:31:02 -08001274 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001275 }
1276 }
1277
The Android Open Source Project28527d22009-03-03 19:31:44 -08001278 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001279 mContext.enforceCallingOrSelfPermission(
1280 android.Manifest.permission.ACCESS_NETWORK_STATE,
1281 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001282 }
1283
1284 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001285 mContext.enforceCallingOrSelfPermission(
1286 android.Manifest.permission.CHANGE_NETWORK_STATE,
1287 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001288 }
1289
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001290 // TODO Make this a special check when it goes public
1291 private void enforceTetherChangePermission() {
1292 mContext.enforceCallingOrSelfPermission(
1293 android.Manifest.permission.CHANGE_NETWORK_STATE,
1294 "ConnectivityService");
1295 }
1296
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001297 private void enforceTetherAccessPermission() {
1298 mContext.enforceCallingOrSelfPermission(
1299 android.Manifest.permission.ACCESS_NETWORK_STATE,
1300 "ConnectivityService");
1301 }
1302
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001303 private void enforceConnectivityInternalPermission() {
1304 mContext.enforceCallingOrSelfPermission(
1305 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1306 "ConnectivityService");
1307 }
1308
The Android Open Source Project28527d22009-03-03 19:31:44 -08001309 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001310 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1311 * network, we ignore it. If it is for the active network, we send out a
1312 * broadcast. But first, we check whether it might be possible to connect
1313 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001314 * @param info the {@code NetworkInfo} for the network
1315 */
1316 private void handleDisconnect(NetworkInfo info) {
1317
Robert Greenwalt2034b912009-08-12 16:08:25 -07001318 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001319
Robert Greenwalt2034b912009-08-12 16:08:25 -07001320 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001321 /*
1322 * If the disconnected network is not the active one, then don't report
1323 * this as a loss of connectivity. What probably happened is that we're
1324 * getting the disconnect for a network that we explicitly disabled
1325 * in accordance with network preference policies.
1326 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001327 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001328 List pids = mNetRequestersPids[prevNetType];
1329 for (int i = 0; i<pids.size(); i++) {
1330 Integer pid = (Integer)pids.get(i);
1331 // will remove them because the net's no longer connected
1332 // need to do this now as only now do we know the pids and
1333 // can properly null things that are no longer referenced.
1334 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001335 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001336 }
1337
The Android Open Source Project28527d22009-03-03 19:31:44 -08001338 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1339 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1340 if (info.isFailover()) {
1341 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1342 info.setFailover(false);
1343 }
1344 if (info.getReason() != null) {
1345 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1346 }
1347 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001348 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1349 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001350 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001351
Robert Greenwalt34848c02011-03-25 13:09:25 -07001352 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001353 tryFailover(prevNetType);
1354 if (mActiveDefaultNetwork != -1) {
1355 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001356 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1357 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001358 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001359 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1360 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001361 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001362 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001363
1364 // Reset interface if no other connections are using the same interface
1365 boolean doReset = true;
1366 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1367 if (linkProperties != null) {
1368 String oldIface = linkProperties.getInterfaceName();
1369 if (TextUtils.isEmpty(oldIface) == false) {
1370 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1371 if (networkStateTracker == null) continue;
1372 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1373 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1374 LinkProperties l = networkStateTracker.getLinkProperties();
1375 if (l == null) continue;
1376 if (oldIface.equals(l.getInterfaceName())) {
1377 doReset = false;
1378 break;
1379 }
1380 }
1381 }
1382 }
1383 }
1384
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001385 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001386 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001387
1388 sendStickyBroadcast(intent);
1389 /*
1390 * If the failover network is already connected, then immediately send
1391 * out a followup broadcast indicating successful failover
1392 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001393 if (mActiveDefaultNetwork != -1) {
1394 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001395 }
1396 }
1397
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001398 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001399 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001400 * If this is a default network, check if other defaults are available.
1401 * Try to reconnect on all available and let them hash it out when
1402 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001403 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001404 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001405 if (mActiveDefaultNetwork == prevNetType) {
1406 mActiveDefaultNetwork = -1;
1407 }
1408
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001409 // don't signal a reconnect for anything lower or equal priority than our
1410 // current connected default
1411 // TODO - don't filter by priority now - nice optimization but risky
1412// int currentPriority = -1;
1413// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001414// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001415// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001416 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001417 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001418 if (mNetConfigs[checkType] == null) continue;
1419 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001420
1421// Enabling the isAvailable() optimization caused mobile to not get
1422// selected if it was in the middle of error handling. Specifically
1423// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1424// would not be available and we wouldn't get connected to anything.
1425// So removing the isAvailable() optimization below for now. TODO: This
1426// optimization should work and we need to investigate why it doesn't work.
1427// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1428// complete before it is really complete.
1429// if (!mNetTrackers[checkType].isAvailable()) continue;
1430
Robert Greenwalt34848c02011-03-25 13:09:25 -07001431// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001432
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001433 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1434 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1435 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1436 checkInfo.setFailover(true);
1437 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001438 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001439 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001440 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001441 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001442 }
1443
1444 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001445 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1446 }
1447
1448 private void sendInetConditionBroadcast(NetworkInfo info) {
1449 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1450 }
1451
1452 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1453 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001454 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1455 if (info.isFailover()) {
1456 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1457 info.setFailover(false);
1458 }
1459 if (info.getReason() != null) {
1460 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1461 }
1462 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001463 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1464 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001465 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001466 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001467 sendStickyBroadcast(intent);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001468 }
1469
1470 /**
1471 * Called when an attempt to fail over to another network has failed.
1472 * @param info the {@link NetworkInfo} for the failed network
1473 */
1474 private void handleConnectionFailure(NetworkInfo info) {
1475 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001476
Robert Greenwalt2034b912009-08-12 16:08:25 -07001477 String reason = info.getReason();
1478 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001479
Robert Greenwalte981bc52010-10-08 16:35:52 -07001480 String reasonText;
1481 if (reason == null) {
1482 reasonText = ".";
1483 } else {
1484 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001485 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001486 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001487
1488 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1489 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1490 if (getActiveNetworkInfo() == null) {
1491 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1492 }
1493 if (reason != null) {
1494 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1495 }
1496 if (extraInfo != null) {
1497 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1498 }
1499 if (info.isFailover()) {
1500 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1501 info.setFailover(false);
1502 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001503
Robert Greenwalt34848c02011-03-25 13:09:25 -07001504 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001505 tryFailover(info.getType());
1506 if (mActiveDefaultNetwork != -1) {
1507 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001508 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1509 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001510 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001511 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1512 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001513 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001514
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001515 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001516 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001517 /*
1518 * If the failover network is already connected, then immediately send
1519 * out a followup broadcast indicating successful failover
1520 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001521 if (mActiveDefaultNetwork != -1) {
1522 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001523 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001524 }
1525
1526 private void sendStickyBroadcast(Intent intent) {
1527 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001528 if (!mSystemReady) {
1529 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001530 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001531 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1532 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001533 }
1534 }
1535
1536 void systemReady() {
1537 synchronized(this) {
1538 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001539 if (mInitialBroadcast != null) {
1540 mContext.sendStickyBroadcast(mInitialBroadcast);
1541 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001542 }
1543 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001544 // load the global proxy at startup
1545 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001546 }
1547
1548 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001549 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001550
1551 // snapshot isFailover, because sendConnectedBroadcast() resets it
1552 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001553 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001554
Robert Greenwalt2034b912009-08-12 16:08:25 -07001555 // if this is a default net and other default is running
1556 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001557 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001558 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1559 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001560 mNetConfigs[mActiveDefaultNetwork].priority >
1561 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001562 mNetworkPreference == mActiveDefaultNetwork) {
1563 // don't accept this one
Wink Savillee70c6f52010-12-03 12:01:38 -08001564 if (DBG) {
1565 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001566 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001567 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001568 teardown(thisNet);
1569 return;
1570 } else {
1571 // tear down the other
1572 NetworkStateTracker otherNet =
1573 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001574 if (DBG) {
1575 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001576 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001577 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001578 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001579 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001580 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001581 return;
1582 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001583 }
1584 }
1585 synchronized (ConnectivityService.this) {
1586 // have a new default network, release the transition wakelock in a second
1587 // if it's held. The second pause is to allow apps to reconnect over the
1588 // new network
1589 if (mNetTransitionWakeLock.isHeld()) {
1590 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001591 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001592 mNetTransitionWakeLockSerialNumber, 0),
1593 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001594 }
1595 }
1596 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001597 // this will cause us to come up initially as unconnected and switching
1598 // to connected after our normal pause unless somebody reports us as reall
1599 // disconnected
1600 mDefaultInetConditionPublished = 0;
1601 mDefaultConnectionSequence++;
1602 mInetConditionChangeInFlight = false;
1603 // Don't do this - if we never sign in stay, grey
1604 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001605 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001606 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001607 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001608 handleConnectivityChange(type, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001609 sendConnectedBroadcast(info);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001610 }
1611
The Android Open Source Project28527d22009-03-03 19:31:44 -08001612 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001613 * After a change in the connectivity state of a network. We're mainly
1614 * concerned with making sure that the list of DNS servers is set up
1615 * according to which networks are connected, and ensuring that the
1616 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001617 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001618 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001619 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1620
The Android Open Source Project28527d22009-03-03 19:31:44 -08001621 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001622 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001623 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001624 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001625 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001626
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001627 LinkProperties curLp = mCurrentLinkProperties[netType];
1628 LinkProperties newLp = null;
1629
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001630 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001631 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001632 if (VDBG) {
1633 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1634 " doReset=" + doReset + " resetMask=" + resetMask +
1635 "\n curLp=" + curLp +
1636 "\n newLp=" + newLp);
1637 }
1638
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001639 if (curLp != null) {
1640 if (curLp.isIdenticalInterfaceName(newLp)) {
1641 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1642 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1643 for (LinkAddress linkAddr : car.removed) {
1644 if (linkAddr.getAddress() instanceof Inet4Address) {
1645 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1646 }
1647 if (linkAddr.getAddress() instanceof Inet6Address) {
1648 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1649 }
Wink Saville051a6642011-07-13 13:44:13 -07001650 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001651 if (DBG) {
1652 log("handleConnectivityChange: addresses changed" +
1653 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1654 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001655 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001656 } else {
1657 if (DBG) {
1658 log("handleConnectivityChange: address are the same reset per doReset" +
1659 " linkProperty[" + netType + "]:" +
1660 " resetMask=" + resetMask);
1661 }
Wink Saville051a6642011-07-13 13:44:13 -07001662 }
1663 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001664 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
1665 log("handleConnectivityChange: interface not not equivalent reset both" +
1666 " linkProperty[" + netType + "]:" +
1667 " resetMask=" + resetMask);
Wink Saville051a6642011-07-13 13:44:13 -07001668 }
Wink Saville051a6642011-07-13 13:44:13 -07001669 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001670 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001671 handleApplyDefaultProxy(netType);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001672 }
1673 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001674 if (VDBG) {
1675 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1676 " doReset=" + doReset + " resetMask=" + resetMask +
1677 "\n curLp=" + curLp +
1678 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001679 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001680 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001681 mCurrentLinkProperties[netType] = newLp;
1682 updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001683
Wink Saville051a6642011-07-13 13:44:13 -07001684 if (doReset || resetMask != 0) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001685 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1686 if (linkProperties != null) {
1687 String iface = linkProperties.getInterfaceName();
1688 if (TextUtils.isEmpty(iface) == false) {
Wink Saville051a6642011-07-13 13:44:13 -07001689 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1690 NetworkUtils.resetConnections(iface, resetMask);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001691 }
1692 }
1693 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001694
1695 // TODO: Temporary notifying upstread change to Tethering.
1696 // @see bug/4455071
1697 /** Notify TetheringService if interface name has been changed. */
1698 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1699 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1700 if (isTetheringSupported()) {
1701 mTethering.handleTetherIfaceChange();
1702 }
1703 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001704 }
1705
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001706 /**
1707 * Add and remove routes using the old properties (null if not previously connected),
1708 * new properties (null if becoming disconnected). May even be double null, which
1709 * is a noop.
1710 * Uses isLinkDefault to determine if default routes should be set or conversely if
1711 * host routes should be set to the dns servers
1712 */
1713 private void updateRoutes(LinkProperties newLp, LinkProperties curLp, boolean isLinkDefault) {
1714 Collection<RouteInfo> routesToAdd = null;
1715 CompareResult<InetAddress> dnsDiff = null;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001716
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001717 if (curLp != null) {
1718 // check for the delta between the current set and the new
1719 CompareResult<RouteInfo> routeDiff = curLp.compareRoutes(newLp);
1720 dnsDiff = curLp.compareDnses(newLp);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001721
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001722 for (RouteInfo r : routeDiff.removed) {
1723 if (isLinkDefault || ! r.isDefaultRoute()) {
1724 removeRoute(curLp, r);
Robert Greenwalt355205c2011-05-10 15:05:02 -07001725 }
1726 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001727 routesToAdd = routeDiff.added;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001728 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001729
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001730 if (newLp != null) {
1731 // if we didn't get a diff from cur -> new, then just use the new
1732 if (routesToAdd == null) {
1733 routesToAdd = newLp.getRoutes();
1734 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001735
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001736 for (RouteInfo r : routesToAdd) {
1737 if (isLinkDefault || ! r.isDefaultRoute()) {
1738 addRoute(newLp, r);
1739 }
1740 }
1741 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001742
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001743 if (!isLinkDefault) {
1744 // handle DNS routes
1745 Collection<InetAddress> dnsToAdd = null;
1746 if (dnsDiff != null) {
1747 dnsToAdd = dnsDiff.added;
1748 for (InetAddress dnsAddress : dnsDiff.removed) {
1749 removeRoute(curLp, RouteInfo.makeHostRoute(dnsAddress));
1750 }
1751 }
1752 if (newLp != null) {
1753 if (dnsToAdd == null) {
1754 dnsToAdd = newLp.getDnses();
1755 }
1756 for(InetAddress dnsAddress : dnsToAdd) {
1757 addRoute(newLp, RouteInfo.makeHostRoute(dnsAddress));
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001758 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001759 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001760 }
1761 }
1762
1763
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001764 /**
1765 * Reads the network specific TCP buffer sizes from SystemProperties
1766 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1767 * wide use
1768 */
1769 public void updateNetworkSettings(NetworkStateTracker nt) {
1770 String key = nt.getTcpBufferSizesPropName();
1771 String bufferSizes = SystemProperties.get(key);
1772
1773 if (bufferSizes.length() == 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001774 loge(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001775
1776 // Setting to default values so we won't be stuck to previous values
1777 key = "net.tcp.buffersize.default";
1778 bufferSizes = SystemProperties.get(key);
1779 }
1780
1781 // Set values in kernel
1782 if (bufferSizes.length() != 0) {
1783 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001784 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001785 + "] which comes from [" + key + "]");
1786 }
1787 setBufferSize(bufferSizes);
1788 }
1789 }
1790
1791 /**
1792 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1793 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1794 *
1795 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1796 * writeMin, writeInitial, writeMax"
1797 */
1798 private void setBufferSize(String bufferSizes) {
1799 try {
1800 String[] values = bufferSizes.split(",");
1801
1802 if (values.length == 6) {
1803 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04001804 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1805 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1806 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1807 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1808 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1809 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001810 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001811 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001812 }
1813 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001814 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001815 }
1816 }
1817
Robert Greenwalt2034b912009-08-12 16:08:25 -07001818 /**
1819 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1820 * on the highest priority active net which this process requested.
1821 * If there aren't any, clear it out
1822 */
1823 private void reassessPidDns(int myPid, boolean doBump)
1824 {
Wink Savillee70c6f52010-12-03 12:01:38 -08001825 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001826 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001827 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001828 continue;
1829 }
1830 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001831 if (nt.getNetworkInfo().isConnected() &&
1832 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001833 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001834 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001835 List pids = mNetRequestersPids[i];
1836 for (int j=0; j<pids.size(); j++) {
1837 Integer pid = (Integer)pids.get(j);
1838 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001839 Collection<InetAddress> dnses = p.getDnses();
1840 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001841 if (doBump) {
1842 bumpDns();
1843 }
1844 return;
1845 }
1846 }
1847 }
1848 }
1849 // nothing found - delete
1850 for (int i = 1; ; i++) {
1851 String prop = "net.dns" + i + "." + myPid;
1852 if (SystemProperties.get(prop).length() == 0) {
1853 if (doBump) {
1854 bumpDns();
1855 }
1856 return;
1857 }
1858 SystemProperties.set(prop, "");
1859 }
1860 }
1861
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001862 // return true if results in a change
1863 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001864 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001865 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001866 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001867 String dnsString = dns.getHostAddress();
1868 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1869 changed = true;
1870 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1871 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001872 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001873 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001874 }
1875
1876 private void bumpDns() {
1877 /*
1878 * Bump the property that tells the name resolver library to reread
1879 * the DNS server list from the properties.
1880 */
1881 String propVal = SystemProperties.get("net.dnschange");
1882 int n = 0;
1883 if (propVal.length() != 0) {
1884 try {
1885 n = Integer.parseInt(propVal);
1886 } catch (NumberFormatException e) {}
1887 }
1888 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07001889 /*
1890 * Tell the VMs to toss their DNS caches
1891 */
1892 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1893 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08001894 /*
1895 * Connectivity events can happen before boot has completed ...
1896 */
1897 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07001898 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001899 }
1900
Chia-chi Yehcc844502011-07-14 18:01:57 -07001901 // Caller must grab mDnsLock.
1902 private boolean updateDns(String network, Collection<InetAddress> dnses, String domains) {
1903 boolean changed = false;
1904 int last = 0;
1905 if (dnses.size() == 0 && mDefaultDns != null) {
1906 ++last;
1907 String value = mDefaultDns.getHostAddress();
1908 if (!value.equals(SystemProperties.get("net.dns1"))) {
1909 if (DBG) {
1910 log("no dns provided for " + network + " - using " + value);
1911 }
1912 changed = true;
1913 SystemProperties.set("net.dns1", value);
1914 }
1915 } else {
1916 for (InetAddress dns : dnses) {
1917 ++last;
1918 String key = "net.dns" + last;
1919 String value = dns.getHostAddress();
1920 if (!changed && value.equals(SystemProperties.get(key))) {
1921 continue;
1922 }
1923 if (DBG) {
1924 log("adding dns " + value + " for " + network);
1925 }
1926 changed = true;
1927 SystemProperties.set(key, value);
1928 }
1929 }
1930 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
1931 String key = "net.dns" + i;
1932 if (DBG) log("erasing " + key);
1933 changed = true;
1934 SystemProperties.set(key, "");
1935 }
1936 mNumDnsEntries = last;
1937
1938 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
1939 SystemProperties.set("net.dns.search", domains);
1940 changed = true;
1941 }
1942 return changed;
1943 }
1944
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001945 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001946 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001947 NetworkStateTracker nt = mNetTrackers[netType];
1948 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001949 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001950 if (p == null) return;
1951 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001952 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001953 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07001954 String network = nt.getNetworkInfo().getTypeName();
1955 synchronized (mDnsLock) {
1956 if (!mDnsOverridden) {
1957 changed = updateDns(network, dnses, "");
Robert Greenwalt94daa182010-09-01 11:34:05 -07001958 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001959 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001960 } else {
1961 // set per-pid dns for attached secondary nets
1962 List pids = mNetRequestersPids[netType];
1963 for (int y=0; y< pids.size(); y++) {
1964 Integer pid = (Integer)pids.get(y);
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001965 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001966 }
1967 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001968 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001969 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001970 }
1971
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001972 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001973 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1974 NETWORK_RESTORE_DELAY_PROP_NAME);
1975 if(restoreDefaultNetworkDelayStr != null &&
1976 restoreDefaultNetworkDelayStr.length() != 0) {
1977 try {
1978 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1979 } catch (NumberFormatException e) {
1980 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001981 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001982 // if the system property isn't set, use the value for the apn type
1983 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1984
1985 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1986 (mNetConfigs[networkType] != null)) {
1987 ret = mNetConfigs[networkType].restoreTime;
1988 }
1989 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001990 }
1991
1992 @Override
1993 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001994 if (mContext.checkCallingOrSelfPermission(
1995 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001996 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001997 pw.println("Permission Denial: can't dump ConnectivityService " +
1998 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1999 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002000 return;
2001 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002002 pw.println();
2003 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002004 if (nst != null) {
2005 if (nst.getNetworkInfo().isConnected()) {
2006 pw.println("Active network: " + nst.getNetworkInfo().
2007 getTypeName());
2008 }
2009 pw.println(nst.getNetworkInfo());
2010 pw.println(nst);
2011 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002012 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002013 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002014
2015 pw.println("Network Requester Pids:");
2016 for (int net : mPriorityList) {
2017 String pidString = net + ": ";
2018 for (Object pid : mNetRequestersPids[net]) {
2019 pidString = pidString + pid.toString() + ", ";
2020 }
2021 pw.println(pidString);
2022 }
2023 pw.println();
2024
2025 pw.println("FeatureUsers:");
2026 for (Object requester : mFeatureUsers) {
2027 pw.println(requester.toString());
2028 }
2029 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002030
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002031 synchronized (this) {
2032 pw.println("NetworkTranstionWakeLock is currently " +
2033 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2034 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2035 }
2036 pw.println();
2037
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002038 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002039
2040 if (mInetLog != null) {
2041 pw.println();
2042 pw.println("Inet condition reports:");
2043 for(int i = 0; i < mInetLog.size(); i++) {
2044 pw.println(mInetLog.get(i));
2045 }
2046 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002047 }
2048
Robert Greenwalt2034b912009-08-12 16:08:25 -07002049 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002050 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07002051 public MyHandler(Looper looper) {
2052 super(looper);
2053 }
2054
The Android Open Source Project28527d22009-03-03 19:31:44 -08002055 @Override
2056 public void handleMessage(Message msg) {
2057 NetworkInfo info;
2058 switch (msg.what) {
2059 case NetworkStateTracker.EVENT_STATE_CHANGED:
2060 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002061 int type = info.getType();
2062 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002063
Wink Savillee70c6f52010-12-03 12:01:38 -08002064 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002065 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002066 state + "/" + info.getDetailedState());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002067
2068 // Connectivity state changed:
2069 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002070 // [12-9] Network subtype (for mobile network, as defined
2071 // by TelephonyManager)
2072 // [8-3] Detailed state ordinal (as defined by
2073 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002074 // [2-0] Network type (as defined by ConnectivityManager)
2075 int eventLogParam = (info.getType() & 0x7) |
2076 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2077 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002078 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002079 eventLogParam);
2080
2081 if (info.getDetailedState() ==
2082 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002083 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002084 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002085 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002086 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002087 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002088 // the logic here is, handle SUSPENDED the same as
2089 // DISCONNECTED. The only difference being we are
2090 // broadcasting an intent with NetworkInfo that's
2091 // suspended. This allows the applications an
2092 // opportunity to handle DISCONNECTED and SUSPENDED
2093 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002094 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002095 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002096 handleConnect(info);
2097 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002098 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002099 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002100 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002101 // TODO: Temporary allowing network configuration
2102 // change not resetting sockets.
2103 // @see bug/4455071
2104 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002105 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002106 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002107 String causedBy = null;
2108 synchronized (ConnectivityService.this) {
2109 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2110 mNetTransitionWakeLock.isHeld()) {
2111 mNetTransitionWakeLock.release();
2112 causedBy = mNetTransitionWakeLockCausedBy;
2113 }
2114 }
2115 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002116 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002117 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002118 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002119 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002120 FeatureUser u = (FeatureUser)msg.obj;
2121 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002122 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002123 case EVENT_INET_CONDITION_CHANGE:
2124 {
2125 int netType = msg.arg1;
2126 int condition = msg.arg2;
2127 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002128 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002129 }
2130 case EVENT_INET_CONDITION_HOLD_END:
2131 {
2132 int netType = msg.arg1;
2133 int sequence = msg.arg2;
2134 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002135 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002136 }
2137 case EVENT_SET_NETWORK_PREFERENCE:
2138 {
2139 int preference = msg.arg1;
2140 handleSetNetworkPreference(preference);
2141 break;
2142 }
2143 case EVENT_SET_BACKGROUND_DATA:
2144 {
2145 boolean enabled = (msg.arg1 == ENABLED);
2146 handleSetBackgroundData(enabled);
2147 break;
2148 }
2149 case EVENT_SET_MOBILE_DATA:
2150 {
2151 boolean enabled = (msg.arg1 == ENABLED);
2152 handleSetMobileData(enabled);
2153 break;
2154 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002155 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2156 {
2157 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002158 break;
2159 }
2160 case EVENT_SET_DEPENDENCY_MET:
2161 {
2162 boolean met = (msg.arg1 == ENABLED);
2163 handleSetDependencyMet(msg.arg2, met);
2164 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002165 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002166 case EVENT_RESTORE_DNS:
2167 {
2168 if (mActiveDefaultNetwork != -1) {
2169 handleDnsConfigurationChange(mActiveDefaultNetwork);
2170 }
2171 break;
2172 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002173 }
2174 }
2175 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002176
2177 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002178 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002179 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002180
2181 if (isTetheringSupported()) {
2182 return mTethering.tether(iface);
2183 } else {
2184 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2185 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002186 }
2187
2188 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002189 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002190 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002191
2192 if (isTetheringSupported()) {
2193 return mTethering.untether(iface);
2194 } else {
2195 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2196 }
2197 }
2198
2199 // javadoc from interface
2200 public int getLastTetherError(String iface) {
2201 enforceTetherAccessPermission();
2202
2203 if (isTetheringSupported()) {
2204 return mTethering.getLastTetherError(iface);
2205 } else {
2206 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2207 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002208 }
2209
2210 // TODO - proper iface API for selection by property, inspection, etc
2211 public String[] getTetherableUsbRegexs() {
2212 enforceTetherAccessPermission();
2213 if (isTetheringSupported()) {
2214 return mTethering.getTetherableUsbRegexs();
2215 } else {
2216 return new String[0];
2217 }
2218 }
2219
2220 public String[] getTetherableWifiRegexs() {
2221 enforceTetherAccessPermission();
2222 if (isTetheringSupported()) {
2223 return mTethering.getTetherableWifiRegexs();
2224 } else {
2225 return new String[0];
2226 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002227 }
2228
Danica Chang96567052010-08-11 14:54:43 -07002229 public String[] getTetherableBluetoothRegexs() {
2230 enforceTetherAccessPermission();
2231 if (isTetheringSupported()) {
2232 return mTethering.getTetherableBluetoothRegexs();
2233 } else {
2234 return new String[0];
2235 }
2236 }
2237
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002238 // TODO - move iface listing, queries, etc to new module
2239 // javadoc from interface
2240 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002241 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002242 return mTethering.getTetherableIfaces();
2243 }
2244
2245 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002246 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002247 return mTethering.getTetheredIfaces();
2248 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002249
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002250 public String[] getTetheringErroredIfaces() {
2251 enforceTetherAccessPermission();
2252 return mTethering.getErroredIfaces();
2253 }
2254
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002255 // if ro.tether.denied = true we default to no tethering
2256 // gservices could set the secure setting to 1 though to enable it on a build where it
2257 // had previously been turned off.
2258 public boolean isTetheringSupported() {
2259 enforceTetherAccessPermission();
2260 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002261 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2262 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2263 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002264 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002265
2266 // An API NetworkStateTrackers can call when they lose their network.
2267 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2268 // whichever happens first. The timer is started by the first caller and not
2269 // restarted by subsequent callers.
2270 public void requestNetworkTransitionWakelock(String forWhom) {
2271 enforceConnectivityInternalPermission();
2272 synchronized (this) {
2273 if (mNetTransitionWakeLock.isHeld()) return;
2274 mNetTransitionWakeLockSerialNumber++;
2275 mNetTransitionWakeLock.acquire();
2276 mNetTransitionWakeLockCausedBy = forWhom;
2277 }
2278 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002279 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002280 mNetTransitionWakeLockSerialNumber, 0),
2281 mNetTransitionWakeLockTimeout);
2282 return;
2283 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002284
Robert Greenwalt986c7412010-09-08 15:24:47 -07002285 // 100 percent is full good, 0 is full bad.
2286 public void reportInetCondition(int networkType, int percentage) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002287 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002288 mContext.enforceCallingOrSelfPermission(
2289 android.Manifest.permission.STATUS_BAR,
2290 "ConnectivityService");
2291
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002292 if (DBG) {
2293 int pid = getCallingPid();
2294 int uid = getCallingUid();
2295 String s = pid + "(" + uid + ") reports inet is " +
2296 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2297 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2298 mInetLog.add(s);
2299 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2300 mInetLog.remove(0);
2301 }
2302 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002303 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002304 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2305 }
2306
2307 private void handleInetConditionChange(int netType, int condition) {
2308 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002309 log("Inet connectivity change, net=" +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002310 netType + ", condition=" + condition +
2311 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2312 }
2313 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002314 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002315 return;
2316 }
2317 if (mActiveDefaultNetwork != netType) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002318 if (DBG) log("given net not default - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002319 return;
2320 }
2321 mDefaultInetCondition = condition;
2322 int delay;
2323 if (mInetConditionChangeInFlight == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002324 if (DBG) log("starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002325 // setup a new hold to debounce this
2326 if (mDefaultInetCondition > 50) {
2327 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2328 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2329 } else {
2330 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2331 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2332 }
2333 mInetConditionChangeInFlight = true;
2334 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2335 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2336 } else {
2337 // we've set the new condition, when this hold ends that will get
2338 // picked up
Wink Savillee70c6f52010-12-03 12:01:38 -08002339 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002340 }
2341 }
2342
2343 private void handleInetConditionHoldEnd(int netType, int sequence) {
2344 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002345 log("Inet hold end, net=" + netType +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002346 ", condition =" + mDefaultInetCondition +
2347 ", published condition =" + mDefaultInetConditionPublished);
2348 }
2349 mInetConditionChangeInFlight = false;
2350
2351 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002352 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002353 return;
2354 }
2355 if (mDefaultConnectionSequence != sequence) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002356 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002357 return;
2358 }
2359 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002360 if (DBG) log("no change in condition - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002361 return;
2362 }
2363 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2364 if (networkInfo.isConnected() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002365 if (DBG) log("default network not connected - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002366 return;
2367 }
2368 mDefaultInetConditionPublished = mDefaultInetCondition;
2369 sendInetConditionBroadcast(networkInfo);
2370 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002371 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002372
2373 public synchronized ProxyProperties getProxy() {
2374 if (mGlobalProxy != null) return mGlobalProxy;
2375 if (mDefaultProxy != null) return mDefaultProxy;
2376 return null;
2377 }
2378
2379 public void setGlobalProxy(ProxyProperties proxyProperties) {
2380 enforceChangePermission();
2381 synchronized (mGlobalProxyLock) {
2382 if (proxyProperties == mGlobalProxy) return;
2383 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2384 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2385
2386 String host = "";
2387 int port = 0;
2388 String exclList = "";
2389 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2390 mGlobalProxy = new ProxyProperties(proxyProperties);
2391 host = mGlobalProxy.getHost();
2392 port = mGlobalProxy.getPort();
2393 exclList = mGlobalProxy.getExclusionList();
2394 } else {
2395 mGlobalProxy = null;
2396 }
2397 ContentResolver res = mContext.getContentResolver();
2398 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2399 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002400 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002401 exclList);
2402 }
2403
2404 if (mGlobalProxy == null) {
2405 proxyProperties = mDefaultProxy;
2406 }
2407 sendProxyBroadcast(proxyProperties);
2408 }
2409
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002410 private void loadGlobalProxy() {
2411 ContentResolver res = mContext.getContentResolver();
2412 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2413 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2414 String exclList = Settings.Secure.getString(res,
2415 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2416 if (!TextUtils.isEmpty(host)) {
2417 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2418 synchronized (mGlobalProxyLock) {
2419 mGlobalProxy = proxyProperties;
2420 }
2421 }
2422 }
2423
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002424 public ProxyProperties getGlobalProxy() {
2425 synchronized (mGlobalProxyLock) {
2426 return mGlobalProxy;
2427 }
2428 }
2429
2430 private void handleApplyDefaultProxy(int type) {
2431 // check if new default - push it out to all VM if so
2432 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2433 synchronized (this) {
2434 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2435 if (mDefaultProxy == proxy) return;
2436 if (!TextUtils.isEmpty(proxy.getHost())) {
2437 mDefaultProxy = proxy;
2438 } else {
2439 mDefaultProxy = null;
2440 }
2441 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002442 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002443 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2444 if (mGlobalProxy != null) return;
2445 sendProxyBroadcast(proxy);
2446 }
2447
2448 private void handleDeprecatedGlobalHttpProxy() {
2449 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2450 Settings.Secure.HTTP_PROXY);
2451 if (!TextUtils.isEmpty(proxy)) {
2452 String data[] = proxy.split(":");
2453 String proxyHost = data[0];
2454 int proxyPort = 8080;
2455 if (data.length > 1) {
2456 try {
2457 proxyPort = Integer.parseInt(data[1]);
2458 } catch (NumberFormatException e) {
2459 return;
2460 }
2461 }
2462 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2463 setGlobalProxy(p);
2464 }
2465 }
2466
2467 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002468 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savillee70c6f52010-12-03 12:01:38 -08002469 log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002470 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002471 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2472 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002473 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002474 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002475 }
2476
2477 private static class SettingsObserver extends ContentObserver {
2478 private int mWhat;
2479 private Handler mHandler;
2480 SettingsObserver(Handler handler, int what) {
2481 super(handler);
2482 mHandler = handler;
2483 mWhat = what;
2484 }
2485
2486 void observe(Context context) {
2487 ContentResolver resolver = context.getContentResolver();
2488 resolver.registerContentObserver(Settings.Secure.getUriFor(
2489 Settings.Secure.HTTP_PROXY), false, this);
2490 }
2491
2492 @Override
2493 public void onChange(boolean selfChange) {
2494 mHandler.obtainMessage(mWhat).sendToTarget();
2495 }
2496 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002497
2498 private void log(String s) {
2499 Slog.d(TAG, s);
2500 }
2501
2502 private void loge(String s) {
2503 Slog.e(TAG, s);
2504 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002505
Wink Savillef6b76692011-02-24 17:58:51 -08002506 int convertFeatureToNetworkType(String feature){
2507 int networkType = -1;
2508 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2509 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2510 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2511 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2512 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2513 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2514 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2515 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2516 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2517 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2518 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2519 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2520 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2521 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2522 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2523 }
2524 return networkType;
2525 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002526
2527 private static <T> T checkNotNull(T value, String message) {
2528 if (value == null) {
2529 throw new NullPointerException(message);
2530 }
2531 return value;
2532 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002533
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002534 /**
2535 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002536 * VpnBuilder and not available in ConnectivityManager. Permissions
2537 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002538 * @hide
2539 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002540 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07002541 public boolean protectVpn(ParcelFileDescriptor socket) {
2542 try {
2543 int type = mActiveDefaultNetwork;
2544 if (ConnectivityManager.isNetworkTypeValid(type)) {
2545 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2546 return true;
2547 }
2548 } catch (Exception e) {
2549 // ignore
2550 } finally {
2551 try {
2552 socket.close();
2553 } catch (Exception e) {
2554 // ignore
2555 }
2556 }
2557 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002558 }
2559
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002560 /**
2561 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002562 * and not available in ConnectivityManager. Permissions are checked
2563 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002564 * @hide
2565 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002566 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07002567 public boolean prepareVpn(String oldPackage, String newPackage) {
2568 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002569 }
2570
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002571 /**
2572 * Configure a TUN interface and return its file descriptor. Parameters
2573 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002574 * and not available in ConnectivityManager. Permissions are checked in
2575 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002576 * @hide
2577 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002578 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002579 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002580 return mVpn.establish(config);
2581 }
2582
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002583 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002584 * Start legacy VPN and return an intent to VpnDialogs. This method is
2585 * used by VpnSettings and not available in ConnectivityManager.
2586 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002587 * @hide
2588 */
2589 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002590 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2591 mVpn.startLegacyVpn(config, racoon, mtpd);
2592 }
2593
2594 /**
2595 * Return the information of the ongoing legacy VPN. This method is used
2596 * by VpnSettings and not available in ConnectivityManager. Permissions
2597 * are checked in Vpn class.
2598 * @hide
2599 */
2600 @Override
2601 public LegacyVpnInfo getLegacyVpnInfo() {
2602 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002603 }
2604
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002605 /**
2606 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2607 * through NetworkStateTracker since it works differently. For example, it
2608 * needs to override DNS servers but never takes the default routes. It
2609 * relies on another data network, and it could keep existing connections
2610 * alive after reconnecting, switching between networks, or even resuming
2611 * from deep sleep. Calls from applications should be done synchronously
2612 * to avoid race conditions. As these are all hidden APIs, refactoring can
2613 * be done whenever a better abstraction is developed.
2614 */
2615 public class VpnCallback {
2616
2617 private VpnCallback() {
2618 }
2619
Chia-chi Yehcc844502011-07-14 18:01:57 -07002620 public void override(List<String> dnsServers, List<String> searchDomains) {
2621 if (dnsServers == null) {
2622 restore();
2623 return;
2624 }
2625
2626 // Convert DNS servers into addresses.
2627 List<InetAddress> addresses = new ArrayList<InetAddress>();
2628 for (String address : dnsServers) {
2629 // Double check the addresses and remove invalid ones.
2630 try {
2631 addresses.add(InetAddress.parseNumericAddress(address));
2632 } catch (Exception e) {
2633 // ignore
2634 }
2635 }
2636 if (addresses.isEmpty()) {
2637 restore();
2638 return;
2639 }
2640
2641 // Concatenate search domains into a string.
2642 StringBuilder buffer = new StringBuilder();
2643 if (searchDomains != null) {
2644 for (String domain : searchDomains) {
2645 buffer.append(domain).append(' ');
2646 }
2647 }
2648 String domains = buffer.toString().trim();
2649
2650 // Apply DNS changes.
2651 boolean changed = false;
2652 synchronized (mDnsLock) {
2653 changed = updateDns("VPN", addresses, domains);
2654 mDnsOverridden = true;
2655 }
2656 if (changed) {
2657 bumpDns();
2658 }
2659
2660 // TODO: temporarily remove http proxy?
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002661 }
2662
Chia-chi Yehcc844502011-07-14 18:01:57 -07002663 public void restore() {
2664 synchronized (mDnsLock) {
2665 if (!mDnsOverridden) {
2666 return;
2667 }
2668 mDnsOverridden = false;
2669 }
2670 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002671 }
2672 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002673}